/* *@description: *@author: hudw *@date: 2022-03-31 17:14:12 */
<template>
  <p-card class="full-card-panel" v-show="st > 0" :loading="loading" :bordered="false">
    <a-space slot="extra" v-if="st !== 1">
      <p-button type="primary" :icon="confirmLoading ? 'loading' : ''" @click="save">保存</p-button>
      <p-button @click="back">取消</p-button>
    </a-space>
    <a-space slot="title">
      <a-icon type="arrow-left" @click="back(record && record.id)" :style="{ color: '#08c' }" />
      {{ title }}
    </a-space>

    <!-- <countExpressions :options="options.CMP_SYMBOL"/> -->

    <p-grid-form ref="grid" :items="formItems" :span="6">
      <template slot="diy" slot-scope="value, form">
        <a-row :gutter="10" style="width: 800px" v-for="(item, index) in form.getFieldValue('strategyBusinessCntViewDTOS')" :key="item.id">
          <a-col :span="6">
            <p-select
              :disabled="st == 1"
              :options="selectOptions"
              @change="
                (...dargs) => {
                  typeChange(...dargs, item, index);
                }
              "
              :value="item.strategyConditionType"
            ></p-select>
          </a-col>
          <a-col v-if="item.is" :span="8">
            <component :disabled="st == 1" :is="item.is" v-bind="item" @change="(...ages) => componentChange(...ages, item, index)" />
          </a-col>
          <a-col :span="9" v-if="item.children">
            <p-search-modal
              :value="item.unitName"
              :disabled="st == 1 || !item.strategyConditionValue"
              v-bind="item.children[~~item.strategyConditionValue]"
              targetClick
              @change="
                (...args) => {
                  unitChange(...args, item, index);
                }
              "
            />
          </a-col>
          <a-col :span="9" v-else-if="item.nodeList && item.nodeList.length > 0">
            <component
              :disabled="st == 1"
              v-for="(node, key) in item.nodeList"
              :key="key"
              :style="node.style"
              :is="node.is"
              v-bind="node"
              @change="
                (...args) => {
                  handelExpChange(...args, item, index);
                }
              "
              :inline-template="true"
            />
          </a-col>
          <areaTree ref="shipperArea" v-if="item.strategyConditionType === 16" :province="shipperProvince" :city="shipperCity" :district="shipperDistrict" :st="st"></areaTree>
          <areaTree ref="consigneeArea" v-if="item.strategyConditionType === 17" :province="consigneeProvince" :city="consigneeCity" :district="consigneeDistrict" :st="st"></areaTree>

          <a-col :span="1" v-if="st !== 1">
            <a-icon class="dynamic-delete-button" type="minus-circle-o" @click="() => remove(index)" />
          </a-col>
        </a-row>
        <a-dropdown v-if="st !== 1" style="width: 800px">
          <a-menu :style="{ width: '100%', maxHeight: '300px', overflowY: 'auto' }" v-if="st !== 1 && options.BUSINESS_CONDITION_TYPE" slot="overlay" @click="addItem">
            <a-menu-item v-for="item in btnOptions" :key="item.value">
              {{ item.label }}
            </a-menu-item>
          </a-menu>
          <a-button block icon="plus">新增条件</a-button>
        </a-dropdown>
        <a-alert v-if="errorMsg" type="error" :message="errorMsg" banner />
      </template>

      <template :slot="st !== 1 && 'colorTagBgdColor'">
        <div class="ant-input color-unit">
          <colorPicker v-model="colorTagBgdColor" defaultColor="transparent" />
        </div>
      </template>
      <template :slot="st !== 1 && 'colorTagFontColor'">
        <div class="ant-input color-unit">
          <colorPicker v-model="colorTagFontColor" defaultColor="rgba(0, 0, 0, 0.65)" />
        </div>
      </template>
    </p-grid-form>

    <p-grid-form ref="grid2" :items="formItems2" :span="6">
      <template v-if="st !== 1" :slot="'colorTagBgdColor'">
        <div class="ant-input color-unit">
          <colorPicker v-model="colorTagBgdColor" defaultColor="transparent" />
        </div>
      </template>
      <template :slot="st !== 1 && 'colorTagFontColor'">
        <div class="ant-input color-unit">
          <colorPicker v-model="colorTagFontColor" defaultColor="rgba(0, 0, 0, 0.65)" />
        </div>
      </template>
    </p-grid-form>
    <a-row :gutter="20">
      <a-col :span="8">
        <p-card title="预览">
          <div class="content-view">
            <div class="content-view-bj" :style="{ background: colorTagBgdColor, color: colorTagFontColor }">正文内容预览</div>
          </div>
        </p-card>
      </a-col>
    </a-row>
  </p-card>
