/* *@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>
    <p-grid-form ref="grid" :items="formItems" :span="12">
      <template slot="diy" slot-scope="value, form">
        <a-row :gutter="10" v-for="(item, index) in form.getFieldValue('strategyCtSaveVOList')" :key="item.id">
          <a-col :span="7">
            <p-select
              :disabled="st == 1"
              :options="selectOptions"
              @change="
                (...args) => {
                  typeChange(...args, item, index)
                }
              "
              :value="item.strategyConditionType"
            ></p-select>
          </a-col>
          <a-col :span="8">
            <component
              :disabled="st == 1"
              :is="item.is"
              v-bind="item"
              @change="
                (...args) => {
                  handelChange(...args, item, index)
                }
              "
            />
          </a-col>
          <a-col :span="8" 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="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">
          <a-menu v-if="st !== 1 && options.STRATEGY_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 style="width: 100%" icon="plus">新增条件</a-button>
        </a-dropdown>
      </template>
      <!-- <a-alert slot="alert" v-show="" type="error" :message="errorMsg" banner /> -->
    </p-grid-form>

    <p-table
      bordered
      :hasRowCount="false"
      style="width: 800px"
      :activeKey="activeID"
      :rowSelectType="0"
      :pagination="false"
      :filterDropdownColumn="false"
      :columns="matchTable"
      :dataSource="matchDataSource"
      rowKey="name"
    >
      <template v-if="st !== 1" slot="operation" slot-scope="text, record, index">
        <a-space>
          <a-icon class="dynamic-delete-button" type="up-circle" :disabled="index === 0" @click="() => up(record, index)" />
          <a-icon class="dynamic-delete-button" type="down-circle" :disabled="index === 3" @click="() => down(record, index)" />
        </a-space>
      </template>
    </p-table>
  </p-card>
</template>
<script>
const titleArr = ['', '查看', '新建', '修改', '复制']

import { setFormItems, CONDITION_TYPE, getDataSource } from './config.js'

import { mainSaveData, getPageView } from '../../api'
let id = 0

import { createID } from '@/blocks/utils'
const matchTable = (self) => {
  let opt = [
    {
      key: 'operation',
      title: '操作',
      width: 140,
      fixed: 'right',
      align: 'center',
      scopedSlots: { customRender: 'operation' },
    },
  ]
  if (self.st === 1) {
    opt = []
  }
  return [{ dataIndex: 'title', title: '匹配方式' }, { dataIndex: '_s', title: '匹配顺序', align: 'center' }, ...opt]
}



const matchObj = {
  '按行政区域-行政区域': 'adminToAdmin',
  '按行政区域-收货方': 'adminToConsignor',
  '按仓库-行政区域': 'branchToAdmin',
  '按仓库-收货方': 'branchToConsignor',
}
export default {
  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 {
      errorMsg: null,
      matchTable: matchTable(this),
      CONDITION_TYPE: CONDITION_TYPE(this),
      vm: this,
      btnOptions: [],
      confirmLoading: false,
      list: [],
      formItems: [],
      activeID: '',
      matchDataSource: [],
      loading: false,
    }
  },

  watch: {
    'options.STRATEGY_CONDITION_TYPE'(STRATEGY_CONDITION_TYPE) {
      if (STRATEGY_CONDITION_TYPE?.length > 0) {
        let form = this.form()
        let strategyCtSaveVOList = form.getFieldValue('strategyCtSaveVOList')

        this.btnOptions = this.selectBtnOptions(STRATEGY_CONDITION_TYPE, strategyCtSaveVOList)
      }
    },

    st(value) {
      /**0=不显示,1=查看,2=新建,3=修改,4=复制 */
      let form = this.form()
      this.matchTable = matchTable(this)

      let provinceCityDistrict = []

      if (value === 2) {
        //新建
        form.resetFields()
        form.setFieldsValue({ strategyCtSaveVOList: [] })
        this.matchDataSource = getDataSource(this)
        this.btnOptions = this.options.STRATEGY_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 { memo, strategyName, lineMthStrategyCtViewDTOS,lineMthStrategyPrioDTOS } = response.data
            let formValue = {
              id: this.record.id,
              memo,
              strategyName,
            }
            this.matchDataSource = lineMthStrategyPrioDTOS.map((item) => {
              return { title: item.matchTypeItem, name: matchObj[item.matchTypeItem], _s: ~~item.num }
            })

            formValue.strategyCtSaveVOList = lineMthStrategyCtViewDTOS.map((item) => {
              const { id, strategyId, strategyConditionType, strategyConditionTypeName, strategyConditionValue, strategyConditionValueName, unitCode, unitId, unitName } = item
              let CONDITION = CONDITION_TYPE(this)[item.strategyConditionType]
              let obj = {
                ...CONDITION,
                id,
                key: strategyConditionType,
                value: strategyConditionValue,
                strategyConditionType,
                strategyConditionValue,
                unitCode,
                unitId,
                unitName,
                strategyId,
              }
              if (CONDITION.is == 'p-search-modal') {
                obj.value = unitName
              } else if (CONDITION.is == 'a-tree-select') {
                obj.value = unitCode
              }
              return obj
            })

            form.setFieldsValue(formValue)
            this.btnOptions = this.selectBtnOptions(this.options.STRATEGY_CONDITION_TYPE, formValue.strategyCtSaveVOList)
          }
        })
      }
      // if (this.record) {
      //   if (value === 1) {
      //     //查看
      //     provinceCityDistrict = [provinceName, cityName, districtName].filter((item) => item && item)
      //     provinceCityDistrict = provinceCityDistrict.join('-')
      //   }
      // }
      // form.setFieldsValue({ ...this.record, provinceCityDistrict })
    },
    formExtendedField(value) {
      if (value.length > 0) {
        this.formItems = setFormItems(this, value)
      }
    },
  },
  computed: {
    selectOptions() {
      if (this.options?.STRATEGY_CONDITION_TYPE) {
        let keys = this.btnOptions.map((item) => {
          return item.value
        })
        return this.options.STRATEGY_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: {
    up(record, index) {
      let prv = record._s
      let title = prv.name

      record._s = this.matchDataSource[index - 1]._s
      this.matchDataSource[index - 1]._s = prv
      this.matchDataSource.sort((a, b) => {
        return a._s - b._s
      })
      this.activeID = ''
      this.$nextTick(() => {
        this.activeID = title
      })
    },
    down(record, index) {
      let prv = record._s
      let title = prv.name
      record._s = this.matchDataSource[index + 1]._s
      this.matchDataSource[index + 1]._s = prv
      this.matchDataSource.sort((a, b) => {
        return a._s - b._s
      })
      this.activeID = ''

      this.$nextTick(() => {
        this.activeID = title
      })
    },
    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 strategyCtSaveVOList = form.getFieldValue('strategyCtSaveVOList')
      let item = strategyCtSaveVOList[index]
      let CONDITION = CONDITION_TYPE(this)[value]

      delete item.suffixIcon
      delete item.treeData
      delete item.replaceFields
      delete item.remoteUrl
      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
      // item={...item}
      form.setFieldsValue({ strategyCtSaveVOList })
      this.btnOptions = this.selectBtnOptions(this.options.STRATEGY_CONDITION_TYPE, strategyCtSaveVOList)
    },
    unitChange(...args) {
      this.errorMsg = null
      let index = args[args.length - 1]
      let form = this.form()
      let strategyCtSaveVOList = form.getFieldValue('strategyCtSaveVOList')
      let item = strategyCtSaveVOList[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 = code
          item.unitName = label
          item.unitId = id
        }
      }
      form.setFieldsValue({ strategyCtSaveVOList })
    },
    handelChange(...args) {
      this.errorMsg = null
      let index = args[args.length - 1]
      let form = this.form()
      let strategyCtSaveVOList = form.getFieldValue('strategyCtSaveVOList')
      let item = strategyCtSaveVOList[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]) {
          let { cargoOwnerId, cargoOwnerCode } = data[0]
          item.unitCode = cargoOwnerCode
          item.unitName = label
          item.unitId = cargoOwnerId
          item.value = 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[0]
        item.unitId = extra.triggerNode.eventKey
        item.strategyConditionValue = null
      }
      form.setFieldsValue({ strategyCtSaveVOList })
    },
    selectBtnOptions(STRATEGY_CONDITION_TYPE, strategyCtSaveVOList) {
      let form = this.form()
      if (form && STRATEGY_CONDITION_TYPE) {
        strategyCtSaveVOList = strategyCtSaveVOList.map((item) => item.key)
        STRATEGY_CONDITION_TYPE = STRATEGY_CONDITION_TYPE.filter((item) => {
          return !strategyCtSaveVOList.includes(item.value)
        })
        return STRATEGY_CONDITION_TYPE
      }

      return []
    },
    remove(i) {
      let form = this.form()
      let strategyCtSaveVOList = form.getFieldValue('strategyCtSaveVOList')
      strategyCtSaveVOList.splice(i, 1)
      form.setFieldsValue({ strategyCtSaveVOList })
      this.btnOptions = this.selectBtnOptions(this.options.STRATEGY_CONDITION_TYPE, strategyCtSaveVOList)
    },
    addItem(e) {
      let item = this.options?.STRATEGY_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,
      }

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

      form.setFieldsValue({ strategyCtSaveVOList })
      this.btnOptions = this.selectBtnOptions(this.options.STRATEGY_CONDITION_TYPE, strategyCtSaveVOList)
    },
    getFieldsValue() {
      return this.form().getFieldsValue()
    },
    form() {
      return this.$refs.grid.form
    },
    save() {
      let form = this.form()
      let _this = this
      _this.errorMsg = null
      form.validateFields((error, value) => {
        if (error) return
        value.strategyCtSaveVOList = value.strategyCtSaveVOList.map((item) => {
          const {
            strategyConditionType, //承运商策略条件类型 ,
            strategyConditionValue, //承运商策略条件值
            unitCode,
            unitName,
            unitId,
            id,
            strategyId,
            value,
            children,
            title,
          } = item
          if (children) {
            if (!value || !unitId || !unitName || !unitCode) {
              this.$message.error('请选择' + title)
              _this.errorMsg = '请选择' + title
              error = true
            }
          } else {
            if (!value) {
              this.$message.error('请选择' + title)
              _this.errorMsg = '请选择' + title
              error = true
            }
          }

          let obj = {
            strategyConditionType, //承运商策略条件类型 ,
            strategyConditionValue, //承运商策略条件值
            unitCode,
            unitName,
            unitId,
          }
          if (this.st === 3) {
            obj.id = id.indexOf('new-') > -1 ? null : id
            obj.strategyId = strategyId || null
          }

          return obj
        })
        if (error) return

        this.matchDataSource.forEach((item) => {
          value[item.name] = item._s
        })

        return mainSaveData(this, value, this.st).then((res) => {
          if (res.success) {
            setTimeout(() => {
              this.back(res.data || value.id, true)
            }, 1000)
          }
        })
      })
    },
    back(id, isReload = false) {
      this.matchDataSource = []
      this.$emit('back', id, isReload)
    },
  },
}
</script>
<style scoped>
.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;
}
</style>
