<template>
  <ContainerTit>
    <div slot="headr">
      <el-button :disabled="!!$route.params.id" @click="delPauseSave(1)">
        清除暂存
      </el-button>
      <el-button
        :loading="loading"
        :disabled="!!$route.params.id"
        @click="addPauseSave"
      >
        暂存
      </el-button>
      <el-button type="primary" :loading="loading" @click="subData">
        提交保存
      </el-button>
    </div>
    <el-form
      ref="add_form"
      :model="add_form"
      :rules="add_rules"
      label-width="100px"
    >
      <div class="detail-tab-item">
        <div class="detail-tab-title">活动信息</div>
        <div class="detail-tab-main">
          <el-form-item label="活动类型" prop="activityType">
            <el-select
              v-model="add_form.activityType"
              clearable
              style="width: 350px"
              placeholder="活动类型"
            >
              <el-option
                v-for="(item, index) in status_list"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="活动标题" prop="title">
            <el-input
              v-model="add_form.title"
              placeholder="请填写活动标题"
              class="width200"
            ></el-input>
          </el-form-item>
          <el-form-item prop="endTime" label="活动时间">
            <el-date-picker
              v-model="time"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="timeChange"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="活动图片" prop="images">
            <UploadQiniu :file-list="img_list" @uploadSuccess="uploadSuccess" />
          </el-form-item>
          <el-form-item label="上下架" prop="enableStatus">
            <el-radio-group v-model="add_form.enableStatus">
              <el-radio :label="5">上架</el-radio>
              <el-radio :label="4">下架</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否互斥：" prop="isMutex">
            <el-switch
              v-model="add_form.isMutex"
              :active-value="5"
              :inactive-value="4"
              active-text="是"
              inactive-text="否"
            ></el-switch>
            <el-tooltip
              effect="dark"
              content="启用互斥，则活动不能与优惠券同时使用，否则反之"
              placement="bottom"
            >
              <i class="el-icon-warning"></i>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="使用范围" prop="useShop">
            <SelectShop
              v-model="add_form.useShop"
              :multiple="true"
              :enable="true"
              @getAllShop="getAllShop"
            />
            <el-button
              size="mini"
              type="text"
              @click="$router.push('/SystemSettings/liansuoguanli/AddShop')"
            >
              【新建商铺】
            </el-button>
          </el-form-item>
          <el-form-item label="内部沟通" prop="remark">
            <el-input v-model="add_form.remark" class="width200"></el-input>
          </el-form-item>
          <el-form-item label="活动描述" prop="describe">
            <el-input
              v-model="add_form.describe"
              type="textarea"
              class="width200"
            ></el-input>
          </el-form-item>
        </div>
      </div>
      <div class="detail-tab-item">
        <div class="detail-tab-title">活动规则</div>
        <div class="detail-tab-main">
          <el-form-item label="促销商品" prop="activityGoods">
            <el-table :data="add_form.activityGoods">
              <el-table-column
                align="center"
                type="index"
                width="60"
              ></el-table-column>
              <el-table-column
                align="center"
                prop="title"
                label="商品名称"
                min-width="180"
              >
                <template slot-scope="scope">
                  <ConditionSelGoods
                    v-if="add_form.useShop.length"
                    v-model="scope.row.title"
                    :is-eq-master="false"
                    :enable-status="5"
                    :spec-check="spec_check"
                    :shop-id="add_form.useShop"
                    @goodsVisibleChange="
                      goodsVisibleChange($event, scope.$index)
                    "
                    @specSelConfirm="specSelConfirm"
                    @selGoods="selGoods"
                  />
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="goodsCode"
                label="商品编码"
                width="140"
              ></el-table-column>
              <el-table-column
                align="center"
                prop="price"
                label="促销价格"
                min-width="120"
              >
                <template slot-scope="scope">
                  <el-input-number
                    v-model="scope.row.price"
                    :controls="false"
                    size="small"
                    style="width: 100%"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="salePrice"
                label="价格"
                min-width="120"
              >
                <template slot-scope="scope">
                  ￥{{ $_common.formatNub(scope.row.salePrice, 2) || 0 }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="unitName"
                label="单位"
                min-width="80"
              ></el-table-column>
              <el-table-column
                align="center"
                prop="skuName"
                label="属性"
                min-width="120"
              ></el-table-column>
              <el-table-column align="center" label="活动数量" min-width="120">
                <template slot-scope="scope">
                  <div v-if="!activityId">
                    <el-input-number
                      v-if="
                        scope.row.inventory > 0 &&
                        scope.row.isDistribution === 4
                      "
                      v-model="scope.row.activityNum"
                      :controls="false"
                      size="small"
                      style="width: 100%"
                      :max="scope.row.inventory"
                    ></el-input-number>
                    <el-input-number
                      v-else-if="scope.row.isDistribution === 5"
                      v-model="scope.row.activityNum"
                      :controls="false"
                      size="small"
                      style="width: 100%"
                    ></el-input-number>
                    <span v-else>库存不足</span>
                  </div>
                  <div v-else>
                    <el-input-number
                      v-if="!!scope.row.inventory"
                      v-model="scope.row.activityNum"
                      :controls="false"
                      size="small"
                      style="width: 100%"
                      :max="scope.row.inventory"
                    ></el-input-number>
                    <el-input-number
                      v-else
                      v-model="scope.row.activityNum"
                      :controls="false"
                      size="small"
                      style="width: 100%"
                    ></el-input-number>
                  </div>
                </template>
              </el-table-column>
              <el-table-column align="center" label="限购数量" min-width="120">
                <template slot-scope="scope">
                  <el-input-number
                    v-model="scope.row.limitNum"
                    :controls="false"
                    :precision="0"
                    size="small"
                    style="width: 100%"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="mini"
                    @click="deleteRowGoods(scope.$index, scope.row)"
                  >
                    删除
                  </el-button>
                  <el-button type="text" size="mini" @click="addListGoods">
                    新增
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="客户类型" prop="customerSourceId">
            <el-radio-group v-model="add_form.customerRange">
              <el-radio :label="5">全部</el-radio>
              <el-radio :label="4">部分</el-radio>
            </el-radio-group>
            <div>
              <el-checkbox
                v-model="checkAll"
                :disabled="add_form.customerRange === 5"
                :indeterminate="isIndeterminate"
                @change="CheckAllChange"
              >
                全选
              </el-checkbox>
              <div style="border-top: 1px solid #eee"></div>
              <el-checkbox-group
                v-model="add_form.customerSourceId"
                :disabled="add_form.customerRange === 5"
                @change="customerTypeChange"
              >
                <el-checkbox
                  v-for="(item, index) in customerType"
                  :key="index"
                  :label="item.id"
                >
                  {{ item.name }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </el-form-item>
        </div>
      </div>
    </el-form>
  </ContainerTit>
</template>

<script>
  import UploadQiniu from "@/component/common/UploadQiniu.vue";
  import ConditionSelGoods from "@/component/common/ConditionSelGoods";
  import SelectShop from "@/component/goods/SelectShop.vue";
  import { addPauseSave, delPauseSave, getPauseSave } from "@/api/common";
  import { getCustomerSourceList } from "@/api/System";
  import { editActivity, addActivity, getInfoActivity } from "@/api/Market";
  export default {
    name: "AddPromotion",
    components: {
      SelectShop,
      UploadQiniu,
      ConditionSelGoods,
    },

    data() {
      const customerRangeVail = (rule, value, callback) => {
        if (!this.add_form.customerRange) {
          callback(new Error("请选择客户类型"));
        } else if (
          this.add_form.customerRange === 4 &&
          !this.add_form.customerSourceId.length
        ) {
          callback(new Error("请选择客户类型"));
        } else {
          callback();
        }
      };
      return {
        show_goods: false,
        spec_check: [],
        goods_index: 0,
        loading: false,
        del_goods_id: [],
        activityId: 0,
        activeName: "first",
        show_shop: false,
        goods_show: false,
        userCenterId: "",
        add_rules: {
          activityType: [{ required: true, message: "活动类型不能为空" }],
          title: [{ required: true, message: "活动标题不能为空" }],
          images: [{ required: true, message: "活动图片不能为空" }],
          enableStatus: [{ required: true, message: "请选择是否上架" }],
          // remark: [{ required: true, message: '内部沟通不能为空' }],
          // sort: [{ required: true, message: '排序值不能为空' }],
          // describe: [{ required: true, message: '活动描述不能为空' }],
          customerSourceId: [
            { required: true, validator: customerRangeVail, trigger: "change" },
          ],
          activityGoods: [
            {
              required: true,
              type: "array",
              message: "请选择促销商品",
              trigger: "change",
            },
          ],
          useShop: [
            {
              required: true,
              type: "array",
              message: "请选择使用范围",
              trigger: "change",
            },
          ],
          endTime: [
            { required: true, message: "请选择活动时间", trigger: "change" },
          ],
        },
        customerType: [],
        checkAll: false,
        checkedcustomer_type: [],
        isIndeterminate: false,
        time: "",
        add_form: {
          activityType: 20,
          title: "",
          startTime: "",
          endTime: "",
          images: [],
          enableStatus: 5,
          useShop: [],
          customerRange: 5,
          customerSourceId: [],
          describe: "",
          remark: "",
          activityGoods: [
            {
              goodsId: "",
              skuId: "",
              skuName: "",
              unitName: "",
              title: "",
              goodsCode: "",
              categoryName: "",
              basicGoodsId: "",
              shopId: "",
              salePrice: "",
              price: "",
              activityNum: "",
              limitNum: "",
            },
          ],
          isMutex: 4,
        },
        img_list: [],
        status_list: [
          // {
          //   label: '商品特价',
          //   value: 10
          // },
          {
            label: "商品秒杀",
            value: 20,
          },
        ],
        user_center_id: 0,
        pageName: "",
      };
    },
    created() {
      this.pageName = this.$route.name;
      if (this.$route.params.id) {
        this.activityId = this.$route.params.id;
        this.getInfoActivity();
      } else {
        this.getPauseSave();
      }
      this.getAllCustomerSource();
    },
    methods: {
      getAllShop(list) {
        if (!this.activityId) {
          this.add_form.useShop = list.map((item) => {
            return item.id;
          });
        }
      },
      selGoods(list) {
        console.log(list);
        let target = this.$_common.deepClone(this.add_form.activityGoods);
        const goodsD = list.map((item) => {
          let specGropName = item.specGroup
            .map((itemS) => {
              return itemS.specValueName;
            })
            .join("_");
          return {
            inventory: item.inventory - 0,
            goodsId: item.id,
            skuId: item.skuId,
            skuName: specGropName,
            unitName: item.unitName,
            title: item.title,
            goodsCode: item.code,
            categoryName: item.categoryName,
            basicGoodsId: item.basicGoodsId,
            shopId: item.shopId,
            salePrice: item.salePrice,
            price: "",
            activityNum: "",
            limitNum: "",
            isDistribution: item.isDistribution,
          };
        });
        goodsD.forEach((item) => {
          const targetD = target.find((itemG) => itemG.skuId === item.skuId);
          if (!targetD) {
            target.push(item);
          }
        });
        this.add_form.activityGoods = target;
        console.log(this.add_form.activityGoods);
      },
      addListGoods() {
        this.add_form.activityGoods.push({
          goodsId: "",
          skuId: "",
          skuName: "",
          unitName: "",
          title: "",
          goodsCode: "",
          categoryName: "",
          basicGoodsId: "",
          shopId: "",
          salePrice: "",
          price: "",
          activityNum: "",
          limitNum: "",
        });
      },
      specSelConfirm(params) {
        let target = this.$_common.deepClone(this.add_form.activityGoods);
        const goodsD = params.goodsD.map((item) => {
          return {
            inventory: params.now_goods_data.inventorTotal - 0,
            goodsId: params.now_goods_data.id,
            skuId: item.skuId,
            skuName: item.spec.specGropName,
            unitName: item.spec.unitName,
            title: params.now_goods_data.title,
            goodsCode: params.now_goods_data.code,
            categoryName: params.now_goods_data.categoryName,
            basicGoodsId: params.now_goods_data.basicGoodsId,
            shopId: params.now_goods_data.shopId,
            salePrice: item.spec.salePrice,
            price: "",
            activityNum: "",
            limitNum: "",
          };
        });
        if (!target[this.goods_index].skuId) {
          target.splice(this.goods_index, 1);
        }

        goodsD.forEach((item) => {
          const targetD = target.find((itemG) => itemG.skuId === item.skuId);
          if (!targetD) {
            target.push(item);
          }
        });

        this.add_form.activityGoods = target;
      },
      goodsVisibleChange(visible, index) {
        if (visible) {
          this.goods_index = index;
        }
      },
      // 暂存
      async addPauseSave() {
        const useShop =
          this.add_form.useShop.length > 0
            ? this.add_form.useShop.join(",")
            : 0;
        const customerSourceId =
          this.add_form.customerSourceId.length > 0
            ? this.add_form.customerSourceId.join(",")
            : 0;
        const obj = {
          activityType: this.add_form.activityType,
          title: this.add_form.title,
          startTime: this.add_form.startTime,
          endTime: this.add_form.endTime,
          images: this.add_form.images,
          enableStatus: this.add_form.enableStatus,
          useShop: useShop,
          customerRange: this.add_form.customerRange,
          describe: this.add_form.describe,
          remark: this.add_form.remark,
          customerSourceId: customerSourceId,
          activityGoods: this.add_form.activityGoods,
          isMutex: this.add_form.isMutex,
        };

        this.loading = true;
        const data = await addPauseSave({
          key: this.pageName,
          data: obj,
        });
        this.loading = false;

        this.$message({
          type: "success",
          message: "暂存成功",
        });
        this.$closeCurrentGoEdit("/Marketing/Promotion/PromotionList");
      },
      // 清除暂存
      async delPauseSave(type) {
        const data = delPauseSave({
          key: this.pageName,
        });

        if (type) {
          this.$message({
            type: "success",
            message: "清除暂存成功",
          });
          this.$closeCurrentGoEdit("/Marketing/Promotion/AddPromotion");
        }
      },
      // 获取暂存信息
      async getPauseSave() {
        const { data } = await getPauseSave({
          key: this.pageName,
        });

        if (JSON.stringify(data) === "{}") return;
        this.add_form = data;
        this.img_list = data.images.map((item) => {
          return {
            name: "",
            url: item,
          };
        });
        if (this.time) {
          this.time = [data.startTime * 1000, data.endTime * 1000];
        } else {
          this.time = [];
        }

        this.add_form.useShop = data.useShop
          ? data.useShop.split(",").map((item) => {
              return parseInt(item);
            })
          : [];

        this.add_form.customerSourceId = data.customerSourceId
          ? data.customerSourceId.split(",").map((item) => {
              return parseInt(item);
            })
          : [];

        this.add_form.activityGoods = data.activityGoods.map((item) => {
          return {
            id: item.id,
            title: item.title,
            shopId: item.shopId,
            goodsCode: item.goodsCode,
            goodsId: item.goodsId,
            skuId: item.skuId,
            unitName: item.unitName,
            basicGoodsId: item.basicGoodsId,
            salePrice: item.salePrice,
            price: item.price,
            activityNum: item.activityNum,
            limitNum: item.limitNum,
          };
        });
      },
      // 获取详情
      async getInfoActivity() {
        const { data } = await getInfoActivity(this.activityId);

        this.add_form = data;
        this.img_list = data.images.map((item) => {
          return {
            name: "",
            url: item,
          };
        });
        this.time = [data.startTime * 1000, data.endTime * 1000];
        this.add_form.useShop = data.useShop
          ? data.useShop.split(",").map((item) => {
              return parseInt(item);
            })
          : [];

        this.add_form.customerSourceId = data.customerSourceId
          ? data.customerSourceId.split(",").map((item) => {
              return parseInt(item);
            })
          : [];

        this.add_form.activityGoods = data.activityGoods.map((item) => {
          let specGropName = item.specGroup
            .map((itemS) => {
              return itemS.specValueName;
            })
            .join("_");
          return {
            id: item.id,
            title: item.goodsName,
            shopId: item.shopId,
            goodsCode: item.goodsCode,
            goodsId: item.goodsId,
            skuId: item.skuId,
            unitName: item.unitName,
            basicGoodsId: item.basicGoodsId,
            salePrice: item.salePrice,
            price: item.price,
            activityNum: item.activityNum,
            limitNum: item.limitNum,
            inventory: item.inventory - 0,
            skuName: specGropName,
          };
        });
      },
      //  删除选择的商品
      deleteRowGoods(index, row) {
        if (this.add_form.activityGoods.length === 1) {
          this.$message.warning("至少保留一条商品");
          return;
        }
        if (row.id) {
          this.del_goods_id.push(row.id);
        }
        this.add_form.activityGoods.splice(index, 1);
      },
      CheckAllChange(val) {
        this.add_form.customerSourceId = val
          ? this.customerType.map((item) => item.id)
          : [];
        this.isIndeterminate = false;
      },
      customerTypeChange(value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.customerType.length;
        this.isIndeterminate =
          checkedCount > 0 && checkedCount < this.customerType.length;
      },
      //  时间
      timeChange(val) {
        this.add_form.startTime = val[0] / 1000;
        this.add_form.endTime = this.$NP.plus(val[1] / 1000, 86399);
      },
      //  活动图片
      uploadSuccess(val, res, file, fileList) {
        this.add_form.images = fileList.map((item) => {
          return item.content;
        });
        this.img_list = fileList;
      },
      //  选择的客户类型
      // 客户类型
      async getAllCustomerSource() {
        const data = await getCustomerSourceList();
        this.customerType = data.data;
      },
      LocationFrom(val) {
        if (val && val.length) {
          this.add_form.start = val[0] / 1000;
          this.add_form.IssueStart = val[0] / 1000;
          this.add_form.end = this.$NP.plus(val[1] / 1000, 86399);
          this.add_form.IssueEnd = this.$NP.plus(val[1] / 1000, 86399);
        } else {
          this.add_form.start = "";
          this.add_form.IssueStart = "";
          this.add_form.end = "";
          this.add_form.IssueEnd = "";
        }
      },
      //    提交保存
      async subData() {
        this.$refs.add_form.validate(async (valid) => {
          if (valid) {
            const goodsList = this.$_common
              .deepClone(this.add_form.activityGoods)
              .filter((item) => item.goodsId);
            if (!goodsList.length) {
              this.$message.warning("请选择促销商品");
              return;
            }
            const useShop =
              this.add_form.useShop.length > 0
                ? this.add_form.useShop.join(",")
                : 0;
            const customerSourceId =
              this.add_form.customerSourceId.length > 0
                ? this.add_form.customerSourceId.join(",")
                : 0;
            const isTruePrice = goodsList.every((item) => {
              return item.price > 0;
            });
            if (!isTruePrice) {
              this.$message.warning("请您输入正确的促销价格");
              return;
            }
            const isTrueNum = goodsList.every((item) => {
              return item.activityNum > 0;
            });

            if (!isTrueNum) {
              this.$message.warning("活动数量不能为0");
              return;
            }
            const isTrueLimitNum = goodsList.every((item) => {
              return item.limitNum > 0;
            });

            if (!isTrueLimitNum) {
              this.$message.warning("限购数量不能为0");
              return;
            }
            const obj = {
              activityType: this.add_form.activityType,
              title: this.add_form.title,
              startTime: this.add_form.startTime,
              endTime: this.add_form.endTime,
              images: this.add_form.images,
              enableStatus: this.add_form.enableStatus,
              useShop: useShop,
              customerRange: this.add_form.customerRange,
              describe: this.add_form.describe,
              remark: this.add_form.remark,
              isMutex: this.add_form.isMutex,
              customerSourceId: customerSourceId,
              activityGoods: goodsList.map((item) => {
                delete item.unitName;
                delete item.inventory;
                delete item.skuName;
                return item;
              }),
            };

            this.loading = true;
            try {
              let target = {};
              if (this.add_form.activityGoods.length > 0) {
                if (this.activityId) {
                  obj.deleteArray = this.del_goods_id;
                  target = await editActivity(this.activityId, obj);
                } else {
                  target = await addActivity(obj);
                }
              }
              const data = target;
              this.loading = false;
              this.$message({
                type: "success",
                message: "提交成功",
              });
              await this.delPauseSave();
              this.$closeCurrentGoEdit("/Marketing/Promotion/PromotionList");
            } catch {
              this.loading = false;
            }
          }
        });
      },
    },
  };
</script>
<style scoped>
  .width200 {
    width: 350px;
  }
  .creat-shop {
    color: #1890ff;
    font-size: 12px;
  }
</style>
