<template>
  <div>
    <dialog-edit :visible.sync="dialogVisible" :title="$t('complianceCheck.feedbackProcess')" width="1480px"
                 :form="form" :api="dialogApi" :editModel="editModel" :saveLabel="$t('common.submit')"
                 :autoSave="false" @onSaved="onSaved">
      <div class="coll-title coll-body">
        <el-collapse v-model="activeNames">
          <!-- 付款确认书变更履历 -->
          <el-collapse-item :title="$t('complianceCheck.payConfirmChangeHistory')" name="payConfirmChangeHistory">
            <pay-confirm-change-history ref="payConfirmChangeHistory"></pay-confirm-change-history>
          </el-collapse-item>
          <!-- 付款确认书信息 -->
          <el-collapse-item :title="$t('complianceCheck.paymentConfirmation')" name="paymentConfirmation">
            <payment-info :keyId="keyId" :titleShow="false" ref="paymentConfirmation"></payment-info>
          </el-collapse-item>
          <!-- 律所审核  第N次反馈 -->
          <el-collapse-item :title="$t('complianceCheck.externalFeedbackTable')" name="externalFeedbackTable">
            <el-form :model="dataForm" :rules="formRules" ref="dataForm" :show-message="false">
              <div class="table-form">
                <vxe-grid border
                          show-overflow
                          highlight-cell
                          ref="xGrid"
                          class="vxeTable"
                          element-loading-text="拼命加载中"
                          element-loading-spinner="el-icon-loading"
                          element-loading-background="rgba(255, 255, 255, 1)"
                          :columns="columns"
                          cell-class-name="common-table-cell"
                          header-cell-class-name="common-table-header"
                          max-height="500"
                          :data="dataForm.sourceData"
                          :optimization="{scrollY: {gt: 10}}"
                          @checkbox-change="selectionData"
                          @checkbox-all="selectionData">
                  <template v-slot:top>
                    <div class="btn-right bottomDiv">
                      <auth-button type="primary" size="medium" icon="iconfont iconzancun" :label="$t('common.save')" @click="save"></auth-button>
                    </div>
                  </template>
                  <!-- 文件列表 -->
                  <template v-slot:fileList="{ row, rowIndex }">
                    <div v-for="(item, index) in row.auditOutOrganFeedbackDetailFileInfoDtos" :key="index">
                      <span v-if="item.fileName" :title="item.fileName" class="span-text">{{item.fileName}}</span>
                      <btn-upload :uploadApi="uploadApi" :classType="true" :rowData="item"
                                  :title="!UtilJs.isEmpty(item.fileId) && item.fileId !== '0' ? $t('common.reUpload') : $t('common.upload')"
                                  :icon="!UtilJs.isEmpty(item.fileId) && item.fileId !== '0' ? 'iconfont iconzhongxinshangchuan' : 'iconfont iconshangchuan1'"
                                  @uploadSuccess="uploadSuccess"></btn-upload>
                      <auth-button v-if="item.fileName" class="iconCircleDel" icon="iconfont iconshanchufujian" :title="$t('common.delete')" @click="delFile(item, row, index)"></auth-button>
                    </div>
                  </template>
                  <!-- 操作 -->
                  <template v-slot:operation="{ row, rowIndex }">
                    <div>
                      <btn-upload :uploadApi="uploadApi" :classType="true" class="upload-btn"
                                  :title="row.auditOutOrganFeedbackDetailFileInfoDtos.length === 0 ? $t('common.upload') : $t('complianceCheck.suppleUpload')"
                                  :rowData="row" @uploadSuccess="bjUploadSuccess"></btn-upload>
                    </div>
                  </template>
                </vxe-grid>
              </div>
            </el-form>
          </el-collapse-item>
        </el-collapse>
      </div>
    </dialog-edit>
  </div>
</template>

<script>
import BaseEdit from '@/pages/baseEditPage.js'
import { DialogEdit, DataTable, paymentInfo, authButton, btnUpload } from 'newepoch-components'
import PayConfirmChangeHistory from '@/pages/dataAudit/lawyerProcess/payConfirmChangeHistory.vue'
import lawyerApi from '@/api/dataAudit/lawyerApi.js'
import { UPLOAD_API } from '@/constant.js'
import * as format from '@/filters/index'
import cn from '@/i18n/langs/cn.js'

