<template>
  <div data-key="EDITOR_STRATEGY" class="edit-pre-sale-strategy">
    <div class="quickOperation">
      <!-- 快捷操作： -->
      <Button
        type="fcdefault"
        style="margin-right:8px"
        @click="handleSubmit('formInline')"
      >
        保存
      </Button>
      <Button
        type="fcdefault"
        @click="closePage"
      >
        关闭
      </Button>
    </div>
    <div class="paramsBox">
      <Form
        ref="formInline"
        :label-width="156"
        label-position="right"
        :model="formInline"
        :rules="ruleInline"
      >
      <FormItem
          prop="strategyType"
          label="策略类型:"
        >
          <Select
            v-model="formInline.strategyType"
            style="width:280px"
            disabled
          >
            <Option
              v-for="item in typeList"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}
            </Option>
          </Select>
          <p
            v-if="isDefault"
            class="bottomTips"
          >
            默认策略为系统中自带策略，不支持修改。
          </p>
        </FormItem>

        <FormItem
          prop="default_strategy_type"
          label="默认策略类型:"
          v-if="formInline.strategyType===2"
          :rules="defaultStrategyRule"
        >
          <Select v-model="formInline.default_strategy_type" :disabled="formInline.strategyType===2" style="width:280px" clearable @on-change="onChangeDefaultStrategyType">
              <Option v-for="item in platformStrategyOptions" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>

        <FormItem
          prop="strategyName"
          label="策略名称:"
          :class="errorNameShow?'ark-form-item-error':''"
        >
          <Input
            v-model="formInline.strategyName"
            style="width: 280px"
            type="text"
            placeholder=""
            @on-keyup="changeStrategyName"
            @on-blur="blurStrategy"
          />
          <p
            v-if="nameTip"
            class="bottomTips"
          >
            {{ nameTip }}
          </p>
          <p
            v-if="errorNameShow"
            class="ark-form-item-error-tip-right"
          >
            {{ errorName }}
          </p>
          <p
            v-if="errorStrategyName"
            class="ark-form-item-error-tip-right"
          >
            {{ errorStrategyName }}
          </p>
        </FormItem>
        <FormItem
          prop="isOpen"
          label="是否开启:"
        >
          <i-switch
            v-model="formInline.isOpen"
            @on-change="changeIsOpen"
          />
        </FormItem>

        <FormItem
          prop="priority"
          label="策略优先级:"
          key="priority"
        >
          <div>
            <Input v-model.number="formInline.priority" :regx="/^[0-9]*$/"  style="width: 280px" />
            <p class="bottomTips">数字越大优先级越高</p>
          </div>
        </FormItem>

        <FormItem
          key="keyword"
          prop="keyword"
          label="识别关键字:"
          :class="errorKeyShow?'ark-form-item-error':''"
        >
          <Input
            v-model="formInline.keyword"
            style="width: 280px"
            type="text"
            placeholder=""
            :disabled="isDefault"
            @keydown.native="keydown($event)"
            @on-keyup="changeKeyword"
            @on-blur="blurKeyword"
          />
          <p
            v-if="errorKeyWord"
            class="ark-form-item-error-tip-right"
          >
            {{ errorKeyWord }}
          </p>
          <p
            v-if="errorKeyShow"
            class="ark-form-item-error-tip"
          >
            {{ errorKey }}
          </p>
          <p class="bottomTips">
            {{ keyTip }}<span v-if="!keyTipAll">系统识别到关键字后，将识别订单为预售订单，设置步骤请参考</span><a
              href="https://burgeonwing.yuque.com/anicqo/zm70bv/est4ys?"
              target="_blank"
            >【预售商品设置操作手册】。</a>
          </p>
        </FormItem>
        <FormItem
          prop="availableFirst"
          v-if="!encryptColumns.includes('ISSTOCKROTATION')"
          label="有货先发:"
        >
          <RadioGroup
            v-model="formInline.availableFirst"
            @on-change="changeAvailableFirst"
            :disabled="disableColumns.includes('ISSTOCKROTATION')"
          >
            <Radio
              label="true"
              :disabled="disableColumns.includes('ISSTOCKROTATION')"
            >
              <span>是</span>
            </Radio>
            <Radio
              label="false"
              :disabled="disableColumns.includes('ISSTOCKROTATION')"
            >
              <span>否</span>
            </Radio>
          </RadioGroup>
          <p class="bottomTips">
            设置有货先发后，仅为订单打【预售】标识。
          </p>
          <div class="sub-item">
            <Checkbox
              v-model="checkEncode"
              @on-change="onCheckChange"
              :disabled="disableColumns.includes('ISSTOCKROTATION')"
              size="small"></Checkbox>
            <span>排除平台SKU编码:</span>
            <Input :disabled="disableColumns.includes('ISSTOCKROTATION')" v-show="checkEncode" style="width: 280px;" v-model="formInline.exclude_extskuid" type="textarea" :autosize="true" placeholder="请输入平台SKU编码，多个支持空格、分号、逗号隔开" />
          </div>
        </FormItem>
        <FormItem
          prop="ispresalesplitorder"
          label="预售拆单:"
        >
          <RadioGroup
            v-model="formInline.ispresalesplitorder"
          >
            <Radio
              label="true"
            >
              <span>是</span>
            </Radio>
            <Radio
              label="false"
            >
              <span>否</span>
            </Radio>
          </RadioGroup>
          <p class="bottomTips">
            勾选是，占单时订单中不同计划发货时间的商品会拆单；勾选否，占单时不拆单，整单的计划发货时间，以订单中计划发货时间最早的商品为准。
          </p>
        </FormItem>
        <FormItem
          v-if="!isDefault"
          prop="planSendDate"
          label="计划发货日期:"
        >
          <Select
            v-model="formInline.planSendDate_type"
            style="width:100px"
            @on-change="onChangeplanSendDateType"
          >
            <Option
              v-for="item in planSendDateTypeOptions"
              :value="item.value"
              :key="item.value"
            >{{ item.label }}</Option>
          </Select>
          <DatePicker
            v-if="formInline.planSendDate_type == 1"
            v-model="formInline.planSendDate"
            type="date"
            format="yyyy-MM-dd"
            :options="options3"
            placeholder=""
            style="width: 280px"
            :editable="editable"
            :disabled="isDefault"
            is-emit-on-change
            @on-change="changeDate(formInline)"
            @on-clear="clearDate"
          />
          <Input
            v-else
            v-model="formInline.planSendDay"
            placeholder=""
            :regx="regx"
            style="width: 240px"
          />
          <p class="bottomTips">
            选择指定日期，匹配到预售策略的订单，计划发货日期将赋值此处维护的日期；选择付款后x天，匹配到预售策略的订单，计划发货日期为订单付款时间+此处维护的天数。
          </p>
        </FormItem>
        <FormItem
          prop="prePlanDays"
          label="提前发货天数:"
        >
          <Input
            v-model="formInline.prePlanDays"
            placeholder=""
            :regx="regx"
            style="width: 280px"
            @on-keyup="changePrePlanDays"
          />
          <p class="bottomTips">
            提前发货天数最大可设置为99
          </p>
          <p class="bottomTips">
            设置提前发货天数后，实际的计划发货时间将为计划发货日期减去提前发货天数，如计划11月11日发货，提前发货天数为2，则实际开始占用库存日期为11月9日。
          </p>
        </FormItem>
        <FormItem
          prop="storeList"
          label="使用店铺:"
        >
          <div class="shopSelect">
            <DropDownCom
              ref="DropDownCom"
              style="width:600px"
              select-width="600"
              :choosed-express-list="choosedExpressList"
              :pre-choosed="preChoosed"
              placeholder=""
              :express-list="shopList"
              :clearable='true'
              @changeShopArr="changeShopArr"
              @searchList="getEnterExpressList"
              @clearAllData="clearAllFilter"
            />
            <div
              v-if="selectShopArr.length"
              class="selectPart"
            >
              <div class="selectGroup">
                <!-- <span style="margin-right:8px;font-size: 11px;font-family: PingFangSC-Regular, PingFang SC;font-weight: 400;color: #CDCDCD;line-height: 16px;">检索项</span> -->
                <div
                  v-for="(item,index) in selectShopArr"
                  :key="index"
                  class="groupItem"
                >
                  <span>{{ item.label }}</span>
                  <Icon
                    type="ios-close"
                    @click="deleteShop(item,index)"
                  />
                </div>
              </div>
              <div class="selectBtn">
                <div
                  style="cursor:pointer; padding:8px;padding-top: 0px;"
                  @click="clearAll"
                >
                  清空
                </div>
                <div style="padding:8px 0;height:40px;padding-top: 0px;">
                  |
                </div>
                <div
                  style="padding:8px;cursor:pointer;padding-top: 0px;padding-right: 0px;"
                  @click="showAll"
                >
                  {{ showAllText }}
                  <Icon :type="isShow?'iconios-arrow-down':'iconios-arrow-up'" />
                </div>
              </div>
            </div>
          </div>
        </FormItem>
      </Form>
    </div>
    <Spin
      v-if="spinShow"
      fix
    >
      <Icon
        type="ios-loading"
        size="18"
        style="animation: ani-demo-spin 1s linear infinite"
      />
      <div>加载中...</div>
    </Spin>
  </div>
