<template>
  <!--保理专员任务台资料补寄-->
  <dialog-edit :visible.sync="dialogVisible"
               :title="$t('traceMgr.supplemenFileFill')"
               :editModel="'V'"
               :form="form"
               :api="api"
               :footerBtnShow="isFootView"
               :appendToBody="true"
               autoClose
               @close="handleClose"
               :saveLabel="$t('common.complete')"
               :before-close="handleClose">
    <el-row>
      <payment-info :keyId="assetInfoId" :title="$t('traceMgr.orderInfo')"></payment-info>
    </el-row>
    <!--律所审核 第2次反馈-->

    <data-table :cellStyle="cellStyle"  :stripe="true"
                :api="api" :handleFlag.sync="handleFlag" :border="true" :showPage="false" :menuFlag="false"
                :queryParas="queryParas" @getTableData="tableData" :sourceData.sync="sourceData" :loadPage="loadPage" :showSelection="true" @selectRowChange="selectionData"
                :loadCount.sync="loadCount" :columns="columns" :operateBtnLayout="operateBtnLayout">
      <template slot="operate" slot-scope="scope">
        <el-row style="text-align: center">
          <el-col  :span="scope.data.row.taskFileId!==undefined && scope.data.row.taskFileId!==''&&scope.data.row.archiveId!==undefined && scope.data.row.archiveId!==''?
          8:(scope.data.row.taskFileId!==undefined && scope.data.row.taskFileId!=='')||(scope.data.row.archiveId!==undefined && scope.data.row.archiveId!=='')?12:''">
            <btn-upload :fileType="fileType" :icon="scope.data.row.taskFileId===undefined||scope.data.row.taskFileId===''?'':'iconfont iconzhongxinshangchuan'"
                        :uploadApi="uploadApi" :rowData="scope.data.row"  @uploadSuccess="uploadSuccess" :title="scope.data.row.taskFileId===undefined||scope.data.row.taskFileId
                        ===''?$t('common.upload'):$t('common.reUpload')" :classType="true"></btn-upload>
          </el-col>
          <el-col :span="scope.data.row.taskFileId!==undefined && scope.data.row.taskFileId!==''
          &&scope.data.row.archiveId!==undefined && scope.data.row.archiveId!==''?8:(scope.data.row.taskFileId!==undefined &&
          scope.data.row.taskFileId!=='')||(scope.data.row.archiveId!==undefined && scope.data.row.archiveId!=='')?12:''" v-show="undefined!==scope.data.row.taskFileId
          &&''!==scope.data.row.taskFileId">
            <btn-download  :fileID="scope.data.row.taskFileId===undefined||scope.data.row.taskFileId===0||scope.data.row.taskFileId===null||scope.data.row.taskFileId===''?
            scope.data.row.archiveId:scope.data.row.taskFileId" :title="$t('traceMgr.loadDownLoding')"></btn-download>
          </el-col>
          <el-col  :span="scope.data.row.taskFileId!==undefined && scope.data.row.taskFileId!==''&&scope.data.row.archiveId!==undefined
          && scope.data.row.archiveId!==''?8:(scope.data.row.taskFileId!==undefined && scope.data.row.taskFileId!=='')||(scope.data.row.archiveId!==undefined &&
          scope.data.row.archiveId!=='')?12:''" v-show="undefined!==scope.data.row.archiveId &&''!==scope.data.row.archiveId">
            <btn-download  :fileID="scope.data.row.archiveId" :circleIcon="'iconfont iconxiazaiwenjian'" :title="$t('traceMgr.downloadArchive')"></btn-download>
          </el-col>
        </el-row>

      </template>
      <template slot="headButton">
        <el-row class="marginBottom4">
          <div  class="textRight handle-divider-style">
            <el-button size="medium" type="primary" class="iconfont iconycxiazai"  @click="loadDown()"> {{$t('traceMgr.downloadingData')}}</el-button>
            <el-button size="medium" type="primary" class="iconfont iconbaocun11" :loading="loading"  @click="submit()"> {{$t('common.save')}}</el-button>
          </div>
          <div class="handle-text-margin-bottom title">
            <span   >{{$t('traceMgr.fileListTableNameHandle')}}{{num}}{{$t('traceMgr.fileListTableNameBody')}}</span>
          </div>
          <el-divider></el-divider>
        </el-row>
      </template>
      <template slot="commissionerFeedback" slot-scope="scope">
        <el-input type="textarea"
                  :rows="1"
                  :placeholder="$t('common.MultilineInput')" size="mini" v-model="scope.data.row.commissionerFeedback"></el-input>
      </template>

    </data-table>
    <!--话术-->
    <el-row>
      <el-row class="head_msg padding-content title" v-for="(employee,index) in employees" :key="index">
        <el-col :span="3" v-if="employee.employeeName">
          <!--联系人-->
          <span>{{$t('common.contact')}}:&nbsp;</span>
          <span>{{employee.employeeName}}</span>
        </el-col>
        <el-col :span="3" v-if="employee.telephone">
          <!--联系人电话-->
          <span>{{$t('common.phoneNum')}}:&nbsp;</span>
          <span>{{employee.telephone}}</span>
        </el-col>
      </el-row>
      <!--话术组件-->
      <el-row class="body_msg">
        <el-col :span="1" class="text-center">
          <span>{{$t('common.discourse')}}</span>
        </el-col>
        <el-col :span="10">
          <speech-craft-input :defaultSpeechFlag="false" @defaultSpeech="resetSpeechCraft" :autosize="autosize" v-model="discourse" ></speech-craft-input>
        </el-col>
      </el-row>
    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button size="medium" type="primary" :loading="loadingOff" @click="submitMessage()">{{$t('common.complete')}}</el-button>
      <el-button size="medium" @click="dialogVisible=false">{{$t('common.close')}}</el-button>
    </div>
    <businessFileDownloadDialog :form="form" :visible.sync="showBusinessFileDownloadDialogValue"></businessFileDownloadDialog>
  </dialog-edit>
