<template>
<!-- 确权资料合并-编辑/查看/新增 -->
  <dialog-edit :visible.sync="dialogVisible" :editModel="editModel" :form="form" :title="headTitle"
               :openPerms="true" savePerms="btnSave" :menuCode="menuCode"
               width="1300px" :api="api" :autoSave="false" @onSaved="onSaved" :loading="editSaveBtn">
    <search-form :formValue.sync="queryParas"
                 class="searchClass component-width"
                v-if="!isEditDisable"
                searchPerms="search"
                resetPerms="reset"
                @handleFilter="handleFilter"
                @clearParam="clearParam"
                @selectChanged="selectChange"
                :componentList="componentList"></search-form>
    <!-- 查看 -->
    <data-table  :api="api" :deleteApi="api" v-if="isEditDisable"
      :headTitle = "$t('confirmationRightData.dialogTableHead2')"
      :showSelection="isEdit" ref="dialogTable1"
      :showPage="false"
      selectable="false"
      :handleFlag.sync="handleFlag"
      :menuFlag="false"
      :pageAll="false"
      :sourceData.sync="sourceData"
      :columns="columns"
      :otherHeight="'240'"
      operateBtnLayout=""
      :IsRight="false"
      key="EV"
      :operatWidth="'200'"
      @selectRowChange="selectRowChange">
      <template slot="headButton" v-if="isEdit">
        <div align="right">
          <auth-button size="small" type="primary" :label="$t('common.del')" @click="dels"></auth-button>
        </div>
      </template>
      <template slot="paginationLeft" v-if="sourceData.length !== 0">
        <div>
          <span>显示第 1 至 {{sourceData.length}} 项结果，共 {{sourceData.length}} 项</span>
        </div>
      </template>
    </data-table>
    <!-- 编辑 -->
    <el-form @submit.native.prevent :inline="true">
      <el-row v-if="isEdit" class="mergeEdit-keyword">
        <el-col :span="12" align="right">
          <el-form-item :label="$t('confirmationRightData.keyWord')">
            <el-input v-model="keyWordPlader" :placeholder="$t('confirmationRightData.keyWordPlader')" @input="keySousuo" :clearable="true"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 编辑/新增 -->
    <div v-if="!isEditDisable" class="merge-created">
      <data-table  :api="apiCreate"
            :headTitle = "$t('confirmationRightData.dialogTableHeadL')"
            :showSelection="true" ref="dialogTable2"
            :showPage="false"
            selectable="false"
            :handleFlag.sync="handleFlag"
            :sourceData.sync="sourceDataL"
            :menuFlag="false"
            :pageAll="false"
            :columns="columns3"
            max-height="300"
            :otherHeight="'240'"
            operateBtnLayout=""
            :IsRight="false"
            class="width80"
            key="CL"
            @selectRowChange="selectRowChangeL"
            :operatWidth="'200'">
            <template slot="paginationLeft" v-if="sourceDataL.length !== 0">
              <div>
                <span>{{$t('uninvoiced.bottomLeftTitle1') + sourceDataL.length + $t('uninvoiced.bottomLeftTitle2') + sourceDataL.length + $t('uninvoiced.bottomLeftTitle3')}}</span>
              </div>
            </template>
      </data-table>
      <div class="merge-created-control">
        <auth-button size="small" icon="iconfont iconzuo" @click="controlToLeft"></auth-button>
        <auth-button size="small" icon="iconfont iconyou" @click="controlToRight" class="marginTop8"></auth-button>
      </div>
      <data-table  :api="api" :deleteApi="api"
            :headTitle = "$t('confirmationRightData.dialogTableHeadR')"
            :showSelection="true"
            :showPage="false"
            selectable="false"
            :handleFlag.sync="handleFlag"
            :menuFlag="false"
            :pageAll="false"
             max-height="300"
            :sourceData.sync="sourceDataR"
            :columns="isEdit?columns:columns2"
            :otherHeight="'240'"
            operateBtnLayout=""
                   class="width80"
            :IsRight="false"
            key="CR"
            @selectRowChange="selectRowChangeR"
            :operatWidth="'200'">
            <template slot="paginationLeft" v-if="sourceDataR.length !== 0">
              <div>
                <span>{{$t('uninvoiced.bottomLeftTitle1') + sourceDataR.length + $t('uninvoiced.bottomLeftTitle2') + sourceDataR.length + $t('uninvoiced.bottomLeftTitle3')}}</span>
              </div>
            </template>
      </data-table>
    </div>
  </dialog-edit>