</template>
<script>
const titleArr = ['', '查看', '新建', '修改', '复制'];

import { setFormItems2, setFormItems, CONDITION_TYPE, baseColor } from './config.js';
import { matchTable } from './tableConfig';

import { mainSaveData, getPageView } from '../../api';

import { createID } from '@/blocks/utils';
import countExpressions from './countExpressions.vue';
import areaTree from './areaTree.vue';

export default {
  components: { countExpressions, areaTree },
  props: {
    options: {
      //字典
      type: Object,
    },
    record: {
      //当前行数据
      type: Object,
    },
    mainId: {
      //主表ID
      type: null,
    },
    formName: {
      //主表：main，表细表：children
      type: 'main',
    },
    formExtendedField: {
      type: Array,
      default: () => [],
    },
    st: {
      type: Number,
      default: 0 /**0=不显示,1=查看,2=新建,3=修改,4=复制 */,
    },
  },
  data() {
    return {
      inputView: true,
      lastEditRange: null,
      errorMsg: null,
      matchTable: matchTable(this),
      CONDITION_TYPE: CONDITION_TYPE(this),
      vm: this,
      btnOptions: [],
      confirmLoading: false,
      list: [],
      formItems: [],
      formItems2: setFormItems2(this),

      loading: false,

      colorTagBgdColor: baseColor.background,
      colorTagFontColor: baseColor.color,
      shipperProvince: [],
      shipperCity: [],
      shipperDistrict: [],
      consigneeProvince: [],
      consigneeCity: [],
      consigneeDistrict: [],

      multipleList: [1, 4, 5, 6, 7], // 多选的参数
    };
  },

  watch: {
    'options.BUSINESS_CONDITION_TYPE'(BUSINESS_CONDITION_TYPE) {
      if (BUSINESS_CONDITION_TYPE?.length > 0) {
        let form = this.form();
        let strategyBusinessCntViewDTOS = form.getFieldValue('strategyBusinessCntViewDTOS');

        this.btnOptions = this.selectBtnOptions(BUSINESS_CONDITION_TYPE, strategyBusinessCntViewDTOS);
      }
    },

    st(value) {
      /**0=不显示,1=查看,2=新建,3=修改,4=复制 */
      let form = this.form();
      this.lastEditRange = null;
      if (value === 2) {
        //新建
        this.colorTagBgdColor = baseColor.background;
        this.colorTagFontColor = baseColor.color;

        form.resetFields();
        form.setFieldsValue({
          strategyBusinessCntViewDTOS: [],
        });
        this.btnOptions = this.options.BUSINESS_CONDITION_TYPE;
        return;
      } else if (value > 0) {
        this.formItems = setFormItems(this, this.formExtendedField);
        return getPageView(this, this.record.id).then((response) => {
          let form = this.form();
          if (response.success) {
            let { strategyBusinessCntViewDTOS } = response.data;
            let formValue = response.data;
            let shipperProvince1, shipperCity1, shipperDistrict1, consigneeProvince1, consigneeCity1, consigneeDistrict1;
            formValue.strategyBusinessCntViewDTOS = strategyBusinessCntViewDTOS?.map((item) => {
              const { id, strategyId, strategyConditionType, strategyConditionValue, unitCode, unitId, unitName } = item;
              let { shipperProvince, shipperCity, shipperDistrict, consigneeProvince, consigneeCity, consigneeDistrict } = item;
              let CONDITION = CONDITION_TYPE(this)[item.strategyConditionType];
              const { lowerLimitSymbol, lowerLimitValue, upperLimitSymbol, upperLimitValue } = item;

              let obj = {
                ...CONDITION,
                id,
                key: strategyConditionType,
                value: this.multipleList.includes(strategyConditionType) ? strategyConditionValue.split(',').map((item) => Number(item)) : Number(strategyConditionValue || ''), // 多选框，修改数据类型
                strategyConditionType,
                strategyConditionValue: this.multipleList.includes(strategyConditionType) ? strategyConditionValue.split(',').map((item) => Number(item)) : Number(strategyConditionValue || ''),
                unitCode,
                unitId,
                unitName,
                strategyId,
                lowerLimit: {
                  lowerLimitSymbol,
                  lowerLimitValue,
                  upperLimitSymbol,
                  upperLimitValue,
                },
              };
              if (CONDITION) {
                if (CONDITION.is == 'p-search-modal') {
                  obj.value = unitName;
                  if (CONDITION.nodeList) {
                    CONDITION.nodeList[0].lowerLimit = {
                      lowerLimitSymbol,
                      lowerLimitValue,
                      upperLimitSymbol,
                      upperLimitValue,
                    };
                  }
                } else if (CONDITION.is == 'countExpressions') {
                  obj.lowerLimit = {
                    lowerLimitSymbol,
                    lowerLimitValue,
                    upperLimitSymbol,
                    upperLimitValue,
                  };
                } else if (CONDITION.is == 'a-tree-select') {
                  obj.value = unitCode.split(',');
                }
              }
              if (strategyConditionType === 16) {
                shipperProvince1 = shipperProvince ? shipperProvince.split(',') : shipperProvince;
                shipperCity1 = shipperCity ? shipperCity.split(',') : shipperCity;
                shipperDistrict1 = shipperDistrict ? shipperDistrict.split(',') : shipperDistrict;
              }
              if (strategyConditionType === 17) {
                consigneeProvince1 = consigneeProvince ? consigneeProvince.split(',') : consigneeProvince;
                consigneeCity1 = consigneeCity ? consigneeCity.split(',') : consigneeCity;
                consigneeDistrict1 = consigneeDistrict ? consigneeDistrict.split(',') : consigneeDistrict;
              }
              return obj;
            });
            let form2 = this.form2();
            form2.setFieldsValue(formValue);
            form.setFieldsValue(formValue);
            this.colorTagBgdColor = formValue.colorTagBgdColor;
            this.colorTagFontColor = formValue.colorTagFontColor;
            this.$nextTick(() => {
              this.btnOptions = this.selectBtnOptions(this.options.BUSINESS_CONDITION_TYPE, formValue.strategyBusinessCntViewDTOS);
              this.shipperProvince = shipperProvince1;
              this.shipperCity = shipperCity1;
              this.shipperDistrict = shipperDistrict1;
              this.consigneeProvince = consigneeProvince1;
              this.consigneeCity = consigneeCity1;
              this.consigneeDistrict = consigneeDistrict1;
            });
          }
        });
      }
    },
    formExtendedField(value) {
      if (value.length > 0) {
        this.formItems = setFormItems(this, value);
      }
    },

    colorTagBgdColor(colorTagBgdColor) {
      let form = this.form2();
      form.setFieldsValue({ colorTagBgdColor });
    },
    colorTagFontColor(colorTagFontColor) {
      let form = this.form2();
      form.setFieldsValue({ colorTagFontColor });
    },
  },
  computed: {
    GOODS_TRANSFINITE_ENABLED() {
      return this.$store.state.sysParameter.sysParameter_TMS?.GOODS_TRANSFINITE_ENABLED.value;

    },

    selectOptions() {
      if (this.options?.BUSINESS_CONDITION_TYPE) {
        let keys = this.btnOptions.map((item) => {
          return item.value;
        });
        return this.options.BUSINESS_CONDITION_TYPE.map((item) => {
          if (!keys.includes(item.value)) {
            item.disabled = true;
          } else {
            item.disabled = false;
          }
          return item;
        });
      } else {
        return [];
      }
    },
    formList() {
      return this[this.formName + 'GetFormList'];
    },
    title() {
      return titleArr[this.st] + this.$route.meta.title;
    },
  },
  mounted() {
    this.formItems = setFormItems(this, this.formExtendedField);
  },
  methods: {
    componentChange(...ages) {
      if (ages[1]?.is === 'countExpressions') {
        return this.handelExpChange(...ages);
      } else {
        return this.handelChange(...ages);
      }
    },
    typeChange(value, label, options, sitem, index) {
      this.errorMsg = null;
      // let _item = this.options?.STRATEGY_CONDITION_TYPE.find((item) => item.value == value)
      let form = this.form();

      let strategyBusinessCntViewDTOS = form.getFieldValue('strategyBusinessCntViewDTOS');
      let item = strategyBusinessCntViewDTOS[index];
      let CONDITION = CONDITION_TYPE(this)[value];

      delete item.suffixIcon;
      delete item.treeData;
      delete item.replaceFields;
      delete item.remoteUrl;
      delete item.nodeList;
      delete item.lowerLimit;

      item.children = null;
      for (let key in CONDITION) {
        item[key] = CONDITION[key];
      }
      item.key = value;
      item.value = undefined;
      item.strategyConditionType = value; //承运商策略条件类型 ,
      item.strategyConditionValue = undefined; //承运商策略条件值
      item.unitCode = null;
      item.unitName = null;
      item.unitId = null;

      form.setFieldsValue({ strategyBusinessCntViewDTOS });
      this.btnOptions = this.selectBtnOptions(this.options.BUSINESS_CONDITION_TYPE, strategyBusinessCntViewDTOS);
      this.$forceUpdate()
    },

    unitChange(...args) {
      this.errorMsg = null;
      let index = args[args.length - 1];
      let form = this.form();
      let strategyBusinessCntViewDTOS = form.getFieldValue('strategyBusinessCntViewDTOS');
      let item = strategyBusinessCntViewDTOS[index];

      if (item.children) {
        let [vode, label, data] = args;
        item.unitCode = null;
        item.unitName = null;
        item.unitId = null;
        if (data[0]) {
          let { id, code } = data[0];
          item.unitCode = data.map((item) => item.code).join(',');
          item.unitName = label;
          item.unitId = data.map((item) => item.id).join(',');
        }
      }
      form.setFieldsValue({ strategyBusinessCntViewDTOS });
    },
    handelExpChange(params, node, index) {
      let form = this.form();
      let strategyBusinessCntViewDTOS = form.getFieldValue('strategyBusinessCntViewDTOS');
      let item = strategyBusinessCntViewDTOS[index];

      item.lowerLimit = params;
      // for (let key in params) {
      //   item[key] = params[key];
      // }
    },
    handelChange(...args) {
      this.errorMsg = null;
      let index = args[args.length - 1];
      let form = this.form();
      let strategyBusinessCntViewDTOS = form.getFieldValue('strategyBusinessCntViewDTOS');
      let item = strategyBusinessCntViewDTOS[index];
      item.unitCode = null;
      item.unitName = null;
      item.unitId = null;
      item.strategyConditionValue = undefined;
      if (item.is == 'p-select') {
        let [value, label, options] = args;
        item.value = value;
        item.strategyConditionValue = value;

      } else if (item.is == 'p-search-modal') {
        let [vode, label, data] = args;
        if (data[0]) {
          if (['商品', '商品重量', '商品件数', '商品品类'].includes(item.title)) {
            item.unitId = [];
            item.unitCode = [];
            data.forEach(({ itemId, itemCode, itemCategoryCode, itemCategoryId }) => {
              item.unitId.push(itemId || itemCategoryId);
              item.unitCode.push(itemCode || itemCategoryCode);
            });
            item.unitId = item.unitId.join(',');
            item.unitCode = item.unitCode.join(',');
          } else {
            let { cargoOwnerId, cargoOwnerCode } = data[0];
            item.unitCode = cargoOwnerCode;
            item.unitId = cargoOwnerId;
          }
          item.value = label;
          item.unitName = label;
          item.strategyConditionValue = undefined;
        }
      } else if (item.is == 'a-tree-select') {
        let [value, label, extra] = args;
        item.unitCode = value;
        item.value = value;
        item.unitName = label;
        item.unitId = extra.allCheckedNodes.map((item) => item.node.key);
        item.strategyConditionValue = null;
      }
      form.setFieldsValue({ strategyBusinessCntViewDTOS });
      if (item.title=="商品超限") {
          this.$forceUpdate()
        }
    },
    selectBtnOptions(BUSINESS_CONDITION_TYPE, strategyBusinessCntViewDTOS) {
      let form = this.form();

      if (form && BUSINESS_CONDITION_TYPE && strategyBusinessCntViewDTOS) {
        strategyBusinessCntViewDTOS = strategyBusinessCntViewDTOS.map((item) => item.key);
        BUSINESS_CONDITION_TYPE = BUSINESS_CONDITION_TYPE.filter((item) => {
          //商品超限
          if (item.label == '商品超限') {

            return this.GOODS_TRANSFINITE_ENABLED==1&&!strategyBusinessCntViewDTOS.includes(item.value)
          } else {
            //18
            return !strategyBusinessCntViewDTOS.includes(item.value);

          }

        },this);
        return BUSINESS_CONDITION_TYPE;
      }

      return [];
    },
    remove(i) {
      let form = this.form();
      let strategyBusinessCntViewDTOS = form.getFieldValue('strategyBusinessCntViewDTOS');
      strategyBusinessCntViewDTOS.splice(i, 1);
      form.setFieldsValue({ strategyBusinessCntViewDTOS });
      this.btnOptions = this.selectBtnOptions(this.options.BUSINESS_CONDITION_TYPE, strategyBusinessCntViewDTOS);
      this.$forceUpdate()

    },
    addItem(e) {
      let item = this.options?.BUSINESS_CONDITION_TYPE.find((item) => item.value == e.key);
      let value = item.value;

      item = this.CONDITION_TYPE[item.value];
      if (!item) return;

      item = {
        id: 'new-' + createID(),
        key: value,
        ...item,
        strategyConditionType: value, //承运商策略条件类型 ,
        strategyConditionValue: undefined, //承运商策略条件值
        unitCode: null,
        unitName: null,
        unitId: null,
        value: undefined,
        lowerLimitSymbol: 0,
        lowerLimitValue: null,
        upperLimitSymbol: 0,
        upperLimitValue: null,
      };

      let form = this.form();
      let strategyBusinessCntViewDTOS = form.getFieldValue('strategyBusinessCntViewDTOS');
      strategyBusinessCntViewDTOS = strategyBusinessCntViewDTOS.concat([item]);

      form.setFieldsValue({ strategyBusinessCntViewDTOS });

      this.btnOptions = this.selectBtnOptions(this.options.BUSINESS_CONDITION_TYPE, strategyBusinessCntViewDTOS);
      this.$forceUpdate()
    },
    getFieldsValue() {
      return this.form().getFieldsValue();
    },
    getFieldsValue2() {
      return this.form2().getFieldsValue();
    },
    form() {
      return this.$refs?.grid?.form??null;
    },
    form2() {
      return this.$refs?.grid2?.form??null;
    },
    save() {
      let form = this.form();
      let _this = this;
      _this.errorMsg = null;
      form.validateFields((error, value) => {
        if (error) return;
        if (value.strategyBusinessCntViewDTOS.length === 0) {
          return _this.$message.error('承运方匹配策略条件不为空');
        }
        value.strategyBusinessCntViewDTOS = value.strategyBusinessCntViewDTOS.map((item) => {
          let {
            strategyConditionType, //承运商策略条件类型 ,
            strategyConditionValue, //承运商策略条件值
            unitCode,
            unitName,
            unitId,
            id,
            strategyId,
            value,
            children,
            nodeList,
            title,
            lowerLimit,
          } = item;
          if (children) {
            if (!value || !unitId || !unitName || !unitCode) {
              if (!unitName && value) {
                title = title.replace('类型', children?.label[value] ?? '');
              }
              this.$message.error('请选择' + title);
              _this.$set(_this, 'errorMsg', '请选择' + title);
              error = true;
            }
          } else {
            if (!value && item.is !== 'countExpressions' && title) {
              this.$message.error('请选择' + title);
              _this.$set(_this, 'errorMsg', '请选择' + title);
              error = true;
            }
            if (strategyConditionType === 16 && !this.$refs.shipperArea[0].provinceValue.length) {
              this.$message.error('请选择发货方省市区');
              _this.$set(_this, 'errorMsg', '请选择发货方省市区');
              error = true;
            }
            if (strategyConditionType === 17 && !this.$refs.consigneeArea[0].provinceValue.length) {
              this.$message.error('请选择收货方省市区');
              _this.$set(_this, 'errorMsg', '请选择收货方省市区');
              error = true;
            }
          }
          let obj = {
            strategyConditionType, //承运商策略条件类型 ,
            strategyConditionValue: this.multipleList.includes(strategyConditionType) ? strategyConditionValue.join(',') : strategyConditionValue, //承运商策略条件值
            unitCode,
            unitName,
            unitId,
            ...lowerLimit,
          };
          if (strategyConditionType === 9) {
            obj.unitCode = obj.unitCode.join(',');
            obj.unitName = obj.unitName.join(',');
            obj.unitId = obj.unitId.join(',');
          }
          if (strategyConditionType === 16) {
            let { provinceValue, cityValue, districtValue } = this.$refs.shipperArea[0];
            obj.shipperProvince = provinceValue.join(',');
            obj.shipperCity = cityValue.join(',');
            obj.shipperDistrict = districtValue.join(',');
          }
          if (strategyConditionType === 17) {
            let { provinceValue, cityValue, districtValue } = this.$refs.consigneeArea[0];
            obj.consigneeProvince = provinceValue.join(',');
            obj.consigneeCity = cityValue.join(',');
            obj.consigneeDistrict = districtValue.join(',');
          }

          if (this.st === 3) {
            obj.id = id.indexOf('new-') > -1 ? null : id;
            obj.strategyId = strategyId || null;
          }

          return obj;
        });
        if (error) return;

        let formData2 = this.getFieldsValue2();
        return mainSaveData(this, { ...value, ...formData2 }, this.st).then((res) => {
          if (res.success) {
            setTimeout(() => {
              this.back(res.data || value.id, true);
            }, 1000);
          }
        });
      });
    },
    back(id, isReload = false) {
      this.lastEditRange = null;
      this.$emit('back', id, isReload);
    },
  },
};
</script>
<style lang="less">
.dynamic-delete-button {
  cursor: pointer;
  position: relative;
  top: 4px;
  font-size: 24px;
  color: #999;
  transition: all 0.3s;
}

