<template>
        <!--区域专员任务台项目公司资料补寄页面-->
        <dialog-edit
                :visible.sync="dialogVisible"
                :title="$t('traceMgr.projectCompanyInformationRepost')"
                center="center"
                :autoSave="false"
                @onSaved="confirmOpen"
                :appendToBody="true"
                :editModel="'U'"
                :form="dialogForm"
                :api="dialogApi"
                autoClose
                @close="handleClose"
                :saveLabel="$t('common.complete')"
                :before-close="closeDialog">
            <!--订单信息-->
            <el-row>
                <el-tabs>
                    <el-tab-pane :label="$t('traceMgr.orderInfo')"></el-tab-pane>
                </el-tabs>
                <payment-info :keyId="assetInfoId" :titleShow="false" :title="$t('traceMgr.orderInfo')"></payment-info>
            </el-row>

            <el-row class="textRight marginBottom">
                <auth-button type="primary" size="medium" :label="$t('traceMgr.downloadingData')" @click="fileDownLoadVisible" class="iconfont iconycxiazai"></auth-button>
                <auth-button type="primary" :label="$t('common.save')" size="medium" @click="save" :loading="isLoading" class="iconfont iconbaocun11"></auth-button>
            </el-row>

            <!--资料补寄 第n次补寄-->
            <el-row>
                <el-tabs>
                    <el-tab-pane :label="$t('traceMgr.informationRepost') + ' ' +$t('traceMgr.no') + titleData.num + $t('traceMgr.sendBack')"></el-tab-pane>
                </el-tabs>

                <!--数据列表-->
                <file-list @selectRowChange="selectRowChange" :loadingFlag="tableLoading" :sourceData="returnDate" :supplierId="supplierId" :bpmId="bpmId" :assetCode="assetCode" :instanceId="instanceId"  :assetInfoId="assetInfoId" :initData="dialogVisible"></file-list>

                <!--话术-->
                <el-col class="marginTop">
                    <!--输入框-->
                    <el-row >
                        <el-col :span="1" class="text-center">
                            <span>{{$t('traceMgr.wordsTechnique')}}</span>
                        </el-col>
                        <el-col :span="12">
                            <speech-craft-input v-loading="speechCraftLoading" v-model="content" :defaultSpeechFlag="false" @defaultSpeech="setDefaultSpeech" :defaultSpeechLabel="$t('common.resetWordsTechnique')"></speech-craft-input>
                        </el-col>
                    </el-row>
                </el-col>
            </el-row>
            <business-file-download-dialog :closeDownBatch="closeDownBatch"
                                           :form="downloadForm"
                                           :visible.sync="downloadVisible"
                                           :editModel="'V'"
                                           :api="downloadApi">
            </business-file-download-dialog>
            <DialogEdit :saveLabel="$t('traceMgr.sure')"
                        :closeLabel="$t('approval.cancel')"
                        editModel="E"
                        :form="{}"
                        :visible.sync="isConfirm"
                        @onSaved="submit"
                        :loading="saveLoading"
                        :title="$t('common.tip')"
                        width="35%"
                        appendToBody
                        :autoSave="false"
                        :close-on-click-modal="false"
                        class="el-dialog--center">
                <p class="text-center">{{$t('common.submitConfirm')}}</p>
            </DialogEdit>
        </dialog-edit>
</template>

<script>

import { DialogEdit, dymForm, paymentInfo, speechCraftInput, DataTable, authButton, btnDownload } from 'newepoch-components'

