<template>
  <dialog-edit :visible.sync="dialogVisible" :title="$t('complianceCheck.dealEditTitle')" width="1480px"
               :form="form" :footerBtnShow="false" :api="api" :editModel="editModel" :append-to-body="true">
    <el-form :model="dataForm" ref="dataForm" class="table-item">
      <data-table :handleFlag.sync="handleFlag" :showPage="false" :columns="columns" ref="auditTable" max-height="540"
                  :queryParas="queryParas" :sourceData.sync="dataForm.sourceData" operateBtnLayout="">

        <template slot="headButton">
          <div class="headButton">
            <span class="spanClass">{{$t('complianceCheck.payCode') + '：' + form.assetCode}}</span>
            <auth-button icon="iconfont iconxiazai12" size="medium" type="primary"
                         :label="$t('complianceCheck.allDownload')" @click="allDownload"></auth-button>
          </div>
        </template>

        <!-- 合规反馈意见 -->
        <template v-slot:complianceOpinions="scope">
          <el-form-item label-width="0" :prop="'sourceData.' + scope.data.$index + '.complianceOpinions'"
                        :rules="scope.data.row.ifsSupplement === 1 ? { required: true, validator: complianceOpinionsCheck, trigger: 'blur', row: scope.data.row } : {}">
            <el-input v-model.trim="scope.data.row.complianceOpinions" maxlength="500" :placeholder="changeHolder(scope.data.row)"></el-input>
          </el-form-item>
        </template>

        <!-- 操作 -->
        <el-table-column :label="$t('common.operate')" align="center" width="120px">
          <template slot-scope="scope">
            <div v-if="scope.row.status">
              <auth-button v-if="scope.row.ifsSupplement === 0" class="iconCircle" icon="iconfont icontingbuji" :title="$t('complianceCheck.stopMail')" @click="stopMail(scope.row)"></auth-button>
              <auth-button v-if="scope.row.ifsSupplement === 1" class="iconCircle" icon="iconfont iconquxiaotingbuji" :title="$t('complianceCheck.stopMailCancel')" @click="stopMailCancel(scope.row)"></auth-button>
            </div>
          </template>
        </el-table-column>
      </data-table>
    </el-form>
    <div class="number">
      <span>{{$t('common.viewTip1')}}{{startNum}}{{$t('common.viewTip2')}}{{endNum}}{{$t('common.viewTip3')}}{{endNum}}{{$t('common.viewTip4')}}</span>
    </div>
    <template slot="footer">
      <auth-button :loading="loading" type="primary" size="medium" :label="$t('common.submit')" @click="submit"></auth-button>
      <auth-button :loading="saveLoad" type="primary" size="medium" :label="$t('common.allSave')" @click="allSave"></auth-button>
      <auth-button size="medium" :label="$t('common.close')" @click="dialogVisible = false"></auth-button>
    </template>
  </dialog-edit>
</template>
<script>
import BaseEdit from '@/pages/baseEditPage.js'
import { DialogEdit, DataTable, authButton, btnBatchDownload } from 'newepoch-components'
import complianceApi from '@/api/dataAudit/complianceApi.js'
import fileApi from '@/api/fileApi.js'
import { downFile } from '@/utils/devUtils.js'
import * as format from '@/filters/index'
import cn from '@/i18n/langs/cn.js'