.dynamic-delete-button:hover {
  color: #777;
}

.dynamic-delete-button[disabled] {
  cursor: not-allowed;
  opacity: 0.5;
}
.code-container span {
  color: #c41d7f;
}
.code-color {
  color: #c41d7f;
}

.color-unit {
  padding: 4px;
  display: block;
  background: #f8f8f8;

  background-image: linear-gradient(45deg, #dbdbdb 25%, transparent 0, transparent 75%, #dbdbdb 0), linear-gradient(45deg, #dbdbdb 25%, transparent 0, transparent 75%, #dbdbdb 0);
  background-position: 0 0, 15px 15px;
  background-size: 10px 10px;

  .colorView {
    position: relative;

    &::before {
      content: '';
      z-index: -1;
      position: absolute;
      width: 100%;
      height: 100%;
      background: #f8f8f8;
      background-image: linear-gradient(45deg, #dbdbdb 25%, transparent 0, transparent 75%, #dbdbdb 0), linear-gradient(45deg, #dbdbdb 25%, transparent 0, transparent 75%, #dbdbdb 0);
      background-position: 0 0, 15px 15px;
      background-size: 10px 10px;
    }
  }

  .m-colorPicker {
    border: 1px solid rgba(0, 0, 0, 0.2); //display: none;
  }

  .m-colorPicker .colorBtn {
    width: 16px;
    height: 16px;
  }
}

.content-view {
  padding: 15px;
  font-size: 24px;
  font-weight: bold;
  background-color: transparent;
  background: #f8f8f8;
  //text-shadow:1px 1px 2px #888;

  background-image: linear-gradient(45deg, #dbdbdb 25%, transparent 0, transparent 75%, #dbdbdb 0), linear-gradient(45deg, #dbdbdb 25%, transparent 0, transparent 75%, #dbdbdb 0);
  background-position: 0 0, 15px 15px;
  background-size: 30px 30px;
  // color: #fff;

  .content-view-bj {
    background: transparent;
    padding: 20px;
  }
}
</style>
