<!-- 项目公司共用文件接收 -->
<template>
  <div>
    <up-down-layout :headerVisible="false" :handleFlag.sync="handleFlag">
      <search-form @clearParam="clearParam" @handleFilter="handleFilter" @selectChanged="searchSelectChanged"
                   :menuCode="menuId" searchPerms="search" resetPerms="reset" :formValue.sync="queryParas"
                   :componentList="componentList" slot="query">
      </search-form>
      <template slot="table">
        <el-row>
          <el-col :span="24" style="text-align: right; height: 40px">
            <!--导出-->
            <btn-export btnSize="medium" templateCode="express04" :openPerms="true" :queryParas="materialList" :menuCode="menuId" perms="btn2Export"></btn-export>
            <!--导入-->
            <btn-import v-if="formTableData.sourceData.length > 0" btnSize="medium" :openPerms="true"
                        :menuCode="menuId" perms="btn2Import"
                        :uploadApi="importApi" style="margin-left: 10px;" @importSuccess="importSuccess"></btn-import>
            <el-dropdown :hide-on-click="false" trigger="click" class="ycDataTableDropdown" style="margin-left: 10px">
              <el-button size="medium" icon="iconfont iconycmore" class="ycMoreCss"></el-button>
              <el-dropdown-menu slot="dropdown">
                <template v-for="(column, index) in diandianCol">
                  <el-dropdown-item  :key="index">
                    <el-checkbox v-model="column.visible" @change="checkboxChange"
                                 :disabled="columnDisable[column.property]">{{column.title}}</el-checkbox>
                  </el-dropdown-item>
                </template>
              </el-dropdown-menu>
            </el-dropdown>
          </el-col>
        </el-row>
        <el-form :model="formTableData" ref="formTableData" :show-message="false">
          <vxe-grid
            border
            resizable
            show-overflow
            highlight-cell
            id="data-table"
            v-bind="elHeightObj"
            ref="xTable"
            class="vxeTable"
            v-loading="vLoading"
            :row-style="rowClassName"
            element-loading-text="拼命加载中"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(255, 255, 255, 1)"
            :columns="tableColumn"
            cell-class-name="common-table-cell"
            header-cell-class-name="common-table-header"
            :data="formTableData.sourceData"
            @checkbox-change="selectionData"
            @checkbox-all="selectionData">
          </vxe-grid>
        </el-form>
        <el-row style="margin-top: 10px">
          <el-col :span="24" style="text-align: center">
            <auth-button size="medium" type="primary" :label="$t('common.save')"
                         :menuCode="menuId" perms="btn2Save" :openPerms="true"
                         @click="save" :loading="saveLoading"></auth-button>
            <auth-button size="medium" type="primary" :label="$t('common.submit')"
                         :menuCode="menuId" perms="btn2Submit" :openPerms="true"
                         @click="submit" :loading="submitLoading"></auth-button>
          </el-col>
        </el-row>
      </template>
    </up-down-layout>
    <audit-mind-edit :visible.sync="auditMindVisible" editModel="E" :form="item"></audit-mind-edit>
    <import-result :visible.sync="importDialogVisible" :editModel="'E'" :form="importResultData" :typeLeiXin="typeLeiXin"></import-result>
  </div>
</template>

<script>
import BasePage from '@/pages/basePage'
import { upDownLayout, searchForm, DataTable, authButton, btnExport, btnImport,
  SelectProductName,
  SelectFinancialInstitutions, SelectSmallArea,
  SelectCoreEnterprise } from 'newepoch-components'