const { common, complianceCheck } = cn
export default {
  extends: new BaseEdit(),
  name: 'lawyerProcessEdit',
  components: {
    DialogEdit,
    DataTable,
    paymentInfo,
    authButton,
    btnUpload,
    PayConfirmChangeHistory
  },
  methods: {
    loadData (params) {
      let _this = this
      _this.dialogApi.getDetail(params).then(res => {
        if (res && res.data) {
          res.data.forEach((it, index) => {
            if (it.feedbackOpinions === undefined) {
              this.$set(it, 'feedbackOpinions', '')
            }
            if (it.planRecuperationTime === undefined) {
              this.$set(it, 'planRecuperationTime', '')
            }
            this.$set(it, 'rowIndex', index)
          })
          _this.dataForm.sourceData = res.data
        }
      })
    },
    selectionData ({ records }) {
      this.selectedRows = records
    },
    // 文件上传成功--修改
    uploadSuccess (returnData, rowData) {
      let _this = this
      let fileUploadDto = {
        fileId: returnData.fileID,
        fileName: returnData.fileName,
        keyId: rowData.keyId,
        relationKeyId: rowData.relationKeyId
      }
      _this.dialogApi.updateFile(fileUploadDto).then(res => {
        if (res && res.data) {
          rowData.fileId = returnData.fileID
          rowData.fileName = returnData.fileName
          _this.success(common.uploadSuccess)
        } else {
          _this.error(common.uploadError)
        }
      })
    },
    // 文件新增
    bjUploadSuccess (returnData, rowData) {
      let _this = this
      let fileSaveUploadDto = {
        fileId: returnData.fileID,
        fileName: returnData.fileName,
        relationKeyId: rowData.relationInfoKeyId
      }
      _this.dialogApi.saveFile(fileSaveUploadDto).then(res => {
        if (res && res.data) {
          rowData.auditOutOrganFeedbackDetailFileInfoDtos.push(res.data)
          _this.success(common.uploadSuccess)
        } else {
          _this.error(common.uploadError)
        }
      })
    },
    // 文件删除
    delFile (item, row, idx) {
      let _this = this
      _this.dialogApi.delFile(item).then(res => {
        if (res && res.data) {
          row.auditOutOrganFeedbackDetailFileInfoDtos.splice(idx, 1)
          _this.success(common.deleteSuccess)
        }
      })
    },
    validateForm () {
      let _this = this
      let props = []
      _this.selectedRows.forEach(it => {
        props.push([`sourceData.${it.rowIndex}.feedbackOpinions`, `sourceData.${it.rowIndex}.planRecuperationTime`])
      })
      props = props.flat(Infinity)
      let validCot = 0
      _this.$refs.dataForm.validateField(props, (valid) => {
        // 不通过校验 validCot加1
        if (!_this.UtilJs.isEmpty(valid)) {
          validCot++
        }
      })
      return validCot > 0
    },
    // 保存
    save () {
      let _this = this
      const { form: { assetInfoId } } = this
      if (_this.selectedRows.length === 0) {
        _this.warning(complianceCheck.selectSaveMsg)
        return
      }
      if (this.validateForm()) {
        _this.warning(complianceCheck.saveValidMsg)
        return
      }
      let saveDto = {
        assetInfoId: assetInfoId,
        documentDetailDtoList: _this.selectedRows
      }
      _this.dialogApi.tempSave(saveDto).then(res => {
        if (res && res.data) {
          _this.success(common.saveSuccess)
          let params = { assetInfoId: assetInfoId }
          _this.selectedRows = []
          _this.loadData(params)
        } else {
          _this.error(common.saveError)
        }
      })
    },
    // 提交
    onSaved () {
      let _this = this
      const { form: { assetInfoId } } = this
      if (_this.selectedRows.length === 0) {
        _this.warning(complianceCheck.selectSubmitMsg)
        return
      }
      if (this.validateForm()) {
        _this.warning(complianceCheck.submitValidMsg)
        return
      }
      let submitDto = {
        assetInfoId: assetInfoId,
        documentDetailDtoList: _this.selectedRows
      }
      _this.dialogApi.submit(submitDto).then(res => {
        if (res && res.data) {
          _this.success(common.submittedSuccess)
          _this.$emit('submit-success')
          _this.dialogVisible = false
        } else {
          _this.error(common.submitFail)
        }
      })
    }
  },
  watch: {
    dialogVisible (val) {
      let _this = this
      if (val) {
        const { form: { assetInfoId } } = _this
        let params = { assetInfoId: assetInfoId }
        _this.$nextTick(() => {
          _this.$refs.payConfirmChangeHistory.loadData(params)
          _this.keyId = assetInfoId
          _this.loadData(params)
        })
      } else {
        _this.keyId = ''
        _this.selectedRows = []
        _this.dataForm = {
          sourceData: []
        }
        _this.$refs.dataForm.clearValidate()
      }
    }
  },
  data () {
    return {
      activeNames: ['payConfirmChangeHistory', 'paymentConfirmation', 'externalFeedbackTable'],
      keyId: '',
      uploadApi: UPLOAD_API,
      dataForm: {
        sourceData: []
      },
      selectedRows: [],
      formRules: {
        feedbackOpinions: [{ required: true, trigger: 'blur', message: common.point + complianceCheck.feedbackOpinions }],
        planRecuperationTime: [{ required: true, trigger: 'change', message: common.point + complianceCheck.planRecuperationTime }]
      },
      columns: [
        // 复选框
        {
          type: 'checkbox',
          align: 'center',
          width: '50px'
        },
        // 外部机构反馈意见
        {
          field: 'outOrganFeedbackOpinion',
          align: 'left',
          headerAlign: 'center',
          minWidth: '240px',
          showOverflow: 'title',
          title: complianceCheck.outOrganFeedbackOpinion,
          formatter: ({ cellValue, row }) => {
            return row.outOrganFeedbackTime + ' ' + cellValue
          }
        },
        // 合规处理意见
        {
          field: 'complianceDealOpinion',
          align: 'left',
          headerAlign: 'center',
          minWidth: '240px',
          showOverflow: 'title',
          title: complianceCheck.complianceDealOpinion,
          formatter: ({ cellValue, row }) => {
            return row.outOrganFeedbackTime + ' ' + cellValue
          }
        },
        // 需补资料
        {
          field: 'needSupplementaryInformation',
          align: 'center',
          headerAlign: 'center',
          minWidth: '200px',
          showOverflow: 'title',
          title: complianceCheck.needSupplementaryInformation
        },
        // 合规人员
        {
          field: 'compliancePersonName',
          align: 'center',
          headerAlign: 'center',
          minWidth: '120px',
          title: complianceCheck.compliancePersonName
        },
        // 反馈
        {
          field: 'feedbackOpinions',
          align: 'left',
          headerAlign: 'center',
          minWidth: '240px',
          title: complianceCheck.feedbackOpinions,
          slots: {
            default: ({ row, rowIndex }) => {
              return [
                <el-form-item prop={'sourceData.' + rowIndex + '.feedbackOpinions'} label-width="0" rules={ this.formRules.feedbackOpinions }>
                  <el-input v-model_trim={row.feedbackOpinions} size="medium" placeholder={common.pleaseInput}></el-input>
                </el-form-item>
              ]
            }
          }
        },
        // 预计补回时间
        {
          field: 'planRecuperationTime',
          align: 'center',
          headerAlign: 'center',
          minWidth: '165px',
          title: complianceCheck.planRecuperationTime,
          slots: {
            default: ({ row, rowIndex }) => {
              return [
                <el-form-item prop={'sourceData.' + rowIndex + '.planRecuperationTime'} label-width="0" rules={ this.formRules.planRecuperationTime }>
                  <el-date-picker v-model={row.planRecuperationTime} size="medium" placeholder={common.pleaseSelect}></el-date-picker>
                </el-form-item>
              ]
            }
          }
        },
        // 文件列表
        {
          field: 'fileList',
          align: 'center',
          headerAlign: 'center',
          minWidth: '250px',
          title: '文件列表',
          slots: { default: 'fileList' }
        },
        // 操作
        {
          field: 'operation',
          align: 'center',
          headerAlign: 'center',
          minWidth: '80px',
          title: complianceCheck.operation,
          slots: { default: 'operation' }
        },
        // 处理状态
        {
          field: 'handleStatus',
          align: 'center',
          headerAlign: 'center',
          minWidth: '120px',
          title: complianceCheck.handleStatus,
          formatter: ({ cellValue }) => {
            return format.formatDict(cellValue, 'handle_status')
          }
        }
      ]
    }
  },
  computed: {
    dialogApi () {
      return lawyerApi.lawyer
    }
  }
}
</script>

<style scoped lang="scss" src="@/styles/dataAudit/lawyerProcess/lawyerProcessEdit.scss">
</style>
