<template>
  <div>
    <!-- 抽样文件待审核 -->
    <dialog-edit ref="dialogEdit" :visible.sync="dialogVisible" :form="forms" :autoSave="autoSave"
      :editModel="editModel" :appendToBody="appendToBody" :title="headerTitle"
      @onSaved="handleSubmit" :formRules="rules" :footerBtnShow="false">
      <div v-if="dialogVisible">
        <el-row class="sampleFileAudit">
          <el-col :span="8" v-if="feedbackType !== '1'">
            <el-form-item :label="$t('feedBackMain.feedbackType')" prop="auditFileType" label-width="100px">
              <file-select-list disabled v-model="forms.auditFileType" :fileQueryType="feedbackType" stampWay="3"></file-select-list>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('feedBackMain.feedbackFrequency')" label-width="100px" prop="freq">
              <feed-back-freq-select-list disabled v-model="forms.freq" :queryParas="newForm"></feed-back-freq-select-list>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <!-- <el-form-item :label="$t('feedBackMain.feedbackFrequency')" label-width="110px" prop="freq">
          <feed-back-freq-select-list :disabled="true" v-model="forms.freq" :queryParas="newForm"></feed-back-freq-select-list>
        </el-form-item> -->
        <div align="right" class="box-column-margin-bottom">
            <auth-button class="iconfont iconxiazai1" :size="'medium'" :label="$t('feedBackMain.batchDownloadNews')" type="primary" :loading="downloading" @click="batchDonwnload"></auth-button>
        </div>
        <fileAuditContentSub :feedbackType="feedbackType" :datas.sync="datas" :queryParas="forms" @handleOpen="handleOpen" :showButton.sync="showButton"></fileAuditContentSub>
      </div>
      <template slot="footer">
          <auth-button v-if="showButton || currentRow.isAudit" :size="'medium'" :label="$t('feedBackMain.store')" type="primary" @click="submit=0,$refs.dialogEdit.save();"></auth-button>
          <auth-button v-if="showButton || currentRow.isAudit" :size="'medium'" :label="$t('common.submit')" type="primary" @click="submit=1,$refs.dialogEdit.save();"></auth-button>
          <auth-button :size="'medium'" :label="$t('common.close')" type="default" @click="dialogVisible = false"></auth-button>
      </template>
    </dialog-edit>
    <asset-info-pop :visible.sync="isOpen" editModel="V" :form="item"></asset-info-pop>
  </div>
</template>

<script>
import BaseEdit from '@/pages/baseEditPage'
import feedBackFreqSelectList from '@/components/element/assetoutfeedback/feedBackFreqSelectList'
import fileAuditContentSub from '@/pages/assetoutfeedback/feedBackMain/fileAuditContentSub'
import assetInfoPop from '@/pages/assetoutfeedback/feedBackMain/assetInfoPop'
import feedBackMain from '@/api/assetoutfeedback/feedBackMain/feedBackMain.js'
import {
  DialogEdit,
  DataTable,
  authButton
} from 'newepoch-components'
// import fileApi from '@/api/fileApi.js'
import {
  downFile
} from '@/utils/devUtils'
import fileSelectList from '@/components/element/assetoutfeedback/fileSelectList'
import * as format from '@/filters/index.js'