</template>

<script>
import { DialogEdit, searchForm, authButton, DataTable, SelectFinancialInstitutions,
  SelectAreaCommissioner, SelectProductName, SelectCoreEnterprise } from 'newepoch-components'
import BasePage from '@/pages/baseEditPage'
import confirmationRightDataApi from '@/api/confirmationRightDataApi'
import SelectArea from '@/components/element/enterpriseInfoManage/SelectArea'
import * as format from '@/filters/index'
import componentsApi from '@/api/componentsApi'
import { regExp } from '@/validator/index'

export default {
  extends: new BasePage('confirmationRightDataMerge'),
  name: 'confirmationRightDataMergeEdit',
  props: {
    menuCode: {
      type: String,
      default: null
    }
  },
  components: {
    DialogEdit,
    searchForm,
    authButton,
    DataTable
  },
  computed: {
    api () {
      return confirmationRightDataApi.confirmationRightDataMerge
    },
    apiCreate () {
      return confirmationRightDataApi.confirmationRightData
    },
    isCreate () {
      return this.editModel === 'C'
    },
    isEdit () {
      return this.editModel === 'E'
    },
    headTitle () {
      return {
        'V': this.$t('confirmationRightData.dialogHead2'),
        'E': this.$t('confirmationRightData.dialogHead3'),
        'C': this.$t('confirmationRightData.dialogHead4')
      }[this.editModel]
    }
  },
  data () {
    return {
      editSaveBtn: false,
      handleFlag: false,
      keyWordPlader: '',
      queryParas: {
        isMerge: '0'
      },
      componentList: [
        {
          // 核心企业
          label: this.$i18n.messages[this.$i18n.locale].confirmationRightData.coreEnterpriseName,
          disabled: false,
          value: 'coreEnterpriseId',
          labelWidth: '160px',
          clearable: true,
          componentName: SelectCoreEnterprise
        },
        {
          // 计划管理人/再保理银行
          label: this.$i18n.messages[this.$i18n.locale].confirmationRightData.planningManagerName,
          disabled: false,
          value: 'planOrBankId',
          labelWidth: '160px',
          clearable: true,
          componentName: SelectFinancialInstitutions
        },
        {
          // 区域
          label: this.$i18n.messages[this.$i18n.locale].confirmationRightData.region,
          value: 'coreAreaTemp',
          name: 'coreAreaTemp',
          labelWidth: '160px',
          multiple: true,
          filterable: true,
          componentName: SelectArea,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseSelect
        },
        {
          // 项目公司名称
          label: this.$i18n.messages[this.$i18n.locale].confirmationRightData.projectCompanyName,
          disabled: false,
          value: 'projectCompanyName',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseInput,
          labelWidth: '160px',
          clearable: true,
          componentName: 'el-input'
        },
        {
          // 付款确认书编号
          label: this.$i18n.messages[this.$i18n.locale].confirmationRightData.payCode,
          disabled: false,
          value: 'assetCode',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseInput,
          labelWidth: '160px',
          clearable: true,
          componentName: 'el-input'
        },
        {
          // 产品名称
          label: this.$i18n.messages[this.$i18n.locale].confirmationRightData.productName,
          value: 'projectId',
          labelWidth: '160px',
          name: 'projectId',
          componentName: SelectProductName
        },
        {
          // 期数
          label: this.$i18n.messages[this.$i18n.locale].confirmationRightData.specialPlanPeriods,
          value: 'specialPlanPeriods',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseInput,
          labelWidth: '160px',
          disabled: false,
          maxlength: '3',
          componentName: 'el-input'
        },
        {
          // 是否合并
          label: this.$i18n.messages[this.$i18n.locale].confirmationRightData.isMerge,
          value: 'isMerge',
          labelWidth: '160px',
          clearable: false,
          disabled: true,
          componentName: 'SelectDictionary',
          dictTypeCode: 'ZD0003'
        },
        {
          // 区域专员
          label: this.$i18n.messages[this.$i18n.locale].confirmationRightData.regionAttache,
          value: 'coreAreaAttache',
          labelWidth: '160px',
          componentName: SelectAreaCommissioner,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseSelect,
          multiple: true
        }
      ],
      columns: [
        {
          // 付款确认书编号
          prop: 'assetCode',
          align: 'left',
          label: this.$i18n.messages[this.$i18n.locale].confirmationRightData.payCode,
          format: (row) => {
            if (row.assetCode !== undefined) {
              return row.assetCode
            } else {
              return ''
            }
          }
        },
        {
          // 区域
          prop: 'coreAreaName',
          align: 'left',
          label: this.$i18n.messages[this.$i18n.locale].confirmationRightData.region,
          format: (row) => {
            if (row.coreAreaName !== undefined) {
              return row.coreAreaName
            } else {
              return ''
            }
          }
        },
        {
          // 项目公司名称
          prop: 'projectCompanyName',
          align: 'left',
          label: this.$i18n.messages[this.$i18n.locale].confirmationRightData.projectCompanyName,
          format: (row) => {
            if (row.projectCompanyName !== undefined) {
              return row.projectCompanyName
            } else {
              return ''
            }
          }
        }
      ],
      columns2: [
        {
          // 付款确认书编号
          prop: 'assetCode',
          align: 'left',
          label: this.$i18n.messages[this.$i18n.locale].confirmationRightData.payCode,
          format: (row) => {
            if (row.assetCode !== undefined) {
              return row.assetCode
            } else {
              return ''
            }
          }
        },
        {
          // 区域
          prop: 'coreAreaName',
          align: 'left',
          label: this.$i18n.messages[this.$i18n.locale].confirmationRightData.region,
          format: (row) => {
            if (row.coreAreaName !== undefined) {
              return row.coreAreaName
            } else {
              return ''
            }
          }
        },
        {
          // 项目公司名称
          prop: 'projectCompanyName',
          align: 'left',
          label: this.$i18n.messages[this.$i18n.locale].confirmationRightData.projectCompanyName,
          format: (row) => {
            if (row.projectCompanyName !== undefined) {
              return row.projectCompanyName
            } else {
              return ''
            }
          }
        }
      ],
      columns3: [
        {
          // 付款确认书编号
          prop: 'assetCode',
          align: 'left',
          label: this.$i18n.messages[this.$i18n.locale].confirmationRightData.payCode,
          format: (row) => {
            if (row.assetCode !== undefined) {
              return row.assetCode
            } else {
              return ''
            }
          }
        },
        {
          // 区域
          prop: 'coreAreaName',
          align: 'left',
          label: this.$i18n.messages[this.$i18n.locale].confirmationRightData.region,
          format: (row) => {
            if (row.coreAreaName !== undefined) {
              return row.coreAreaName
            } else {
              return ''
            }
          }
        },
        {
          // 项目公司名称
          prop: 'projectCompanyName',
          align: 'left',
          label: this.$i18n.messages[this.$i18n.locale].confirmationRightData.projectCompanyName,
          format: (row) => {
            if (row.projectCompanyName !== undefined) {
              return row.projectCompanyName
            } else {
              return ''
            }
          }
        }
      ],
      selectRList: [],
      selectLList: [],
      selectList: [],
      sourceData: [],
      sourceDataL: [],
      sourceDataR: [],
      sourceDataRTemp: []
    }
  },
  methods: {
    // 改变选择信息、日期
    selectChangeLocal (isAbs) {
      this.componentList[6].disabled = isAbs !== '1'
      if (this.componentList[6].disabled) {
        delete this.componentList[6].placeholder
        this.componentList[6].placeholder = ' '
      } else {
        this.componentList[6].placeholder = this.$i18n.messages[this.$i18n.locale].common.pleaseInput
      }
    },
    selectChange (obj, b, c) {
      if (obj.hasOwnProperty('projectIdInfo')) {
        if (obj.projectIdInfo && obj.projectIdInfo.keyId) {
          this.getTypeById(obj.projectIdInfo.keyId)
        } else {
          this.selectChangeLocal('1')
        }
      }
    },
    // 根据ID获取产品类别
    getTypeById (projectId) {
      componentsApi.productenterprise.getclassify({ projectId: projectId }).then(res => {
        var a = res.data ? res.data.productType : '2'
        this.selectChangeLocal(a)
      })
    },
    keySousuo () {
      let sourceDataRTemp = JSON.parse(JSON.stringify(this.sourceDataRTemp))
      if (!format.isNull(this.keyWordPlader) && this.keyWordPlader !== '') {
        let arr = []
        arr = sourceDataRTemp.filter(item => {
          // item.projectCompanyName = ''
          return (item.assetCode.indexOf(this.keyWordPlader) >= 0 || item.projectCompanyName.indexOf(this.keyWordPlader) >= 0)
        })
        this.sourceDataR = arr
      } else {
        this.sourceDataR = sourceDataRTemp
      }
    },
    onSaved () {
      if (this.editModel === 'C') {
        let data = {
          mergeRelDTOList: []
        }
        this.sourceDataR.forEach(it => {
          data.mergeRelDTOList.push({
            assetCode: it.assetCode,
            assetInfoId: it.keyId
          })
        })
        if (this.sourceDataR.length !== 0) {
          this.editSaveBtn = true
          this.api.create(data).then(res => {
            this.$emit('onSave')
            this.dialogVisible = false
          }).finally(() => {
            this.editSaveBtn = false
          })
        } else {
          this.warning(this.regMsg.confirmationRightData.pleaseCreateMerge)
        }
      } else if (this.editModel === 'E') {
        let mergeRelDTOList = []
        this.form.mergeRelDTOList.forEach(it => {
          if (this.sourceDataRTemp.some(it1 => it1.keyId === it.assetInfoId)) {
            mergeRelDTOList.push(it)
          }
        })
        this.sourceDataRTemp.forEach(it => {
          if (!mergeRelDTOList.some(it1 => it1.assetInfoId === it.keyId)) {
            mergeRelDTOList.push({
              assetCode: it.assetCode,
              assetInfoId: it.keyId
            })
          }
        })
        if (mergeRelDTOList.length !== 0) {
          let data = { keyId: this.form.keyId, mergeRelDTOList: mergeRelDTOList }
          console.log(data)
          this.editSaveBtn = true
          this.api.update(data).then(res => {
            this.$emit('onSave')
            this.dialogVisible = false
          }).finally(() => {
            this.editSaveBtn = false
          })
        } else {
          this.warning(this.regMsg.confirmationRightData.pleaseCreateMerge)
        }
        // this.form.assetInfoDTOList
        // if (this.sourceDataR.length !== 0) {
        //   let form = Object.assign({}, this.form)
        //   form.assetInfoMergeRelDtoList = this.sourceDataR
        //   this.api.update('', form).then(res => {
        //     this.$emit('onSave')
        //     this.dialogVisible = false
        //   })
        // } else {
        //   this.warning(this.regMsg.confirmationRightData.pleaseCreateMerge)
        // }
      }
    },
    setSourceDataRTemp () {
      this.sourceDataRTemp = JSON.parse(JSON.stringify(this.sourceDataR))
    },
    controlToLeft () {
      if (this.selectRList.length !== 0) {
        this.sourceDataL = [...this.sourceDataL, ...this.selectRList]
        this.sourceDataR = this.sourceDataR.filter(e => {
          return !this.selectRList.includes(e)
        })
        this.setSourceDataRTemp()
        this.selectRList = []
      } else {
        this.warning(`${this.$t('common.pleaseSelect')}${this.$t('confirmationRightData.dialogTableHeadR')}`)
      }
    },
    controlToRight () {
      if (this.selectLList.length !== 0) {
        if (this.isEdit) {
          let selectLList = JSON.parse(JSON.stringify(this.selectLList))
          if (this.checkControlToRight(this.sourceDataR, selectLList)) {
            this.sourceDataL = this.sourceDataL.filter(e => {
              return !this.selectLList.includes(e)
            })
            this.sourceDataR = [...this.sourceDataR, ...selectLList]
            this.setSourceDataRTemp()
            this.selectLList = []
          }
        } else {
          if (this.checkControlToRight(this.sourceDataR, this.selectLList, 'keyId')) {
            this.sourceDataL = this.sourceDataL.filter(e => {
              return !this.selectLList.includes(e)
            })
            this.sourceDataR = [...this.sourceDataR, ...this.selectLList]
            this.setSourceDataRTemp()
            this.selectLList = []
          }
        }
      } else {
        this.warning(`${this.$t('common.pleaseSelect')}${this.$t('confirmationRightData.dialogTableHeadL')}`)
      }
    },
    checkControlToRight (list, isList, type = 'keyId') {
      let listObj = {}
      let txt = ''
      list.forEach(v => {
        listObj[v[type]] = true
      })
      isList.forEach(v => {
        if (listObj[v[type]]) {
          txt += v.assetCode + ','
        }
      })
      if (txt === '') {
        return true
      } else {
        txt = txt.slice(0, -1)
        this.warning(`${this.$t('confirmationRightData.showdialogText1')}${txt}${this.$t('confirmationRightData.showdialogText2')}`)
        return false
      }
    },
    dels () {
      this.sourceData = this.sourceData.filter(e => {
        return !this.selectList.includes(e)
      })
    },
    selectRowChangeL (data) {
      this.selectLList = data
    },
    selectRowChangeR (data) {
      this.selectRList = data
    },
    selectRowChange (data) {
      this.selectList = data
    },
    // 查询
    handleFilter () {
      if (!this.UtilJs.isEmpty(this.queryParas.specialPlanPeriods) && !regExp.number.test(this.queryParas.specialPlanPeriods)) {
        return this.warning(this.$i18n.messages[this.$i18n.locale].expressDataList.specialPlanPeriodsCheck)
      }
      let requst = {}
      Object.keys(this.queryParas).forEach(it => {
        if (!this.UtilJs.isEmpty(this.queryParas[it])) {
          requst[it] = this.queryParas[it]
        }
      })
      this.queryParas.coreArea = []
      if (this.UtilJs.isEmpty(this.queryParas.coreAreaTemp)) {
        delete this.queryParas.coreArea
      } else {
        this.queryParas.coreAreaTemp.forEach(it => {
          this.queryParas.coreArea.push(it[1])
        })
      }
      if (format.isNull(requst.projectId)) {
        this.warning(this.regMsg.confirmationRightData.cepNameIsMerge)
      } else {
        this.$refs.dialogTable2.vLoading = true
        this.apiCreate.getList({
          ...requst
        }).then(res => {
          if (res.success) {
            let sourceDataL = res.data
            let arr = []
            if (sourceDataL.length !== 0) {
              if (this.isEdit) {
                arr = sourceDataL
                // sourceDataL.forEach(v => {
                //   let obj = {}
                //   if (!v.assetInfoDto) {
                //     obj.assetInfoDto = v
                //     obj.keyId = ''
                //     obj.payCode = v.payCode
                //     obj.assetInfoId = v.keyId
                //   } else {
                //     obj = v
                //   }
                //   arr.push(obj)
                // })
              } else {
                arr = sourceDataL
              }
            }
            sourceDataL = null
            this.sourceDataL = arr
          }
        }).finally(() => {
          this.$refs.dialogTable2.vLoading = false
        })
      }
    },
    // 清除查询条件
    clearParam () {
      this.queryParas = {
        // fileBussType: '1',
        isMerge: '0'
      }
      this.selectChangeLocal('1')
    },
    initData () {
      this.sourceDataL = []
      this.clearParam()
      if (this.isEdit) {
        let assetInfoMergeRelDtoList = this.form.assetInfoDTOList
        // let coreEnterpriseId = assetInfoMergeRelDtoList[0] ? assetInfoMergeRelDtoList[0].assetInfoDto.coreEnterpriseId : ''
        // let coreEnterpriseName = assetInfoMergeRelDtoList[0] ? assetInfoMergeRelDtoList[0].assetInfoDto.coreEnterpriseName : ''
        // this.$set(this.queryParas, 'coreEnterpriseId', coreEnterpriseId)
        // this.$set(this.queryParas, 'coreEnterpriseName', coreEnterpriseName)
        this.componentList.forEach(v => {
          // if (v.value === 'coreEnterpriseId' || v.value === 'isMerge') {
          //   v.disabled = true
          // }
        })
        this.sourceDataR = assetInfoMergeRelDtoList
        this.setSourceDataRTemp()
      } else {
        this.componentList.forEach(v => {
          // if (v.value === 'coreEnterpriseId' || v.value === 'isMerge') {
          //   v.disabled = false
          // }
        })
        this.sourceDataR = []
        this.setSourceDataRTemp()
      }
    },
    parentDialogVisible () {
      this.$nextTick(() => {
        this.sourceDataL = []
        this.sourceDataR = []
        if (this.dialogVisible) {
          if (!this.isEditDisable) {
            this.initData()
          } else {
            if (this.form.assetInfoDTOList.length !== 0) {
              // assetInfoDto
              this.sourceData = this.form.assetInfoDTOList
            }
          }
        }
        if (this.$refs.dialogTable2) {
          this.$refs.dialogTable2.vLoading = false
        }
        if (this.$refs.dialogTable1) {
          this.$refs.dialogTable1.vLoading = false
        }
      })
    }
  },
  watch: {
    // 处理期数输入框限制3位
    'queryParas.specialPlanPeriods' (n, o) {
      if (n && n.length > 3) {
        this.queryParas.specialPlanPeriods = o
      }
    }
  }
}
</script>

<style scoped lang="scss">
  @import '~@/styles/shourang/confirmationRightData/confirmationRightDataMergeList.scss';
</style>
