<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类" prop="cateId">
        <el-select   v-model="queryParams.cateId" placeholder="请选择分类" clearable size="small" >
         <el-option
                v-for="item in cateOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
        </el-select>
      </el-form-item>
      <el-form-item label="套餐名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入套餐名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select   v-model="queryParams.status" placeholder="请选择状态" clearable size="small" >
         <el-option
                v-for="item in statusOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['store:storeProductPackage:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="handleUpdateMore"
          v-hasPermi="['store:storeProductPackage:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['store:storeProductPackage:remove']"
        >删除</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['store:storeProductPackage:export']"
        >导出</el-button>
      </el-col>

	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table  height="500" border v-loading="loading" :data="storeProductPackageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="packageId" />
      <el-table-column label="封面" align="center" width="120">
        <template slot-scope="scope">
          <el-popover
            placement="right"
            title=""
            trigger="hover">
            <img slot="reference" :src="scope.row.imgUrl" width="100">
            <img :src="scope.row.imgUrl" style="max-width: 150px;">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="所属分类" align="center" prop="cateId" width="150px" >
          <template slot-scope="scope">
              <el-tag prop="cateId" v-for="(item, index) in cateOptions"    v-if="scope.row.cateId==item.dictValue">{{item.dictLabel}}</el-tag>
          </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="title" show-overflow-tooltip />
      <el-table-column label="描述" align="center" prop="descs" show-overflow-tooltip />
      <el-table-column label="原价" align="center"  >
          <template slot-scope="scope">
              <div  v-if="scope.row.money!=null"  >
                {{scope.row.money.toFixed(2)}}
              </div>
          </template>
      </el-table-column>
      <el-table-column label="套餐价格" align="center"  >
          <template slot-scope="scope">
              <div  v-if="scope.row.payMoney!=null"  >
                {{scope.row.payMoney.toFixed(2)}}
              </div>
          </template>
      </el-table-column>
       <el-table-column label="支付类型" align="center" prop="payType" width="150px" >
          <template slot-scope="scope">
              <el-tag prop="payType" v-for="(item, index) in storePayTypeOptions"    v-if="scope.row.payType==item.dictValue">{{item.dictLabel}}</el-tag>
          </template>
      </el-table-column>

      <el-table-column label="限购次数" align="center" prop="limitCount" />
      <el-table-column label="排序" align="center" prop="sort" />
      <!-- <el-table-column label="所属部门" align="center" prop="deptName" /> -->
      <el-table-column label="状态" align="center" prop="status" >
          <template slot-scope="scope">
              <el-tag prop="status" v-for="(item, index) in statusOptions"    v-if="scope.row.status==item.dictValue">{{item.dictLabel}}</el-tag>
          </template>
      </el-table-column>

      <el-table-column label="操作" align="center" fixed="right" width="120px" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['store:storeProductPackage:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['store:storeProductPackage:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" :visible.sync="open1" width="580px" append-to-body>
       <el-form ref="form1" :model="form1" :rules="rules" label-width="80px">
         <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form1.status">
                <el-radio :label="item.dictValue" v-for="item in statusOptions" >{{item.dictLabel}}</el-radio>
              </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm1">确 定</el-button>
          <el-button @click="cancel1">取 消</el-button>
        </div>
    </el-dialog>

    <!-- 添加或修改商品组合套餐对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="套餐封面" prop="imgUrl">
          <Material v-model="imageArr" type="image" :num="1" :width="150" :height="150" />
        </el-form-item>
        <el-form-item label="套餐组图" prop="images">
           <Material v-model="photoArr" type="image" :num="10" :width="150" :height="150" />
        </el-form-item>
        <el-form-item label="套餐标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入套餐标题" />
        </el-form-item>
        <el-form-item label="所属分类" props="cateId">
            <el-select style="width: 200px" v-model="form.cateId" placeholder="请选择分类" clearable size="small" >
              <el-option
                      v-for="item in cateOptions"
                      :key="item.dictValue"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                    />
            </el-select>
        </el-form-item>
        <el-form-item label="套餐描述" prop="descs">
          <el-input type="textarea" v-model="form.descs" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="套餐详情" prop="content">
          <Editor ref="myeditor"   :min-height="192" @on-text-change="updateText" />
        </el-form-item>

        <el-form-item label="套餐商品" prop="productList"  >
              <el-row>
                <el-col>
                      <el-button plain  type="primary" icon="el-icon-plus" @click="handleAddProduct">添加商品</el-button>
                </el-col>
              </el-row>
              <el-table border width="100%" style="margin-top:5px;"  :data="products">
                <el-table-column label="商品编号" align="center" prop="barCode" />
                <el-table-column label="商品图片" align="center" width="100">
                  <template slot-scope="scope">
                    <el-popover
                      placement="right"
                      title=""
                      trigger="hover"
                    >
                      <img slot="reference" :src="scope.row.image" width="50">
                      <img :src="scope.row.image" style="max-width: 50px;">
                    </el-popover>
                  </template>
                </el-table-column>
                <el-table-column label="商品名称" show-overflow-tooltip align="center" prop="productName" />
                <el-table-column label="商品规格" align="center" prop="sku" />
                <!-- <el-table-column label="库存" align="center" prop="stock" /> -->
                <el-table-column label="售价" align="center"  prop="price"  >
                   <template slot-scope="scope">
                    <div v-if="scope.row.price!=null">
                         {{scope.row.price.toFixed(2)}}
                    </div>
                  </template>
                </el-table-column>
                <!-- <el-table-column label="代理价" align="center" prop="agentPrice" /> -->
                <el-table-column label="数量" align="center"  prop="count" width="200px" >
                   <template slot-scope="scope">
                    <div>
                        <el-input-number v-model="scope.row.count"  @change="handleProductCountChange(scope.row)"  size="mini" :min="1"   ></el-input-number>
                    </div>
                  </template>
                </el-table-column>
                 <el-table-column label="小计" align="center"  prop="money"  >
                   <template slot-scope="scope">
                    <div v-if="scope.row.money!=null">
                         {{scope.row.money.toFixed(2)}}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="100px" >
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-delete"
                      @click="handleProductDelete(scope.row)"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-row  >
                <el-col  >
                      <span style="margin-left:10px;" v-if="totalMoney!=null">商品总价:{{totalMoney}}</span>
                </el-col>
              </el-row>
        </el-form-item>

        <el-form-item label="原价" prop="money">
          <el-input-number v-model="form.money" :precision="2"  :min="0.00" placeholder="请输入原价" />
        </el-form-item>
        <el-form-item label="套餐价格" prop="payMoney">
          <el-input-number v-model="form.payMoney" :precision="2"  :min="0.00" placeholder="请输入套餐价格" />
        </el-form-item>
        <el-form-item label="支付类型" props="payType">
              <el-radio-group v-model="form.payType">
                <el-radio  v-if="item.dictValue!=3" :label="item.dictValue" v-for="item in storePayTypeOptions" >{{item.dictLabel}}</el-radio>
              </el-radio-group>
        </el-form-item>
         <el-form-item label="限购次数" prop="limitCount">
              <el-input-number v-model="form.limitCount" :min="0" :step="1" placeholder="请输入限购次数" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort"  :min="1"  />
        </el-form-item>
        <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :label="item.dictValue" v-for="item in statusOptions" >{{item.dictLabel}}</el-radio>
              </el-radio-group>
        </el-form-item>
        <el-form-item label="分期赠送优惠券" prop="icgEnable" v-hasPermi="['store:storeProductPackage:edit:coupon']">
          <el-radio-group v-model="icgEnableModel">
            <el-radio :label="item.dictValue" v-for="item in icgEnableOptions" >{{item.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="优惠券" prop="icgCouponsId" v-if="form.icgEnable==1" v-hasPermi="['store:storeProductPackage:edit:coupon']">
          <el-select v-model="form.icgCouponsId" filterable multiple placeholder="请选择">
            <el-option
              v-for="item in icgCouponsOptions"
              :key="item.couponId"
              :label="item.couponName"
              :value="item.couponId">
              <span style="float: left">{{ item.couponName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">id:{{item.id}},剩余{{ item.remainCount }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发放月数" prop="icgMonth" v-if="form.icgEnable==1" v-hasPermi="['store:storeProductPackage:edit:coupon']">
          <el-input-number v-model="form.icgMonth" placeholder="月数"/>
        </el-form-item>
        <el-form-item label="优惠券跳转URL" prop="icgUrl" v-if="form.icgEnable==1" v-hasPermi="['store:storeProductPackage:edit:coupon']">
          <el-input v-model="form.icgUrl" placeholder="优惠券跳转URL(没有则无跳转)"/>
        </el-form-item>
        <el-form-item label="优惠券备注信息" prop="icgMark" v-if="form.icgEnable==1" v-hasPermi="['store:storeProductPackage:edit:coupon']">
          <el-input v-model="form.icgMark" placeholder="优惠券备注信息"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="product.title" v-if="product.open"  :visible.sync="product.open" width="1000px" append-to-body>
        <product-attr-value-select  ref="product"  @selectProduct="selectProduct" />
    </el-dialog>
  </div>
</template>

<script>
import { listStoreProductPackage, getStoreProductPackage, delStoreProductPackage, addStoreProductPackage, updateStoreProductPackage, exportStoreProductPackage,modifyStoreProductPackages } from "@/api/store/storeProductPackage";
import Editor from '@/components/Editor/wang';
import productAttrValueSelect from "../components/productAttrValueSelect";
import Material from '@/components/Material'
import singleImg from '@/components/Material/single'
import {listAllAvailable} from "../../../api/store/storeCouponIssue";
export default {
  name: "StoreProductPackage",
  components: {
    Editor,
    productAttrValueSelect,
    Material,
    singleImg,
  },
  watch: {
    imageArr: function(val) {
      this.form.imgUrl = val.join(',')
    },
    photoArr: function(val) {
      this.form.images = val.join(',')
    }
  },
  data() {
    return {
      icgCouponsOptions:[],
      statusOptions:[],
      cateOptions:[],
      photoArr:[],
      imageArr:[],
      storePayTypeOptions:[],
      icgEnableOptions: [],
      totalMoney:0.00,
      products:[],
      product:{
        open:false,
        title:"商品选择"
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品组合套餐表格数据
      storeProductPackageList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示批量修改弹出层
      open1: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        descs: null,
        content: null,
        imgUrl: null,
        productIds: null,
        productAttrValueIds: null,
        money: null,
        payMoney: null,
        companyId: null,
        companyUserId: null
      },
      // 表单参数
      form: {},
       // 表单参数
      form1: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "标题不能为空" }
        ],
        descs: [
          { required: true, message: "描述不能为空" }
        ],
        content: [
          { required: true, message: "详情不能为空" }
        ],
        imgUrl: [
          { required: true, message: "封面不能为空" }
        ],
        images: [
          { required: true, message: "组图不能为空" }
        ],
        productList: [
          { required: true, message: "商品不能为空" }
        ],
        payMoney: [
          { required: true, message: "套餐价格不能为空" }
        ],
        payType: [
          { required: true, message: "支付类型不能为空" }
        ],
        limitCount: [
          { required: true, message: "限购次数不能为空" }
        ],

      }
    };
  },
  created() {

    this.getDicts("common_status").then((response) => {
      this.statusOptions = response.data;
    });
    this.getDicts("store_product_package_cate").then((response) => {
      this.cateOptions = response.data;
    });

    this.getDicts("store_pay_type").then((response) => {
      this.storePayTypeOptions = response.data;
    });

    this.getDicts('coupon_installment_switch').then(response=>{
      this.icgEnableOptions = response.data;
    })
    this.getList();

    this.loadStoreCouponList();
  },
  computed:{
    icgEnableModel: {
      get(){
        return this.form.icgEnable?.toString();
      },
      set(newVal){
        this.form.icgEnable = newVal;
      }
    }
  },
  methods: {
    loadStoreCouponList(){
      listAllAvailable().then(response=>{
        this.icgCouponsOptions=response.data;
      })
    },
    handleProductCountChange(row){
      row.money=row.count*row.price;
      this.$forceUpdate();
      this.compute();
    },
    handleProductDelete(row){
       this.products.splice(this.products.findIndex(item => item.id === row.id), 1)
       this.compute();
    },
    compute(){
      this.totalMoney=0;
      var that=this;
      this.products.forEach (function (value) {
          that.totalMoney += value.money;
      });
      that.totalMoney=that.totalMoney.toFixed(2);
    },
    selectProduct(row){
      console.log(row);
      for(var i=0;i<this.products.length;i++){
        if(this.products[i].id==row.id){
          return;
        }
      }
      row.count=1;
      row.money=row.count*row.price;
      this.products.push(row);
      this.compute();
    },
    handleAddProduct(){
      this.product.open=true;
      // setTimeout(() => {
      //   this.$refs.product.getData(1);
      // }, 200);

    },
    handleAvatarSuccess(res, file) {
        if(res.code==200){
          this.form.imgUrl=res.url;
        }
        else{
          this.msgError(res.msg);
        }
    },
    beforeAvatarUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1;
      if (!isLt1M) {
        this.$message.error('上传图片大小不能超过 1MB!');
      }
      return   isLt1M;
    },
    updateText(text){
      this.form.content=text;
    },
    /** 查询商品组合套餐列表 */
    getList() {
      this.loading = true;
      listStoreProductPackage(this.queryParams).then(response => {
        this.storeProductPackageList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        packageId: null,
        title: null,
        descs: null,
        content: null,
        imgUrl: null,
        images: null,
        money: null,
        payMoney: null,
        companyId: null,
        companyUserId: null,
        payType:"1",
        limitCount:0,
        cateId:"0",
        status:"1",
        icgEnable: "0",
        productList:null,
        icgCouponsId: [],
        icgMonth: 0,
        icgUrl: null,
        icgMark: null,
      };
      this.products=[];
      this.photoArr=[];
      this.imageArr=[];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.packageId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品组合套餐";
      setTimeout(() => {
        this.$refs.myeditor.setText("");
      }, 200);

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const packageId = row.packageId || this.ids
      getStoreProductPackage(packageId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品组合套餐";
        this.products=this.form.productList;
        for(var i=0;i<this.products.length;i++){
          this.products[i].money=this.products[i].count*this.products[i].price;
        }
        this.compute();
        setTimeout(() => {
          if(this.form.content==null){
            this.$refs.myeditor.setText("");
          }
          else{
            this.$refs.myeditor.setText(this.form.content);
          }
        }, 200);
        this.form.payType = response.data.payType.toString();
        this.form.status = response.data.status.toString();
        if(this.form.imgUrl!=null){
          this.imageArr=this.form.imgUrl.split(",");
        }
        if(this.form.images!=null){
          this.photoArr=this.form.images.split(",");
        }
         if(this.form.cateId!=null){
          this.form.cateId = response.data.cateId.toString();
        }
        this.$forceUpdate();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.productList=[];
      this.products.forEach((item) => {
        var data={id:item.id,count:item.count}
        this.form.productList.push(data)
      })
      // console.log(this.form)
      // return;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.packageId != null) {
            updateStoreProductPackage(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addStoreProductPackage(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const packageIds = row.packageId || this.ids;
      this.$confirm('是否确认删除商品组合套餐编号为"' + packageIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delStoreProductPackage(packageIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有商品组合套餐数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportStoreProductPackage(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    handleUpdateMore(row){
        this.title = "批量修改套餐状态";
        const packageIds = row.packageId || this.ids;
        this.form1.packageIds=packageIds;
        this.open1 = true;
    },
      // 取消按钮
    cancel1() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset1() {
      this.form1 = {
        status:"1",
        packageIds:[],
      };
      this.resetForm("form1");
    },
       /** 提交按钮 */
    submitForm1() {

       if(this.form1.status==null){
          this.msgError("请选择套餐状态");
          return;
       }
      this.$refs["form1"].validate(valid => {
        if (valid) {
            if (this.form1.packageIds != null) {
                modifyStoreProductPackages(this.form1).then(response => {
                    if (response.code === 200) {
                      this.msgSuccess("操作成功");
                      this.open1 = false;
                      this.getList();
                    }
                });
           }
         }
      });

    },


  }
};

</script>
<style scoped lang="scss">
.items{
  margin: 5px 0px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
  .pic{
    width:60px;
    height:60px;
  }
  .goods-content{
    margin-left: 10px;
    max-width: 200px;
    text-align: left;
    .goods-title{

      overflow:hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      -o-text-overflow:ellipsis;
    }
  }
}
</style>