</template>
<script>
import { DataTable, btnDownload, btnUpload, paymentInfo, speechCraftInput, authButton, DialogEdit } from 'newepoch-components'
import authcenterApi from '@/api/tracemgrApi.js'
import BasePage from '@/pages/basePage'
import businessFileDownloadDialog from '@/components/tracemgr/common/businessFileDownloadDialog.vue'
import { UPLOAD_API } from '@/constant.js'
import fileApi from '@/api/fileApi'
import tracemgrApi from '@/api/tracemgrApi'
import { downFile } from '@/utils/devUtils'
import * as format from '@/filters/index'
import mixin from '@/pages/mixin'
export default {
  extends: new BasePage('fileList'),
  mixins: [mixin],
  name: 'fileList',
  props: {
    visible: {
      type: Boolean
    },
    handler: {
      type: Function
    },
    form: {
      type: Object
    }
  },
  components: {
    DataTable,
    fileApi,
    DialogEdit,
    downFile,
    businessFileDownloadDialog,
    format,
    speechCraftInput,
    paymentInfo,
    authcenterApi,
    authButton,
    UPLOAD_API,
    btnDownload,
    btnUpload
  },
  data () {
    return {
      selectData: [],
      employees: [],
      uploadApi: UPLOAD_API,
      loadCount: 0,
      isFootView: false,
      showBusinessFileDownloadDialogValue: false,
      queryParas: {},
      assetInfoId: '',
      fileType: '.pdf,.png,.gif,.bmp,.jpg,.jpeg,.rar,.zip',
      fileIdToSaveMess: '',
      loadingOff: false,
      assetCode: '',
      assetInfomations: {},
      customerAccountName: '',
      userInfo: {},
      num: '',
      uploadStatus: 0,
      rowSpan: '',
      operateBtnLayout: '',
      loadPage: 'getList',
      loading: false,
      taskId: '',
      bussCon: '',
      factoringMoney: '',
      autosize: {
        minRows: 8,
        maxRows: 10
      },
      handleFlag: true,
      discourse: '',
      sourceData: [],
      columns: [
        // 任务类型
        {
          prop: 'taskType',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.taskType,
          width: 120,
          format: function (row) {
            return format.formatDict(row.taskType, 'tracemgr_supplementary_task_type')
          }
        },
        // 补寄类型
        {
          prop: 'replacementFileType',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.supplementaryType,
          width: 120,
          format: function (row) {
            return row.replacementFileType === 0 ? '' : format.formatDict(row.replacementFileType + '', 'tracemgr_supplementary_type')
          }
        },
        // 文件名称
        {
          prop: 'fileName',
          align: 'left',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.fileName,
          width: 150
        },
        // 审核意见
        {
          prop: 'auditOpinion',
          align: 'left',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.auditOpinion,
          width: 200
        },
        // 补寄份数
        {
          prop: 'replacementCount',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.quantityOfSupplement,
          width: 90
        },
        // 截至时间
        {
          prop: 'deadlineTime',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].common.deadline,
          width: 90
        },
        // 操作
        {
          prop: 'operate',
          align: 'center',
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].common.operate,
          width: 140,
          slot: true
        },
        // 区域专员反馈
        {
          prop: 'commissionerFeedback',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.CommissionerRemarks,
          width: 190,
          slot: true
        },
        // 审核人员
        {
          prop: 'auditUserName',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.auditor,
          width: 140
        },
        // 处理状态
        {
          prop: 'status',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.processingStatus,
          width: 140,
          format: function (row) {
            if (row.status === 4) {
              return format.formatDict('4', 'tracemgr_abnormal_status')
            } else if (row.status === 1 || row.status === undefined || row.status === null || row.task.status === 0) {
              return format.formatDict('1', 'tracemgr_abnormal_status')
            } else if (row.status === 2) {
              return format.formatDict('2', 'tracemgr_abnormal_status')
            } else if (row.status === 3) {
              return format.formatDict('3', 'tracemgr_abnormal_status')
            }
          }
        }
      ]
    }
  },
  computed: {
    api () {
      return authcenterApi['supplemenTaskApi']
    },
    dialogVisible: {
      get: function () {
        return this.visible
      },
      set: function (val) {
        this.$emit('update:visible', val)
      }
    }
  },
  watch: {
    visible: {
      handler: function (newValue) {
        let $this = this
        if (newValue) {
          $this.sourceData = []
          $this.$nextTick(function () {
            $this.taskId = $this.form.taskId
            $this.assetInfoId = $this.form.assetInfoId
            $this.assetCode = $this.form.assetCode
            $this.queryParas.assetInfoId = $this.form.assetInfoId
            authcenterApi['onlineAuditTaskDialog'].getOrderInfo($this.form.assetInfoId).then(res => {
              $this.bussCon = res.data.assetPaymentInfoDTO.bussContractName
              $this.factoringMoney = res.data.assetPaymentInfoDTO.factoringMoney
              $this.customerAccountName = res.data.assetPaymentPoolOperDTO.customerAccountName
            }, res => {
              this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.getorderInfoFial)
            })
            authcenterApi['orderTrackApi'].getPhone().then(info => {
              this.userInfo = info.data
              this.resetSpeechCraft()
            }, res => {
              this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.getUserInfoFial)
            })
            $this.handleFilter()
            authcenterApi['onlineAuditTaskDialog'].getEmployeeInfos({ 'assetCode': this.assetCode }).then(res => {
              this.employees = res.data
            })
            this.$nextTick(function () {
              this.resetSpeechCraft()
            })
          })
        }
      }
    },
    uploadStatus: {
      handler: function (val) {
        this.fileSubmit()
      }
    }
  },
  methods: {
    /**
     * 选择数据
     * @param value
     */
    selectionData (item) {
      // 任务状态  1:待处理  2:待盖电子章  3:待单证审核  4:补寄完成
      // 已完成的条目不允许选择，不允许编辑和上传文件
      if (item.status === 4) {
        return this.error('当前记录已完成，不能执行该操作！')
      }
      this.selectData = item
    },
    passRowFileId (row) {
    },
    cellStyle ({ row, column, rowIndex, columnIndex }) {
      return ''
    },
    transData (data) {
      this.$emit('submitData', data)
    },
    uploadSuccess (returnData, rowData, fileList) {
      // '.' + file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase()
      if (rowData.status === 4) {
        return this.error('当前记录已完成，不能执行该操作')
      }
      this.success(this.$i18n.messages[this.$i18n.locale].traceMgr.file + returnData.fileName + this.$i18n.messages[this.$i18n.locale].traceMgr.UploadSucessFileIdIs)
      this.fileIdToSaveMess = ''
      this.fileIdToSaveMess = returnData.fileID
      this.sort = ''
      this.sort = rowData.sort
      rowData.fileId = returnData.fileID
      this.uploadStatus = this.uploadStatus + 1
    },
    loadDown: function () {
      this.showBusinessFileDownloadDialogValue = true
    },
    submit: function () {
      this.loading = true
      let message = this.sourceData
      let submitInfo = []
      let sum = 0
      message.forEach(item => {
        // 判断所有行数据，是否上传文件，如果没有上传文件单单是修改备注信息也不会影响保存
        if (item.commissionerFeedbackCopy === '') {
          item.commissionerFeedbackCopy = undefined
        }
        if (item.commissionerFeedback === '') {
          item.commissionerFeedback = undefined
        }
        if (item.fileId === '') {
          item.fileId = undefined
        }
        if (item.commissionerFeedbackCopy !== item.commissionerFeedback || item.fileId !== undefined) {
          sum = sum + 1
          submitInfo.push(item)
        }
        // 这里为了防止 不刷新页面 重复提交，修改行数据中的saveMessage标记为true 表示已经保存过了
        if (!item.saveMessage) {
          item.saveMessage = true
        }
      })
      if (sum === 0) {
        this.sourceData.forEach(item => {
          item.saveMessage = false
        })
        this.warning(this.$i18n.messages[this.$i18n.locale].traceMgr.PleaseUploadFileedClickSaveButton)
        this.loading = false
        return
      }
      if (submitInfo.length === 0) {
        this.sourceData.forEach(item => {
          item.saveMessage = false
        })
        this.warning(this.$i18n.messages[this.$i18n.locale].traceMgr.UKSaveInfoOrSaveSUCed)
        this.loading = false
        return
      }
      authcenterApi['supplemenTaskApi'].save({ 'param': JSON.stringify(submitInfo) }).then(item => {
        if (item.data) {
          this.sourceData.forEach(item => {
            item.saveMessage = false
          })
          this.success(this.$i18n.messages[this.$i18n.locale].common.saveSuccess)
          this.loading = false
          this.handleFilter()
        } else {
          this.loading = false
          this.error(this.$i18n.messages[this.$i18n.locale].common.saveError)
        }
      }, res => {
        this.loading = false
        this.sourceData.forEach(item => {
          item.saveMessage = false
        })
        this.error(this.$i18n.messages[this.$i18n.locale].common.saveError)
      })
    },
    tableData (data) {
      this.sourceData = data.detailDtoList
      this.num = data.num
      this.assetInfomations = data

      for (var i = 0; i < data.detailDtoList.length; i++) {
        if (data.detailDtoList[i].taskType === 1) {
          // 更新入池需补异常的状态
          let params = {
            assetInfoId: this.assetInfoId,
            abnormalType: 3,
            dealPersonType: 1,
            dealStatus: 2
          }
          tracemgrApi['fcTaskTablePage'].updateAbnormalOrderStatus(params).then(res => {
          })
          break
        }
      }

      // 更新资料补寄异常的状态
      let params = {
        assetInfoId: this.assetInfoId,
        abnormalType: 4,
        dealPersonType: 1,
        dealStatus: 2
      }
      tracemgrApi['fcTaskTablePage'].updateAbnormalOrderStatus(params).then(res => {
      })
    },
    submitMessage: function () {
      this.loadingOff = true
      // let message = this.sourceData
      // 判断是否选择数据
      if (this.selectData.length === 0) {
        this.loadingOff = false
        return this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.leastSelectOne)
      }
      let message = this.selectData
      let submitInfo = []
      let onUpload = true
      message.forEach(item => {
        if (item.taskFileId === undefined || item.taskFileId === '') {
          onUpload = false
        }
        item.assetInfoId = this.form.assetInfoId
        item.assetCode = this.form.assetCode
        item.taskId = this.taskId
        item.fileStampWay = this.form.fileStampWay
        submitInfo.push(item)
      })
      if (!onUpload) {
        this.warning(this.$i18n.messages[this.$i18n.locale].traceMgr.notCommit)
        this.loadingOff = false
        return
      }

      // 判断当前列表记录是否存在未完成的数据 0表示数据记录都是已完成状态，1、表示数据记录存在未完成
      let sign = '0'
      let exist = false
      this.sourceData.forEach(dt => {
        if (dt.status === 1) {
          let flag = false
          this.selectData.forEach(item => {
            if (dt.fileCode === item.fileCode) {
              flag = true
            }
          })
          if (!flag) {
            exist = true
          }
        }
      })
      if (exist) {
        sign = 1
      }

      submitInfo.forEach(itm => {
        itm.sign = sign
      })

      authcenterApi['supplemenTaskApi'].submit({ 'param': JSON.stringify(submitInfo) }).then(item => {
        if (item.data) {
          this.success(this.$i18n.messages[this.$i18n.locale].common.submittedSuccessfully)
          this.loadingOff = false
          this.handler()
          this.dialogVisible = false
        }
      }, res => {
        this.loadingOff = false
        this.error(this.$i18n.messages[this.$i18n.locale].common.submitFail)
      })
    },
    closeDialog () {
      this.dialogVisible = false
    },
    handleClose (done) {
      if (!this.dialogVisible) {
        return
      }
      let data = this.sourceData
      let editMessage = false
      data.forEach(item => {
        if (item.fileId === '') {
          item.fileId = undefined
        }
        if (item.commissionerFeedback !== item.commissionerFeedbackCopy || item.fileId !== undefined) {
          editMessage = true
        }
      })
      if (data.length === 0) {
        this.dialogVisible = false
        return
      }
      if (!editMessage) {
        this.dialogVisible = false
        return
      }
      var p = new Promise((resolve, reject) => {
        this.$confirm(this.$i18n.messages[this.$i18n.locale].traceMgr.TipsInfo, this.$i18n.messages[this.$i18n.locale].common.tip, {
          confirmButtonText: this.$i18n.messages[this.$i18n.locale].traceMgr.leaveInfo,
          cancelButtonText: this.$i18n.messages[this.$i18n.locale].approval.cancel,
          type: 'warning'
        }).then(() => {
          // 点击离开
          this.dialogVisible = false
          p.toString()
        }).catch(err => {
          reject(err)
        })
      })
    },
    fileSubmit: function () {
      this.sourceData.forEach((item, key) => {
        if (item.sort === this.sort) {
          this.$set(this.sourceData[key], 'taskFileId', this.fileIdToSaveMess)
        }
      }
      )
    },
    getTaskName (task) {
      return task.replacementFileType === 0 ? '' : format.formatDict(task.replacementFileType + '', 'tracemgr_supplementary_type')
    },
    resetSpeechCraft () {
      let $this = this
      let text = ''
      text = $this.$i18n.messages[$this.$i18n.locale].traceMgr.fileListOne +
              $this.$i18n.messages[$this.$i18n.locale].traceMgr.contentOne + $this.form.assetCode +
              $this.$i18n.messages[$this.$i18n.locale].traceMgr.fileListTwo + $this.bussCon +
              $this.$i18n.messages[$this.$i18n.locale].traceMgr.fileListThere + $this.factoringMoney +
              $this.$i18n.messages[$this.$i18n.locale].traceMgr.fileListFour
      let taskTypeNames = []
      $this.sourceData.forEach((item, key) => {
        if (item.replacementFileType) {
          let change = false
          taskTypeNames.forEach((data) => {
            if (item.replacementFileType === data.replacementFileType) {
              change = true
            }
          })

          if (!change) {
            taskTypeNames.push({ 'status': item.status, 'replacementFileType': item.replacementFileType })
          }
        }
      })
      taskTypeNames.forEach((item, key) => {
        let handel = ''
        let body = ''
        let taskTypeName = $this.getTaskName(item)
        handel = $this.$i18n.messages[$this.$i18n.locale].traceMgr.fileListSix + taskTypeName + '\n'
        if (handel !== '') {
          text += handel
        }
        $this.sourceData.forEach((data, index) => {
          if (item.replacementFileType === data.replacementFileType) {
            body = index + 1 + '.' + $this.$i18n.messages[$this.$i18n.locale].traceMgr.fileListIndex + data.fileName + '\n'
          }
          if (body !== '') {
            text += body
          }
        })
      })

      text += $this.$i18n.messages[$this.$i18n.locale].traceMgr.fileListText

      // 保理专员
      text = text + $this.$i18n.messages[$this.$i18n.locale].traceMgr.four + $this.userInfo.nickName
      // 座机
      text = text + $this.$i18n.messages[$this.$i18n.locale].traceMgr.five
      // 手机
      text = text + $this.$i18n.messages[$this.$i18n.locale].traceMgr.six
      if (this.userInfo.mobile !== undefined && this.userInfo.mobile !== '') {
        text = text + this.userInfo.mobile
      }
      $this.discourse = text
    }
  }
}
</script>
<style scoped lang="scss">
  @import '~@/styles/tracemgr/factoringCommissioner/taskTable/supplierSealNotice/taskDialog.scss';
</style>