import fileList from './fileList'
import businessFileDownloadDialog from '@/components/tracemgr/common/businessFileDownloadDialog'
import tracemgrApi from '@/api/tracemgrApi'
export default {
  name: 'taskDialog',

  components: {
    DialogEdit,
    dymForm,
    paymentInfo,
    fileList,
    businessFileDownloadDialog,
    tracemgrApi,
    speechCraftInput,
    DataTable,
    authButton,
    btnDownload
  },

  data () {
    return {
      selecteData: [],
      tableLoading: false,
      // 提交禁用
      submitDisabled: false,
      // 保存禁用
      saveDisabled: false,
      factoringCommissioner: '',
      factoringPhoneNumber: '',
      regionalCommissioner: '',
      regionalPhoneNumber: '',
      regionalTelephone: '',
      speechCraftLoading: false,
      debtor: '',
      creditor: '',
      factoringMoney: '',
      No: this.$i18n.messages[this.$i18n.locale].traceMgr.no,
      pageData: {},
      emptyIndex: [],
      returnDate: [],
      saveDone: false,
      isConfirm: false,
      titleData: {
        employeeInfoDTOS: [],
        num: 0
      },
      queryParas: {
        bpmId: this.bpmId,
        assetInfoId: this.assetInfoId,
        supplierId: this.supplierId
      },
      initData: [],
      dataIsChange: false,
      saveLoading: false,
      downloadApi: '',
      downloadForm: {
        assetCode: this.assetCode,
        assetInfoId: this.assetInfoId
      },
      downloadVisible: false,
      isLoading: false,
      resultMsg: {
        success: this.$i18n.messages[this.$i18n.locale].common.saveSuccess,
        submittedSuccess: this.$i18n.messages[this.$i18n.locale].common.submittedSuccess,
        submitFail: this.$i18n.messages[this.$i18n.locale].common.submitFail,
        fail: this.$i18n.messages[this.$i18n.locale].common.saveFailed,
        uploadPlease: this.$i18n.messages[this.$i18n.locale].common.uploadPlease,
        noData: this.$i18n.messages[this.$i18n.locale].common.noDataError
      },
      closeNotice: this.$i18n.messages[this.$i18n.locale].traceMgr.noSaveConfirmClose,
      postData: {
        bpmId: this.bpmId,
        assetInfoId: this.assetInfoId,
        detailListDTOList: this.sourceData,
        fileListSaveJson: ''
      },
      content: '',
      initContent: '',
      showTable: false,
      BtnText: this.$i18n.messages[this.$i18n.locale].common.open,
      tempBtnText: this.$i18n.messages[this.$i18n.locale].common.fold,
      dialogApi: {},
      dialogForm: {},
      dymForm: {
        productType: '',
        productId: ''
      },
      componentList: [
        // 产品信息
        {
          value: 'productType',
          disabled: true,
          componentName: 'el-input',
          name: 'productType',
          label: this.$i18n.messages[this.$i18n.locale].common.productInformation,
          cols: [14, 14, 14, 14],
          prop: 'productType',
          labelWidth: '150px'
        },
        // 签约主体
        {
          value: 'productType',
          disabled: true,
          componentName: 'el-input',
          name: 'productType',
          label: this.$i18n.messages[this.$i18n.locale].common.contractingBody,
          cols: [8, 8, 8, 8],
          prop: 'productType',
          labelWidth: '200px'
        },
        // 付款确认书编号
        {
          value: 'productType',
          disabled: true,
          componentName: 'el-input',
          name: 'productType',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.paymentConfirmationNo,
          cols: [7, 7, 7, 7],
          prop: 'productType',
          labelWidth: '150px'
        },
        // 供应商名称
        {
          value: 'productType',
          disabled: true,
          componentName: 'el-input',
          name: 'productType',
          label: this.$i18n.messages[this.$i18n.locale].common.supplierName,
          cols: [7, 7, 7, 7],
          prop: 'productType',
          labelWidth: '150px'
        },
        // 项目公司名称
        {
          value: 'productType',
          disabled: true,
          componentName: 'el-input',
          name: 'productType',
          label: this.$i18n.messages[this.$i18n.locale].common.NameOfProjectCompany,
          cols: [8, 8, 8, 8],
          prop: 'productType',
          labelWidth: '200px'
        },
        // 保理金额
        {
          value: 'productType',
          disabled: true,
          componentName: 'el-input',
          name: 'productType',
          label: this.$i18n.messages[this.$i18n.locale].common.TheAmountOfFactoring,
          cols: [7, 7, 7, 7],
          prop: 'productType',
          labelWidth: '150px'
        },
        // 合同名称
        {
          value: 'productType',
          disabled: true,
          componentName: 'el-input',
          name: 'productType',
          label: this.$i18n.messages[this.$i18n.locale].common.nameOfTheContract,
          cols: [7, 7, 7, 7],
          prop: 'productType',
          labelWidth: '150px'
        },
        // 合同编号
        {
          value: 'productType',
          disabled: true,
          componentName: 'el-input',
          name: 'productType',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.contractNo,
          cols: [8, 8, 8, 8],
          prop: 'productType',
          labelWidth: '200px'
        },
        // 区域
        {
          value: 'productType',
          disabled: true,
          componentName: 'el-input',
          name: 'productType',
          label: this.$i18n.messages[this.$i18n.locale].common.district,
          cols: [7, 7, 7, 7],
          prop: 'productType',
          labelWidth: '150px'
        },
        // 业务人员
        {
          value: 'productType',
          disabled: true,
          componentName: 'el-input',
          name: 'productType',
          label: this.$i18n.messages[this.$i18n.locale].common.businessPersonnel,
          cols: [7, 7, 7, 7],
          prop: 'productType',
          labelWidth: '150px'
        },
        // 保理专员
        {
          value: 'productType',
          disabled: true,
          componentName: 'el-input',
          name: 'productType',
          label: this.$i18n.messages[this.$i18n.locale].common.FactoringCommissioner,
          cols: [8, 8, 8, 8],
          prop: 'productType',
          labelWidth: '200px'
        },
        // 区域编号
        {
          value: 'productType',
          disabled: true,
          componentName: 'el-input',
          name: 'productType',
          label: this.$i18n.messages[this.$i18n.locale].common.SectionNumber,
          cols: [7, 7, 7, 7],
          prop: 'productType',
          labelWidth: '150px'
        },
        // 资产到期日
        {
          value: 'productType',
          disabled: true,
          componentName: 'el-input',
          name: 'productType',
          label: this.$i18n.messages[this.$i18n.locale].common.maturityDate,
          cols: [7, 7, 7, 7],
          prop: 'productType',
          labelWidth: '150px'
        }
      ],
      columns: [
        {
          prop: 'operationalMatters',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].common.operationalMatters,
          showOverflowTooltip: true,
          width: '200px'
        },
        {
          prop: 'operator',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].common.operator,
          showOverflowTooltip: true,
          width: '100px'
        },
        {
          prop: 'operateTime',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.operateTime,
          showOverflowTooltip: true,
          width: '150px'
        },
        {
          prop: 'completeTime',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].common.completeTime,
          showOverflowTooltip: true,
          width: '150px'
        },
        {
          prop: 'details',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].common.details,
          showOverflowTooltip: true,
          width: '200px'
        }
      ]
    }
  },
  watch: {
    dialogVisible: {
      handler: function (val, oldVal) {
        if (val) {
          this.tableLoading = true
          // 初始化列表数据
          this.returnDate = []
          // 初始化话术
          this.content = ''
          this.initContent = ''
          this.saveDone = false
          // 初始化备份数据
          this.initData = []
          // 初始化数据改变标志
          this.dataIsChange = false
          this.getList()
        }
      }
    }
  },
  methods: {
    // 设置默认话术
    setDefaultSpeech () {
      this.content = this.initContent
    },
    selectRowChange (selectedRow) {
      this.selecteData = selectedRow
    },
    getContent () {
      let bodyWord = ''
      this.returnDate.forEach((item, index) => {
        bodyWord += ++index + '.' + item.fileName + ':' + item.auditOpinion + '\n'
      })
      this.content = this.$i18n.messages[this.$i18n.locale].traceMgr.contentMessage10 + this.assetCode +
        this.$i18n.messages[this.$i18n.locale].traceMgr.contentMessage2 + this.creditor +
        this.$i18n.messages[this.$i18n.locale].traceMgr.contentMessage3 + this.debtor + this.$i18n.messages[this.$i18n.locale].traceMgr.contentMessage4 +
        this.factoringMoney + this.$i18n.messages[this.$i18n.locale].traceMgr.contentFour +
        this.$i18n.messages[this.$i18n.locale].traceMgr.contentMessage5 +
        bodyWord + this.$i18n.messages[this.$i18n.locale].traceMgr.lzyJp +
        this.$i18n.messages[this.$i18n.locale].traceMgr.person + this.regionalCommissioner + '\n' +
        this.$i18n.messages[this.$i18n.locale].traceMgr.beforePhone + '：' + this.regionalTelephone + '\n' +
        this.$i18n.messages[this.$i18n.locale].traceMgr.contentMessage9 + this.regionalPhoneNumber
      // 话术信息备份
      this.initContent = JSON.parse(JSON.stringify(this.content))
    },
    // 获取话术信息:保理专员、电话、手机号
    getSpeechCraftInfo () {
      let that = this
      tracemgrApi['fileList'].getSpeechCraftInfo({ 'assetId': that.assetInfoId }).then(res => {
        that.factoringCommissioner = res.data.factoringCommissioner
        that.factoringPhoneNumber = res.data.factoringPhoneNumber
        that.regionalCommissioner = res.data.regionalCommissioner
        that.regionalPhoneNumber = res.data.regionalPhoneNumber
        that.regionalTelephone = res.data.regionalTelephone
        that.getContent()
      })
    },
    getAssetInfoByKeyId () {
      let $this = this
      this.speechCraftLoading = true
      tracemgrApi['onlineAuditSave'].getOrderInfo(this.assetInfoId).then(res => {
        console.log(res.data)
        $this.factoringMoney = res.data.assetPaymentInfoDTO.factoringMoney
        $this.creditor = res.data.assetPaymentInfoDTO.creditor
        $this.debtor = res.data.assetPaymentInfoDTO.debtor
        // 填充话术信息
        this.getSpeechCraftInfo()
        this.speechCraftLoading = false
      }).catch(res => {
        this.content = this.$i18n.messages[this.$i18n.locale].common.zwsj
        this.speechCraftLoading = false
      })
    },
    // 判断页面数据是否改变
    judgeChange: function () {
      for (let i = 0; i < this.initData.length; i++) {
        if (this.returnDate[i].fileId !== this.initData[i].fileId) {
          this.dataIsChange = true
          this.saveDone = false
          break
        } else if (this.returnDate[i].factoringCommissionerFeedback !== this.initData[i].factoringCommissionerFeedback) {
          this.dataIsChange = true
          this.saveDone = false
          break
        }
      }
    },
    setInitData () {
      // 更新初始化数据
      this.initData = []
      for (let i = 0; i < this.returnDate.length; i++) {
        this.initData.push(JSON.parse(JSON.stringify(this.returnDate[i])))
      }
    },
    closeDialog () {
      this.dialogVisible = false
    },
    handleClose (done) {
      if (!this.dialogVisible) {
        return
      }
      this.$parent.handleFilter()
      this.judgeChange()
      if (this.saveDone || !this.dataIsChange) {
        this.dialogVisible = false
        return
      }
      this.$confirm(this.closeNotice)
        .then(_ => {
          this.dialogVisible = false
          done()
        })
        .catch(_ => {})
    },
    confirmOpen () {
      this.isConfirm = true
    },
    submit () {
      let that = this
      let fileIdCount = 0
      this.emptyIndex = []
      // 判断是否选择数据
      if (this.selecteData.length === 0) {
        return this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.leastSelectOne)
      }
      this.selecteData.forEach((item, index) => {
        if (item.fileId !== '') {
          fileIdCount++
        } else {
          this.emptyIndex.push(item.fileName)
        }
      })
      if (this.selecteData.length === 0) {
        this.error(this.resultMsg.noData)
        return
      }
      if (fileIdCount === this.selecteData.length && this.selecteData.length !== 0) {
        that.saveLoading = true
        this.postData.fileStampWay = this.fileStampWay
        this.postData.bpmId = this.bpmId
        this.postData.assetInfoId = this.assetInfoId
        this.postData.assetCode = this.assetCode
        this.postData.supplierId = this.supplierId
        that.postData.fileListSaveJson = JSON.stringify(that.selecteData)
        // 判断当前列表记录是否存在未完成的数据 0表示数据记录都是已完成状态，1、表示数据记录存在未完成
        let sign = '0'
        let exist = false
        this.returnDate.forEach(dt => {
          if (dt.status === 1) {
            let flag = false
            this.selecteData.forEach(item => {
              if (dt.fileCode === item.fileCode) {
                flag = true
              }
            })
            if (!flag) {
              exist = true
            }
          }
        })
        if (exist) {
          sign = 1
        }
        that.postData.sign = sign
        tracemgrApi['supplemenFileInPool'].submit(that.postData).then(res => {
          if (res.data) {
            that.isConfirm = false
            this.setInitData()
            this.success(that.resultMsg.submittedSuccess)
            this.dialogVisible = false
            this.$parent.handleFilter()
          } else {
            this.error(that.resultMsg.submitFail)
          }
          that.saveLoading = false
        }).catch(res => {
          that.saveLoading = false
          that.isConfirm = false
        })
      } else {
        this.error(that.resultMsg.uploadPlease + JSON.stringify(this.emptyIndex))
        that.isConfirm = false
      }
    },
    getList () {
      let $this = this
      this.queryParas.bpmId = this.bpmId
      this.queryParas.assetInfoId = this.assetInfoId
      this.queryParas.assetCode = this.assetCode
      this.queryParas.supplierId = this.supplierId
      // 获取列表信息
      tracemgrApi['supplemenFileInPool'].getList(this.queryParas).then(res => {
        this.pageData = res.data
        this.returnDate = this.pageData['detailListDTOList']
        this.tableLoading = false
        // 填充第几次补寄
        $this.titleData = res.data
        this.getAssetInfoByKeyId()
        // 备份初始化数据
        for (let i = 0; i < this.returnDate.length; i++) {
          this.initData.push(JSON.parse(JSON.stringify(this.returnDate[i])))
        }
      }).catch(res => {
        this.tableLoading = false
      })
      // 获取联系人信息
      // tracemgrApi['supplemenFileInPool'].getEmployeeInfos({ 'supplierId': $this.supplierId }).then(res => {
      //   $this.titleData.employeeInfoDTOS = res.data
      // })
    },
    save () {
      let fileIdCount = 0
      this.emptyIndex = []
      this.returnDate.forEach((item, index) => {
        if (item.fileId !== '') {
          fileIdCount++
        } else {
          this.emptyIndex.push(item.fileName)
        }
      })
      if (this.returnDate.length === 0) {
        this.error(this.resultMsg.noData)
        return
      }
      let that = this
      if (fileIdCount === this.returnDate.length) {
        this.isLoading = true
        this.postData.bpmId = this.bpmId
        this.postData.assetInfoId = this.assetInfoId
        this.postData.assetCode = this.assetCode
        this.postData.supplierId = this.supplierId
        this.postData.fileListSaveJson = JSON.stringify(this.returnDate)
        tracemgrApi['supplemenFileInPool'].save(that.postData).then(res => {
          if (res.data) {
            this.setInitData()
            this.success(that.resultMsg.success)
          } else {
            this.error(that.resultMsg.fail)
          }
          this.saveDone = true
          this.isLoading = false
        }).catch(
          res => {
            this.isLoading = false
          }
        )
      } else {
        this.error(that.resultMsg.uploadPlease + JSON.stringify(this.emptyIndex))
      }
    },
    closeDownBatch () {
      this.downloadVisible = false
    },
    fileDownLoadVisible () {
      this.downloadForm.assetCode = this.assetCode
      this.downloadForm.assetInfoId = this.assetInfoId
      this.downloadVisible = true
    },
    changBtnText () {
      this.showTable = !this.showTable
      let t = this.BtnText
      this.BtnText = this.tempBtnText
      this.tempBtnText = t
    }
  },

  props: {
    visible: {
      type: Boolean
    },
    bpmId: {
      type: String
    },
    assetInfoId: {
      type: String
    },
    assetCode: {
      type: String
    },
    instanceId: {
      type: String
    },
    supplierId: {
      type: String
    },
    assetPoolId: {
      type: String
    },
    taskType: {
      type: String
    },
    fileStampWay: {
      type: String
    }
  },
  computed: {
    dialogVisible: {
      get: function () {
        return this.visible
      },
      set: function (val) {
        this.$emit('update:visible', val)
      }
    }
  }
}
</script>
