<template>
  <div>
    <DialogEdit :footerBtnShow="false"
                :form="form"
                autoClose
                @close="handleClose"
                :title="$t('traceMgr.onlineAuditFeedbackProcess')"
                :visible.sync="onlineAuditVisible"
                class="el-dialog--center"
                :close-on-click-modal="false"
                :editModel="editModel">
      <payment-info :keyId="instanceId" :title="$t('traceMgr.orderInfo')"></payment-info>
      <el-row class="textRight marginBottom5">
        <auth-button type="primary" size="medium" @click="downBatch"
                     :label="$t('traceMgr.downloadingData')" class="iconfont iconycxiazai"></auth-button>
      </el-row>
      <el-form :model="formTableData" ref="formTableData" :show-message="false">
        <el-row class="marginBottom8">
          <span class="title">{{$t('traceMgr.onlineCheck')}}&nbsp;&nbsp;&nbsp;&nbsp;{{$t('traceMgr.no')}}{{feedbackTimes}}{{$t('traceMgr.feedback')}}</span>
          <div class="divider"></div>
        </el-row>
        <el-row class="marginBottom2">
          <el-col :span="18" class="box_border">
            <el-col class="lineHeight" :span="6">{{$t('traceMgr.auditor')}}&nbsp;&nbsp;&nbsp;&nbsp;{{auditor}}</el-col>
            <el-col class="lineHeight" :span="8">{{$t('traceMgr.checkTime')}}&nbsp;&nbsp;&nbsp;&nbsp;{{checkTime}}</el-col>
            <el-col class="lineHeight" :span="8">{{$t('traceMgr.feedbackTime')}}&nbsp;&nbsp;&nbsp;&nbsp;{{feedbackTime}}</el-col>
          </el-col>
          <el-col :span="6" class="textRight"  style="margin-top: 10px">
            <btn-batch-upload btnSize="medium" class="marginRight" :btnDisplay="true" @uploadSuccess="batchUploadSuccess" :uploadApi="batchUploadApi"></btn-batch-upload>
            <div class="floatRight">
              <auth-button class="marginTop iconfont iconbaocun11" size="medium" type="primary" :label="$t('common.save')" :loading="isLoading" @click="save" :disabled="saveDisabled"></auth-button>
            </div>
          </el-col>
        </el-row>
        <!--文件列表-->
        <file-list :loadingFlag="tableLoading" :formTableData="fileListformTableData"></file-list>
      </el-form>
      <!--联系人信息展示（多个）-->
      <el-row class="title" v-if="employees.length > 0">
        <el-col :span="2"><span>{{$t('common.contact')}}：</span></el-col><br/>
      </el-row>
      <el-row class="marginBottom2 title paddingLeft20">
        <el-col :span="8" v-for="(employee,index) in employees" :key="index">
          <span v-if="employee.employeeName">{{employee.employeeName}}</span>
          <span v-if="employee.telephone">-{{employee.telephone}}</span>
          <span v-if="employee.account">-{{employee.account}}</span>
        </el-col>
      </el-row>
      <el-row class="word_wrap marginBottom6">
        <el-col :span="0.5" class="text-center">
          <span>{{$t('traceMgr.wordsTechnique')}}&nbsp;:&nbsp;</span>
        </el-col>
        <el-col :span="12">
          <speech-craft-input v-loading="speechCraftLoading" :defaultSpeechFlag="false" @defaultSpeech="setDefaultSpeech" v-model="content"></speech-craft-input>
        </el-col>
      </el-row>
      <div v-show="showTable" class="copyImg">
        <auth-button type="primary" size="small" :label="$t('traceMgr.copyImg')" @click="copyImg"></auth-button>
      </div>
      <div slot="footer" class="dialog-footer">
        <auth-button size="medium" type="primary" :label="$t('common.complete')" @click="complete" :disabled="submitDisabled"></auth-button>
        <auth-button size="medium" type="primary" :label="$t('traceMgr.feedBackSupplier')" @click="feedBackSupplier"></auth-button>
        <el-button size="medium" @click="handleClose">{{$t('common.close')}}</el-button>
      </div>
    </DialogEdit>
    <business-file-download-dialog :form="downloadForm"
                                   :visible.sync="downloadVisible"
                                   :editModel="editModel"
                                   :api="downloadApi">
    </business-file-download-dialog>
    <DialogEdit :saveLabel="$t('traceMgr.sure')"
                :closeLabel="$t('approval.cancel')"
                editModel="E" :form="form"
                :visible.sync="doSave"
                @onSaved="submit"
                :loading="saveLoading"
                :title="$t('common.tip')"
                width="35%"
                :autoSave="autoSave"
                :close-on-click-modal="false"
                class="el-dialog--center">
      <p class="text-center">{{$t('traceMgr.checkComplete')}}</p>
    </DialogEdit>
    <DialogEdit :saveLabel="$t('traceMgr.sure')"
                :closeLabel="$t('approval.cancel')"
                editModel="E"
                :form="form"
                :loading="backSupplierLoading"
                :autoSave="autoSave"
                @onSaved="backSupplier"
                :visible.sync="doFeed"
                :title="$t('common.tip')"
                width="35%"
                :close-on-click-modal="false"
                class="el-dialog--center">
      <p class="text-center">{{$t('traceMgr.checkFeed')}}</p>
    </DialogEdit>
  </div>
