<template>
  <ContainerTit>
    <div slot="headr">
      <!--      <el-button>取消</el-button>-->
      <el-button type="primary" @click="addSetFn">保存</el-button>
    </div>
    <el-form
      ref="base_form"
      :model="setMeal_form"
      label-width="140px"
      size="small"
      style="background-color: #fff; padding: 20px"
    >
      <el-form-item label="活动名称：">
        <el-input
          v-model="setMeal_form.activity_name"
          placeholder="请输入活动名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="活动有效时间：">
        <el-date-picker
          v-model="activity_time"
          :disabled="setMeal_form.time_limit === 4"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="timestamp"
          @change="TimeChange"
        ></el-date-picker>
        <el-checkbox
          v-model="setMeal_form.time_limit"
          style="margin-left: 10px"
          :true-label="4"
          :false-label="5"
        >
          无时间限制
        </el-checkbox>
      </el-form-item>
      <el-form-item label="选择产品：">
        <div class="clearfix">
          <span class="float_left" style="color: #999">
            最多可选择5件产品，并支持设置是否在其详情页展示
          </span>
          <el-button
            size="small"
            class="float_right"
            @click="goods_show = true"
          >
            选择产品
          </el-button>
        </div>
        <el-table
          :data="setMeal_form.goodsList"
          style="width: 100%; margin-top: 10px"
          border
        >
          <el-table-column prop="title" label="产品名称" min-width="180">
            <template slot-scope="scope">
              <div class="goods-title">
                {{ scope.row.title }}
              </div>
              <div class="goods-no">
                {{ scope.row.code }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="详情页展示" min-width="100">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.flag_istrue"></el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="操作" min-width="100">
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="editGoods(scope.row, scope.$index)"
              >
                编辑
              </el-button>
              <el-button type="text" @click="delSetMeal(scope.$index)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="套餐价：">
        <el-input
          v-model="setMeal_form.setMeal_price"
          placeholder="请输入套餐价"
        ></el-input>
      </el-form-item>
      <el-form-item label="原套餐价：">
        <el-input
          v-model="setMeal_form.start_setMeal_price"
          placeholder="请输入原套餐价"
        ></el-input>
        <p class="tip">减去套餐价得到套餐，"可省套餐"</p>
      </el-form-item>
      <el-form-item label="套餐库存：">
        <el-input
          v-model="setMeal_form.setMeal_stock"
          placeholder="请输入套餐库存"
        ></el-input>
        <p class="tip">当套餐库存为0时，即使套餐产品均有库存，也无法购买套餐</p>
      </el-form-item>
      <el-form-item label="每人限购：">
        <el-checkbox
          v-model="setMeal_form.purchase_limit"
          :true-label="5"
          :false-label="4"
        >
          开启限购
        </el-checkbox>
        <el-input
          v-model="setMeal_form.purchase_num"
          placeholder=""
          style="margin-left: 10px"
          :disabled="setMeal_form.purchase_limit === 4"
        ></el-input>
      </el-form-item>
      <el-form-item label="运费设置：">
        <el-radio-group v-model="setMeal_form.freight">
          <el-radio :label="4">默认</el-radio>
          <el-radio :label="5">包邮</el-radio>
        </el-radio-group>
        <p class="tip">无论采用何种配送方式，套餐购买将不收取配送费用</p>
      </el-form-item>
    </el-form>
    <el-dialog
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      title="编辑套餐产品"
      :visible.sync="goods_istrue"
      width="46%"
    >
      <span>
        <el-table
          :data="setMeal_goods"
          style="width: 100%"
          border
          :span-method="objectSpanMethod"
        >
          <el-table-column prop="title" label="产品" min-width="140">
            <template slot-scope="scope">
              <div class="goods-title">
                {{ scope.row.title }}
              </div>
              <div class="goods-no">
                {{ scope.row.code }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="unitName" label="规格" min-width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.unitName }},</span>
              <span>{{ scope.row.specValueName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="salePrice"
            label="商城价"
            min-width="100"
          ></el-table-column>
          <el-table-column prop="address" label="参与活动" min-width="100">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.activity_istrue"></el-switch>
            </template>
          </el-table-column>
        </el-table>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="goods_istrue = false">取 消</el-button>
        <el-button type="primary" @click="addSet">确 定</el-button>
      </span>
    </el-dialog>
    <SaleGoodsList
      v-if="goods_show"
      :is-show="goods_show"
      @cancel="goods_show = false"
      @confirm="selGoods"
    ></SaleGoodsList>
  </ContainerTit>
</template>

<script>
  import SaleGoodsList from "@/component/goods/SaleGoodsList";
  import {
    addComBinPackage,
    getComBinPackage,
    editComBinPackage,
  } from "@/api/Market";
  import { getGoodsInfo } from "@/api/goods";
  export default {
    name: "AddSetMeal",
    components: {
      SaleGoodsList,
    },
    data() {
      return {
        setMeal_form: {
          activity_name: "",
          start_time: "",
          end_time: "",
          time_limit: 4,
          goodsList: [],
          setMeal_price: "",
          start_setMeal_price: "",
          setMeal_stock: "",
          freight: 4,
          purchase_limit: 5,
          purchase_num: 1,
        },
        activity_time: [],
        select_page: "商品详情页",
        goods_istrue: false,
        setMeal_goods: [],
        activity_istrue: false,
        goods_show: false,
        flag_istrue: true,
        spanArr: [],
        goodsList: [],
        goods_index: 0,
        shopName: "",
        shopId: 0,
        setMeal_id: "",
      };
    },
    created() {
      this.setMeal_id = this.$route.params.id;
      if (this.setMeal_id) {
        this.getComBinPackage();
      }
    },
    methods: {
      delSetMeal(index) {
        this.setMeal_form.goodsList.splice(index, 1);
      },
      TimeChange(val) {
        if (val && val.length) {
          this.setMeal_form.start_time = val[0] / 1000;
          this.setMeal_form.end_time = val[1] / 1000 + 86399;
        } else {
          this.setMeal_form.start_time = "";
          this.setMeal_form.end_time = "";
        }
      },
      editGoods(val, index) {
        this.goods_istrue = true;
        this.showSpec(val, index);
      },
      // 选择商品
      selGoods(val) {
        this.shopId = val[0].shopId;
        this.shopName = val[0].shopName;
        const goodsArr = val.map((item) => {
          return {
            ...item,
            flag_istrue: true,
            goodsId: item.id,
          };
        });
        this.setMeal_form.goodsList = this.$_common.unique(
          this.setMeal_form.goodsList.concat(goodsArr),
          ["goodsId"]
        );
      },
      objectSpanMethod({ row, column, rowIndex, columnIndex }) {
        if (["产品"].includes(column.label)) {
          const _row = this.spanArr[rowIndex];
          const _col = _row > 0 ? 1 : 0;
          return {
            rowspan: _row,
            colspan: _col,
          };
        }
      },
      // 编辑商品
      async showSpec(val, index) {
        let target = this.$_common.deepClone(this.setMeal_goods);
        const { data } = await getGoodsInfo(val.id || val.goodsId);

        if (data.specType === 2) {
          target = data.specMultiple.map((item) => {
            const specValueName = item.specGroup
              .map((itemS) => {
                return itemS.specValueName;
              })
              .join("_");
            // 判断该规格是否参与活动
            let activityIstrue = true;
            if (val.joinSku) {
              activityIstrue = val.joinSku.includes(item.id);
            }

            return {
              ...item,
              specValueName: specValueName,
              activity_istrue: activityIstrue,
              images: val.images,
              title: val.title,
              code: val.code,
              goodsId: val.id,
              materielId: val.basicGoodsId,
            };
          });
        } else if (data.specType === 1) {
          target = data.specMultiple.map((item) => {
            // 判断该规格是否参与活动
            let activityIstrue = true;
            if (val.joinSku) {
              activityIstrue = val.joinSku.includes(item.id);
            }
            return {
              ...item,
              specValueName: "无",
              activity_istrue: activityIstrue,
              images: val.images,
              title: val.title,
              code: val.code,
              goodsId: val.id,
              materielId: val.basicGoodsId,
            };
          });
        }
        this.setMeal_goods = target;
        const getSpanArr = this.$_common.getSpanArr(
          this.setMeal_goods,
          "goodsId"
        );
        this.spanArr = getSpanArr.spanArr;
        // let joinSku = this.setMeal_goods.map((itemJ) => {
        //   return itemJ.id;
        // });
        // this.setMeal_form.goodsList[index].joinSku = joinSku;
        this.goods_index = index;
      },
      // 编辑确定
      addSet() {
        this.goods_istrue = false;
        let joinSkuList = this.setMeal_goods.filter(
          (itemS) => itemS.activity_istrue
        );
        let joinSku = joinSkuList.map((itemJ) => {
          return itemJ.id;
        });
        this.setMeal_form.goodsList[this.goods_index].joinSku = joinSku;
        console.log(this.setMeal_form.goodsList);
      },
      // 提交保存
      async addSetFn() {
        let goodsData = [];
        goodsData = this.setMeal_form.goodsList.map((item) => {
          return {
            title: item.title,
            goodsId: item.goodsId,
            materielId: item.basicGoodsId,
            shopId: item.shopId,
            comNum: 1,
            isShow: item.flag_istrue,
            joinSku: item.joinSku,
            flag_istrue: item.flag_istrue,
          };
        });
        let params = {
          title: this.setMeal_form.activity_name,
          isExpire: this.setMeal_form.time_limit,
          startTime: this.setMeal_form.start_time,
          endTime: this.setMeal_form.end_time,
          shopId: this.shopId,
          shopName: this.shopName,
          price: this.setMeal_form.setMeal_price,
          originPrice: this.setMeal_form.start_setMeal_price,
          inventory: this.setMeal_form.setMeal_stock,
          isLimit: this.setMeal_form.purchase_limit,
          limitNum: this.setMeal_form.purchase_num,
          expressType: this.setMeal_form.freight,
          enableStatus: 5,
          materielNum: goodsData.length,
          goodsData: goodsData,
        };
        if (goodsData.length <= 1) {
          this.$message.warning("请至少选择两个产品");
          return;
        }
        if (this.setMeal_form.setMeal_price <= 0) {
          this.$message.warning("套餐价不能为0");
          return;
        }
        if (this.setMeal_form.start_setMeal_price <= 0) {
          this.$message.warning("原套餐价不能为0");
          return;
        }
        if (this.setMeal_form.setMeal_stock <= 0) {
          this.$message.warning("库存不能为0");
          return;
        }
        if (
          this.setMeal_form.purchase_limit === 5 &&
          this.setMeal_form.purchase_num <= 0
        ) {
          this.$message.warning("限购次数不能为0");
          return;
        }
        if (this.setMeal_id) {
          const data = await editComBinPackage(this.setMeal_id, params);
        } else {
          const data = await addComBinPackage(params);
        }
        this.$message.success("保存成功");
        this.$closeCurrentGoEdit("/Marketing/SetMeal/index");
      },
      // 详情
      async getComBinPackage() {
        const { data } = await getComBinPackage(this.setMeal_id);
        this.setMeal_form = {
          activity_name: data.title,
          start_time: data.startTime,
          end_time: data.endTime,
          time_limit: data.isExpire,
          goodsList: data.goodsData,
          setMeal_price: data.price,
          start_setMeal_price: data.originPrice,
          setMeal_stock: data.inventory,
          freight: data.expressType,
          purchase_limit: data.isLimit,
          purchase_num: data.limitNum,
        };
        if (this.setMeal_form.time_limit === 5) {
          this.activity_time = [data.startTime * 1000, data.endTime * 1000];
        }
        this.shopId = data.shopId;
        this.shopName = data.shopName;
      },
    },
  };
</script>

<style scoped>
  .el-input {
    width: 30%;
  }
  .tip {
    color: #999999;
    font-size: 12px;
  }
  .goods-name-view {
    width: calc(100% - 76px);
  }
  .goods-title {
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
  }
</style>