</template>

<script>
  import DropDownCom from '@yunque/component/customizedContent/DropDownCom';

  const R3 = window.R3;

  const { network } = R3;
  export default {
    components: { DropDownCom },
    data() {
      return {
        isDefault: false,
        maskClosable: false,
        precision: 2,
        regx: /^\d{0,15}?$/, // 0-99正整数
        spinShow: false,
        editable: false,
        choosedExpressList: [],
        preChoosed: [],
        shopList: [],
        selectShopArr: [], // 搜索列表选中数据
        isShowItem: true,
        isShow: false,
        showAllText:'展开',
        options3: {
          disabledDate(date) {
            return date && date.valueOf() < Date.now();
          }
        },
        typeList: [
          {
            value: 2,
            label: '默认策略'
          },
          {
            value: 1,
            label: '自定义策略'
          }
        ],
        keyTipAll: false,
        keyTip: '在平台商品名称或商家编码或商品规格中添加【识别关键字】，系统识别到关键字后，将识别订单为预售订单/商品为预售商品，设置步骤请参考，',
        errorNameShow: false,
        errorName: '',
        errorKeyShow: false,
        errorKey: '',
        formInline: {
          strategyName: '',
          isOpen: false,
          keyword: '',
          availableFirst: 'false',
          ispresalesplitorder: 'true',
          planSendDate_type: 1,
          planSendDate: '',
          planSendDay: '',
          prePlanDays: '0',
          storeList: [],
          exclude_extskuid: '',
          strategyType: 1, // 策略类型,1自定义,2默认
          default_strategy_type: '', // 默认策略类型
          priority: undefined, // 优先级
        },
        ruleInline: {
          strategyType: [
            { required: true }
          ],
          strategyName: [
            { required: true, message: '请输入策略名称', trigger: 'blur' }
          ],
          keyword: [
            { required: true, message: '请输入识别关键字', trigger: 'blur' }
          ],
        },
        nameTip: '',
        PreDateTip: '',
        errorKeyWord: '',
        errorStrategyName: '',
        checkEncode: false,
        strategyTypeOptions: [
          {
              value: 1,
              label: '自定义策略'
          },
          {
              value: 2,
              label: '默认策略'
          },
        ],
        platformStrategyOptions: [
          {
              value: 1,
              label: '淘宝/天猫全款预售'
          },
          {
              value: 2,
              label: '抖音全款预售'
          },
          {
              value: 3,
              label: '得物全款预售'
          },
          {
              value: 4,
              label: '微盟全款预售'
          },
          {
              value: 5,
              label: '预售xx.xx发'
          },
          {
              value: 6,
              label: '预售xx月xx日发'
          },
          {
              value: 7,
              label: '小红书全款预售'
          },
          {
              value: 8,
              label: '微盟（WOS）全款预售'
          },
          {
              value: 9,
              label: '视频号小店全款预售'
          },
          {
              value: 10,
              label: '拼多多全款预售'
          },
          {
              value: 11,
              label: '快手全款预售'
          },
          {
              value: 12,
              label: '有赞全款预售'
          },
          {
              value: 13,
              label: '京东全款预售'
          },
        ],
        planSendDateTypeOptions: [
        {
            value: 1,
            label: '指定日期'
          },
          {
            value: 2,
            label: '付款后x天'
          },
        ],
        defaultStrategyRule: {
          required: true,
          validator: (rule, value, callback) => {
            if(value) {
              callback()
            } else {
              callback(new Error('请输入默认策略类型'));
            }
          }
        },

        encryptColumns: [],
        disableColumns: [],
      };
    },
    created() {
      // this.setPlanSendDate();
      // if (this.$route.params.customizedModuleId == 1 || this.$route.params.customizedModuleId == 2 || this.$route.params.customizedModuleId == 3) {
      //   this.isDefault = true;
      // }
      this.getStrategyInfo();
      this.getShopArr(); // 获取店铺列表
    },
    methods: {
      // 修改默认策略类型
      onChangeDefaultStrategyType(val) {
        const res = this.platformStrategyOptions.find(item => item.value === val)
        if(res) {
          this.formInline.strategyName = `默认预售策略-${res.label}`
        }
      },
      // 修改计划发货日期类型
      onChangeplanSendDateType(val) {
        this.formInline.planSendDate = ''
        this.formInline.planSendDay = ''
      },

      changeStrategyName(event) { // 输入策略名称触发事件
        if (event.target.value.length > 20) {
          this.formInline.strategyName = event.target.value.slice(0, 20);
          this.errorNameShow = true;
          this.errorStrategyName = '最多只能输入20字符';
        }
      },
      blurStrategy() { // 输入名称失去焦点事件
        this.errorNameShow = false;
        this.errorStrategyName = '';
      },
      changeKeyword(event) { // 输入关键字触发事件
        console.log(event)
        if (event.target.value.length > 15) {
          this.formInline.keyword = event.target.value.slice(0, 15);
          this.errorKeyShow = true;
          this.errorKeyWord = '最多只能输入15字符';
        }
      },
      blurKeyword() { // 输入关键字失去焦点事件
        this.errorKeyShow = false;
        this.errorKeyWord = '';
      },
      changePrePlanDays(e) { // 提前发货天数输入框校验
        if (Number(e.target.value) > 99) {
          this.formInline.prePlanDays = '99';
        } else if (e.target.value[0] == 0 && e.target.value.length > 1) {
          this.formInline.prePlanDays = e.target.value.slice(1, e.target.value.length);
        }
      },
      // 获取敏感列
      async getSensitiveColumns() {
        await network.post(`/p/cs/query/protect/column?hash=${+new Date()}`, {
          table: 'T_OMSPRESELLSTRATEGY'
        }).then(res=> {
          if (res.data.code == 0) {
            const data = res.data.data
            const encryptColumns = data.UNREADCOLUMUS // 加密字段
            const disableColumns = data.UNWRITECOLUMUS // 不可编辑字段
            this.encryptColumns = []
            this.disableColumns = []

            if(encryptColumns) {
              this.encryptColumns = encryptColumns.split(';')
            }

            if(disableColumns) {
              this.disableColumns = disableColumns.split(';')
            }
          }
        })
      },
      // 敏感列设置
      setSensitiveColumns(tableData) {
        if(this.encryptColumns.length > 0) {
            const fieldList = this.encryptColumns
            console.log(fieldList)
            tableData.forEach(row => {
              fieldList.forEach(field => {
                row[`_decrypt_${field}`] = row[field] // 缓存解密前数据
                row[field] = '***'
              })
            })
          }
      },
      // 获取预售策略详情
      async getStrategyInfo() {
        await this.getSensitiveColumns()
        let params = {
          id: this.$route.params.customizedModuleId
        };
        network.post('/p/cs/pre/sell/strategy/info', params).then((res) => {
          if (res.data.code == 0) {
            let data = res.data.data;
            if(data.strategyType == 2){
              this.isDefault = true;
            }
            // 敏感列设置。不可见设置
            // this.setSensitiveColumns(data)
            // 敏感列设置。不可见编辑
            // const disabledList = this.disableColumns

            this.formInline.strategyName = data.name;
            this.formInline.strategyType = data.strategyType;
            this.formInline.isOpen = data.is_active == "N" ? false : true;
            this.formInline.keyword = data.keywords;
            this.formInline.availableFirst = data.is_advance == 0 ? 'false' : 'true';
            this.formInline.default_strategy_type = data.default_strategy_type
            this.formInline.priority = data.priority

            if(this.formInline.availableFirst ==='false') {
              this.setPlanSendDate();
            }
            this.formInline.ispresalesplitorder = data.ispresalesplitorder == 0 ? 'false' : 'true';
            this.formInline.exclude_extskuid = data.exclude_extskuid
            this.checkEncode = this.formInline.exclude_extskuid ? true : false

            if (this.formInline.availableFirst == 'true') {
              this.isShowItem = false;
            }
            if (this.$route.params.customizedModuleId == 1) {
              this.keyTip = '在各平台商品名称或商家编码（淘宝/京东额外支持商品规格）结尾添加【预售xx月xx日发】，';
              this.formInline.planSendDate = 'xx月xx日';
              this.PreDateTip = '计划发货日期为xx值，比如在商品结尾添加【预售11月11日发】，则该商品计划发货日期为11月11日。注意：日期为个位数，也需要维护两位，如9月9日必须维护09月09日。';
            } else if (this.$route.params.customizedModuleId == 2) {
              this.keyTip = '在各平台商品名称或商家编码（淘宝/京东额外支持商品规格）结尾添加【预售xx.xx发】，';
              this.formInline.planSendDate = 'xx月xx日';
              this.PreDateTip = '计划发货日期为xx值，比如在商品结尾添加【预售11.11发】，则该商品计划发货日期为11月11日。注意：日期为个位数，也需要维护两位，如9月9日必须维护09月09日。';
            } else if (this.$route.params.customizedModuleId == 3) {
              this.nameTip = '全款预售有最高的优先级，当订单同时满足此预售策略和其他策略时，匹配这个预售策略。'; // 淘宝/天猫
              this.formInline.keyword = '【淘宝商品中设置的发货时间】';
              this.formInline.planSendDate = '淘宝商品设置全款预售的【发货时间】';
              this.keyTipAll = true;
              this.keyTip = '淘宝商品中-付款方式-预售模式中可设置全款预售，识别设置的【发货时间】内容。';
            } else if(data.strategyType == 2 && this.$route.params.customizedModuleId !=1 && this.$route.params.customizedModuleId !=2 && this.$route.params.customizedModuleId != 3){
              this.nameTip = '全款预售有最高的优先级，当订单同时满足此预售策略和其他策略时，匹配这个预售策略。';
              // this.nameTip = '';
              this.formInline.keyword = data.keywords;
              this.formInline.planSendDate = data.keywords;
              this.keyTipAll = true;
              // this.keyTip = '';
              // this.keyTip = '淘宝商品中-付款方式-预售模式中可设置全款预售，识别设置的【发货时间】内容。';
            }else {
              this.formInline.planSendDate_type = data.planned_type;
              if(data.planned_type == 1){
                this.formInline.planSendDate = data.plan_delivery_date ? data.plan_delivery_date.slice(0, 10) : this.formInline.planSendDate;
              }else {
                this.formInline.planSendDay = data.payafter_day ? data.payafter_day : '';
              }
            }
            this.formInline.prePlanDays = data.advance_days ? String(data.advance_days) : '0';
            // 预先发货为是，且提前发货天数没值时，不给默认值
            if(this.formInline.availableFirst === 'true' && data.advance_days === null) {
              this.formInline.prePlanDays = ''
            }
            this.formInline.storeList = data.shopIds ? data.shopIds : [];
            this.getShopArr();
          }
        });
      },
      // 初始化发货日期
      setPlanSendDate() {
        let nowDate = new Date();
        // 当前日期
        // let systemDate = `${date.year}-${date.month}-${date.date}`;
        let afterdate = new Date(nowDate);
        afterdate.setDate(nowDate.getDate() + 30);
        // 30天后
        this.formInline.planSendDate = `${afterdate.getFullYear()}-${afterdate.getMonth() + 1 < 10 ? `0${afterdate.getMonth() + 1}` : afterdate.getMonth() + 1}-${afterdate.getDate()<10 ? `0${afterdate.getDate()}` : afterdate.getDate()}`;
      },
      // 以下为使用店铺相关逻辑
      // 初始化店铺列表
      getShopArr() {
        let data = {
          table: 'T_V_IESSHOP',
          range: 1000,
          isdroplistsearch: true,
          fkdrplist: {
            searchcols: ['ID', 'SHOPTITLE']
          }
        };
        if (this.$route.params.customizedModuleId == 3) {
          data.fixedcolumns = { PLATFORM: ['2'] };
        }
        network.post('/p/cs/list/query', data).then((res) => {
          this.selectShopArr = [];
          if (res.data.rows.length) {
            this.shopList = res.data.rows.map(item=>({
              value: item.ID.val,
              label: item.SHOPTITLE.val
            }));
            if (this.formInline.storeList.length > 0) {
              this.formInline.storeList.forEach(item => {
                this.shopList.forEach(obj => {
                  if (item == obj.value) {
                    this.choosedExpressList.push(String(obj.value));
                    this.selectShopArr.push(obj);
                  }
                });
              });
              this.$refs.DropDownCom.choosedExpress = this.choosedExpressList;
            }
          }
        });
      },
      changeShopArr(val, deffArr) {
        if (val.length) {
          if (val.some(item=>Object.hasOwnProperty.call(item, 'label'))) { // 全选时第一次传入没有label
            this.shopName = '';
            this.shopIds = '';
            this.choosedExpressList = [];
            let Data = [...val].filter(x => [...this.selectShopArr].every(y => y.value !== x.value));
            this.selectShopArr = [...this.selectShopArr, ...Data];
            if (deffArr.length) {
              this.selectShopArr = this.selectShopArr.filter(x => [...deffArr].every(y => y.value !== x.value)); // 过滤掉取消项
            }

            this.selectShopArr.forEach(item=>{
              this.choosedExpressList.push(String(item.value));
              this.shopName = this.shopName == '' ? item.label.replace(/[\r\n]/g, '').replace(/\ +/g, '') : (`${this.shopName},${item.label.replace(/[\r\n]/g, '').replace(/\ +/g, '')}`);
              this.shopIds = this.shopIds == '' ? item.value : `${this.shopIds},${item.value}`;
            });
            this.$refs.DropDownCom.choosedExpress = this.choosedExpressList;
          }
        } else { // 当前下拉列表里全部清空
          this.shopName = '';
          this.shopIds = '';
          this.choosedExpressList = [];
          if (deffArr.length) {
            this.selectShopArr = this.selectShopArr.filter(x => [...deffArr].every(y => y.value !== x.value)); // 过滤掉取消项
          }

          this.selectShopArr.forEach(item=>{
            this.choosedExpressList.push(String(item.value));
            this.shopName = this.shopName == '' ? item.label.replace(/[\r\n]/g, '').replace(/\ +/g, '') : (`${this.shopName},${item.label.replace(/[\r\n]/g, '').replace(/\ +/g, '')}`);
            this.shopIds = this.shopIds == '' ? item.value : `${this.shopIds},${item.value}`;
          });
          this.$refs.DropDownCom.choosedExpress = this.choosedExpressList;
        }
      },
      getEnterExpressList(val) {
        let data = {
          table: 'T_V_IESSHOP',
          range: 1000,
          isdroplistsearch: true,
          fkdrplist: {
            searchcols: ['ID', 'SHOPTITLE']
          },
          fixedcolumns: { SHOPTITLE: val },
        };
        this.$refs.DropDownCom.choosedExpress = this.choosedExpressList;
        network.post('/p/cs/list/query', data).then((res) => {
          this.shopList = res.data.rows.map(item=>({
            value: item.ID.val,
            label: item.SHOPTITLE.val
          }));
        });
      },
      deleteShop(obj, index) { // 删除某一检索项
        this.$refs.DropDownCom.choosedExpress = this.$refs.DropDownCom.choosedExpress.filter(item=>obj.value != item);
        this.selectShopArr = this.selectShopArr.filter(item=>obj.value != item.value);
        this.shopName = '';
        this.shopIds = '';
        this.choosedExpressList = [];
        this.selectShopArr.forEach(item=>{
          this.choosedExpressList.push(String(item.value));
          this.shopName = this.shopName == '' ? item.label.replace(/[\r\n]/g, '').replace(/\ +/g, '') : (`${this.shopName},${item.label.replace(/[\r\n]/g, '').replace(/\ +/g, '')}`);
          this.shopIds = this.shopIds == '' ? item.value : `${this.shopIds},${item.value}`;
        });
        this.$refs.DropDownCom.choosedExpress = this.choosedExpressList;
      },
      clearAllFilter(value) { // 清空带有筛选的检索项
        value.forEach(itemOne => {
          this.selectShopArr.forEach((item, index) => {
            if (itemOne.value == item.value) {
              this.selectShopArr.splice(index, 1);
            }
          });
        });
        this.choosedExpressList = [];
        this.selectShopArr.forEach(item=>{
          this.choosedExpressList.push(String(item.value));
          this.shopName = this.shopName == '' ? item.label.replace(/[\r\n]/g, '').replace(/\ +/g, '') : (`${this.shopName},${item.label.replace(/[\r\n]/g, '').replace(/\ +/g, '')}`);
          this.shopIds = this.shopIds == '' ? item.value : `${this.shopIds},${item.value}`;
        });
        this.$refs.DropDownCom.choosedExpress = this.choosedExpressList;
      },
      clearAll() { // 清空全部检索项
        this.$refs.DropDownCom.choosedExpress = [];// 检索项清空
        this.selectShopArr = [];
        this.shopName = '';
        this.shopIds = '';
      },
      showAll() { // 显示所有搜索项
        this.isShow = !this.isShow;
        if (this.isShow) {
          this.showAllText = '收起';
          document.getElementsByClassName('selectGroup')[0].style.height = 'auto';
        } else {
          document.getElementsByClassName('selectGroup')[0].style.height = '52px';
          this.showAllText = '展开';
        }
      },
      // 以上为使用店铺相关逻辑
      // 禁止输入空格
      keydown(e) {
        if (e.keyCode == 32) {
          e.returnValue = false;
        }
      },
      dateChange(date) {
        let d = new Date(date);
        let mouth = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
        let day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
        let datetime = `${d.getFullYear()}-${mouth}-${day}`;
        return datetime;
      },
      changeDate(formInline) {
        if(formInline.planSendDate == '' || formInline.planSendDate == 'NaN-NaN-NaN'){
          formInline.planSendDate = '';
        }else {
          formInline.planSendDate = this.dateChange(formInline.planSendDate);
        }
      },
      clearDate(){
        this.formInline.planSendDate = '';
      },
      changeIsOpen() {
        console.log(this.formInline);
      },
      changeAvailableFirst(value) {
        if (value == 'true') {
          this.isShowItem = false;
          this.formInline.planSendDate = ''
          this.formInline.planSendDay = ''
          this.formInline.prePlanDays = ''
        } else {
          this.isShowItem = true;
        }
      },

      validate() {
        let isValid = false
        // 【有货先发】为'否'，【计划发货日期】和【提前发货天数】都必填
        // 【有货先发】为'是'，且【排除平台SKU编码】有值，【计划发货日期】和【提前发货天数】都必填
        if(this.formInline.strategyType===2) {
          if (this.formInline.availableFirst === 'false') {
            if (!this.formInline.prePlanDays) {
              isValid = false
            } else {
              isValid = true
            }
          } else{
            if (this.formInline.exclude_extskuid && !this.formInline.prePlanDays) {
              isValid = false
            } else {
              isValid = true
            }
          }
          if (!isValid) {
            this.$Message.error('请填写提前发货天数');
          }
        } else {
          if (this.formInline.availableFirst === 'false') {
            if ((!this.formInline.planSendDate && !this.formInline.planSendDay) || !this.formInline.prePlanDays) {
              isValid = false
            } else {
              isValid = true
            }
          } else{
            if (this.formInline.exclude_extskuid && (!this.formInline.prePlanDays)) {
              isValid = false
            } else {
              isValid = true
            }
          }

          if (!isValid) {
            this.$Message.error('请填写计划发货日期和提前发货天数');
          }
        }

        console.log('校验结果', isValid)
        return isValid
      },

      handleSubmit(name) {
        if(!this.validate()) {
          return
        }
        this.$refs[name].validate((valid) => {
          if (valid) {
            this.saveStrategy();
          //   this.$Message.success('Success!');
          } else {
          //   this.$Message.error('Fail!');
          }
        });
      },
      saveStrategy() {
        // 默认策略类型时不显示，不显示不判断
        if(this.formInline.strategyType !=2 && this.formInline.availableFirst === 'false' && !this.formInline.planSendDate && this.formInline.planSendDate_type ===1){
          return this.$Message.error('请填写计划发货日期');
        }
        if(this.formInline.availableFirst === 'false' && this.formInline.planSendDate_type == 2 && !this.formInline.planSendDay){
          return this.$Message.error('请填写计划发货天数');
        }
        this.errorNameShow = false;
        this.errorKeyShow = false;
        let params = {
          id: this.$route.params.customizedModuleId,
          name: this.formInline.strategyName,
          is_active: this.formInline.isOpen ? 'Y' : "N",
          is_advance: this.formInline.availableFirst == 'true' ? 1 : 0,
          ispresalesplitorder: this.formInline.ispresalesplitorder == 'true' ? 1 : 0,
          keywords: this.formInline.keyword,
          shopIds: this.choosedExpressList,
          exclude_extskuid: this.formInline.exclude_extskuid?this.formInline.exclude_extskuid.replace(/\n/g, ' '):'',
          planned_type:this.formInline.planSendDate_type,
          advance_days: this.formInline.prePlanDays,
          priority: this.formInline.priority,
          strategyType: this.formInline.strategyType,
        };
        if (this.formInline.planSendDate_type == 1) {
          params.plan_delivery_date = this.formInline.planSendDate
        }else if(this.formInline.planSendDate_type == 2) {
          params.payafter_day = this.formInline.planSendDay
        }
        // if (this.formInline.availableFirst == 'false') {
        //   params.plan_delivery_date = this.formInline.planSendDate;
        //   params.advance_days = this.formInline.prePlanDays;
        // } else {
        //   params.plan_delivery_date = null;
        //   params.advance_days = null;
        // }
        if (this.isDefault) {
          params.plan_delivery_date = null;
          params.default_strategy_type = this.formInline.default_strategy_type
        }
        network.post('/p/cs/pre/sell/strategy/modify', params).then((res) => {
          if (res.data.code == 0) {
            this.$Message.success('修改预售策略成功');
            // this.closePage();
            if(this.formInline.availableFirst ==='false') {
              this.setPlanSendDate();
            }
            if (this.$route.params.customizedModuleId == 1 || this.$route.params.customizedModuleId == 2 || this.$route.params.customizedModuleId == 3) {
              this.isDefault = true;
            }
            this.getStrategyInfo();
            // this.getShopArr(); // 获取店铺列表
          } else if (res.data.code == 1) {
            this.errorNameShow = true;
            this.errorName = '已存在相同的策略名称，请检查后重新输入';
          } else if (res.data.code == 2) {
            this.errorKeyShow = true;
            this.errorKey = '已存在相同的识别关键字，请检查后重新输入';
          } else {
            this.$Message.error(res.data.message);
          }
        });
      },
      closeTab() {
        // 关闭自定义界面，
        const { path } = this.$route;
        const { keepAliveModuleName, tableName } = this.$store.state.global.activeTab;
        this.$store.commit('global/tabCloseAppoint', {
          tableName,
          routeFullPath: path,
          keepAliveModuleName,
          stopRouterPush: false,
        });
      },
      closePage() {
        // 关闭自定义界面，
        const { path } = this.$route;
        const { keepAliveModuleName, tableName } = this.$store.state.global.activeTab;
        this.$store.commit('global/tabCloseAppoint', {
          tableName,
          routeFullPath: path,
          keepAliveModuleName,
          stopRouterPush: false,
        });
        // 跳转
        setTimeout(() => {
          R3.store.commit('global/tabOpen', {
            type: 'S',
            tableName: 'T_OMSPRESELLSTRATEGY',
            tableId: '11407',
            back: true
          });
        }, 0);
      },

      // 【排除平台SKU编码】勾选变化
      onCheckChange(val) {
        if(val === false) {
          this.formInline.exclude_extskuid = ''
        }
      },
    },
  };