</template>

<script>
import { DataTable, authButton, DialogEdit, speechCraftInput, btnBatchUpload, paymentInfo, componentsApi } from 'newepoch-components'
import mixin from '@/pages/mixin'
import { BATCH_UPLOAD_API } from '@/constant.js'
import BasePage from '@/pages/basePage'
import fileList from './fileList'
import businessFileDownloadDialog from '@/components/tracemgr/common/businessFileDownloadDialog'
import tracemgrApi from '@/api/tracemgrApi'

export default {
  extends: new BasePage(),
  mixins: [mixin],
  components: {
    DataTable,
    componentsApi,
    authButton,
    DialogEdit,
    BATCH_UPLOAD_API,
    tracemgrApi,
    fileList,
    speechCraftInput,
    btnBatchUpload,
    businessFileDownloadDialog,
    paymentInfo
  },
  props: {
    handler: {
      type: Function
    },
    visible: {
      type: Boolean,
      default: false
    },
    instanceId: {
      type: String,
      default: ''
    },
    assetCode: {
      type: String
    },
    taskId: {
      type: String,
      default: ''
    },
    taskName: {
      type: String,
      default: '保理专员处理线上反馈'
    },
    createTime: {
      type: String,
      default: ''
    },
    supplierId: {
      type: String,
      default: ''
    },
    api: {
      type: String,
      default: ''
    },
    form: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  computed: {
    onlineAuditVisible: {
      get () {
        return this.visible
      },
      set (val) {
        this.$emit('update:visible', val)
      }
    }
  },
  data () {
    return {
      areaId: '',
      tableLoading: false,
      // 提交禁用
      submitDisabled: false,
      // 保存禁用
      saveDisabled: false,
      factoringCommissioner: '',
      factoringPhoneNumber: '',
      regionalCommissioner: '',
      regionalPhoneNumber: '',
      factoringTelephone: '',
      speechCraftLoading: false,
      factoringMoney: '',
      bussContractName: '',
      content: '',
      initContent: '',
      No: this.$i18n.messages[this.$i18n.locale].traceMgr.no,
      feedBackNoRequestPro: {
        taskId: '',
        assetId: '',
        createTime: ''
      },
      emptyIndex: [],
      dataIsChange: false,
      saveDone: false,
      closeNotice: this.$i18n.messages[this.$i18n.locale].traceMgr.noSaveConfirmClose,
      saveLoading: false,
      backSupplierLoading: false,
      autoSave: false,
      resultMsg: {
        success: this.$i18n.messages[this.$i18n.locale].common.saveSuccess,
        submitSuccess: this.$i18n.messages[this.$i18n.locale].common.submittedSuccessfully,
        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,
        noDataError: this.$i18n.messages[this.$i18n.locale].common.noDataError
      },
      employees: [],
      isLoading: false,
      editModel: 'V',
      doFeed: false,
      doSave: false,
      downloadForm: {
        assetCode: this.assetCode,
        assetInfoId: this.assetInfoId
      },
      downloadVisible: false,
      downloadApi: '',
      batchUploadApi: BATCH_UPLOAD_API,
      changingText: this.$i18n.messages[this.$i18n.locale].common.open,
      uploadSuccess: this.$i18n.messages[this.$i18n.locale].common.uploadSuccess,
      showTable: false,
      auditor: '',
      checkTime: '',
      feedbackTime: '',
      contact: '',
      initData: [],
      fileListformTableData: {
        sourceData: []
      },
      postData: {
        instanceId: '',
        supplierId: '',
        taskId: '',
        detailListJson: ''
      },
      handleFlag: true,
      feedbackTimes: '',
      formTableData: {
        sourceData: []
      },
      columns: [
        {
          prop: 'businessProcessState',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].common.BusinessProcessState,
          showOverflowTooltip: true
        },
        {
          prop: 'operator',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].common.operator,
          showOverflowTooltip: true
        },
        {
          prop: 'startTime',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.startTime,
          showOverflowTooltip: true
        },
        {
          prop: 'operate',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].common.operate,
          showOverflowTooltip: true
        },
        {
          prop: 'operateTime',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.operateTime,
          showOverflowTooltip: true
        },
        {
          prop: 'details',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].common.details,
          showOverflowTooltip: true
        }
      ]
    }
  },
  methods: {
    // 设置默认话术
    setDefaultSpeech () {
      this.content = this.initContent
    },
    getAssetInfoByKeyId () {
      let $this = this
      this.speechCraftLoading = true
      tracemgrApi['onlineAuditSave'].getOrderInfo(this.instanceId).then(res => {
        if (res.data) {
          $this.factoringMoney = res.data.assetPaymentInfoDTO.factoringMoney
          $this.bussContractName = res.data.assetPaymentInfoDTO.bussContractName
          $this.areaId = res.data.assetPaymentPoolOperDTO.coreArea
          $this.getSpeechCraftInfo()
        }
        $this.speechCraftLoading = false
      }).catch(res => {
        $this.content = this.$i18n.messages[this.$i18n.locale].common.zwsj
        $this.speechCraftLoading = false
      })
    },
    // 获取话术信息:保理专员、电话、手机号
    getSpeechCraftInfo () {
      let that = this
      tracemgrApi['fileList'].getSpeechCraftInfo({ 'assetId': that.instanceId }).then(res => {
        that.factoringCommissioner = res.data.factoringCommissioner
        that.factoringPhoneNumber = res.data.factoringPhoneNumber
        that.regionalCommissioner = res.data.regionalCommissioner
        that.regionalPhoneNumber = res.data.regionalPhoneNumber
        that.factoringTelephone = res.data.factoringTelephone
        that.getContent()
      })
    },
    getContent () {
      let bodyWord = ''
      this.fileListformTableData.sourceData.forEach((item, index) => {
        bodyWord += ++index + '.' + item.fileName + ':' + item.auditOpinion + '\n'
      })
      this.content = this.$i18n.messages[this.$i18n.locale].traceMgr.taskTable_onlineAudit_msg1 + this.assetCode + this.$i18n.messages[this.$i18n.locale].traceMgr.taskTable_onlineAudit_msg2 + this.bussContractName + this.$i18n.messages[this.$i18n.locale].traceMgr.taskTable_onlineAudit_msg3 + this.factoringMoney +
        this.$i18n.messages[this.$i18n.locale].traceMgr.taskTable_onlineAudit_msg4 +
        bodyWord +
        this.$i18n.messages[this.$i18n.locale].traceMgr.taskTable_onlineAudit_msg5 +
         this.$i18n.messages[this.$i18n.locale].traceMgr.four +
         this.factoringCommissioner + this.$i18n.messages[this.$i18n.locale].traceMgr.five +
         this.factoringTelephone + this.$i18n.messages[this.$i18n.locale].traceMgr.six +
         this.factoringPhoneNumber
      // 话术信息备份
      this.initContent = JSON.parse(JSON.stringify(this.content))
    },
    batchUploadSuccess (returnData) {
      let tableList = this.fileListformTableData.sourceData
      let returnFileList = returnData.fileList
      for (let i = 0; i < tableList.length; i++) {
        for (let j = 0; j < returnFileList.length; j++) {
          let filenameItem = returnFileList[j].fileName.substring(0, returnFileList[j].fileName.lastIndexOf('.'))
          if (tableList[i].fileName === filenameItem) {
            tableList[i].fileId = returnFileList[j].keyId
            break
          }
        }
      }
      this.success(returnData.fileName + this.uploadSuccess)
    },
    handleClose (done) {
      if (!this.onlineAuditVisible) {
        return
      }
      this.$parent.handleFilter()
      this.judgeChange()
      if (this.saveDone || !this.dataIsChange) {
        this.onlineAuditVisible = false
      } else {
        this.$confirm(this.closeNotice)
          .then(() => {
            this.onlineAuditVisible = false
            done()
          }).catch(() => {})
      }
    },
    save () {
      this.submitDisabled = true
      let that = this
      let fileIdCount = 0
      this.emptyIndex = []
      this.fileListformTableData.sourceData.forEach((item, index) => {
        fileIdCount++
      })
      if (fileIdCount === this.fileListformTableData.sourceData.length && this.fileListformTableData.sourceData.length !== 0) {
        this.isLoading = true
        tracemgrApi['onlineAuditSave'].save({ 'fileListSaveJson': JSON.stringify(that.fileListformTableData.sourceData), 'bpmId': that.taskId }).then(res => {
          if (res.data) {
            this.success(that.resultMsg.success)
            this.setInitData()
          } else {
            this.error(that.resultMsg.fail)
          }
          this.saveDone = true
          this.isLoading = false
          this.submitDisabled = false
        }).catch(res => {
          this.isLoading = false
          this.submitDisabled = false
        }
        )
      } else if (this.fileListformTableData.sourceData.length === 0) {
        this.submitDisabled = false
        this.error(that.resultMsg.noDataError)
      } else {
        this.submitDisabled = false
        this.error(that.resultMsg.uploadPlease + JSON.stringify(this.emptyIndex))
      }
    },
    setInitData () {
      // 更新初始化数据
      this.initData = []
      for (let i = 0; i < this.fileListformTableData.sourceData.length; i++) {
        this.initData.push(JSON.parse(JSON.stringify(this.fileListformTableData.sourceData[i])))
      }
    },
    // 提交
    submit () {
      this.saveDisabled = true
      let that = this
      let fileIdCount = 0
      this.emptyIndex = []
      for (let i = 0; i < this.fileListformTableData.sourceData.length; i++) {
        fileIdCount++
        let factoringCommissionerFeedback = this.fileListformTableData.sourceData[i].factoringCommissionerFeedback
        if (factoringCommissionerFeedback === '' || factoringCommissionerFeedback === undefined || factoringCommissionerFeedback === null) {
          this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.onlineAuditNoInputRemarkTip)
          return
        }
      }
      if (fileIdCount === this.fileListformTableData.sourceData.length && this.fileListformTableData.sourceData.length !== 0) {
        that.saveLoading = true
        tracemgrApi['onlineAuditSave'].save({ 'fileListSaveJson': JSON.stringify(that.fileListformTableData.sourceData), 'bpmId': that.taskId }).then(res => {
          if (res.data) {
            that.postData['detailListJson'] = JSON.stringify(that.fileListformTableData.sourceData)
            that.postData['orderId'] = that.taskId
            that.postData['instanceId'] = that.instanceId
            that.postData['supplierId'] = that.supplierId
            that.postData['currentRole'] = 1
            that.postData['assetCode'] = that.assetCode
            tracemgrApi['onlineAuditSave'].submit(that.postData).then(res => {
              if (res.data) {
                that.success(that.resultMsg.submitSuccess)
                this.setInitData()
                that.onlineAuditVisible = false
                that.handler()
              } else {
                that.error(that.resultMsg.submitFail)
              }
              that.saveLoading = false
              that.doSave = false
              that.saveDisabled = false
            }).catch(res => {
              that.doSave = false
              that.saveLoading = false
              that.saveDisabled = false
            }
            )
            this.setInitData()
          } else {
            that.saveLoading = false
            this.error(that.resultMsg.submitFail)
          }
          this.saveDone = true
        }).catch(res => {
          that.saveLoading = false
        })
      } else if (this.fileListformTableData.sourceData.length === 0) {
        this.error(that.resultMsg.noDataError)
      } else {
        this.error(that.resultMsg.uploadPlease + JSON.stringify(this.emptyIndex))
      }
    },
    // 退回至供应商
    backSupplier () {
      let $this = this
      $this.backSupplierLoading = true
      tracemgrApi['onlineAuditSave'].backSupplier({ 'taskId': $this.taskId, 'instanceId': $this.instanceId }).then(res => {
        if (res.data) {
          this.setInitData()
          this.success($this.resultMsg.submitSuccess)
        } else {
          this.error($this.resultMsg.submitFail)
        }
        $this.doFeed = false
        $this.backSupplierLoading = false
        $this.onlineAuditVisible = false
      }).catch(res => {
        $this.doFeed = false
        $this.backSupplierLoading = false
      })
    },
    complete () {
      this.doSave = true
    },
    feedBackSupplier () {
      this.doFeed = true
    },
    open () {
      if (this.changingText === this.$i18n.messages[this.$i18n.locale].common.fold) {
        this.changingText = this.$i18n.messages[this.$i18n.locale].common.open
      } else {
        this.changingText = this.$i18n.messages[this.$i18n.locale].common.fold
      }
      this.showTable = !this.showTable
    },
    downBatch () {
      this.downloadForm.assetCode = this.assetCode
      this.downloadForm.assetInfoId = this.instanceId
      this.downloadVisible = true
    },
    closeDownBatch () {
      // 传个资产id过去 装在这个downloadForm
      this.downloadVisible = false
    },
    copyImg () {
      console.log('copyImg')
    },
    // 判断页面数据是否改变
    judgeChange: function () {
      for (let i = 0; i < this.initData.length; i++) {
        if (this.fileListformTableData.sourceData[i].fileId !== this.initData[i].fileId) {
          this.dataIsChange = true
          this.saveDone = false
          break
        } else if (this.fileListformTableData.sourceData[i].factoringCommissionerFeedback !== this.initData[i].factoringCommissionerFeedback) {
          this.dataIsChange = true
          this.saveDone = false
          break
        }
      }
    },
    // 获取列表数据
    getList () {
      let that = this
      that.postData['taskId'] = that.taskId
      that.postData['instanceId'] = that.instanceId
      that.postData['supplierId'] = that.supplierId
      that.postData['detailListJson'] = ''
      tracemgrApi['fileList'].getList(that.postData).then(res => {
        if (res.data) {
          that.auditor = res.data.auditors
          that.checkTime = res.data.reviewTime
          that.feedbackTime = res.data.feedbackTime
          // that.employees = res.data.employeeInfoDTOs
          console.log(res.data.feedbackFileDTOLists)
          that.fileListformTableData.sourceData = res.data.feedbackFileDTOLists
        }
        this.tableLoading = false
        this.getAssetInfoByKeyId()
        // 备份到初始化数据用于提交前比较
        for (let i = 0; i < that.fileListformTableData.sourceData.length; i++) {
          that.initData.push(JSON.parse(JSON.stringify(that.fileListformTableData.sourceData[i])))
        }
      }).catch(res => {
        this.tableLoading = false
      })
      // 获取联系人信息
      tracemgrApi['supplemenFileInPool'].getEmployeeInfos({ 'assetCode': that.assetCode }).then(res => {
        that.employees = res.data
      })
      // 获取第几次反馈
      that.feedBackNoRequestPro['taskId'] = that.taskId
      that.feedBackNoRequestPro['assetId'] = that.instanceId
      that.feedBackNoRequestPro['createTime'] = that.createTime
      that.feedBackNoRequestPro['taskName'] = that.taskName
      tracemgrApi['fileList'].getFeedBackNo(that.feedBackNoRequestPro).then(res => {
        that.feedbackTimes = res.data.times
      })
    }
  },
  watch: {
    onlineAuditVisible: {
      handler: function (newValue, oldValue) {
        if (newValue) {
          this.tableLoading = true
          // 初始化表格数据
          this.fileListformTableData.sourceData = []
          // 初始化话术信息
          this.content = ''
          this.initContent = ''
          this.initData = []
          this.saveDone = false
          this.dataIsChange = false
          this.saveDisabled = false
          this.submitDisabled = false
          let $this = this
          this.$nextTick(() => {
            $this.getList()
          })
        }
      }
    }
  },
  mounted: function () {
    // this.getList()
  }
}
</script>

<style scoped>
  @import '~@/styles/tracemgr/factoringCommissioner/taskTable/onlineAudit/taskDialog.scss'
</style>
