<template>
  <div>
    <!-- 确权文件批量下载 -->
    <dialog-edit ref="dialogEdit" :visible.sync="dialogVisible" :form="forms" :autoSave="autoSave"
      :editModel="editModel" :appendToBody="appendToBody" :title="headerTitles"
      @onSaved="handleSubmit" :loading="loading" :formRules="rules" :saveLabel="$t('common.downLoad')" v-bind="{width:'600px'}">
      <el-row type="flex" justify="center">
        <el-col :span="15">
          <div class="flex-center">
            <!-- 下载表单 -->
            <div>
            <!-- <el-form ref="form" :model="forms" label-width="80px"> -->
              <el-form-item :label="$t('feedBackMain.auditFileType')" prop="auditFileType">
                <!-- 第三方待调试 -->
                <file-select-list filterable v-model="forms.auditFileType" :fileQueryType="feedbackType" :stampWay="stampWay === '0' ? '' : stampWay"></file-select-list>
              </el-form-item>
              <el-collapse-transition>
                <el-form-item v-if="downRangeList.length > 1" :label="$t('feedBackMain.downloadType')">
                  <el-checkbox-group v-model="forms.sendFrequency" @change="handleChange">
                    <template v-for="item in downRangeList">
                      <el-checkbox v-if="item.isShow || item.id === '0'" :key="item.id" :label="item.id" name="downRange" style="display:block">{{item.label}}</el-checkbox>
                    </template>
                  </el-checkbox-group>
                </el-form-item>
              </el-collapse-transition>
            <!-- </el-form> -->
            </div>
          </div>
        </el-col>
      </el-row>
    </dialog-edit>
  </div>
</template>
<script>
import BaseEdit from '@/pages/baseEditPage'
import externalTransition from '@/components/element/assetoutfeedback/externalTransition'
import {
  DialogEdit,
  DataTable,
  authButton
} from 'newepoch-components'
import fileSelectList from '@/components/element/assetoutfeedback/fileSelectList'
import feedBackMain from '@/api/assetoutfeedback/feedBackMain/feedBackMain.js'
// import fileApi from '@/api/fileApi.js'
import components from '@/api/assetoutfeedback/componentsApi.js'

