<template>
  <ContainerTit>
    <div slot="headr">
      <el-button v-if="!marketId" @click="delPauseSave(1)">清除暂存</el-button>
      <el-button v-if="!marketId" :loading="loading" @click="addPauseSave">
        暂存
      </el-button>
      <el-button type="primary" :loading="loading" @click="subData">
        提交保存
      </el-button>
    </div>
    <el-form
      ref="add_form"
      :rules="add_rules"
      size="small"
      :model="add_form"
      label-width="120px"
    >
      <div class="detail-tab-item">
        <div class="detail-tab-title">
          <span>基础信息</span>
        </div>
        <div class="detail-tab-main">
          <el-form-item label="优惠券名称：" prop="name">
            <el-input
              v-model="add_form.name"
              style="width: 350px"
              placeholder="请输入十个字以内优惠券的名称"
              maxlength="10"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="有效时间："
            prop="endTime"
            :required="add_form.couponType !== 20 && add_form.grantType !== 10"
          >
            <el-date-picker
              v-model="time"
              style="width: 350px"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="timestamp"
              @change="LocationFrom"
            ></el-date-picker>
            <div v-if="add_form.couponType === 20 && add_form.grantType === 10">
              <p
                class="el-icon-warning"
                style="font-size: 12px; color: #e6a23c"
              >
                提示：用户可每个月领取一张会员卡优惠券，自会员领取后30日内有效
              </p>
            </div>
            <div v-if="add_form.couponType === 20 && add_form.grantType === 50">
              <p
                class="el-icon-warning"
                style="font-size: 12px; color: #e6a23c"
              >
                提示：用户开通会员卡后自动发放此优惠券，自发放后30日内有效！
              </p>
            </div>
          </el-form-item>
          <el-form-item label="优惠券面值：" prop="reducePrice">
            <el-input-number
              v-model="add_form.reducePrice"
              :controls="false"
              style="width: 350px"
              placeholder=""
            ></el-input-number>
          </el-form-item>
          <el-form-item label="优惠券类型：" prop="couponType">
            <el-radio-group v-model="add_form.couponType">
              <el-radio
                v-for="item in couponList"
                :key="item.id"
                :label="item.id"
              >
                {{ item.title }}
              </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="userTypeId">
            <el-radio-group v-model="add_form.userTypeId">
              <el-radio
                v-for="item in userType"
                :key="item.userTypeId"
                :label="item.userTypeId"
              >
                {{ item.title }}
              </el-radio>
            </el-radio-group>
            <el-input-number
              v-model="add_form.minPrice"
              :controls="false"
              style="width: 100px; margin-left: 10px"
              placeholder=""
            ></el-input-number>
            <i style="margin-left: 10px">元可用</i>
          </el-form-item>
          <el-form-item label="使用说明：">
            <el-input
              v-model="add_form.remark"
              style="width: 350px"
              type="textarea"
              :rows="2"
              placeholder="暂无说明"
            ></el-input>
          </el-form-item>
        </div>
      </div>
      <div class="detail-tab-item">
        <div class="detail-tab-title">
          <span>发放配置</span>
        </div>
        <div class="detail-tab-main">
          <el-form-item label="发放方式：" prop="grantType">
            <el-radio-group
              v-if="add_form.couponType !== 20"
              v-model="add_form.grantType"
            >
              <el-radio
                v-for="item in distributionMethodList"
                :key="item.distributionMethod"
                :label="item.distributionMethod"
              >
                {{ item.title }}
              </el-radio>
            </el-radio-group>
            <el-radio-group v-else v-model="add_form.grantType">
              <el-radio
                v-for="item in vipList"
                :key="item.distributionMethod"
                :label="item.distributionMethod"
              >
                {{ item.title }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="add_form.couponType !== 20"
            label="总共发放："
            prop="totalNum"
          >
            <el-input-number
              v-model="add_form.totalNum"
              :controls="false"
              style="width: 200px"
              placeholder=""
            ></el-input-number>
            <i style="margin-left: 10px">张</i>
          </el-form-item>
          <el-form-item label="每人领取：" prop="allowNum">
            <el-input-number
              v-model="add_form.allowNum"
              :controls="false"
              style="width: 200px"
            ></el-input-number>
            <i style="margin-left: 10px">张</i>
          </el-form-item>
          <el-form-item
            v-if="add_form.grantType === 40"
            label="满减赠送："
            prop="mustCondition"
          >
            下单满
            <el-input-number
              v-model="add_form.mustCondition"
              :controls="false"
              style="width: 100px; margin: 0 10px"
            ></el-input-number>
            <i>元送</i>
            <div>
              <p
                class="el-icon-warning"
                style="font-size: 12px; color: #e6a23c"
              >
                提示：订单状态已付款时赠送(仅限在线支付)
              </p>
            </div>
          </el-form-item>
          <el-form-item
            v-if="
              parseInt(add_form.grantType) !== 20 &&
              parseInt(add_form.couponType) !== 20
            "
            label="领取范围："
            prop="customerSourceId"
          >
            <el-radio-group v-model="customerRange">
              <el-radio :label="5">全部</el-radio>
              <el-radio :label="4">部分</el-radio>
            </el-radio-group>
            <div>
              <el-checkbox
                v-model="checkAll"
                :disabled="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="customerRange === 5"
                @change="customerTypeChange"
              >
                <el-checkbox
                  v-for="(item, index) in customerType"
                  :key="index"
                  :label="item.id"
                >
                  {{ item.name }}
                </el-checkbox>
              </el-checkbox-group>
              <!-- <el-select
            clearable
            multiple
            v-model="add_form.customerSourceId"
            placeholder="客户类型"
          >
            <el-option
              v-for="(item,index) in customerType"
              :key="index"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>-->
              <el-button type="text" size="mini" @click="getAllCustomerSource">
                【刷新】
              </el-button>
              <el-button type="text" size="mini" @click="show_model = true">
                【新建类型】
              </el-button>
            </div>
          </el-form-item>
          <el-form-item
            v-if="add_form.grantType === 20"
            label="选择客户："
            prop="customerIds"
          >
            <el-button type="primary" @click="customer_show = true">
              选择客户
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="$router.push('/Customer/CustomerAdmin/AddCustomer')"
            >
              【新建客户】
            </el-button>
            <div style="display: inline-block">
              <el-tag
                v-for="(item, index) in chooseCustomer"
                :key="index"
                closable
                @close="closeTag('customer', index)"
              >
                {{ item.name }}
              </el-tag>
            </div>
          </el-form-item>
          <el-form-item label="使用范围：" prop="useShop">
            <el-button type="primary" @click="show_shop = true">
              选择商铺
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="$router.push('/SystemSettings/liansuoguanli/AddShop')"
            >
              【新建商铺】
            </el-button>
            <div style="display: inline-block">
              <el-tag
                v-for="(item, index) in useShopNameArr"
                :key="index"
                closable
                @close="closeTag('usershop', index)"
              >
                {{ item.name }}
              </el-tag>
            </div>
          </el-form-item>
          <el-form-item
            v-if="add_form.couponType !== 20"
            label="发放时间："
            prop="grantEndTime"
            :required="add_form.couponType !== 20"
          >
            <el-date-picker
              v-model="grantTime"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="timestamp"
              @change="grantTimeChange"
            ></el-date-picker>
          </el-form-item>
        </div>
      </div>
      <div class="detail-tab-item">
        <div class="detail-tab-title">
          <span>商品配置</span>
        </div>
        <div class="detail-tab-main">
          <el-form-item label="商品范围：" prop="applyRange">
            <el-radio-group v-model="add_form.applyRange">
              <el-radio
                v-for="item in productRange"
                :key="item.productRangeId"
                :label="item.productRangeId"
              >
                {{ item.title }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="add_form.applyRange === 40">
            <el-button type="primary" @click="goods_show = true">
              选择商品
            </el-button>
            <el-table border style="margin-top: 10px" :data="goods_list">
              <el-table-column prop="code" label="商品编码"></el-table-column>
              <el-table-column prop="title" label="商品名称"></el-table-column>
              <el-table-column prop="shopName" label="店铺"></el-table-column>
              <el-table-column prop="address" label="操作">
                <template slot-scope="scope">
                  <el-button size="small" @click="delGoods(scope.$index)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item v-if="add_form.applyRange === 20">
            <GoodsCategory
              is-type="tree"
              :checked-keys="add_form.categoryCollect"
              @change="cateChange"
            />
          </el-form-item>
          <el-form-item v-if="add_form.applyRange === 30">
            <el-button type="primary" @click="sel_brand = true">
              选择品牌
            </el-button>
            <div v-if="brandNameArr" style="display: inline-block">
              <el-tag
                v-for="(item, index) in brandNameArr"
                :key="index"
                closable
                @close="closeTag('brand', index)"
              >
                {{ item.title }}
              </el-tag>
            </div>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <GoodsChooseShop
      :dialog-visible="show_shop"
      :is-show-add="true"
      @getAllShop="getAllShop"
      @close="show_shop = false"
      @confirm="selShop"
    ></GoodsChooseShop>
    <!--    选择品牌-->
    <BrandSelModel
      v-if="sel_brand"
      :is-check="true"
      :dialog-visible="sel_brand"
      :is-show-add="true"
      @close="sel_brand = false"
      @confirm="brandConfirm"
    />
    <!--  客户选择-->
    <ClientListModal
      v-if="customer_show"
      :is-show="customer_show"
      :is-check="true"
      :is-show-add="true"
      @cancel="customer_show = false"
      @confirm="customerSel"
    />
    <!--    新建客户类型-->
    <el-dialog
      name="新增客户类型"
      :visible.sync="show_model"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      width="40%"
      :before-close="handleClose"
    >
      <el-form
        ref="add_form"
        :model="add_custorm"
        :rules="rules"
        size="small"
        label-width="100px"
      >
        <el-form-item label="客户类型：" prop="name">
          <el-input
            v-model="add_custorm.name"
            placeholder="请输入客户类型"
          ></el-input>
        </el-form-item>
        <el-form-item label="是否默认：" prop="defaultStatus">
          <el-switch
            v-model="add_custorm.defaultStatus"
            :active-value="5"
            :inactive-value="4"
          ></el-switch>
        </el-form-item>
        <el-form-item label="是否禁用：" prop="enableStatus">
          <el-radio-group v-model="add_custorm.enableStatus">
            <el-radio :label="4">是</el-radio>
            <el-radio :label="5">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="show_model = false">取 消</el-button>
        <el-button type="primary" size="small" @click="addData">
          确 定
        </el-button>
      </span>
    </el-dialog>
    <SaleGoodsList
      v-if="goods_show"
      :shop-id="add_form.useShop"
      :show-sku="false"
      :is-show="goods_show"
      @cancel="goods_show = false"
      @confirm="selGoods"
    />
  </ContainerTit>
</template>

<script>
  import GoodsChooseShop from "../../../component/goods/GoodsChooseShop";
  import GoodsCategory from "@/component/common/GoodsCategory.vue";
  import BrandSelModel from "@/component/goods/BrandSelModel.vue";
  import ClientListModal from "@/component/common/ClientListModal";
  import SaleGoodsList from "@/component/goods/SaleGoodsList";
  import {
    addCustomerSource,
    editCustomerSource,
    getAllCustomerSource,
  } from "@/api/System";
  import { addPauseSave, delPauseSave, getPauseSave } from "@/api/common";
  import { editMarket, addMarket, getInfo } from "@/api/Market";
  export default {
    name: "AddCoupon",
    components: {
      GoodsChooseShop,
      GoodsCategory,
      ClientListModal,
      BrandSelModel,
      SaleGoodsList,
    },
    data() {
      const applyRangeVali = (rule, value, callback) => {
        if (value === 20 && !this.add_form.categoryCollect.length) {
          callback(new Error("请选择指定分类"));
        } else if (value === 30 && !this.add_form.brandCollect.length) {
          callback(new Error("请选择指定品牌"));
        } else if (value === 40 && !this.goods_list.length) {
          callback(new Error("请选择指定商品"));
        } else {
          callback();
        }
      };
      const userTypeIdVali = (rule, value, callback) => {
        if (value === 2 && this.add_form.minPrice <= 0) {
          callback(new Error("请输入正确的门槛金额"));
        } else {
          callback();
        }
      };
      const mustConditionVali = (rule, value, callback) => {
        if (this.add_form.grantType === 40 && value <= 0) {
          callback(new Error("请输入正确的满减金额"));
        } else {
          callback();
        }
      };
      const grantEndTimeVali = (rule, value, callback) => {
        if (this.add_form.couponType !== 20 && !value) {
          callback(new Error("请选择发放时间"));
        } else {
          callback();
        }
      };
      const customerSourceIdVali = (rule, value, callback) => {
        if (
          this.customerRange === 4 &&
          parseInt(this.add_form.grantType) !== 20 &&
          parseInt(this.add_form.couponType) !== 20 &&
          !value.length
        ) {
          callback(new Error("请选择领取范围"));
        } else {
          callback();
        }
      };
      const customerIdsVali = (rule, value, callback) => {
        if (this.add_form.grantType === 20 && !value.length) {
          callback(new Error("请选择选择客户"));
        } else {
          callback();
        }
      };
      const endTimeVali = (rule, value, callback) => {
        if (
          this.add_form.couponType !== 20 &&
          this.add_form.grantType !== 10 &&
          !value
        ) {
          callback(new Error("请选择有效时间"));
        } else {
          callback();
        }
      };
      return {
        goods_list: [], // 商品范围，指定商品
        goods_show: false, // 商品范围，选择指定商品弹窗
        show_model: false, // 客户类型
        // 新增客户类型数据
        add_custorm: {
          name: "",
          defaultStatus: 4,
          enableStatus: 5,
        }, // 新增客户类型的验证
        rules: {
          name: [
            { required: true, message: "请输入客户类型", trigger: "blur" },
          ],
        },
        loading: false,
        categoryCollect: [],
        marketId: "",
        show_shop: false,
        customer_show: false,
        distributionMethodList: [
          { distributionMethod: 10, title: "主动领取" },
          { distributionMethod: 20, title: "定向发放" },
          { distributionMethod: 30, title: "注册领取" },
          { distributionMethod: 40, title: "在线支付领取" },
        ],
        // 当选择会员卡优惠券
        vipList: [
          { distributionMethod: 10, title: "主动领取" },
          { distributionMethod: 50, title: "开卡赠送" },
        ],
        productRange: [
          { productRangeId: 10, title: "全部商品" },
          { productRangeId: 40, title: "指定商品" },
          { productRangeId: 20, title: "指定分类" },
          { productRangeId: 30, title: "指定品牌" },
        ],
        couponList: [
          { id: 10, title: "普通优惠券" },
          { id: 20, title: "会员卡优惠券" },
        ],
        userType: [
          { userTypeId: -1, title: "不限用" },
          { userTypeId: 2, title: "满" },
        ],
        add_rules: {
          name: [
            { required: true, message: "请输入优惠券名称", trigger: "blur" },
          ],
          reducePrice: [
            { required: true, message: "请输入优惠券值", trigger: "blur" },
          ],
          endTime: [{ validator: endTimeVali, trigger: "change" }],
          grantEndTime: [{ validator: grantEndTimeVali, trigger: "change" }],
          userTypeId: [{ validator: userTypeIdVali, trigger: "change" }],
          grantType: [
            { required: true, message: "请选择发放方式", trigger: "change" },
          ],
          totalNum: [
            { required: true, message: "请输入总发放数", trigger: "blur" },
          ],
          userDetail: [
            { required: true, message: "请输入每人发放数", trigger: "blur" },
          ],
          useShop: [
            {
              type: "array",
              required: true,
              message: "请选择使用范围",
              trigger: "change",
            },
          ],
          customerSourceId: [
            {
              required: true,
              validator: customerSourceIdVali,
              trigger: "change",
            },
          ],
          customerIds: [
            { required: true, validator: customerIdsVali, trigger: "change" },
          ],
          applyRange: [{ validator: applyRangeVali, trigger: "blur" }],
          allowNum: [
            { required: true, message: "请输入每人领取数", trigger: "blur" },
          ],
          mustCondition: [
            { required: true, validator: mustConditionVali, trigger: "blur" },
          ],
        },
        time: [],
        grantTime: [],
        brandNameArr: [],
        address_list: [],
        customerType: [],
        useShopNameArr: [],
        chooseCustomer: [], // 选择客户
        sel_brand: false,
        add_form: {
          name: "",
          startTime: "",
          endTime: "",
          reducePrice: "",
          couponType: 10, // 优惠券类型
          remark: "",
          minPrice: "", // 使用门槛(-1不限用)
          userTypeId: -1,
          grantType: 10, // 发放方式
          totalNum: "",
          allowNum: "",
          mustCondition: "", // 满减赠送
          customerSourceId: [],
          useShop: [], // 使用范围
          customerIds: [], // 选择客户
          grantStartTime: "",
          grantEndTime: "",
          applyRange: 10,
          isMutex: 4, // 是否与其他活动互斥
          categoryCollect: [],
          brandCollect: [],
          goodsCollect: [], // 商品id集合
        },
        user_center_id: 0,
        pageName: "",
        //  修改客户类型选择方式
        customerRange: 5,
        isIndeterminate: false,
        checkAll: false,
      };
    },
    created() {
      this.pageName = this.$route.name;
      this.marketId = this.$route.params.id;
      if (this.marketId) {
        this.getInfo();
      } else {
        this.getPauseSave();
      }
      this.getAllCustomerSource();
    },
    methods: {
      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;
      },
      // 关闭弹窗
      handleClose() {
        this.add_custorm = {
          name: "",
          defaultStatus: 4,
          enableStatus: 5,
        };
        this.show_model = false;
      },
      // 新增客户类型
      async addData() {
        this.$refs.add_form.validate(async (valid) => {
          if (valid) {
            let target = {};

            if (!this.is_edit) {
              target = await addCustomerSource({
                ...this.add_custorm,
              });
            } else {
              target = await editCustomerSource(this.type_id, {
                ...this.add_custorm,
              });
            }
            const data = target;

            this.$message("客户类型创建成功");
            this.show_model = false;
          }
        });
      },
      // 暂存
      async addPauseSave() {
        const useShop =
          this.add_form.useShop.length > 0
            ? this.add_form.useShop.join(",")
            : 0;
        const minPrice =
          this.add_form.userTypeId === -1 ? 0 : this.add_form.minPrice;
        const customerSourceId =
          this.add_form.customerSourceId.length > 0
            ? this.add_form.customerSourceId.join(",")
            : 0;
        const customerIds =
          this.add_form.customerIds.length > 0
            ? this.add_form.customerIds.join(",")
            : 0;
        const form = {
          name: this.add_form.name,
          startTime: this.add_form.startTime,
          endTime: this.add_form.endTime,
          reducePrice: this.add_form.reducePrice,
          remark: this.add_form.remark,
          // 'userTypeId': this.add_form.userTypeId,
          minPrice: minPrice, // 使用门槛(-1不限用)
          grantType: this.add_form.grantType, // 发放方式
          couponType: this.add_form.couponType, // 优惠券类型
          totalNum: this.add_form.totalNum,
          allowNum: this.add_form.allowNum,
          mustCondition: this.add_form.mustCondition, // 满减赠送
          isMutex: this.add_form.isMutex, // 是否与其他活动互斥
          customerSourceId: customerSourceId,
          useShop: useShop, // 使用范围
          useShopName: this.useShopName,
          brandNameArr: this.brandNameArr,
          customerIds: customerIds, // 选择客户
          customerNames: this.chooseCustomer,
          grantStartTime: this.add_form.grantStartTime,
          grantEndTime: this.add_form.grantEndTime,
          applyRange: this.add_form.applyRange,
          categoryCollect: this.add_form.categoryCollect.join(","),
          brandCollect: this.add_form.brandCollect.join(","),
        };

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

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

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

        if (JSON.stringify(data) === "{}") return;
        this.add_form = {
          ...data,
          useShop: data.useShop ? data.useShop.split(",") : [],
          brandCollect: data.brandCollect ? data.brandCollect.split(",") : [],
          categoryCollect: data.categoryCollect
            ? data.categoryCollect.split(",").map((item) => {
                return parseInt(item);
              })
            : [],
          customerSourceId: data.customerSourceId
            ? data.customerSourceId.split(",").map((item) => {
                return parseInt(item);
              })
            : [],
          userTypeId: data.minPrice > 0 ? 2 : -1,
        };
        this.useShopNameArr = data.useShopName
          ? data.useShopName.map((item, index) => {
              return {
                name: item,
                id: parseInt(this.add_form.useShop[index]),
              };
            })
          : [];
        this.chooseCustomer = data.customerNames
          ? data.customerNames.map((item, index) => {
              return {
                name: item.name,
                id: parseInt(this.add_form.useShop[index]),
              };
            })
          : [];
        this.brandNameArr = data.brandNameArr
          ? data.brandNameArr.map((item, index) => {
              return {
                title: item.title,
                id: parseInt(this.add_form.brandCollect[index]),
              };
            })
          : [];
        if (data.startTime !== "" && data.endTime !== "") {
          this.time = [data.startTime * 1000, data.endTime * 1000];
        }
        if (data.grantStartTime !== "" && data.grantEndTime !== "") {
          this.grantTime = [
            data.grantStartTime * 1000,
            data.grantEndTime * 1000,
          ];
        }
      },
      //  选择商铺
      selShop(row) {
        if (this.useShopNameArr.length) {
          this.useShopNameArr = this.$_common.unique(
            this.useShopNameArr.concat(row),
            ["id"]
          );
        } else {
          this.useShopNameArr = row;
        }

        this.add_form.useShop = this.useShopNameArr.map((item) => {
          return item.id;
        });
        this.useShopName = this.useShopNameArr.map((item) => {
          return item.name;
        });
      },
      //  选择品牌
      brandConfirm(row) {
        if (this.brandNameArr.length) {
          this.brandNameArr = this.$_common.unique(
            this.brandNameArr.concat(row),
            ["id"]
          );
        } else {
          this.brandNameArr = row;
        }
        this.add_form.brandCollect = this.brandNameArr.map((item) => {
          return item.id;
        });
      },
      // 选择客户
      customerSel(row) {
        if (this.chooseCustomer.length) {
          this.chooseCustomer = this.$_common.unique(
            this.chooseCustomer.concat(row),
            ["id"]
          );
        } else {
          this.chooseCustomer = row;
        }
        this.add_form.customerIds = this.chooseCustomer.map((item) => {
          return item.id;
        });
      },
      // 选择商品范围分类 指定分类
      cateChange(nowData, checkedKeysObj) {
        const { checkedKeys, checkedNodes } = checkedKeysObj;
        this.add_form.categoryCollect = checkedKeys;
      },
      //  选择的客户类型
      async getAllCustomerSource() {
        const data = await getAllCustomerSource({
          page: 1,
          pageSize: 999,
        });

        this.customerType = data.data;
        if (!this.marketId) {
          this.customerRange = 5;
          /* this.add_form.customerSourceId = data.data.map(item => {
            return item.id
          }) */
        }
      },
      getAllShop(list) {
        if (!this.marketId) {
          this.useShopNameArr = list;
          this.add_form.useShop = this.useShopNameArr.map((item) => {
            return item.id;
          });
          this.useShopName = this.useShopNameArr.map((item) => {
            return item.name;
          });
        }
      },
      // 有效时间
      LocationFrom(val) {
        if (val && val.length) {
          this.add_form.startTime = val[0] / 1000;
          this.add_form.endTime = this.$NP.plus(val[1] / 1000, 86399);
        } else {
          this.add_form.startTime = "";
          this.add_form.endTime = "";
        }
      },
      // 发放时间
      grantTimeChange(val) {
        if (val && val.length) {
          this.add_form.grantStartTime = val[0] / 1000;
          this.add_form.grantEndTime = this.$NP.plus(val[1] / 1000, 86399);
        } else {
          this.add_form.grantStartTime = "";
          this.add_form.grantEndTime = "";
        }
      },
      //  关闭标签
      closeTag(name, index) {
        if (name === "usershop") {
          this.useShopNameArr.splice(index, 1);
          this.add_form.useShop = this.useShopNameArr.map((item) => {
            return item.id;
          });
        } else if (name === "customer") {
          this.chooseCustomer.splice(index, 1);
          this.add_form.customerIds = this.chooseCustomer.map((item) => {
            return item.id;
          });
        } else if (name === "brand") {
          this.brandNameArr.splice(index, 1);
          this.add_form.brandCollect = this.brandNameArr.map((item) => {
            return item.id;
          });
        }
      },
      //    提交保存
      async subData() {
        this.$refs.add_form.validate(async (valid) => {
          if (valid) {
            if (
              !(
                parseInt(this.add_form.grantType) !== 20 &&
                parseInt(this.add_form.couponType) !== 20
              )
            ) {
              this.add_form.customerSourceId = "";
            }
            if (this.add_form.grantType !== 20) {
              this.add_form.customerIds = "";
            }
            const useShop =
              this.add_form.useShop.length > 0
                ? this.add_form.useShop.join(",")
                : "";
            const minPrice =
              this.add_form.userTypeId === -1 ? 0 : this.add_form.minPrice;
            const customerSourceId =
              this.customerRange === 5
                ? 0
                : this.add_form.customerSourceId.length > 0
                ? this.add_form.customerSourceId.join(",")
                : "";
            const customerIds =
              this.add_form.customerIds.length > 0
                ? this.add_form.customerIds.join(",")
                : "";
            const goodsCollect = this.goods_list
              .map((item) => {
                return item.id;
              })
              .join(",");
            const form = {
              name: this.add_form.name,
              startTime: this.add_form.startTime,
              endTime: this.add_form.endTime,
              reducePrice: this.add_form.reducePrice,
              remark: this.add_form.remark,
              // 'userTypeId': this.add_form.userTypeId,
              minPrice: minPrice, // 使用门槛(-1不限用)
              grantType: this.add_form.grantType, // 发放方式
              couponType: this.add_form.couponType, // 优惠券类型
              totalNum: this.add_form.totalNum,
              allowNum: this.add_form.allowNum,
              mustCondition: this.add_form.mustCondition, // 满减赠送
              isMutex: this.add_form.isMutex, // 是否与其他活动互斥
              customerSourceId: customerSourceId,
              useShop: useShop, // 使用范围
              customerIds: customerIds, // 选择客户
              grantStartTime: this.add_form.grantStartTime,
              grantEndTime: this.add_form.grantEndTime,
              applyRange: this.add_form.applyRange,
              categoryCollect: this.add_form.categoryCollect.join(","),
              brandCollect: this.add_form.brandCollect.join(","),
              goodsCollect: goodsCollect,
            };

            this.loading = true;
            let target = {};
            if (this.marketId) {
              target = await editMarket(this.marketId, form);
            } else {
              target = await addMarket(form);
            }
            const data = target;
            this.loading = false;

            this.$message({
              type: "success",
              message: "提交成功!",
            });
            this.delPauseSave();
            this.$closeCurrentGoEdit("/Marketing/MarketingList/Coupon");
          }
        });
      },
      //  获取详情
      async getInfo() {
        const { data } = await getInfo(this.marketId);

        this.add_form = {
          ...data,
          customerIds: data.customerIds.split(",").filter((item) => item > 0),
          useShop: data.useShop.split(","),
          brandCollect: data.brandCollect.split(","),
          categoryCollect: data.categoryCollect
            ? data.categoryCollect.split(",").map((item) => {
                return parseInt(item);
              })
            : [],
          customerSourceId: data.customerSourceId
            ? data.customerSourceId
                .split(",")
                .map((item) => {
                  return parseInt(item);
                })
                .filter((item) => item > 0)
            : [],
          userTypeId: data.minPrice > 0 ? 2 : -1,
        };
        if (this.add_form.customerSourceId.length === 0) {
          this.customerRange = 5;
        } else {
          this.customerRange = 4;
        }
        this.useShopNameArr = data.useShopName.map((item, index) => {
          return {
            name: item,
            id: parseInt(this.add_form.useShop[index]),
          };
        });
        this.chooseCustomer = data.customerNames
          ? data.customerNames.map((item, index) => {
              return {
                name: item,
                id: parseInt(this.add_form.customerIds[index]),
              };
            })
          : [];
        this.brandNameArr = data.brandCollectName
          ? data.brandCollectName.map((item, index) => {
              return {
                title: item,
                id: parseInt(this.add_form.brandCollect[index]),
              };
            })
          : [];
        this.time = [data.startTime * 1000, data.endTime * 1000];
        this.grantTime = [data.grantStartTime * 1000, data.grantEndTime * 1000];
        this.goods_list = data.goodsCollectList || [];
      },
      // 商品范围 删除指定商品
      delGoods(index) {
        this.goods_list.splice(index, 1);
      },
      // 商品范围 选择指定商品
      selGoods(goods) {
        if (this.goods_list.length) {
          this.goods_list = this.$_common.unique(
            this.goods_list.concat(goods),
            ["id"]
          );
        } else {
          this.goods_list = goods;
        }
      },
    },
  };
</script>
<style>
  .orderadd {
    padding: 5px 0;
  }
</style>
<style scoped>
  .content-wrp {
    padding: 0 20px;
  }
  .handle-wrp {
    padding: 20px 0;
  }
  .creat-shop {
    color: #1890ff;
    font-size: 12px;
  }
</style>