</script>
<style lang='less'>
  .SystemParamsSetting .ark-form .ark-form-item-label {
    color: #333;
  }
  .SystemParamsSetting .ark-select-single .ark-select-selection,.SystemParamsSetting input.ark-input {
    height: 32px;
  }
  .SystemParamsSetting .ark-select-single .ark-select-selection .ark-select-placeholder,.SystemParamsSetting .ark-select-single .ark-select-selection .ark-select-selected-value,.SystemParamsSetting .ark-input-icon {
    height: 32px;
    line-height: 32px;
  }
  .SystemParamsSetting .DropDownSelectInput .ark-input-icon.iconios-search {
    display: none;
  }
  .SystemParamsSetting .DropDownSelectInput input.ark-input {
    height: 36px !important;
  }
  .SystemParamsSetting .ark-date-picker-cells span em,.SystemParamsSetting .ark-date-picker-cells-cell-today em {
    color: unset;
  }
  .SystemParamsSetting .ark-date-picker-cells-cell.ark-date-picker-cells-cell-prev-month em,.SystemParamsSetting .ark-date-picker-cells-cell.ark-date-picker-cells-cell-next-month em {
    color: #D8D8D8 !important;
  }
  .showTipModel .fcWarning {
    color:#f7b901;
    font-size: 24px;
    margin-right: 10px;
    vertical-align: middle;
  }
  .showTipModel p {
    height: 50px;
    line-height: 50px;
  }
  .showTipModel .ark-modal-footer .ark-btn {
    border: 1px solid var(--primary-color);
    background: #fff;
    color: var(--primary-color);
  }
  .SystemParamsSetting .ark-form .ark-input-wrapper textarea {
    min-height: 60px !important;
  }
  .SystemParamsSetting .ark-form-item-error-tip-right {
    position: absolute;
    top: 5px;
    left: 250px;
    line-height: 1;
    padding-top: 6px;
    color: #fd6442;
  }
  .planSendDate .ark-input-prefix i, .planSendDate .ark-input-suffix i {
    line-height: 32px;
  }
