<template>
<!-- 确权资料合并 -->
  <div>
    <up-down-layout :header="$t('confirmationRightData.title2')" :handleFlag.sync="handleFlag">
      <search-form :formValue.sync="queryParas"
                   searchPerms="search"
                   @handleFilter="coustomHandleFilter"
                   @clearParam="clearParam"
                   slot="query"
                   resetPerms="reset"
                   :menuCode="menuId"
                   class="component-width"
                   :componentList="componentList"></search-form>
      <template slot="table">
        <data-table :api="api" :deleteApi="api"
          :headTitle = "$t('confirmationRightData.tableHead2')"
          :showSelection="true"
          selectable="false"
          :columns="columns"
          :handleFlag.sync="handleFlag"
          :sourceData.sync="sourceData"
          :menuFlag="true"
          :queryParas="queryParas"
          :loadCount.sync="loadCount"
          :otherHeight="'240'"
          operateBtnLayout=""
          :IsRight="false"
          :pageAll="true"
          :operatWidth="'200'"
          v-bind="elHeightObj"
          @getTableData="getTableData"
          @selectRowChange="selectRowChange">
          <template slot="headButton">
            <div align="right">
              <!--新增-->
              <auth-button size="medium" type="primary" icon="iconfont iconxinzeng"
                           :menuCode="menuId" perms="btnCreate" :openPerms="true"
                           :label="$t('common.create')" @click="handleClick({}, 'C')"></auth-button>
              <!--删除-->
              <auth-button size="medium" type="danger" icon="iconfont iconshanchu"
                           :menuCode="menuId" perms="btnDels" :openPerms="true"
                           :label="$t('common.del')" @click="dels"></auth-button>
            </div>
          </template>
          <!-- 付款确认书相关信息 -->
          <template slot-scope="scope" slot="payConfInfo">
            <div>
              <expand-collapse :sourceData="sourceData" :colProp="'assetInfoDTOList'"
                               :valueProp="'assetAll'" :rowIndex="scope.data.$index"></expand-collapse>
            </div>
          </template>
          <template slot-scope="scope" slot="mergeTime">
            {{handlemergeTime(scope.data.row)}}
          </template>
          <template slot-scope="scope" slot="mergerName">
            {{handlemergerName(scope.data.row)}}
          </template>
          <!-- 操作 -->
          <el-table-column align="center" :label="$t('common.operate')" width="280">
            <template slot-scope="scope">
              <!--编辑-->
              <auth-button size="small" class="iconCircle" icon="iconfont iconbianji"
                           :menuCode="menuId" perms="btnEdit" :openPerms="true"
                           :title="$t('common.edit')" @click="handleClick(scope.row, 'E')"></auth-button>
              <auth-button size="small" class="iconCircle" icon="iconfont iconchakan"
                           :menuCode="menuId" perms="btnShow" :openPerms="true"
                           :title="$t('common.view')" @click="handleClick(scope.row, 'V')"></auth-button>
              <auth-button size="small" class="iconCircle" icon="iconfont iconxiazai" :title="$t('common.downLoad')"
                           :menuCode="menuId" perms="btnDownload" :openPerms="true"
                           v-if="scope.row.mergeFileDTOList && scope.row.mergeFileDTOList.length > 0"
                           @click="handleClick(scope.row, 'DL')" :loading="scope.row.downLoading"></auth-button>
              <auth-button size="small" class="iconCircle" icon="iconfont iconf"
                           :menuCode="menuId" perms="btnAreaMeger" :openPerms="true"
                           :title="$t('confirmationRightData.areaMerge')" @click="handleClick(scope.row, 'AM')" :loading="scope.row.downLoadingAM"></auth-button>
              <auth-button size="small" class="iconCircle" icon="iconfont iconhebing"
                           :menuCode="menuId" perms="btnProjectMerge" :openPerms="true"
                           :title="$t('confirmationRightData.projectMerge')" @click="handleClick(scope.row, 'PM')" :loading="scope.row.downLoadingPM"></auth-button>
            </template>
          </el-table-column>
        </data-table>
      </template>
    </up-down-layout>
    <confirmation-right-data-merge-edit :editModel="editModel" :form="item" :visible.sync="visible" :menuCode="menuId"
                                        :menuId="menuId" :regMsg="regMsg" @onSave="handleFilter" ref="edit"></confirmation-right-data-merge-edit>
  </div>