const { complianceCheck, common } = cn
export default {
  name: 'auditHistoryEdit',
  extends: new BaseEdit(),
  components: {
    DialogEdit,
    DataTable,
    authButton,
    btnBatchDownload
  },
  data () {
    return {
      handleFlag: false,
      loading: false,
      saveLoad: false,
      queryParas: {},
      startNum: 0,
      endNum: 0,
      dataForm: {
        sourceData: []
      },
      formRules: {
        complianceOpinions: [{ required: true, validator: this.complianceOpinionsCheck, trigger: 'blur' }]
      },
      columns: [
        // 资料名称
        {
          prop: 'fileName',
          align: 'left',
          label: complianceCheck.fileName,
          width: '200px'
        },
        // 需求份数
        {
          prop: 'needCopies',
          align: 'right',
          label: complianceCheck.neededNumber,
          width: '120px'
        },
        // 已有份数
        {
          prop: 'validCopies',
          align: 'right',
          label: complianceCheck.existNumber,
          width: '120px'
        },
        // 单证审核意见
        {
          prop: 'auditOpinions',
          align: 'left',
          label: complianceCheck.documentsAuditOpinion,
          width: '200px',
          format: (row) => { return row.status ? row.auditOpinions : '-' }
        },
        // 合规反馈意见
        {
          prop: 'complianceOpinions',
          align: 'left',
          label: complianceCheck.complianceFeedbackOpinion,
          width: '200px',
          slot: true
        },
        // 合规已停补寄
        {
          prop: 'ifsSupplement',
          align: 'center',
          label: complianceCheck.complianceMail,
          width: '120px',
          format: (row) => { return row.status ? format.formatDict(row.ifsSupplement, 'ZDZD0024') : '-' }
        }
      ]
    }
  },
  computed: {
    api () {
      return complianceApi.assetAuditApi
    }
  },
  methods: {
    changeHolder (data) {
      if (data.holderFlag === 0) {
        return complianceCheck.complianceOpinionsMsg
      } else {
        return complianceCheck.inputMsg
      }
    },
    complianceOpinionsCheck (rule, value, callback) {
      let _this = this
      let data = rule.row
      if (!_this.UtilJs.isEmpty(value)) {
        data.holderFlag = 1
        callback()
      } else {
        data.holderFlag = 0
        callback(new Error(complianceCheck.complianceOpinionsMsg))
        // _this.warning(complianceCheck.complianceOpinionsMsg)
      }
    },
    loadData (paras) {
      let _this = this
      _this.api.getDetail(paras).then(res => {
        if (res && res.data) {
          if (res.data.length > 0) {
            _this.startNum = 1
            _this.endNum = res.data.length
          } else {
            _this.startNum = 0
            _this.endNum = 0
          }
          _this.dataForm.sourceData = res.data
          _this.dataForm.sourceData.forEach(it => {
            if (it.validCopies >= it.needCopies) {
              _this.$set(it, 'status', false)
            } else {
              _this.$set(it, 'status', true)
            }
            _this.$set(it, 'holderFlag', 1)
          })
        }
      })
    },
    // 一键下载
    allDownload () {
      let _this = this
      let fileIds = []
      _this.api.download({ assetInfoId: _this.form.assetInfoId }).then(res => {
        if (res && res.data) {
          fileIds = res.data
          if (fileIds.length > 0) {
            fileApi.file.batchDownload({ keyIds: fileIds }).then(res => {
              downFile(res)
            })
          } else {
            _this.warning(common.noDownloadFileMsg)
          }
        } else {
          _this.warning(common.noDownloadFileMsg)
        }
      })
    },
    // 停补寄
    stopMail (row) {
      if (!this.UtilJs.isEmpty(row.ifsSupplement)) {
        row.ifsSupplement = 1
      }
    },
    // 取消停补寄
    stopMailCancel (row) {
      if (!this.UtilJs.isEmpty(row.ifsSupplement)) {
        row.ifsSupplement = 0
        row.holderFlag = 1
      }
    },
    // 提交
    submit () {
      let _this = this
      _this.$refs.dataForm.validate((valid) => {
        if (valid) {
          _this.$confirm(this.$i18n.messages[this.$i18n.locale].complianceCheck.submitMsg, this.$i18n.messages[this.$i18n.locale].common.tip, {
            type: 'warning'
          }).then(() => {
            let submitArr = _this.buildDto(_this.dataForm.sourceData)
            _this.loading = true
            _this.api.submit(submitArr).then(res => {
              if (res && res.data) {
                this.success(complianceCheck.submitSucMsg)
                this.dialogVisible = false
                this.$emit('deal-success')
              } else {
                this.error(complianceCheck.submitFailMsg)
              }
              _this.loading = false
            }).catch(() => {
              _this.loading = false
            })
          }).catch(() => {})
        } else {
          this.error(this.$i18n.messages[this.$i18n.locale].complianceCheck.validSubmitMsg)
        }
      })
    },
    // 一键保存
    allSave () {
      let _this = this
      _this.$refs.dataForm.validate((valid) => {
        if (valid) {
          let saveArr = _this.buildDto(_this.dataForm.sourceData)
          _this.saveLoad = true
          _this.api.save(saveArr).then(res => {
            if (res && res.data) {
              this.success(complianceCheck.saveSucMsg)
              this.dialogVisible = false
              this.$emit('deal-success')
            } else {
              this.error(complianceCheck.saveFailMsg)
            }
            _this.saveLoad = false
          }).catch(() => {
            _this.saveLoad = false
          })
        } else {
          this.error(this.$i18n.messages[this.$i18n.locale].complianceCheck.validSaveMsg)
        }
      })
    },
    buildDto (data) {
      let _this = this
      let arr = []
      data.forEach(item => {
        arr.push(Object.assign({
          auditorUserId: _this.$store.getters.user.userId,
          auditorUserName: _this.$store.getters.user.userName,
          complianceCheckAssetsInfoId: _this.form.keyId
        }, item))
      })
      return arr
    }
  },
  watch: {
    visible (val) {
      let _this = this
      if (val) {
        _this.loadData({ assetInfoId: _this.form.assetInfoId })
      } else {
        this.dataForm.sourceData = []
      }
    }
  }
}
</script>
<style scoped lang="scss" src="@/styles/dataAudit/compliance/dealDetailEdit.scss">
</style>
