<template>
    <!--线上审核反馈 dialog-->
    <div>
        <dialog-edit :autoClose="true" @close="closeDialog" :before-close="closeDialog" :form="form" :title="$t('traceMgr.onlineAuditFeedbackProcess')" :visible.sync="visible"
                    class="el-dialog--center"
                    :close-on-click-modal="false" :editModel="editModel" :footerBtnShow="false">
            <!--订单信息-->
            <el-row>
                <payment-info :keyId="assetInfoId" :title="$t('traceMgr.orderInfo')"></payment-info>
            </el-row>
            <el-row class="textRight marginBottom20">
                <auth-button type="primary" size="medium" :label="$t('traceMgr.downloadingData')" @click="showBusinessFileDownloadDialog" class="iconfont iconycxiazai"></auth-button>
            </el-row>
            <el-row>
                <el-row class="marginBottom8">
                  <span class="title">{{stringReplace($t('traceMgr.onlineAudit'), feedbackTimes)}}</span>
                  <div class="divider"></div>
                </el-row>
            </el-row>
            <!--线上审核反馈列表-->
            <pro-blem-list :instanceId="instanceId" :taskId="taskId" :assetsId="assetInfoId" :visible="visible" @sourceData="sourceData" @whetherSave="haveSave" @saveTableData="saveTableData"></pro-blem-list>
            <!--话术-->
            <el-row class="margin_top_10">
                <!--话术-->
                <el-row class="body_msg">
                    <el-col :span="0.5" class="text-center">
                        <span>{{$t('common.discourse')}}&nbsp;:&nbsp;</span>
                    </el-col>
                    <el-col :span="14">
                        <speech-craft-input v-model="content" :defaultSpeechFlag="false" @defaultSpeech="setDefaultSpeech"
                                            v-loading="contentLoading"
                                            :element-loading-text="$t('traceMgr.contentLoading')"
                                            element-loading-spinner="el-icon-loading"
                                            element-loading-background="rgba(255, 255, 255, 0.7)"></speech-craft-input>
                    </el-col>
                </el-row>
            </el-row>

            <!--弹出资料下载-->
            <business-file-download-dialog
                    :visible.sync = "showBusinessFileDownloadDialogValue"
                    :form="downloadForm"
                    >
            </business-file-download-dialog>
            <!--提交审核确认-->
            <dialog-edit :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%"
                        :appendToBody="true"
                        :autoSave="autoSave"
                        :close-on-click-modal="false"
                        class="el-dialog--center">
                <p class="text-center">{{$t('traceMgr.checkComplete')}}</p>
            </dialog-edit>

          <!--底部按钮-->
          <div slot="footer" class="dialog-footer">
            <auth-button size="medium" type="primary" :label="$t('traceMgr.submitAudit')" @click="complete"></auth-button>
            <el-button size="medium" @click="closeDialog">{{$t('common.close')}}</el-button>
          </div>

        </dialog-edit>
    </div>
</template>
<script>
import { DataTable, authButton, DialogEdit, speechCraftInput, btnBatchUpload, btnBatchDownload, paymentInfo } from 'newepoch-components'
import mixin from '@/pages/mixin'
import BasePage from '@/pages/basePage'
import tracemgrApi from '@/api/tracemgrApi'
import DatePicker from '@/components/element/DatePick.vue'
import businessFileDownloadDialog from '@/components/tracemgr/common/businessFileDownloadDialog.vue'
import proBlemList from '@/components/tracemgr/regionalCommissioner/TaskTable/onlineAudit/problemList.vue'