</style>
<style lang='less' scoped>
  .quickOperation{
    position: fixed;
    top: 82px;
    background: #fff;
    width: calc(100% - 130px);
    z-index: 10;
    height: 64px;
    display: flex;
    align-items: center;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #333333;
    padding-left: 16px;
  }
  .r3-vertical-content .quickOperation{ 
    top: 32px;
  }
  .paramsBox {
    margin-top: 64px;
    padding: 8px 8px;
  }
  .bottomTips {
    color: #989898;
    font-size: 12px;
    line-height: 20px;
    margin-top: 6px;
  }
  .foldpanelDIV {
    margin-bottom: 10px;
  }

  .shopSelect{
          .selectPart{
            display: flex;
            width: 700px;
            .selectGroup{
              flex: 1;
              height:52px;
              overflow: hidden;
              margin-top: 8px;
              display: flex;
              flex-wrap: wrap;
              .groupItem{
                background: #F2F2F2;
                border-radius: 2px;
                margin-right:8px;
                margin-bottom:8px;
                padding: 0 8px;
                height: 18px;
                font-size: 11px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #333333;
                line-height: 16px;
              }
            }
            .selectBtn{
              display: flex;
              height:40px;
              color:#0F6AFB;
              font-family: PingFangSC-Medium, PingFang SC;
              font-weight: 500;

            }
          }

        }

  .sub-item {
    margin-top: 8px;
    display: flex;
    align-items: flex-start;
  }
</style>