import SelectReceiver from '@/components/element/shourang/SelectReceiver'
import SelectDictionary from '@/components/element/shourang/SelectDictionary.vue'
import inputSweepCode from '@/components/element/shourang/inputSweepCode'
import { regExp } from '@/validator/index'
import expressApi from '@/api/expressApi'
import { IMPORT_API } from '@/constant'
import AuditMindEdit from '@/pages/shourang/expressFileReceive/auditMindEdit'
import SelectExpressName from '@/components/element/shourang/SelectExpressName'
import importResult from '@/pages/shourang/expressFileReceive/importResult'
import * as format from '@/filters/index.js'
import sysApi from '@/api/sysApi'
import fileApi from '@/api/fileApi'
import { downFile } from '@/utils/devUtils'
import mixin from '@/pages/mixin.js'
import tipsDatePicker from '@/components/element/shourang/tipsDatePicker'
export default {
  extends: new BasePage(),
  mixins: [mixin],
  components: {
    AuditMindEdit,
    upDownLayout,
    searchForm,
    DataTable,
    authButton,
    btnExport,
    btnImport,
    SelectDictionary,
    SelectReceiver,
    inputSweepCode,
    SelectExpressName,
    importResult
  },
  data () {
    return {
      typeLeiXin: '0',
      preQueryParas: {},
      columnDisable: {},
      diandianCol: [],
      importDialogVisible: false,
      importResultData: {},
      vLoading: false,
      isHeadWrite: false,
      headReceiverCode: '',
      // 保存校验多行、提交检验一行标志
      checkFlag: false,
      // 保存按钮等待
      saveLoading: false,
      // 提交按钮等待
      submitLoading: false,
      headData: {
        receiveCopies: '',
        origin: '',
        expressNumber: '',
        dataSource: ''
      },
      // expressForm: {
      //   expressNo: '',
      //   receptionNo: ''
      // },
      auditMindVisible: false,
      operateBtnLayout: '',
      // expressForm: '',
      formTableData: {
        sourceData: []
      },
      fromDataRules: {
        receiveCopies: [
          { required: true, validator: this.numberCheck, trigger: 'blur' }
        ],
        // 请选择资料来源
        assetSource: [
          { required: true, message: '', trigger: 'change' }
        ],
        expressNo: [
          { required: true, trigger: 'blur' }
        ],
        coreAreaAttache: [
          { required: true, message: '', trigger: 'change' }
        ]
      },
      importApi: IMPORT_API,
      // 导出
      materialList: {
        api: {
          sqlfig: []
        }
      },
      queryParas: {
        productIfsFallowAsset: '否',
        taskType: ['5'],
        keyWord: '',
        receiverId: '',
        receiveDate: [],
        receiveDateStart: '',
        receiveDateEnd: '',
        planningManagerId: '',
        accomplishSituation: '',
        coreArea: '',
        projectId: '',
        specialPlanPeriods: '',
        coreEnterpriseId: '',
        fileCode: []
      },
      selectedRows: [],
      componentList: [
        // 关键字
        {
          label: this.$i18n.messages[this.$i18n.locale].expressFileReceiveList.keyword,
          value: 'keyWord',
          placeholder: this.$i18n.messages[this.$i18n.locale].expressFileReceiveList.inputKeyword,
          componentName: 'el-input',
          labelWidth: '165px'
        },
        // 文件名称
        {
          label: this.$i18n.messages[this.$i18n.locale].expressFileReceiveList.fileName,
          value: 'fileCode',
          multiple: true,
          componentName: SelectExpressName,
          labelWidth: '165px'
        },
        // 接收人
        {
          label: this.$i18n.messages[this.$i18n.locale].expressFileReceiveList.receiver,
          value: 'receiverId',
          componentName: SelectReceiver,
          labelWidth: '165px',
          attrs: { isYongyou: true }
        },
        // 接收时间
        {
          label: this.$i18n.messages[this.$i18n.locale].expressFileReceiveList.receiveTime,
          value: 'receiveDate',
          componentName: tipsDatePicker,
          format: 'yyyy-MM-dd HH:mm:ss',
          startPlaceholder: '请选择',
          endPlaceholder: '请选择',
          type: 'datetimerange',
          labelWidth: '165px'
        },
        // 完成情况
        {
          label: this.$i18n.messages[this.$i18n.locale].expressFileReceiveList.completion,
          value: 'accomplishSituation',
          componentName: SelectDictionary,
          dictTypeCode: 'receive_completion',
          store: this.$store,
          labelWidth: '165px'
        },
        // 产品名称
        {
          label: this.$i18n.messages[this.$i18n.locale].common.productName,
          value: 'projectId',
          componentName: SelectProductName,
          labelWidth: '165px'
        },
        // 计划管理人/再保理银行
        {
          label: this.$i18n.messages[this.$i18n.locale].common.refactorBank,
          value: 'planningManagerId',
          queryName: 'projectId',
          queryValue: 'projectId',
          componentName: SelectFinancialInstitutions,
          labelWidth: '165px'
        },
        // 期数
        {
          label: this.$i18n.messages[this.$i18n.locale].common.periodsNum,
          value: 'specialPlanPeriods',
          placeholder: '请输入',
          queryName: 'projectId',
          queryValue: 'projectId',
          componentName: 'el-input',
          labelWidth: '165px'
        },
        // 核心企业
        {
          label: this.$i18n.messages[this.$i18n.locale].common.coreEnterprises,
          value: 'coreEnterpriseId',
          name: 'coreEnterpriseId',
          queryName: 'projectId',
          queryValue: 'projectId',
          componentName: SelectCoreEnterprise,
          labelWidth: '165px'
        },
        // 区域
        {
          label: this.$i18n.messages[this.$i18n.locale].common.area,
          value: 'coreArea',
          name: 'coreArea',
          queryName: 'coreCompanyId',
          queryValue: 'coreEnterpriseId',
          componentName: SelectSmallArea,
          labelWidth: '165px'
        }
      ],
      tableColumn: [
        { type: 'checkbox', align: 'center', width: 50, fixed: 'left' },
        // 核心企业
        {
          field: 'coreEnterpriseName',
          title: this.$i18n.messages[this.$i18n.locale].common.coreEnterprises,
          minWidth: '200px',
          align: 'left',
          headerAlign: 'center'
        },
        // 项目公司名称
        {
          field: 'debtor',
          title: this.$i18n.messages[this.$i18n.locale].expressFileReceiveList.projectCompanyName,
          minWidth: '200px',
          align: 'left',
          headerAlign: 'center'
        },
        // 区域
        {
          field: 'coreAreaName',
          title: this.$i18n.messages[this.$i18n.locale].common.area,
          minWidth: '200px',
          align: 'left',
          headerAlign: 'center'
        },
        // 文件名称
        {
          field: 'fileName',
          title: this.$i18n.messages[this.$i18n.locale].expressFileReceiveList.fileName,
          minWidth: '200px',
          align: 'left',
          headerAlign: 'center'
        },
        // 本次接收份数
        {
          field: 'copiesReceived',
          title: this.$i18n.messages[this.$i18n.locale].expressFileReceiveList.receiveCopies,
          minWidth: '200px',
          align: 'left',
          headerAlign: 'center',
          slots: {
            default: ({ row, rowIndex }) => {
              return [
                <el-form-item prop= {'sourceData.' + rowIndex + '.copiesReceived'} class="margin-bottom0"
                  rules= {this.ifCheck(row) || !this.checkFlag ? this.fromDataRules.receiveCopies : []}>
                  <el-input size="medium" v-model= {row.copiesReceived} maxlength="2" clearable={true} placeholder="请输入小于3位的正整数" oninput={(...a) => this.listenrInput(...a, rowIndex)}></el-input>
                </el-form-item>
              ]
            },
            header: ({ column }) => {
              return [
                <div style="text-align: center">
                  {this.$i18n.messages[this.$i18n.locale].expressFileReceiveList.receiveCopies}
                  <div class="el-input el-input--mini el-input--suffix">
                    <input size="mini" v-model= {this.headData.receiveCopies}
                      onchange= {() => this.headDataBlur(this.headData.receiveCopies, 'copiesReceived')}
                      placeholder="请输入小于3位的正整数" maxlength="2"  class="el-input__inner">
                    </input>
                  </div>
                </div>
              ]
            }
          }
        },
        // 任务类型
        {
          field: 'taskType',
          title: this.$i18n.messages[this.$i18n.locale].expressFileReceiveList.taskType,
          minWidth: '150px',
          align: 'left',
          headerAlign: 'center',
          formatter: ({ cellValue }) => {
            return this.formatTaskType('5')
          }
        },
        // 完成情况
        {
          field: 'accomplishSituation',
          title: this.$i18n.messages[this.$i18n.locale].expressFileReceiveList.completion,
          minWidth: '100px',
          align: 'center',
          headerAlign: 'center',
          formatter: ({ cellValue }) => {
            if (cellValue === '-1') return ''
            return format.formatDict(cellValue, 'receive_completion')
          }
        },
        // 资料来源
        {
          field: 'receiveSource',
          title: this.$i18n.messages[this.$i18n.locale].expressFileReceiveList.dataSource,
          minWidth: '200px',
          align: 'left',
          headerAlign: 'center',
          slots: {
            default: ({ row, rowIndex }) => {
              return [
                <el-form-item prop= {'sourceData.' +rowIndex + '.receiveSource'}
                  class="margin-bottom0" rules={this.ifCheck(row) || !this.checkFlag ? this.fromDataRules.assetSource : []}>
                  <select-dictionary name="receiveSource" v-model= {row.receiveSource}
                    dictTypeCode="receive_source"
                    onselectChanged= {(...aaa) => this.headDataChangeItem(...aaa, rowIndex)}>
                  </select-dictionary>
                </el-form-item>
              ]
            },
            header: ({ column }) => {
              return [
                <div style="text-align: center">
                  {this.$i18n.messages[this.$i18n.locale].expressFileReceiveList.dataSource}
                  <select-dictionary size="mini" dictTypeCode="receive_source"
                    v-model={this.headData.dataSource} onselectChanged= {this.headDataChange} name="receiveSource">
                  </select-dictionary>
                </div>
              ]
            }
          }
        },
        // 来源人
        {
          field: 'coreAreaAttache',
          title: this.$i18n.messages[this.$i18n.locale].expressFileReceiveList.origin,
          headerAlign: 'center',
          minWidth: '200px',
          align: 'left',
          slots: {
            default: ({ row, rowIndex }) => {
              let check = (row.receiveSource === '2' || row.receiveSource === '3' || row.receiveSource === '4')
              return [
                <el-form-item prop= {'sourceData.' + rowIndex + '.receiverId'}
                  class="margin-bottom0" rules={(check && this.ifCheck(rowIndex)) || !this.checkFlag ? this.fromDataRules.coreAreaAttache : []}>
                    <select-receiver v-model= {row.receiverId} onselectChanged= {(...aaa) => this.headDataChangeItem(...aaa, rowIndex)}
                    filterable={row.isWrite} allowCreate={row.isWrite} receiverCode={row.headReceiverCode} itemType={"H"} parQueryParas={row.assetInfoId}>
                  </select-receiver>
                </el-form-item>
              ]
            },
            header: ({ column }) => {
              return [
                <div style="text-align: center">
                  {this.$i18n.messages[this.$i18n.locale].expressFileReceiveList.origin}
                  <select-receiver size="mini" v-model= {this.headData.origin} onselectChanged= {this.headDataChange}
                    receiverCode={this.headReceiverCode} name="receiverId" filterable= {this.isHeadWrite} allowCreate= {this.isHeadWrite}>
                  </select-receiver>
                </div>
              ]
            }
          }
        },
        // 快递单号
        {
          field: 'expressNo',
          title: this.$i18n.messages[this.$i18n.locale].expressFileReceiveList.expressNumber,
          minWidth: '150px',
          align: 'left',
          headerAlign: 'center',
          slots: {
            default: ({ row, rowIndex }) => {
              return [
                <el-form-item prop={'sourceData.' + rowIndex + '.expressNo'} class="margin-bottom0"
                  rules={row.receiveSource === '1' && (this.ifCheck(row) || !this.checkFlag) ? this.fromDataRules.expressNo : []}>
                  <el-input size="medium" v-model= {row.expressNo} placeholder={row.receiveSource === '1' ? '输入快递单号' : ''} oninput={(...a) => this.listenrInput(...a, rowIndex)}></el-input>
                </el-form-item>
              ]
            },
            header: ({ column }) => {
              return [
                <div style="text-align: center">
                  {this.$i18n.messages[this.$i18n.locale].expressFileReceiveList.expressNumber}
                  <div class="el-input el-input--mini el-input--suffix">
                    <input size = "mini" v-model={this.headData.expressNumber}
                      onchange={() => this.headDataBlur(this.headData.expressNumber, 'expressNo')} class="el-input__inner"
                      clearable={true}>
                    </input>
                  </div>
                </div>
              ]
            }
          }
        },
        // 操作
        {
          field: 'operate',
          align: 'center',
          fixed: 'right',
          title: this.$i18n.messages[this.$i18n.locale].common.operate,
          headerAlign: 'center',
          minWidth: '150px',
          slots: {
            default: ({ row, rowIndex }) => {
              return [
                <div>
                  <auth-button size="small" class="iconCircle" icon="iconfont iconyijian"
                    title= {this.$t('expressFileReceiveList.auditMind')} onClick= {() => this.showAuditMind(row)}>
                  </auth-button>
                </div>
              ]
            }
          }
        }
      ]
    }
  },
  created () {
    this.$nextTick(() => {
      this.diandianCol = this.$refs.xTable.getColumns()
      this.diandianCol = this.diandianCol.slice(1, this.diandianCol.length)
      this.diandianCol.forEach(it => {
        this.$set(it, 'visible', true)
        this.$set(this.columnDisable, it.property, false)
      })
    })
  },
  computed: {
    api: function () {
      return expressApi.assetsfileReceiveApi
    }
  },
  methods: {
    checkboxChange () {
      let a = this.diandianCol.filter(it => it.visible)
      if (a.length === 1) {
        let field = a[0].property
        this.$set(this.columnDisable, field, true)
      } else {
        for (let key in this.columnDisable) {
          this.$set(this.columnDisable, key, false)
        }
      }
      this.$refs.xTable.refreshColumn()
    },
    listenrInput (...arg) {
      this.formTableData.sourceData[arg[1]].isModify = true
    },
    // 行修改
    rowClassName ({ $rowIndex, column, columnIndex, $columnIndex }) {
      if (this.formTableData.sourceData[$rowIndex].isModify) {
        return 'background: #FFDAB9; color: #000000'
      }
    },
    // 任务类型
    formatTaskType (value) {
      if (value && value === '5') {
        return '项目公司共用文件'
      } else {
        return ''
      }
    },
    // 是否拥有校验
    ifCheck (index) {
      let as = this.selectedRows.length !== 0 && this.selectedRows.some(it => it === index)
      return as
    },
    // 清除表格头输入
    clearHeadTitle () {
      this.headData = {
        receiveCopies: '',
        origin: '',
        expressNumber: '',
        dataSource: ''
      }
    },
    // 资料来源
    headDataChange (key, name, items, buff) {
      if (name === 'receiveSource') {
        this.$refs['formTableData'].clearValidate()
        // 自送
        this.isHeadWrite = items && (items.dictId === '5' || items.dictId === '1')
        this.$nextTick(() => {
          if (items) {
            this.headReceiverCode = items.dictId
          } else {
            this.headReceiverCode = ''
          }
          this.headData.origin = ''
          this.formTableData.sourceData.forEach(it => {
            this.$set(it, 'headReceiverCode', this.headReceiverCode)
            this.$set(it, 'receiveSource', this.headReceiverCode)
            this.$set(it, 'receiver', '')
            this.$set(it, 'receiverId', '')
            this.$set(it, 'isModify', true)
            this.$set(it, 'expressNo', '')
          })
        })
      } else if (name === 'receiverId') {
        this.formTableData.sourceData.forEach(it => {
          if (it.receiveSource !== '1' || it.receiveSource !== '5') {
            // this.$set(it, name, key)
            // this.$set(it, 'receiver', items ? items.nickName : '')
            if (key && !items) {
              this.$set(it, name, key)
              this.$set(it, 'receiver', key)
            } else {
              this.$set(it, name, key)
              this.$set(it, 'receiver', items ? items.nickName : '')
            }
          } else {
            this.$set(it, name, '')
            this.$set(it, 'receiver', '')
          }
          this.$set(it, 'isModify', true)
        })
      }
    },
    headDataChangeItem (...arg) {
      let val = arg
      let index = val[1] === 'receiveSource' ? val[4] : val[3]
      if (index !== -1) {
        if (val[1] === 'receiveSource') {
          this.$refs['formTableData'].clearValidate()
          if (!this.UtilJs.isEmpty(arg[2])) {
            this.$nextTick(() => {
              this.formTableData.sourceData[index].isWrite = val[2] && (val[2].dictId === '5' || val[2].dictId === '1')
              if (val[2]) {
                this.formTableData.sourceData[index].headReceiverCode = val[2].dictId
              } else {
                this.formTableData.sourceData[index].headReceiverCode = ''
              }
              if (!this.UtilJs.isEmpty(arg[0]) && !this.UtilJs.isEmpty(val[2])) {
                this.formTableData.sourceData[index].receiver = ''
                this.formTableData.sourceData[index].receiverId = ''
                this.formTableData.sourceData[index].isModify = true
                this.$set(this.formTableData.sourceData[index], 'expressNo', '')
              }
            })
          } else if (this.UtilJs.isEmpty(arg[0]) && this.UtilJs.isEmpty(val[2])) {
            this.formTableData.sourceData[index].receiver = ''
            this.formTableData.sourceData[index].receiverId = ''
            this.formTableData.sourceData[index].isModify = true
            this.$set(this.formTableData.sourceData[index], 'expressNo', '')
          }
        } else {
          if (!this.UtilJs.isEmpty(val[0]) && !this.UtilJs.isEmpty(val[2])) {
            this.formTableData.sourceData[index].isModify = true
            this.formTableData.sourceData[index].receiver = val[2].nickName
          } else if (!this.UtilJs.isEmpty(val[0]) && this.UtilJs.isEmpty(val[2])) {
            this.formTableData.sourceData[index].receiver = val[0]
          } else if (this.UtilJs.isEmpty(val[0]) && !this.UtilJs.isEmpty(val[2])) {
            this.formTableData.sourceData[index].receiver = val[2].nickName
          } else {
            this.formTableData.sourceData[index].isModify = true
            this.formTableData.sourceData[index].receiver = ''
          }
        }
      }
      // if (val[2]) {
      //   this.formTableData.sourceData[index].coreAreaAttacheName = val[2].nickName
      // } else {
      //   this.formTableData.sourceData[index].coreAreaAttacheName = ''
      // }
    },
    headDataBlur (...arg) {
      this.formTableData.sourceData.forEach(it => {
        this.$set(it, arg[1], arg[0])
        this.$set(it, 'isModify', true)
      })
      // this.formTableData.sourceData.forEach(it => {
      //   this.$set(it, str, data)
      // })
    },
    numberCheck (rule, value, callback) {
      if (!this.UtilJs.isEmpty(value) && regExp.number.test(value)) {
        return callback()
      }
      return callback(new Error(''))
    },
    clearParam () {
      this.queryParas = {
        productIfsFallowAsset: '否',
        taskType: ['5'],
        keyWord: '',
        receiverId: '',
        receiveDate: [],
        receiveDateStart: '',
        receiveDateEnd: '',
        planningManagerId: '',
        accomplishSituation: '',
        coreArea: '',
        projectId: '',
        specialPlanPeriods: '',
        coreEnterpriseId: '',
        fileCode: []
      }
    },
    // 查询
    handleFilter (queryParas) {
      if (this.UtilJs.isEmpty(queryParas)) {
        this.preQueryParas = JSON.parse(JSON.stringify(this.queryParas))
      }
      let a = queryParas || this.queryParas
      if (!this.UtilJs.isEmpty(a.coreEnterpriseId)) {
        if (a.receiveDate && a.receiveDate !== '') {
          a.receiveDateStart = new Date(a.receiveDate[0]).getTime()
          a.receiveDateEnd = new Date(a.receiveDate[1]).getTime()
          if (isNaN(a.receiveDateStart) || a.receiveDateStart === 0) delete a.receiveDateStart
          if (isNaN(a.receiveDateEnd) || a.receiveDateEnd === 0) delete a.receiveDateEnd
        }
        let queryParas = JSON.parse(JSON.stringify(a))
        // if ($this.UtilJs.isEmpty(queryParas.coreAreaName)) {
        //   queryParas.coreAreaName = queryParas.coreArea
        //   delete queryParas.coreArea
        // }
        this.getDataTable(queryParas)
        this.$nextTick(function () {
          this.$refs['formTableData'].clearValidate()
        })
      } else {
        this.warning('请选择核心企业')
      }
    },
    // 获取数据
    getDataTable (data) {
      this.vLoading = true
      this.clearHeadTitle()
      this.api.getList(data).then(res => {
        if (res.success && res.data) {
          this.selectedRows = []
          res.data.forEach(it => {
            if (!it.copiesReceived) it.copiesReceived = ''
          })
          this.getTableData(res.data)
        }
      }).finally(res => {
        this.vLoading = false
      })
    },
    // 导出数据获取
    getTableData (data) {
      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 ismodify = this.formTableData.sourceData.some(it => {
        return it.isModify === true
      })
      if (ismodify) {
        this.$confirm(this.$i18n.messages[this.$i18n.locale].expressDataList.ismodifySave, '提示', { type: 'warning' }).then(res => {
          this.getTableDataFun(data)
        })
      } else {
        this.getTableDataFun(data)
      }
    },
    getTableDataFun (data) {
      let dataList = this.copyData(data)
      dataList.forEach(it => {
        this.$set(it, 'headReceiverCode', it.receiveSource)
        it.isWrite = (it.receiveSource === '5' || it.receiveSource === '1')
        if (it.coreEnterpriseName === '万科') {
          it.sourcePerson = it.coreAreaBussUserName
        } else {
          it.sourcePerson = it.coreAreaAttache
        }
        // it.taskType = it.publishStatus = format.formatDict(it.taskType, 'task_type')
        // it.accomplishSituation = format.formatDict(it.accomplishSituation, 'receive_completion')
        // it.receiveSource = it.publishStatus = format.formatDict(it.receiveSource, 'receive_source')
      })
      this.materialList.api.sqlfig = this.copyData(data)
      this.materialList.api.sqlfig.forEach(it => {
        it.sourcePerson = it.receiver
        it.taskType = '项目公司共用文件'
        it.receiveSource = format.formatDict(it.receiveSource, 'receive_source')
        if (it.accomplishSituation.toString() === '-1') {
          it.accomplishSituation = ''
        } else {
          it.accomplishSituation = format.formatDict(it.accomplishSituation, 'receive_completion')
        }
      })
      this.formTableData.sourceData = dataList
    },
    // 深度拷贝
    copyData (data) {
      var obj = {}
      obj = JSON.parse(JSON.stringify(data))
      return obj
    },
    importSuccess (returnData) {
      let data = []
      returnData.forEach((item, index) => {
        let tempData = {
          coreEnterpriseName: item[1],
          debtor: item[2],
          fileName: item[3],
          copiesReceived: item[4],
          receiveCopies: item[4],
          fileSource: item[5],
          receiver: item[6],
          expressNo: item[7]
        }
        if (index < 2) return
        let datList = this.checkImport(tempData)
        data.push(datList)
        // if (flag) {
        //   tempData.index = index
        //   data.push(tempData)
        // } else {
        //   errDataList.push(tempData)
        // }
        // allData.push(tempData)
      })
      data.forEach(item => {
        if (item.isOk) {
          let it = item.tempData
          let temp = this.formTableData.sourceData.filter(it1 => it1.debtor === it.debtor && it1.fileName === it.fileName)
          temp.forEach(it1 => {
            let copiesReceived = 0
            copiesReceived = Number(it1.copiesReceived) + Number(it.receiveCopies)
            it1.copiesReceived = copiesReceived
            it1.receiveSource = this.getDictId(it.fileSource)
            it1.expressNo = it.expressNo
            it1.isModify = true
          })
        }
      })
      if (data.length > 0) {
        this.importResultData = Object.assign({}, { data: data })
        this.importDialogVisible = true
      }
    },
    checkImport (tempData) {
      let flag = true
      if (this.UtilJs.isEmpty(tempData.receiveCopies) || !regExp.number.test(tempData.receiveCopies) || Number(tempData.receiveCopies) >= 100) {
        flag = false
        tempData.failureReason = '接收份数必填并且不能超过两位正整数'
      } else if (this.UtilJs.isEmpty(tempData.debtor)) {
        flag = false
        tempData.failureReason = '项目公司名称不能为空'
      } else if (this.UtilJs.isEmpty(tempData.fileName)) {
        flag = false
        tempData.failureReason = '文件名称不能为空'
      } else if (this.UtilJs.isEmpty(tempData.fileSource)) {
        flag = false
        tempData.failureReason = '来源不能为空'
      } else if (!this.UtilJs.isEmpty(tempData.fileSource) && tempData.fileSource === '快递' && this.UtilJs.isEmpty(tempData.expressNo)) {
        flag = false
        tempData.failureReason = '来源为快递，则快递单号不能为空'
      }
      if (flag) {
        if (this.formTableData.sourceData.some(it1 => it1.debtor === tempData.debtor && it1.fileName === tempData.fileName)) {
          tempData.isTable = true
        } else {
          flag = false
          tempData.isTable = false
          tempData.failureReason = '该项目公司和文件名称不在表格中'
        }
      }
      return { isOk: flag, tempData: tempData }
    },
    getDictId (data) {
      if (data === '快递') {
        return '1'
      } else if (data === '保理专员') {
        return '2'
      } else if (data === '区域专员') {
        return '3'
      } else if (data === '业务人员') {
        return '4'
      } else if (data === '自送') {
        return '5'
      }
    },
    selectionData ({ records }) {
      this.selectedRows = records
    },
    // 保存按钮
    saveNext () {
      let $this = this
      this.$refs['formTableData'].validate((valid) => {
        if (valid) {
          // let flag = false
          let arr = []
          $this.formTableData.sourceData.forEach(it => {
            // if (it.receiveSource === '1') {
            //   it.expressNo = $this.expressForm.expressNo
            //   flag = true
            // }
            // if (!$this.UtilJs.isEmpty($this.expressForm.receptionNo)) {
            //   it.copiesReceived = $this.expressForm.receptionNo
            // }
            it.receiverId = $this.$store.getters.userId
            it.receiver = $this.$store.getters.nikeName
            let obj = Object.assign({}, it)
            obj.keyId = it.assetReceivingInfoId
            obj.assetMaterialDetailId = it.keyId
            arr.push(obj)
          })
          // if (flag && $this.UtilJs.isEmpty($this.expressForm.expressNo)) {
          //   $this.warning('请填写快递单号')
          //   return
          // }
          if (arr.length === 0) return
          this.saveLoading = true
          expressApi.assetsfileReceiveApi.batchSave(arr).then(res => {
            if (res.success && res.data) {
              $this.handleFilter(this.preQueryParas)
              $this.success('保存成功')
            } else {
              $this.error('保存失败')
            }
          }).finally(() => {
            this.saveLoading = false
          })
        } else {
          this.warning('请检查表格标红的数据是否正确')
          return false
        }
      })
    },
    save () {
      this.$refs['formTableData'].clearValidate()
      this.checkFlag = true
      this.$nextTick(() => {
        this.saveData()
      })
    },
    handData (data) {
      let postData = this.copyData(data)
      postData.forEach(it => {
        if (!it.receiverId || it.receiverId === '') it.receiverId = '-1'
        if (it.receiver === it.receiverId) it.receiverId = '-1'
      })
      // postData.forEach(it => {
      //   if (it.assetReceivingInfoDTOList.length === 0) {
      //     it.assetReceivingInfoDTOList.push({
      //       assetPoolId: it.assetPoolId,
      //       assetPoolMaterialGroupId: it.assetPoolMaterialGroupId,
      //       expressNo: it.expressNo,
      //       fileCode: it.fileCode,
      //       fileName: it.fileName,
      //       memo: it.memo,
      //       receiveCopies: it.receiveCopies,
      //       receiveDate: new Date().getTime(),
      //       receiveId: it.receiveId,
      //       receiveSource: it.receiveSource,
      //       receiver: it.receiver,
      //       receiverId: it.receiverId,
      //       submitTaskDate: new Date().getTime(),
      //       taskType: it.taskType
      //     })
      //   } else {
      //     it.assetReceivingInfoDTOList.forEach(it1 => {
      //       it1.assetPoolId = it.assetPoolId
      //       it1.assetPoolMaterialGroupId = it.assetPoolMaterialGroupId
      //       it1.expressNo = it.expressNo
      //       it1.fileCode = it.fileCode
      //       it1.fileName = it.fileName
      //       it1.memo = it.memo
      //       it1.receiveCopies = it.receiveCopies
      //       it1.receiveDate = new Date().getTime()
      //       it1.receiveId = it.receiveId
      //       it1.receiveSource = it.receiveSource
      //       it1.receiver = it.receiver
      //       it1.receiverId = it.receiverId
      //       it1.submitTaskDate = new Date().getTime()
      //       it1.taskType = it.taskType
      //     })
      //   }
      // })
      return postData
    },
    // 2020-3-20
    saveData () {
      let $this = this
      if (this.selectedRows.length > 0) {
        this.$refs['formTableData'].validate((valid) => {
          if (valid) {
            let postData = JSON.parse(JSON.stringify(this.handData(this.selectedRows)))// this.handData(this.formTableData.sourceData)
            this.saveLoading = true
            this.api.saveProjectAsset(postData).then(res => {
              if (res.success && res.data) {
                this.success('保存成功')
                this.formTableData.sourceData.forEach(it => {
                  it.isModify = false
                })
                $this.$nextTick(() => {
                  this.handleFilter(this.preQueryParas)
                })
              } else {
                this.error('保存失败')
              }
            }).finally(() => {
              this.saveLoading = false
            })
          } else {
            this.warning('请检查表格标红的数据是否正确')
            return false
          }
        })
      } else {
        this.warning('请选择要保存的数据')
      }
    },
    // 提交按钮
    submitNext () {
      let $this = this
      if (this.selectedRows.length > 0) {
        this.$refs['formTableData'].validate((valid) => {
          if (valid) {
            let arr = JSON.parse(JSON.stringify(this.handData(this.selectedRows)))// this.handData(this.selectedRows)
            if (arr.length === 0) return
            this.submitLoading = true
            this.api.submitProjectAsset(arr).then(res => {
              if (res.success && res.data) {
                $this.success('提交成功')
                this.formTableData.sourceData.forEach(it => { it.isModify = false })
                $this.$nextTick(() => {
                  this.handleFilter(this.preQueryParas)
                })
              } else {
                $this.error('提交失败')
              }
            }).finally(() => {
              this.submitLoading = false
            })
          } else {
            this.warning('请检查表格标红的数据是否正确')
            return false
          }
        })
      } else {
        this.warning('请选择要提交的数据')
      }
    },
    submit () {
      let ismodify = this.formTableData.sourceData.some(it => {
        return it.isModify === true
      })
      if (ismodify) {
        this.$confirm(this.$i18n.messages[this.$i18n.locale].expressDataList.ismodifySave, '提示', { type: 'warning' }).then(res => {
          this.$refs['formTableData'].clearValidate()
          this.checkFlag = true
          this.$nextTick(() => {
            this.submitNext()
          })
        })
      } else {
        this.$refs['formTableData'].clearValidate()
        this.checkFlag = true
        this.$nextTick(() => {
          this.submitNext()
        })
      }
    },
    showAuditMind (row) {
      this.item = Object.assign({}, row)
      this.auditMindVisible = true
    },
    // 导入数据错误导出事件
    creaFile (obj) {
      let $this = this
      sysApi.exportFileTemplate.createTemplate(obj, 'CREATE', 'shourangsql005').then(res => {
        if (res.success) {
          let returnData = {}
          returnData.fileId = res.data.keyId
          returnData.fileName = res.data.fileName
          fileApi.file.download({ keyId: res.data.keyId }).then(res => {
            $this.loading = false
            downFile(res, this.reName, this.inlineName)
          }).catch(function () {
            $this.loading = false
          })
        } else {
          $this.loading = false
          $this.error('导出失败')
        }
      }).catch(function () {
        $this.loading = false
      })
    },
    searchSelectChanged (a) {
      let keys = Object.keys(a)
      if (keys.some(it => it === 'coreEnterpriseIdInfo')) {
        this.$set(this.queryParas, 'coreArea', '')
      }
      // if (keys.some(it => it === 'coreAreaInfo')) {
      //   this.queryParas.coreAreaName = (a.coreAreaInfo && a.coreAreaInfo.areaName) || ''
      // }
    }
  },
  watch: {
    'queryParas.coreEnterpriseId' (val) {
      if (!val) {
        this.queryParas.coreArea = ''
      }
    },
    elHeightObj: {
      deep: true,
      immediate: true,
      handler (n, o) {
        this.$nextTick(() => {
          this.$refs.xTable.updateData()
        })
      }
    }
  }
}
</script>

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