export default {
  extends: new BasePage('supplemenFileInPoolAbnormalDetailDialog'),
  mixins: [mixin],
  components: {
    speechCraftInput,
    authButton,
    tracemgrApi,
    DataTable,
    DialogEdit,
    DatePicker,
    proBlemList,
    btnBatchUpload,
    btnBatchDownload,
    paymentInfo,
    businessFileDownloadDialog
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    /* editModel: {
      type: String
    }, */
    api: {
      type: String,
      default: ''
    },
    /* form: {
      type: Object
    }, */
    taskId: {
      type: String
    },
    assetCode: {
      type: String
    },
    instanceId: {
      type: String
    },
    assetInfoId: {
      type: String
    },
    createTime: {
      type: String
    },
    taskType: {
      type: String
    },
    supplierId: {
      type: String
    }
  },
  data () {
    return {
      initContent: '',
      content: '',
      areaCode: '',
      supplierName: '',
      projectCompanyName: '',
      factorAmount: '',
      feedBack: '',
      regionAttache: '',
      officePhone: '',
      phone: '',
      contentLoading: false,
      keyId: '2002241636461020001',
      whetherSave: false,
      showBusinessFileDownloadDialogValue: false,
      problemListformTableData: {
        sourceData: []
      },
      initialTableData: [],
      saveData: [],
      doSave: false,
      autoSave: false,
      saveLoading: false,
      editModel: 'V',
      form: {},
      downloadForm: {
        assetCode: '',
        assetInfoId: ''
      },
      //
      feedbackTimes: '',
      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
        }
      ]
    }
  },
  computed: {
    dialogVisible: {
      get: function () {
        return this.visible
      },
      set: function (value) {
        this.$emit('update:visible', value)
      }
    }
  },
  watch: {
    visible: {
      handler: function (newVal, oldVal) {
        if (newVal) {
          let $this = this
          $this.content = ''
          $this.initContent = ''
          this.$nextTick(function () {
            let data = {}
            data['taskId'] = $this.taskId
            data['assetId'] = $this.assetInfoId
            data['createTime'] = $this.createTime
            data['taskName'] = $this.taskType
            // 获取第几次反馈
            tracemgrApi['fileList'].getFeedBackNo(data).then(res => {
              $this.feedbackTimes = res.data.times
              $this.getAssetPaymentInfo()
            })
          })
        }
      }
    }
  },
  methods: {
    stringReplace (str, replaceParam1) {
      if (replaceParam1 !== '' && replaceParam1 !== null && replaceParam1 !== undefined) {
        return str.replace('{0}', replaceParam1)
      }
    },
    showBusinessFileDownloadDialog () {
      this.downloadForm.assetCode = this.assetCode
      this.downloadForm.assetInfoId = this.assetInfoId
      this.showBusinessFileDownloadDialogValue = true
    },
    businessFileDownloadDialogClose () {
      this.showBusinessFileDownloadDialogValue = false
    },
    sourceData (data) {
      this.problemListformTableData.sourceData = data
      for (let i = 0; i < this.problemListformTableData.sourceData.length; i++) {
        this.initialTableData.push(JSON.parse(JSON.stringify(this.problemListformTableData.sourceData[i])))
      }
    },
    haveSave (data) {
      this.whetherSave = data
    },
    saveTableData (data) {
      this.saveData = data
    },
    complete () {
      this.doSave = true
    },
    submit () {
      let that = this
      let fileIdCount = 0
      let noFileIdnum = []
      let saveDatas = []
      for (let i = 0; i < this.problemListformTableData.sourceData.length; i++) {
        fileIdCount++
        let factoringCommissionerFeedback = this.problemListformTableData.sourceData[i].factoringCommissionerFeedback
        if (factoringCommissionerFeedback === '') {
          this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.onlineAuditNoInputRemarkTip)
          return
        }
      }
      if (fileIdCount === that.problemListformTableData.sourceData.length && that.problemListformTableData.sourceData.length !== 0) {
        that.saveLoading = true
        that.problemListformTableData.sourceData.forEach((item, index) => {
          let data = {}
          data['taskInfoId'] = that.taskId
          data['fileCode'] = item.fileCode
          data['fileId'] = item.fileId
          data['factoringCommissionerFeedback'] = item.factoringCommissionerFeedback
          data['fileName'] = item.fileName
          saveDatas.push(data)
        })
        tracemgrApi['problemList'].save(saveDatas).then(res => {
          if (res.data) {
            let problemListData = {}
            problemListData['instanceId'] = that.assetInfoId
            problemListData['taskId'] = that.taskId
            problemListData['currentRole'] = 2
            problemListData['assetCode'] = that.assetCode
            problemListData['detailListJson'] = JSON.stringify(that.problemListformTableData.sourceData)
            tracemgrApi['onlineAuditTaskDialog'].submit(problemListData).then(res => {
              if (res.data) {
                that.success(that.$i18n.messages[that.$i18n.locale].traceMgr.submitSuccess)
                that.close()
              } else {
                that.error(that.$i18n.messages[that.$i18n.locale].traceMgr.submitFailed)
              }
              that.saveLoading = false
              that.doSave = false
            }, res => {
              that.saveLoading = false
            })
            that.whetherSave = true
            that.saveTableData = []
            for (let i = 0; i < that.formTableData.sourceData.length; i++) {
              that.saveTableData.push(JSON.parse(JSON.stringify(that.formTableData.sourceData[i])))
            }
          } else {
            that.error(that.$i18n.messages[that.$i18n.locale].traceMgr.submitFailed)
            that.saveLoading = false
          }
        }, res => {
          that.saveLoading = false
        })
      } else if (this.problemListformTableData.sourceData.length === 0) {
        this.error(this.$i18n.messages[this.$i18n.locale].common.noDataError)
      } else {
        this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.uploadMessage8 + noFileIdnum + this.$i18n.messages[this.$i18n.locale].traceMgr.uploadMessage9)
      }
    },
    closeDialog () {
      if (!this.dialogVisible) {
        return
      }

      let flag = ''
      for (let i = 0; i < this.problemListformTableData.sourceData.length; i++) {
        if (this.problemListformTableData.sourceData[i].fileId !== this.initialTableData[i].fileId || this.problemListformTableData.sourceData[i].factoringCommissionerFeedback !== this.initialTableData[i].factoringCommissionerFeedback) {
          if (!this.whetherSave) {
            flag = true
            break
          } else {
            if (this.problemListformTableData.sourceData[i].fileId !== this.saveData[i].fileId || this.problemListformTableData.sourceData[i].factoringCommissionerFeedback !== this.saveData[i].factoringCommissionerFeedback) {
              flag = true
              break
            } else {
              flag = false
            }
          }
        } else {
          flag = false
        }
      }

      if (flag) {
        // 确认是否关闭窗口
        this.$confirm(this.$i18n.messages[this.$i18n.locale].traceMgr.noSaveConfirmClose, this.$i18n.messages[this.$i18n.locale].common.tip, {
          confirmButtonText: this.$i18n.messages[this.$i18n.locale].traceMgr.sure,
          cancelButtonText: this.$i18n.messages[this.$i18n.locale].traceMgr.cancel,
          type: 'warning'
        }).then(() => {
          this.initialTableData = []
          this.whetherSave = false
          this.dialogVisible = false
          this.$parent.handleFilter()
        })
      } else {
        this.initialTableData = []
        this.whetherSave = false
        this.dialogVisible = false
        this.$parent.handleFilter()
      }
    },
    close () {
      this.whetherSave = false
      this.dialogVisible = false
      this.$parent.handleFilter()
    },
    // 获取话术信息相关信息
    getAssetPaymentInfo () {
      let $this = this
      this.contentLoading = true
      tracemgrApi['onlineAuditTaskDialog'].getOrderInfo($this.assetInfoId).then(res => {
        // 区域编号
        $this.areaCode = res.data.assetPaymentInfoDTO.regionCode
        // 供应商名称
        $this.supplierName = res.data.assetPaymentInfoDTO.creditor
        // 项目公司名称
        $this.projectCompanyName = res.data.assetPaymentInfoDTO.debtor
        // 保理金额
        $this.factorAmount = res.data.assetPaymentInfoDTO.factoringMoney
        $this.getSpeechCraftInfo()
      }).catch(res => {
        $this.content = this.$i18n.messages[this.$i18n.locale].traceMgr.noneData
        $this.contentLoading = false
      })
    },
    // 获取话术信息:区域专员、电话、手机号
    getSpeechCraftInfo () {
      let $this = this
      tracemgrApi['fileList'].getSpeechCraftInfo({ 'assetId': $this.assetInfoId }).then(res => {
        // 区域专员
        $this.regionAttache = res.data.regionalCommissioner
        // 座机
        $this.officePhone = res.data.regionalTelephone
        // 手机
        $this.phone = res.data.regionalPhoneNumber
        $this.getContent()
      }).catch(res => {
        $this.content = this.$i18n.messages[this.$i18n.locale].traceMgr.noneData
        $this.contentLoading = false
      })
    },
    // 话术
    getContent () {
      // 反馈
      this.feedBack = ''
      for (let i = 0; i < this.problemListformTableData.sourceData.length; i++) {
        this.feedBack = this.feedBack + (i + 1) + '.' + this.problemListformTableData.sourceData[i].fileName + '：' + this.problemListformTableData.sourceData[i].checkResult + '\n'
      }

      this.content = this.$i18n.messages[this.$i18n.locale].traceMgr.contentMessage1 + this.areaCode +
        this.$i18n.messages[this.$i18n.locale].traceMgr.contentMessage2 + this.supplierName +
        this.$i18n.messages[this.$i18n.locale].traceMgr.contentMessage3 + this.projectCompanyName +
        this.$i18n.messages[this.$i18n.locale].traceMgr.contentMessage4 + parseFloat(this.factorAmount).toFixed(2) + this.$i18n.messages[this.$i18n.locale].traceMgr.contentFour +
        this.$i18n.messages[this.$i18n.locale].traceMgr.contentMessage5 +
        this.feedBack +
        '\n' +
        this.$i18n.messages[this.$i18n.locale].traceMgr.contentMessage6 +
        '\n' +
        this.$i18n.messages[this.$i18n.locale].traceMgr.contentMessage7 + this.regionAttache + '\n' +
        this.$i18n.messages[this.$i18n.locale].traceMgr.contentMessage8 + this.officePhone + '\n' +
        this.$i18n.messages[this.$i18n.locale].traceMgr.contentMessage9 + this.phone

      this.initContent = JSON.parse(JSON.stringify(this.content))
      this.contentLoading = false
    },
    setDefaultSpeech () {
      this.content = this.initContent
    }
  }
}
</script>

<style lang="scss" scoped>
    @import './src/styles/tracemgr/regionalCommissioner/taskTable/lawFirm/taskDialog.scss';
</style>