import {
  downFile
} from '@/utils/devUtils'
export default {
  extends: new BaseEdit(),
  name: 'confirmFileDownBatchPop',
  components: {
    DialogEdit,
    DataTable,
    authButton,
    fileSelectList,
    externalTransition
  },
  props: {
    autoSave: {
      type: [Boolean],
      default: false
    },
    headerTitle: {
      type: [String],
      default: ''
    },
    // 反馈文件类型
    feedbackType: {
      type: [String],
      default: '1'
    }
  },
  computed: {
    headerTitles () {
      return this.feedbackType === '2' ? {
        '0': this.$t('feedBackMain.fileDownload'),
        '1': this.$t('feedBackMain.fileDownloadOne'),
        '2': this.$t('feedBackMain.fileDownloadTwo')
      }[this.stampWay] : this.headerTitle
    }
  },
  data () {
    return {
      stampWay: '0', // 盖章方式,默认为空
      appendToBody: true,
      toolMenuFlag: true,
      loadCount: 0,
      menuFlag: false,
      operateBtnLayout: '',
      loading: false, // 加载控件
      loadingFlag: false, // 加载动画控件
      queryParas: {},
      forms: {
        auditFileType: '',
        sendFrequency: []
      },
      // 校验规则
      rules: {
        auditFileType: [
          {
            required: true,
            message: this.$t('feedBackMain.fileTypePrompt'),
            trigger: 'change'
          },
          {
            required: true,
            message: this.$t('feedBackMain.fileTypePrompt'),
            trigger: 'blur'
          }
        ]
      },
      // 批次列表
      downRangeList: [{
        id: '0',
        label: this.$t('feedBackMain.downloadAll')
      }],
      // 表头
      modifyColumns: [
        // 付款确认书编号
        {
          prop: 'assetCode',
          align: 'center',
          sortable: true,
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].sendLoanInfo.payCode,
          width: '160px'
        }
      ],
      maxSendFrequency: ''
    }
  },
  methods: {
    handleChange (e) {
      if (e.length > 0) {
        if (e[e.length - 1] === '0' || e[e.length - 1] === '-1') {
          this.forms.sendFrequency = [e[e.length - 1]]
        } else {
          if (this.forms.sendFrequency.indexOf('0') !== -1) {
            this.forms.sendFrequency.splice(this.forms.sendFrequency.indexOf('0'), 1)
          }
          if (this.forms.sendFrequency.indexOf('-1') !== -1) {
            this.forms.sendFrequency.splice(this.forms.sendFrequency.indexOf('-1'), 1)
          }
        }
      }
    },
    // 下载
    handleSubmit (e) {
      // let list = this.UtilJs.cloneDeep(this.downRangeList)
      this.loading = true
      let args = {
        auditFileType: this.forms.auditFileType,
        periods: this.form.periods,
        projectId: this.form.projectId
      }
      // 是否下载全部
      if (e.sendFrequency.indexOf('0') !== -1) {
        args.downloadFlag = '1'
        args.maxSendFrequency = this.maxSendFrequency
      } else if (e.sendFrequency.indexOf('-1') !== -1) {
        args.downloadFlag = '2'
        args.maxSendFrequency = this.maxSendFrequency
      } else if (e.sendFrequency.indexOf('0') === -1 && e.sendFrequency.indexOf('-1') === -1) {
        // console.log(e.sendFrequency)
        args.sendFrequency = e.sendFrequency
        if (args.sendFrequency.length < 1) {
          this.warning(this.$t('feedBackMain.noRange'))
          this.loading = false
          return
        }
      }
      feedBackMain.asset.getList(args).then(res => {
        if (res.success && res.data.fileMakerDTOList && res.data.fileMakerDTOList.length > 0) {
          feedBackMain.compressDownload.getFile(res.data).then(ress => {
            //   fileApi.file.downloadByUUID({
            //     uuid: res.data,
            //     encoding: 'utf-8'
            //   }, '{Encoding}').then(ress => {
            this.loading = false
            downFile(ress)
            // downFile(ress, this.$t('feedBackMain.sampleFile'))
            //   }).catch(res => {
            //     this.loading = false
            //   })
          }).catch(res => {
            this.loading = false
          })
        } else {
          this.loading = false
          this.warning(this.$t('feedBackMain.noFiles'))
        }
        // if (res.success && res.data) {
        //   fileApi.file.downloadByUUID({
        //     uuid: res.data,
        //     encoding: 'utf-8'
        //   }, '{Encoding}').then(ress => {
        // this.loading = false
        // downFile(res, this.$t('feedBackMain.sampleFile'))
        //   }).catch(res => {
        //     this.loading = false
        //   })
        // } else {
        //   this.loading = false
        //   this.warning(this.$t('feedBackMain.noFiles'))
        // }
      }).catch(res => {
        this.loading = false
      })
    },
    // 获取最大批次
    getList () {
      let args = {
        auditFileType: this.forms.auditFileType,
        periods: this.form.periods,
        projectId: this.form.projectId
      }
      feedBackMain.assetFreq.getDefault(args).then(res => {
        if (res.success && !this.UtilJs.isEmpty(res.data)) {
          let list = [{
            id: '0',
            label: this.$t('feedBackMain.downloadAll')
          }]
          if (res.data.maxSendFrequency > 0) {
            this.maxSendFrequency = res.data.maxSendFrequency
            let isNew = this.forms.auditFileType === '2003' || this.feedbackType === '3'
            list.push({
              label: this.$t('feedBackMain.downloadCurrent'),
              isShow: isNew,
              id: '-1'
            })
            for (let index = 0; index < res.data.maxSendFrequency; index++) {
              list.push({
                label: `第${index + 1}批资料`,
                isShow: !isNew,
                id: (index + 1).toString()
              })
            }
            // if (this.forms.auditFileType === '2003' || this.feedbackType === '3') {
            //   list.push({
            //     label: this.$t('feedBackMain.downloadCurrent'),
            //     id: res.data.maxSendFrequency
            //   })
            // } else {
            //   for (let index = 0; index < res.data.maxSendFrequency; index++) {
            //     list.push({
            //       label: `第${index + 1}批资料`,
            //       id: (index + 1).toString()
            //     })
            //   }
            // }
          } else {
            this.warning(this.$t('feedBackMain.noFreg'))
          }
          this.downRangeList = list
        } else {
          this.downRangeList = []
          this.warning(this.$t('feedBackMain.noFreg'))
        }
      })
    },
    // 获取盖章方式
    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('0')
          }
        }).catch(res => {
          resolve('0')
        })
      })
    }
  },
  watch: {
    async visible (val) {
      let $this = this
      if (!val) {
        $this.forms.auditFileType = ''
      } else {
        this.downRangeList = []
        if (this.feedbackType === '2') {
          $this.stampWay = await $this.getStamp()
          if ($this.stampWay === '1') {
            $this.forms.auditFileType = '2001'
          } else if ($this.stampWay === '2') {
            $this.forms.auditFileType = '2002'
          }
        } else {
          $this.forms.auditFileType = '3001'
        }
        if ($this.form.auditFileType) {
          $this.forms.auditFileType = $this.form.auditFileType
        }
      }
    },
    'forms.auditFileType' (val) {
      this.forms.sendFrequency = []
      if (val && ((this.feedbackType === '2' && this.stampWay !== '0') || this.feedbackType === '3')) {
        this.$nextTick(() => {
          this.getList()
        })
      }
    }
  }
}
</script>
