<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>
          <el-col :span="8" v-if="feedbackType === '3' || (feedbackType === '2' && stampWay === '2')">
            <el-form-item :label="$t('feedBackMain.feedbackType')" prop="auditFileType" label-width="120px">
              <file-select-list v-model="forms.auditFileType" :fileQueryType="feedbackType" :stampWay="stampWay"></file-select-list>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('feedBackMain.feedbackFrequency')" label-width="110px" prop="freq">
              <feed-back-freq-select-list v-model="forms.freq" :queryParas="newForm"></feed-back-freq-select-list>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-form-item :label="$t('feedBackMain.feedbackFrequency')" label-width="110px" prop="freq">
          <feed-back-freq-select-list 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 iconycpiliangxiazai" :size="'medium'" :label="$t('feedBackMain.batchDownloadNews')" type="primary" :loading="downloading" @click="batchDonwnload"></auth-button>
        </div>
        <fileAuditContentSub :feedbackType="feedbackType" :isBatch="true" :datas.sync="datas" :queryParas="forms" @handleOpen="handleOpen"></fileAuditContentSub>
      </div>
      <template slot="footer">
          <auth-button :size="'medium'" :label="$t('feedBackMain.store')" type="primary" @click="submit=0,$refs.dialogEdit.save();"></auth-button>
          <auth-button :size="'medium'" :label="$t('common.submit')" type="primary" @click="submit=1,$refs.dialogEdit.save();"></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 fileSelectList from '@/components/element/assetoutfeedback/fileSelectList'
import components from '@/api/assetoutfeedback/componentsApi.js'
import * as format from '@/filters/index.js'