</template>
<script>
import { searchForm, upDownLayout, DataTable, authButton, SelectProjectCompanyName, SelectAreaCommissioner, ExpandCollapse } from 'newepoch-components'
import BasePage from '@/pages/basePage'
import SelectArea from '@/components/element/enterpriseInfoManage/SelectArea'
import confirmationRightDataMergeEdit from '@/pages/shourang/confirmationRightData/confirmationRightDataMergeEdit.vue'
import * as format from '@/filters/index'
import fileApi from '@/api/fileApi'
import { downFile } from '@/utils/devUtils'
import confirmationRightDataApi from '@/api/confirmationRightDataApi'
import mixin from '@/pages/mixin'
export default {
  extends: new BasePage(),
  mixins: [mixin],
  name: 'confirmationRightDataMerge',
  components: {
    searchForm,
    upDownLayout,
    DataTable,
    authButton,
    confirmationRightDataMergeEdit,
    ExpandCollapse
  },
  data () {
    return {
      reload: true,
      formatDate: format.formatDate,
      payConfInfoLen: 3,
      editModel: 'V',
      templateCode: '',
      handleFlag: true,
      visible: false,
      forceAllFiles: false,
      loadCount: 0,
      queryParas: {
        fileBussType: '1'
      },
      item: {},
      componentList: [
        {
          // 付款确认书编号
          label: this.$i18n.messages[this.$i18n.locale].confirmationRightData.payCode,
          disabled: false,
          value: 'assetCode',
          labelWidth: '120px',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseInput,
          clearable: true,
          componentName: 'el-input'
        },
        {
          // 区域
          label: this.$i18n.messages[this.$i18n.locale].confirmationRightData.region,
          value: 'areaId',
          componentName: SelectArea,
          labelWidth: '120px',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseSelect,
          multiple: true,
          filterable: true
        },
        {
          // 区域编号
          label: this.$i18n.messages[this.$i18n.locale].confirmationRightData.regionCode,
          value: 'regionCode',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseSelect,
          labelWidth: '120px',
          componentName: 'el-input'
        },
        {
          // 项目公司名称
          label: this.$i18n.messages[this.$i18n.locale].confirmationRightData.projectCompanyName,
          disabled: false,
          value: 'projectCompanyId',
          clearable: true,
          labelWidth: '120px',
          componentName: SelectProjectCompanyName,
          multiple: true
        },
        {
          // 区域专员
          label: this.$i18n.messages[this.$i18n.locale].confirmationRightData.regionAttache,
          value: 'coreAreaAttache',
          componentName: SelectAreaCommissioner,
          labelWidth: '120px',
          reload: this.reload,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseSelect,
          multiple: true
        }
      ],
      columns: [
        // 付款确认书相关信息
        {
          prop: 'payConfInfo',
          align: 'left',
          label: this.$i18n.messages[this.$i18n.locale].confirmationRightData.payConfInfo,
          width: '570px',
          slot: true
        },
        // 合并时间
        {
          prop: 'mergeTime',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].confirmationRightData.mergeTime,
          width: '140px',
          slot: true
        },
        // 合并人
        {
          prop: 'mergerName',
          align: 'left',
          label: this.$i18n.messages[this.$i18n.locale].confirmationRightData.merger,
          width: '140px',
          slot: true
        }
      ],
      sourceData: [],
      selectRows: []
    }
  },
  computed: {
    apiDownload () {
      return confirmationRightDataApi.confirmationRightData
    },
    api () {
      return confirmationRightDataApi.confirmationRightData
    },
    confirmationRightDataMerge () {
      return confirmationRightDataApi.confirmationRightDataMerge
    }
  },
  // mounted () {
  //   // this.loadCount = this.loadCount + 1
  //   this.handleFilter()
  // },
  methods: {
    // 数据获取到
    getTableData (data) {
      let localData = JSON.parse(JSON.stringify(data))
      localData.forEach(it => {
        it.assetInfoDTOList.forEach(it1 => {
          let assetAll = `${it1.assetCode}` + '-' + `${it1.coreAreaName}` + '-' + `${it1.regionCode}` + '-' + `${it1.projectCompanyName}` + '-' + (`${it1.coreAreaAttacheName || []}`)
          this.$set(it1, 'assetAll', assetAll)
        })
      })
      this.sourceData = localData
    },
    // 处理合并时间
    handlemergeTime (data) {
      return data.mergeFileDTOList[0] ? format.formatDateTpcModify(data.mergeFileDTOList[0].mergeTime) : ''
    },
    // 处理合并人
    handlemergerName (data) {
      return data.mergeFileDTOList[0] ? data.mergeFileDTOList[0].mergerName : ''
    },
    // 处理数据
    getAMdList (list, index, flNo = 10, fileIded = true) {
      let arr = []
      if (Array.isArray(list) && list.length !== 0) {
        if (fileIded) {
          arr = list.filter(item => item.assetMaterialDetailFileDTOList[0] ? item.assetMaterialDetailFileDTOList[0].fileId : false)
        } else {
          arr = list
        }
        if (!this.sourceData[index].isOpen && arr.length > flNo) {
          arr = arr.slice(0, flNo)
        }
      }
      return arr
    },
    clearParam () {
      this.queryParas = {
        pageIndex: 1,
        fileBussType: '1',
        pageSize: 10
      }
    },
    handleClick (row, editModel) {
      let mergeFn = (mergeType) => {
        let assetInfoIdList = []
        row.assetInfoDTOList.forEach(it => {
          assetInfoIdList.push(it.keyId)
        })
        let data = { mergeType: mergeType, assetInfoIdList: assetInfoIdList, keyId: row.keyId }
        this.confirmationRightDataMerge.merge(data).then(res => {
          if (res.data) {
            this.success(this.regMsg.confirmationRightData.mergeSuccess)
            this.handleFilter()
          } else {
            this.success(this.regMsg.confirmationRightData.mergeFail)
          }
        }).finally((res) => {
          if (mergeType === 1) {
            this.$set(row, 'downLoadingAM', false)
          } else if (mergeType === 2) {
            this.$set(row, 'downLoadingPM', false)
          }
          this.coustomHandleFilter()
        })
      }
      switch (editModel) {
        case 'V':
        case 'C':
        case 'E':
          this.editModel = editModel
          this.item = Object.assign({}, row)
          this.visible = true
          this.$refs['edit'].parentDialogVisible()
          break
        case 'DL':
          // 下载
          this.downloadRow(row)
          break
        case 'AM':
          // 区域合并
          this.$set(row, 'downLoadingAM', true)
          mergeFn(1)
          break
        case 'PM':
          // 项目公司合并
          this.$set(row, 'downLoadingPM', true)
          mergeFn(2)
          break
        default:
          break
      }
    },
    // 单个下载
    beforeBtchDownload (data, flieid, index) {
      fileApi.file.downloadByUUID({ uuid: flieid }).then(res => {
        downFile(res)
      }).finally(res => {
        if (index) {
          this.$set(data, 'downLoading', false)
        }
      })
    },
    downloadRow (row) {
      if (row.mergeFileDTOList && row.mergeFileDTOList.length !== 0) {
        let fileIds = []
        row.mergeFileDTOList.forEach(v => {
          fileIds.push(v.fileId)
        })
        this.$set(row, 'downLoading', true)
        fileIds.forEach((it, index) => {
          this.beforeBtchDownload(row, it, index === (fileIds.length - 1))
        })
        // this.apiDownload.download({
        //   fileBussType: '1',
        //   assetInfoIds,
        //   fileIds
        // }).then(res => {
        //   if (res.success) {
        //     if (res.data) {
        //       fileApi.file.batchDownloadList({ uuid: res.data }).then(res => {
        //         downFile(res)
        //       })
        //     } else {
        //       this.warning(this.regMsg.confirmationRightData.noDownLoadList)
        //     }
        //   } else {
        //     this.warning(this.regMsg.confirmationRightData.downLoadFail)
        //   }
        // })
      } else {
        this.warning(this.regMsg.confirmationRightData.downloadFileIds)
      }
    },
    selectRowChange (selectRows) {
      this.selectRows = selectRows
    },
    // 删除
    dels () {
      if (this.selectRows.length !== 0) {
        this.$confirm(this.regMsg.confirmationRightData.confirmTitle, this.$i18n.messages[this.$i18n.locale].common.tip, {
          type: 'warning'
        }).then(() => {
          let ids = []
          this.selectRows.forEach(it => {
            ids.push(it.keyId)
          })
          this.confirmationRightDataMerge.dels({ ids }).then(res => {
            if (res.data) {
              this.success(this.regMsg.confirmationRightData.delsSuccess)
              this.handleFilter()
            }
          })
        })
      } else {
        this.warning(this.regMsg.confirmationRightData.checklistMsg)
      }
    },
    coustomHandleFilter () {
      this.queryParas.coreArea = []
      if (this.UtilJs.isEmpty(this.queryParas.areaId)) {
        delete this.queryParas.coreArea
      } else {
        this.queryParas.areaId.forEach(it => {
          this.queryParas.coreArea.push(it[1])
        })
      }
      // let queryParas = this.queryParas
      // if (queryParas.areaId) {
      //   this.queryParas.factoringStartDate = queryParas.areaId[0]
      //   this.queryParas.factoringExpirationDate = queryParas.areaId[1]
      // } else {
      //   if (this.queryParas.factoringStartDate) {
      //     delete this.queryParas.factoringStartDate
      //   }
      //   if (this.queryParas.factoringExpirationDate) {
      //     delete this.queryParas.factoringExpirationDate
      //   }
      //   delete this.queryParas.accrualDate
      // }
      this.handleFilter()
    }
  }
}
</script>
<style scoped lang="scss">
  @import '~@/styles/shourang/confirmationRightData/confirmationRightDataMergeList.scss';
</style>