export default {
  extends: new BaseEdit(),
  name: 'sampleFileAuditSinglePop',
  components: {
    DialogEdit,
    DataTable,
    assetInfoPop,
    fileSelectList,
    authButton,
    feedBackFreqSelectList,
    fileAuditContentSub
  },
  props: {
    autoSave: {
      type: [Boolean],
      default: false
    },
    // 弹窗标题
    headerTitle: {
      type: [String],
      default: ''
    },
    // 反馈文件类型
    feedbackType: {
      type: [String],
      default: '1'
    },
    // 传进表单参数
    currentRow: {
      type: [Object],
      default () {
        return null
      }
    }
  },
  data () {
    return {
      options: [],
      item: {}, // 请求资产参数
      isOpen: false, // 资产信息显隐控件
      datas: [], // 处理列表
      appendToBody: true,
      menuFlag: false,
      // 校验规则
      rules: {
        freq: [
          {
            required: true,
            message: this.$t('feedBackMain.freqPrompt'),
            trigger: 'change'
          },
          {
            required: true,
            message: this.$t('feedBackMain.freqPrompt'),
            trigger: 'blur'
          }
        ]
      },
      forms: {
        freq: ''
      },
      showButton: true,
      downloading: false
    }
  },
  computed: {
    // 是否暂存
    isTempSave () {
      for (let index in this.datas) {
        let item = this.datas[index]
        for (let index2 in item.feedAuditAssetQstDetailListDtos) {
          let item2 = item.feedAuditAssetQstDetailListDtos[index2]
          if (item2.tempSaveFlag || item2.extOrgQustionResult === '4') {
            return true
          }
        }
      }
      return false
    },
    newForm () {
      return {
        projectId: this.currentRow.projectId,
        periods: this.currentRow.periods,
        auditFileType: this.currentRow.auditFileType
      }
    }
  },
  methods: {
    // 批量下载资料
    batchDonwnload (ids) {
      let that = this
      let selectedRows = that.datas
      this.downloading = true
      // 校验批次
      this.$refs.dialogEdit.$refs['editForm'].validate((valid) => {
        if (valid) {
          // 是否有选中项
          if (selectedRows.length > 0) {
            // 编辑目录结构
            let fileList = [] // 文件列表
            let fileMakerDTOList = []
            selectedRows.forEach((item, index) => {
              let path = `${this.currentRow.projectName + this.currentRow.periods}期第${this.forms.freq}批资料/${index + 1 + '.' + item.assetCode + (item.creditor || '')}/`
              let fileIds = []
              // 筛选出补出资料
              if (item.feedAuditAssetQstDetailListDtos && item.feedAuditAssetQstDetailListDtos.length > 0) {
                item.feedAuditAssetQstDetailListDtos.forEach((item2, idx) => {
                  if (item2.fileInfos && item2.fileInfos.length > 0) {
                    fileIds = item2.fileInfos.map((i, idx2) => {
                      let fileMakerDTO = {}
                      fileMakerDTO.name = `（${item2.qusetionNumber}）${i.fileName}`
                      fileMakerDTO.path = path
                      fileMakerDTO.keyId = i.fileId
                      fileMakerDTOList.push(fileMakerDTO)
                      return i.fileId
                    })
                  }
                })
              }
              // 计算文件
              if (fileIds.length > 0) {
                fileList.push(fileIds)
              }
            })
            // 是否存在文件
            if (fileList.length < 1) {
              this.downloading = false
              this.warning(that.$t('feedBackMain.downPrompt'))
              return false
            }
            let args = {
              encoding: 'utf-8',
              fileMakerDTOList: fileMakerDTOList,
              fileName: `${this.currentRow.projectName + this.currentRow.periods}期第${this.forms.freq}批资料`
            }
            this.$confirm(this.$t('common.confirm') + this.$t('common.downLoad'), this.$t('common.tip'), {
              type: 'warning'
            }).then(() => {
              feedBackMain.compressDownload.getFile(args).then(res => {
                this.downloading = false
                downFile(res)
              }).catch(res => {
                this.downloading = false
              })
            }).catch((e) => {
              this.downloading = false
            })
          } else {
            this.downloading = false
            that.warning(that.$t('common.selectOperateTip'))
          }
        } else {
          this.downloading = false
        }
      })
    },
    // 打开资产信息
    handleOpen (id) {
      this.item.keyId = id
      this.isOpen = true
    },
    // 暂存/提交
    handleSubmit () {
      // 请求地址
      let url = ['feedauditSingleTpsave', 'feedauditSingleSave'][this.submit]
      // 成功提示
      let success = [this.$t('feedBackMain.saveSuccess'), this.$t('feedBackMain.submitSuccess')][this.submit]
      // 错误提示
      let error = [this.$t('feedBackMain.saveError'), this.$t('feedBackMain.submitError')][this.submit]
      // 筛选操作的资产
      // console.log(this.datas)
      let datas = this.UtilJs.cloneDeep(this.datas).map(item => {
        if (item.feedAuditAssetQstDetailListDtos) {
          item.saveFeedBackAuditContentDtos = item.feedAuditAssetQstDetailListDtos.map((e, index) => {
            // 是否为暂存意见
            if (e.index || e.tempSaveFlag) {
              e.feedbackQustionNo = item.keyId + (e.index || e.qusetionNumber)
              e.feedbackAssetKey = item.keyId
              e.qusetionNumber = e.index || e.qusetionNumber
              delete e.index
            }
            if (e.tempSaveFlag) {
              e.extOrgQustionResult = '4'
            }
            // 提交时，若问题状态为：6 审核中 or 问题状态为：(7 通过 or 8 不通过) 暂存处理标志为： 2 暂存中
            if (this.submit === 1 && (e.questionStatus === '6' || (e.questionStatus === '7' && e.dealTempSaveFlag === '2') || (e.questionStatus === '8' && e.dealTempSaveFlag === '2'))) {
              if (e.extOrgQustionResult === '1') {
                e.questionStatus = '7'
              } else if (e.extOrgQustionResult === '2' || e.extOrgQustionResult === '3') {
                e.questionStatus = '8'
              }
              e.dealTempSaveFlag = '2'
            }
            // e.feedbackTimes = '1'
            // e.qusetionNumber = (index + 1).toString()
            // e.feedbackAssetKey = item.keyId
            // e.feedbackQustionNo = item.keyId + (index + 1).toString()
            return e
          })
          delete item.feedAuditAssetQstDetailListDtos
        }
        // 是审核还是查看，审核flag设为0，反之为1
        if (this.$parent.componentType && this.$parent.componentType === 4) {
          item.flag = '0'
        } else {
          item.flag = '1'
        }
        // 删除多余参数
        delete item.position
        delete item.spanArr
        delete item.number
        delete item.position2
        delete item.isShow
        delete item.assetCode
        delete item.dealEndFlag
        delete item.chargeBackStatus
        return item
      })
      // 配置请求参数
      // let args = {
      //   'auditFileType': this.form.auditFileType,
      //   'feedbackFrequency': this.forms.freq.toString(),
      //   'periods': this.form.periods,
      //   'projectId': this.form.projectId,
      //   'sampleFeedBackListDtos': datas
      // }
      // 校验意见是否存在
      let item = datas[0]
      let extOrgQustionResultList = [] // 审核结果集合
      let questionNumberList = [] // 已检测问题序号
      if (item.saveFeedBackAuditContentDtos) {
        for (let index2 in item.saveFeedBackAuditContentDtos) {
          let item2 = item.saveFeedBackAuditContentDtos[index2]
          // 若此问题序号未检测，则遍历履历，取最后一个履历（仅限提交时）
          if (this.submit === 1 && !questionNumberList.includes(item2.qusetionNumber)) {
            questionNumberList.push(item2.qusetionNumber)
            // 问题履历集合
            let questionList = item.saveFeedBackAuditContentDtos.filter(t => {
              return item2.qusetionNumber === t.qusetionNumber
            })
            // 问题的最末履历
            let qusetionHistoryNumberLast = questionList[questionList.length - 1]
            // 最末履历列表的第一条的审核结果（可能会有多个相关方，合并时，审核结果取得第一条）
            let extOrgQustionResult = questionList.filter(m => {
              return m.qusetionHistoryNumber === qusetionHistoryNumberLast.qusetionHistoryNumber
            })[0].extOrgQustionResult
            // 添加到审核结果集合里
            extOrgQustionResultList.push(extOrgQustionResult)
          }
          // 若不合格，则判断意见是否填写
          if (item2.extOrgQustionResult === '2' || item2.extOrgQustionResult === '3') {
            if (!item2.extOrgOpinionContent) {
              this.warning(this.$t('feedBackMain.auditPrompt'))
              return false
            }
          }
          // 若是暂存，则判断意见是否填写
          if (item2.extOrgQustionResult === '4') {
            if (!item2.feedbackQuestionContent) {
              this.warning(this.$t('feedBackMain.addFeedbackPrompt'))
              return false
            }
          }
        }
      } else {
        this.warning(this.$t('feedBackMain.noDeal'))
        return
      }
      // 问题审核结果是否全部合格（全部为1）
      if (extOrgQustionResultList.length > 0 && extOrgQustionResultList.every(i => {
        return i === '1'
      })) {
        // 是否确认合格
        this.$confirm(this.$t('feedBackMain.allSuccess'), this.$t('common.tip'), {
          type: 'warning'
        }).then(() => {
          // 确认
          item.qualifiedFlag = '2'
          // 合格回调
          this.getEndFeedbackFlag(url, item, success, error)
        }).catch((e) => {
          // 取消合格，提交完成
          item.qualifiedFlag = '1'
          this.submitForm(url, item, success, error, (res) => {
            this.success(success)
            this.$parent.handleFilter()
            this.dialogVisible = false
          })
        })
      } else {
        if (this.submit === 1) {
          item.qualifiedFlag = '1'
        }
        // 提交或暂存
        this.submitForm(url, item, success, error, (res) => {
          this.success(success)
          this.$parent.handleFilter()
          this.dialogVisible = false
        })
      }
    },
    // 合格过后回调
    async getEndFeedbackFlag (url, item, success, error) {
      // 获取结束反馈标志
      let datas = await new Promise((resolve, reject) => {
        this.submitForm(url, item, success, error, (res) => {
          resolve(res.data)
        })
      })
      // endFeedbackFlag为2代表可以结束反馈
      if (datas && datas.endFeedbackFlag === '2') {
        // 确认结束反馈
        this.$confirm(this.$t('feedBackMain.allEnd'), this.$t('common.tip'), {
          type: 'warning'
        }).then(() => {
          // 去结束反馈
          this.handleFeedback(datas)
        }).catch((e) => {
          // 取消结束，提交完成
          this.success(success)
          this.$parent.handleFilter()
          this.dialogVisible = false
        })
        // 不能结束反馈，提交完成
      } else {
        this.success(success)
        this.$parent.handleFilter()
        this.dialogVisible = false
      }
    },
    // 结束反馈
    handleFeedback (datas) {
      let $this = this
      // console.log(this.modifyTime)
      // 配置参数：产品，期数，文件类型，更新时间，反馈类型
      let args = {
        projectId: $this.currentRow.projectId,
        periods: $this.currentRow.periods,
        auditFileType: $this.currentRow.auditFileType,
        modifyTime: datas.modifyTime,
        operType: '1' // 结束
      }
      // $this.loading = true
      feedBackMain.over.putData(args).then(res => {
        $this.loading = false
        if (res.success && res.data) {
          $this.success($this.$t('feedBackMain.handleSuccess'))
          // 重置列表
          $this.$parent.handleFilter()
          $this.dialogVisible = false
        } else {
          $this.error($this.$t('feedBackMain.handleError'))
        }
      }).catch(res => {
        // $this.loading = false
      })
    },
    // 提交表单
    submitForm (url, item, success, error, callback) {
      this.assetpkgmgrFullScreenLoading()
      feedBackMain[url].putData(item).then(res => {
        this.assetpkgmgrFullScreenLoading().close()
        let success = res.success && res.data && (this.submit === 1 ? res.data.flag : true)
        if (success) {
          callback && callback(res)
        } else {
          this.error(error)
        }
      }).catch(res => {
        this.assetpkgmgrFullScreenLoading().close()
      })
    }
  },
  watch: {
    visible (val) {
      if (val) {
        let $this = this
        // 初始化
        $this.datas = []
        $this.showButton = false
        $this.$nextTick(() => {
          // 批次是否存在，不存在默认为1
          $this.forms.freq = $this.currentRow.feedbackFrequency ? Number($this.currentRow.feedbackFrequency) : 1
          // 设置文件类型
          this.$set(this.forms, 'auditFileType', $this.currentRow.auditFileType)
          let args = {
            keyId: $this.currentRow.keyId
          }
          feedBackMain.assetSingle.getDefault(args).then(res => {
            if (res.success && res.data) {
              res.data.factoringMoney = format.thousandFilter(res.data.factoringMoney)
              let datas = [res.data]
              $this.datas = datas
              for (let index in datas) {
                let item = datas[index]
                for (let index2 in item.feedAuditAssetQstDetailListDtos) {
                  let item2 = item.feedAuditAssetQstDetailListDtos[index2]
                  if (item2.tempSaveFlag) {
                    $this.showButton = true
                    return true
                  }
                }
              }
              this.showButton = false
            }
          })
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
  @import '~@/styles/assetoutfeedback/common.scss';
</style>
<style lang="scss">
.sampleFileAudit .el-form-item{
  margin-bottom: 0 !important;
}
</style>