import {
  DialogEdit,
  DataTable,
  authButton
} from 'newepoch-components'
import {
  downFile
} from '@/utils/devUtils'
import feedBackMain from '@/api/assetoutfeedback/feedBackMain/feedBackMain.js'
export default {
  extends: new BaseEdit(),
  name: 'sampleFeedBackBatchPop',
  components: {
    DialogEdit,
    DataTable,
    authButton,
    assetInfoPop,
    fileSelectList,
    feedBackFreqSelectList,
    fileAuditContentSub
  },
  props: {
    autoSave: {
      type: [Boolean],
      default: false
    },
    // 弹窗标题
    headerTitle: {
      type: [String],
      default: ''
    },
    // 反馈文件类型
    feedbackType: {
      type: [String],
      default: '1'
    }
  },
  data () {
    return {
      stampWay: '',
      options: [],
      item: {}, // 请求资产参数
      isOpen: false, // 资产信息显隐控件
      datas: [], // 处理列表
      appendToBody: true,
      menuFlag: false,
      // 校验规则
      rules: {
        freq: [
          {
            required: true,
            message: this.$t('feedBackMain.freqPrompt'),
            trigger: 'blur'
          }
        ],
        auditFileType: [
          {
            required: true,
            message: this.$t('feedBackMain.fileTypePrompt'),
            trigger: 'blur'
          }
        ]
      },
      forms: {
        freq: '',
        auditFileType: ''
      },
      downloading: false
    }
  },
  computed: {
    newForm () {
      return {
        projectId: this.form.projectId,
        periods: this.form.periods,
        auditFileType: this.forms.auditFileType
      }
    }
  },
  methods: {
    // 获取盖章方式
    getStamp () {
      let args = {
        projectId: this.form.projectId,
        participant: '60',
        specialPlanPeriods: this.form.periods
      }
      return new Promise((resolve, reject) => {
        components.stamp.getDefault(args).then(res => {
          if (res.success && res.data && res.data.length > 0) {
            resolve(res.data[0].stampWay)
          } else {
            this.warning(this.$t('feedBackMain.noStamp'))
            resolve('')
          }
        }).catch(res => {
          resolve('')
        })
      })
    },
    // 批量下载资料
    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 fileMakerDTOList = []
            let fileList = [] // 文件列表
            selectedRows.forEach((item, index) => {
              let fileIds = []
              let path = `${this.form.projectName + this.form.periods}期第${this.forms.freq}批资料/${index + 1 + '.' + item.assetCode + (item.creditor || '')}/`
              // 筛选出补出资料
              if (item.feedAuditAssetQstDetailListDtos && item.feedAuditAssetQstDetailListDtos.length > 0) {
                item.feedAuditAssetQstDetailListDtos.forEach(item2 => {
                  if (item2.fileInfos && item2.fileInfos.length > 0) {
                    let len = item2.fileInfos.length
                    fileIds = item2.fileInfos.map((i, idx) => {
                      let fileMakerDTO = {}
                      if (len === 1) {
                        fileMakerDTO.name = `（${item2.qusetionNumber}）${i.fileName}`
                      } else {
                        fileMakerDTO.name = `（${item2.qusetionNumber}）-${idx + 1}${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.noFiles'))
              return false
            }
            // 配置请求参数
            let args = {
              encoding: 'utf-8',
              fileMakerDTOList: fileMakerDTOList,
              fileName: `${this.form.projectName + this.form.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('feedBackMain.noFiles'))
          }
        } else {
          this.downloading = false
        }
      })
    },
    // 打开资产信息
    handleOpen (id) {
      this.item.keyId = id
      this.isOpen = true
    },
    // 暂存/提交
    handleSubmit () {
      // 请求地址
      let url = ['feedauditBatchTpsave', 'feedauditBatchSave'][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).filter(item => {
        return item.isShow === true
      }).map(item => {
        if (item.feedAuditAssetQstDetailListDtos) {
          item.saveFeedBackAuditContentDtos = item.feedAuditAssetQstDetailListDtos.map((e, index) => {
            if (e.tempSaveFlag) {
              e.extOrgQustionResult = '4'
              delete e.index
            }
            // e.feedbackTimes = '1'
            // e.qusetionNumber = (index + 1).toString()
            // e.feedbackAssetKey = item.keyId
            // e.feedbackQustionNo = item.keyId + (index + 1).toString()
            return e
          })
          delete item.feedAuditAssetQstDetailListDtos
        }
        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
      })
      if (datas.length < 1) {
        this.warning(this.$t('feedBackMain.noData'))
      }
      // 配置请求参数
      // let args = {
      //   'auditFileType': this.form.auditFileType,
      //   'feedbackFrequency': this.forms.freq.toString(),
      //   'periods': this.form.periods,
      //   'projectId': this.form.projectId,
      //   'sampleFeedBackListDtos': datas
      // }
      // 校验意见是否存在
      for (let index in datas) {
        let item = datas[index]
        if (item.saveFeedBackAuditContentDtos) {
          for (let index2 in item.saveFeedBackAuditContentDtos) {
            let item2 = item.saveFeedBackAuditContentDtos[index2]
            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
              }
            }
          }
        }
      }
      this.assetpkgmgrFullScreenLoading()
      feedBackMain[url].putData(datas).then(res => {
        this.assetpkgmgrFullScreenLoading().close()
        if (res.success && res.data) {
          this.success(success)
          // 若母组件是外部机构反馈页面
          if (this.$parent.handleFilter) {
            this.$parent.handleFilter()
          // 若是其他页面
          } else {
            this.$emit('handleFilter')
          }
          this.dialogVisible = false
        } else {
          this.error(error)
        }
      }).catch(res => this.assetpkgmgrFullScreenLoading().close())
    },
    getList () {
      let args = {
        projectId: this.form.projectId,
        projectName: this.form.projectName,
        periods: this.form.periods,
        auditFileType: this.forms.auditFileType
      }
      if (!args.auditFileType) {
        this.$nextTick(() => {
          this.warning(this.$t('feedBackMain.checkAuditFileType'))
        })
        return false
      }
      this.assetpkgmgrFullScreenLoading()
      feedBackMain.feedauditBatchList.getList(args).then(res => {
        this.assetpkgmgrFullScreenLoading().close()
        if (res.success && res.data && res.data.length > 0) {
          this.datas = res.data.map(item => {
            item.isShow = true
            item.factoringMoney = format.thousandFilter(item.factoringMoney)
            return item
          })
        } else {
          this.warning(this.$t('feedBackMain.noData'))
        }
      }).catch(res => this.assetpkgmgrFullScreenLoading().close())
    }
  },
  watch: {
    async visible (val) {
      if (val) {
        let $this = this
        // 初始化
        $this.datas = []
        $this.forms.auditFileType = $this.form.auditFileType || ''
        if (this.feedbackType === '2') {
          $this.stampWay = await $this.getStamp()
          if ($this.stampWay === '1') {
            $this.forms.freq = 1
            $this.forms.auditFileType = '2001'
          } else if ($this.stampWay === '2') {
            $this.forms.freq = ''
            $this.forms.auditFileType = ''
          } else {
            $this.forms.freq = ''
            $this.forms.auditFileType = ''
          }
        } else if (this.feedbackType === '1') {
          $this.forms.freq = 1
        } else {
          $this.forms.freq = ''
        }
        $this.$nextTick(() => {
          this.getList()
        })
      }
    },
    'forms.auditFileType' (val) {
      this.datas = []
      this.newForm.auditFileType = val
      this.$nextTick(() => {
        this.getList()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  @import '~@/styles/assetoutfeedback/common.scss'
</style>
