<template>
  <div>
    <!-- 批量下载资料 -->
    <dialog-edit ref="dialogEdit" :visible.sync="dialogVisible" :form="form" :autoSave="autoSave"
     label-position="left"
      :editModel="editModel" :appendToBody="appendToBody" :title="headerTitle"
      @onSaved="handleSubmit" :loading="loading" :saveLabel="$t('common.downLoad')">
        <!-- 下载范围 -->
        <el-form-item :label="$t('feedBackMain.downloadType')" label-width="110px">
          <el-radio-group v-model="forms.downloadFlag">
            <el-radio label="1">{{$t('feedBackMain.customiseAsset')}}</el-radio>
            <el-radio label="2">{{$t('feedBackMain.allSampleFiles')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-collapse-transition>
          <div v-show="forms.downloadFlag == '1'">
            <el-form ref="form" :model="queryParas" :rules="rules" label-width="110px" label-position="left">
                <el-form-item :label="$t('feedBackMain.assetCode')" prop="assetCode" label-position="left">
                  <el-row :gutter="10">
                    <el-col :span="4">
                      <el-input :placeholder="$t('common.pleaseInput')+$t('feedBackMain.assetCode')" v-model="queryParas.assetCode" :clearable="true" maxLength="50"></el-input>
                    </el-col>
                    <el-col :span="10">
                      <auth-button size="medium" :classType="true" icon="iconfont iconycchaxun" :label="$t('common.search')" type="primary" @click="handleFilter"></auth-button>
                      <btn-upload fileType=".xlsx,.xls" :uploadApi="uploadApi" type="primary" :btnSize="'medium'" :uploadName="$t('feedBackMain.importList')" @uploadSuccess="importAsset" style="margin-left:10px"></btn-upload>
                    </el-col>
                  </el-row>
                </el-form-item>
            </el-form>
            <el-row type="flex" justify="space-between">
              <el-col :span="11" style="overflow-x:scroll">
                  <external-transition :title="$t('feedBackMain.unChoosed')">
                    <template #button>
                        <auth-button #button size="medium" icon="iconfont iconxinzeng" :classType="true" :label="$t('feedBackMain.addNew')" type="primary" @click="handleToggle(0)"></auth-button>
                    </template>
                  </external-transition>
                  <data-table ref="dataTable" :api="api" v-bind="{height:'300px'}" :queryParas="queryParas" :showSelection="true" :columns="modifyColumns" :loadCount.sync="loadCount" :sourceData.sync="sourceDataOne" :selectedRows.sync="selectedRowsOne"></data-table>

              </el-col>
              <el-col :span="11" style="overflow-x:scroll">
                  <external-transition :title="$t('feedBackMain.Choosed')">
                    <template #button>
                        <auth-button #button size="medium" icon="iconfont iconquxiao" :classType="true" :label="$t('feedBackMain.cancelChoose')" type="primary" @click="handleToggle(1)"></auth-button>
                    </template>
                  </external-transition>
                  <data-table ref="dataTable" v-bind="{height:'300px'}" :queryParas="queryParas" :showSelection="true" :columns="modifyColumns" :sourceData.sync="sourceData" :selectedRows.sync="selectedRowsTwo" @sizeChange="sizeChange" @currentChange="sizeChange"></data-table>
                  <!-- <data-table v-bind="{height:'300px'}" :showSelection="true" :columns="modifyColumns" :sourceData.sync="sourceDataTwo" :selectedRows.sync="selectedRowsTwo"></data-table> -->
              </el-col>
            </el-row>
          </div>
      </el-collapse-transition>
    </dialog-edit>
    <!-- 导出结果 -->
    <!-- <dialog-form :attr="{width:'500px'}" :visible.sync="isExport" editModel="E" :form="exportResult" :autoSave="false" :isExport="true">
    </dialog-form> -->
  </div>
</template>

<script>
import BaseEdit from '@/pages/baseEditPage'
import dialogForm from '@/components/element/assetoutfeedback/dialogForm'
import externalTransition from '@/components/element/assetoutfeedback/externalTransition'
import {
  DialogEdit,
  DataTable,
  btnUpload,
  validate,
  authButton
} from 'newepoch-components'
import feedBackMain from '@/api/assetoutfeedback/feedBackMain/feedBackMain.js'
import {
  downFile
} from '@/utils/devUtils'
import { UPLOAD_API } from '@/constant.js'

export default {
  extends: new BaseEdit(),
  name: 'sampleFileDownBatchPop',
  components: {
    DialogEdit,
    DataTable,
    dialogForm,
    authButton,
    btnUpload,
    externalTransition
  },
  props: {
    autoSave: {
      type: [Boolean],
      default: false
    },
    headerTitle: {
      type: [String],
      default: ''
    }
  },
  data () {
    return {
      uploadApi: UPLOAD_API,
      chooseIndex: '', // 选中项索引值
      appendToBody: true,
      toolMenuFlag: true,
      loadCount: 0,
      menuFlag: false,
      operateBtnLayout: '',
      loading: false, // 加载控件
      loadingFlag: false, // 加载动画控件
      // isExport: false, // 导入控件
      exportResult: {}, // 导入结果
      // exportStatus: false, // 导入状态
      queryParas: {
        pageIndex: 1,
        pageSize: 10,
        assetCode: '',
        // feedbackResource: '10',
        auditFileType: '1001'
      },
      forms: {
        downloadFlag: '1'
      },
      rules: {
        assetCode: [{ validator: validate.payNumValidate, trigger: 'blur' }]
      },
      // 待选择资产
      sourceDataOne: [],
      // 选中待选择资产
      selectedRowsOne: [],
      // 已选择资产
      sourceDataTwo: [],
      // 选中已选择资产
      selectedRowsTwo: [],
      // 表头
      modifyColumns: [
        // 付款确认书编号
        {
          prop: 'assetCode',
          align: 'center',
          sortable: true,
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].sendLoanInfo.payCode,
          width: '160px'
        }
      ]
    }
  },
  computed: {
    api () {
      return feedBackMain.spasset
    },
    sourceData: {
      get: function () {
        return this.exportStatus ? this.sourceDatas() : this.sourceDataTwo
      },
      set: function (e) {}
    }
  },
  methods: {
    // 获取当前页资产（导入清单）
    sourceDatas () {
      let pageSize = this.queryParas.pageSize
      let pageIndex = this.queryParas.pageIndex
      let source = this.sourceDataTwo.map(item => { return item }) // 总数
      let start = (pageIndex - 1) * pageSize // 当前显示数
      let resounce = source.length - start // 剩余数
      let datas = source.splice(start, resounce < pageSize ? resounce : pageSize)
      return datas
    },
    // 资产去重
    filterArray (a, b) {
      for (let index in b) {
        let item = b[index]
        for (let index2 in a) {
          let item2 = a[index2]
          if (item.keyId === item2.keyId) {
            a.splice(index2, 1)
            index2--
          }
        }
      }
    },
    // 数组对象去重
    filterArraySelf (a, b) {
      let obj = {}
      a = a.concat(b).reduce((item, next) => {
        if (!obj[next.keyId]) {
          obj[next.keyId] = true
          item.push(next)
        }
        return item
      }, [])
      return a
    },
    // 导入清单
    importAsset (e) {
      let args = Object.assign({
        keyId: e.fileID.toString()
      }, this.UtilJs.cloneDeep(this.queryParas))
      delete args.assetCode
      delete args.auditFileType
      delete args.pageIndex
      delete args.pageSize
      feedBackMain.exports.getDefault(args).then(res => {
        if (res.success && res.data && res.data.length > 0) {
          // 打开导入结果
          // this.exportResult = res.data.sampleAssetReturnInfoDTO
          // this.isExport = true
          // 成功数大于0
          // if (res.data.sampleAssetReturnInfoDTO.success > 0) {
          //   this.exportStatus = true
          this.sourceDataTwo = this.sortAssets(res.data)
          this.sizeChange()
          setTimeout(() => {
            this.success(this.$t('feedBackMain.importSuccess'))
          }, 300)
          // } else {
          //   setTimeout(() => {
          //     this.error(this.$t('feedBackMain.importFaile'))
          //   }, 300)
          // }
        } else {
          this.error(this.$t('feedBackMain.importFaile'))
        }
      })
    },
    // 排序资产编号
    sortAssets (data) {
      return data.sort((a, b) => {
        return a.assetCode > b.assetCode ? 1 : -1
      })
    },
    // 添加/取消选择
    handleToggle (type) {
      let selectedRows = [this.selectedRowsOne, this.selectedRowsTwo][type]
      let sourceDataSelf = [this.sourceDataOne, this.sourceDataTwo][type]
      if (selectedRows.length > 0) {
        // 添加到已选择
        if (!type) {
          this.sourceDataTwo = this.sortAssets(this.filterArraySelf(this.sourceDataTwo, selectedRows))
        } else {
          // this.sourceDataOne = this.filterArraySelf(this.sourceDataOne, selectedRows)
          this.filterArray(sourceDataSelf, selectedRows)
        }
        this.queryParas.pageIndex = 1
        this.sizeChange()
      } else {
        this.warning(this.$t('common.selectOperateTip'))
      }
    },
    // 查询
    handleFilter () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.exportStatus = false
          this.$nextTick(() => {
            this.loadCount++
          })
        }
      })
    },
    // 下载
    handleSubmit () {
      // 根据下载类型配置参数
      let args = Object.assign(this.UtilJs.cloneDeep(this.queryParas), this.UtilJs.cloneDeep(this.forms))
      delete args.pageIndex
      delete args.pageSize
      delete args.assetCode
      this.loading = true
      if (this.forms.downloadFlag === '1') {
        if (this.sourceDataTwo.length > 0) {
          args.assetCodes = this.sourceDataTwo.map(item => { return item.assetCode })
        } else {
          this.loading = false
          this.warning(this.$t('feedBackMain.noFiles'))
          return
        }
      }
      // 请求文件Id并下载
      feedBackMain.spasset.getList(args).then(res => {
        if (res.success && res.data.fileMakerDTOList && res.data.fileMakerDTOList.length > 0) {
          feedBackMain.compressDownload.getFile(res.data).then(ress => {
            //   fileApi.file.downloadByUUID({
            //     uuid: res.data,
            //     encoding: 'utf-8'
            //   }, '{Encoding}').then(ress => {
            this.loading = false
            // downFile(ress, this.$t('feedBackMain.sampleFile'))
            downFile(ress)
            //   }).catch(res => {
            //     this.loading = false
            //   })
          }).catch(res => {
            this.loading = false
          })
        } else {
          this.loading = false
          this.warning(this.$t('feedBackMain.noFiles'))
        }
      }).catch(res => {
        this.loading = false
      })
    },
    sizeChange () {
      // if (this.exportStatus) {
      this.$nextTick(() => {
        this.$refs.dataTable.buildTableData(this.sourceDatas(), this.sourceDataTwo.length)
      })
      // }
    }
  },
  watch: {
    visible (val) {
      if (val) {
        // 初始化
        this.forms.downloadFlag = '1'
        this.queryParas.assetCode = ''
        this.exportStatus = false
        this.sourceDataOne = []
        this.sourceDataTwo = []
        this.queryParas = Object.assign(this.queryParas, this.form)
        this.sizeChange()
      }
    }
  },
  mounted () {
  }
}
</script>
