<template>
  <div>
    <template v-for="(item,index) in list1">
      <!-- 意见处理页面子组件(单笔资产处理信息) -->
      <el-card v-if="item.isShow || !isBatch" class="box-column-margin-bottom" style="position:relative" :key="index">
        <div class="question-number">{{index + 1}}</div>
        <!-- 基础信息 -->
        <div class="viewForm">
          <dym-form :formValue.sync="item" :componentList="componentList"></dym-form>
        </div>
        <!-- 表格列表 -->
        <data-table :class="'dataTable'+index"  v-bind="{maxHeight:'400px',spanMethod:e => objectSpanMethod(item,e)}" selectable="false"
          :queryParas="forms" :sourceData="item.feedAuditAssetQstDetailListDtos" :toolMenuFlag="true" :columns="modifyColumns"
          :showPage="false" :headTitle="$t('common.bankImport')"
          :loadingFlag="loadingFlag">
          <!-- 头部操作按钮 -->
          <template slot="headButton">
            <div align="right">
              <auth-button class="iconfont iconjichuxinxi" :size="'medium'" :label="$t('feedBackMain.assetInfo')" type="primary" @click="handleOpen(item.keyId)"></auth-button>
              <!-- <auth-button :size="'medium'" :label="$t('feedBackMain.baseAssetData')" type="primary"></auth-button> -->
              <auth-button class="iconfont iconxiazai1" :size="'medium'" :label="$t('feedBackMain.baseAssetPlaceData')" type="primary" @click="handleDownload(item)"></auth-button>
              <auth-button v-if="item.dealEndFlag !== '2' && item.chargeBackStatus !== '2'" class="iconfont iconxinzeng" :size="'medium'" :label="$t('feedBackMain.addSuggestion')" type="primary" @click="addSuggestion(index)"></auth-button>
            </div>
          </template>
          <!-- 索引值 -->
          <template #number="scope">
            <div>{{scope.data.row.index}}</div>
          </template>
          <!-- 反馈意见 -->
          <template #feedbackQuestionContent="scope">
              <span-plus v-if="scope.data.row.qusetionHistoryNumber || scope.data.row.tempSaveFlag === '1'" :index="scope.data.$index"
                            :text="scope.data.row.feedbackQuestionContent"></span-plus>
              <div class="flex-spaceB" v-else style="width:20%">
                <el-input :placeholder="$t('feedBackMain.placeholder')" v-model.trim="scope.data.row.feedbackQuestionContent " maxlength="500"></el-input>
                <i class="el-icon-error cancel-icon" @click="delSuggestion(index,scope.data.$index)"></i>
              </div>
          </template>
          <!-- 保理商意见 -->
          <template #replyLawContent="scope">
              <span-plus :index="scope.data.$index"
                            :text="scope.data.row.replyLawContent"></span-plus>
          </template>
          <!-- 保理商补充资料 -->
          <template #fileOssid="scope">
            <div v-if="scope.data.row.fileInfos && scope.data.row.fileInfos.length > 0">
              <el-popover
                placement="left"
                width="200"
                trigger="hover">
                <div v-for="(item,index) in scope.data.row.fileInfos" :key="index">
                  <el-link type="primary" @click="preView(getFile(item.fileName),item.fileId)">{{item.fileName}}</el-link>
                </div>
                <auth-button slot="reference" :size="'medium'" class="iconCircle" icon="iconfont iconyulan" :title="$t('common.preview')"></auth-button>
              </el-popover>
              <auth-button :size="'medium'" class="iconCircle box-column-margin-left" icon="iconfont iconycxiazai1" :title="$t('common.download')" :disabled="!scope.data.row.fileInfos || scope.data.row.fileInfos.length < 1" @click="downloadFile(scope.data.row.fileInfos)"></auth-button>
              <!-- <btn-batch-download :downloadFileName="$t('feedBackMain.fileOssid')+ '.zip'" size="medium" :fileID="scope.data.row.fileInfos.map(item=>{return item.fileId})" :disabled="!scope.data.row.fileInfos || scope.data.row.fileInfos.length < 1" class="box-column-margin-left"></btn-batch-download> -->
            </div>
          </template>
          <!-- 审核结果 -->
          <template #extOrgQustionResult="scope">
              <div v-if="scope.data.row.questionStatus !== '6' &&scope.data.row.dealTempSaveFlag !== '2'">
                  {{scope.data.row.extOrgQustionResult > 0 ? formatDict(scope.data.row.extOrgQustionResult,'AUDIT_OUT_LAW_RESULT_STATUS') : ''}}
              </div>
              <div v-else>
                <div>
                  <el-radio label="1" v-model="scope.data.row.extOrgQustionResult" :name="scope.$index">{{$t('feedBackMain.extOrgQustionResultOne')}}</el-radio>
                </div>
                <div style="margin-top:10px">
                  <el-radio label="2" v-model="scope.data.row.extOrgQustionResult" :name="scope.$index">{{$t('feedBackMain.extOrgQustionResultTwo')}}</el-radio>
                </div>
                <div style="margin-top:10px">
                  <el-radio label="3" v-model="scope.data.row.extOrgQustionResult" :name="scope.$index">{{$t('feedBackMain.extOrgQustionResultThree')}}</el-radio>
                </div>
              </div>
          </template>
          <!-- 审核意见 -->
          <template #extOrgOpinionContent="scope">
            <div v-if="scope.data.row.extOrgQustionResult === '2' || scope.data.row.extOrgQustionResult === '3'">
              <span-plus v-if="scope.data.row.questionStatus !== '6' && scope.data.row.dealTempSaveFlag === '1'" :index="scope.data.$index"
                              :text="scope.data.row.extOrgOpinionContent"></span-plus>
              <div class="flex-spaceB" v-else style="width:100%">
                <el-input :placeholder="$t('feedBackMain.placeholder')" v-model.trim="scope.data.row.extOrgOpinionContent" maxlength="500"></el-input>
              </div>
            </div>
          </template>
        </data-table>
      </el-card>
    </template>
    <pre-view ref="preView" :oosUrl="config.VUE_APP_OSS_URL" :fileUrl="config.VUE_APP_BASE_URL" :dialogAttrs="dialogAttrs"></pre-view>
  </div>
</template>

<script>
import {
  DataTable,
  dymForm,
  preView,
  SpanPlus,
  btnBatchDownload,
  authButton
} from 'newepoch-components'
import components from '@/api/assetoutfeedback/componentsApi.js'
import fileApi from '@/api/fileApi.js'
import { formatDict } from '@/filters/index.js'
import {
  downFile
} from '@/utils/devUtils'
export default {
  name: 'feedBackContentSub',
  components: {
    DataTable,
    dymForm,
    SpanPlus,
    btnBatchDownload,
    preView,
    authButton
  },
  props: {
    // 反馈类型：1 抽样；2 确权；3 其他
    feedbackType: {
      type: [String, Number],
      default: 0
    },
    // 是否批量
    isBatch: {
      type: [Boolean],
      default () {
        return false
      }
    },
    // 处理列表
    datas: {
      type: [Array],
      default () {
        return []
      }
    },
    // 参数
    queryParas: {
      type: [Object],
      default () {
        return null
      }
    }
  },
  computed: {
    list: {
      get: function () {
        return this.datas
      },
      set: function (value) {
        this.$emit('update:datas', value)
      }
    },
    list1: {
      get: function () {
        return this.rowspan()
      },
      set: function (value) {
        this.list = value
      }
    },
    isShow: {
      get: function () {
        return this.showButton
      },
      set: function (value) {
        this.$emit('update:showButton', value)
      }
    }
  },
  mounted () {
    this.isFist = true
  },
  data () {
    return {
      config: process.env,
      isFist: true,
      forms: {},
      loadingFlag: false,
      modifyColumns: [
        // 序号
        {
          prop: 'number',
          slot: true,
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].feedBackMain.number,
          width: '50px'
        },
        // 反馈意见
        {
          prop: 'feedbackQuestionContent',
          headalign: 'center',
          slot: true,
          label: this.$i18n.messages[this.$i18n.locale].feedBackMain.feedbackQuestionContent,
          width: '230px'
        },
        // 保理商意见
        {
          prop: 'replyLawContent',
          align: 'center',
          slot: true,
          label: this.$i18n.messages[this.$i18n.locale].feedBackMain.replyLawContent,
          width: '230px'
        },
        // 保理商补充资料
        {
          prop: 'fileOssid',
          align: 'center',
          slot: true,
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].feedBackMain.fileOssid,
          width: '150px'
        },
        // 审核结果
        {
          prop: 'extOrgQustionResult',
          headalign: 'center',
          slot: true,
          // showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].feedBackMain.extOrgQustionResult,
          width: '280px'
        },
        // 审核意见
        {
          slot: true,
          prop: 'extOrgOpinionContent',
          align: 'center',
          // showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].feedBackMain.extOrgOpinionContent,
          width: '230px'
        }
      ],
      // 查看表单
      componentList: [
        {
        // 付款确认书编号
          label: this.$i18n.messages[this.$i18n.locale].feedBackMain.assetCode,
          disabled: true,
          value: 'assetCode',
          prop: 'assetCode',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.noForm,
          labelWidth: '120px',
          cols: [12, 12, 12, 8],
          clearable: true,
          componentName: 'el-input'
        },
        {
        // 供应商名称
          label: this.$i18n.messages[this.$i18n.locale].feedBackMain.creditor,
          disabled: true,
          value: 'creditor',
          prop: 'creditor',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.noForm,
          labelWidth: '120px',
          cols: [12, 12, 12, 8],
          clearable: true,
          componentName: 'el-input'
        },
        {
        // 项目公司名称
          label: this.$i18n.messages[this.$i18n.locale].feedBackMain.debtor,
          disabled: true,
          value: 'debtor',
          prop: 'debtor',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.noForm,
          labelWidth: '120px',
          cols: [12, 12, 12, 8],
          clearable: true,
          componentName: 'el-input'
        },
        {
        // 保理金额
          label: this.$i18n.messages[this.$i18n.locale].feedBackMain.factoringMoney,
          disabled: true,
          value: 'factoringMoney',
          prop: 'factoringMoney',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.noForm,
          labelWidth: '120px',
          cols: [12, 12, 12, 8],
          clearable: true,
          componentName: 'el-input'
        },
        {
        // 合同名称
          label: this.$i18n.messages[this.$i18n.locale].feedBackMain.basicContractName,
          disabled: true,
          value: 'basicContractName',
          prop: 'basicContractName',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.noForm,
          labelWidth: '120px',
          cols: [12, 12, 12, 8],
          clearable: true,
          componentName: 'el-input'
        },
        {
        // 合同编号
          label: this.$i18n.messages[this.$i18n.locale].feedBackMain.basicContractCode,
          disabled: true,
          value: 'basicContractCode',
          prop: 'basicContractCode',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.noForm,
          labelWidth: '120px',
          cols: [12, 12, 12, 8],
          clearable: true,
          componentName: 'el-input'
        }
      ],
      spanArr: [],
      position: [],
      dialogAttrs: {
        'append-to-body': true,
        'center': true,
        'title': this.$t('common.preview')
      }
    }
  },
  watch: {
    // 监听表单
    // queryParas: {
    //   deep: true,
    //   immediate: true,
    //   handler (newVal) {
    //     this.$nextTick(() => {
    //       // 初始化
    //       if (this.isBatch) {
    //         if (this.datas.length > 0) {
    //           // 映射反馈列表
    //           this.list = this.datas.map(item => {
    //             item.isShow = newVal.freq === '' ? false : item.feedbackFrequency <= newVal.freq.toString()
    //             return item
    //           })
    //         } else {
    //           if (newVal.freq) {
    //             this.$nextTick(() => {
    //               this.warning(this.$t('feedBackMain.noData'))
    //             })
    //           }
    //         }
    //       }
    //     })
    //   }
    // },
    datas: {
      deep: true,
      immediate: true,
      handler (val) {
        if (val.length > 0) {
          // if (this.isFist) {
          //   this.rowspan()
          // } else {
          //   return
          // }
          // 有退单资产的需要提示
          let message = []
          const h = this.$createElement
          // 筛选已退单资产
          for (let index in val) {
            let item = val[index]
            if (item.chargeBackStatus === '2') {
              message.push(h('div', null, item.assetCode + '，'))
            }
          }
          // 提示已退单资产
          if (message.length > 0) {
            message.push(h('div', { style: 'color: red' }, this.$t('feedBackMain.abandund')))
            this.$msgbox({
              title: this.$t('common.tip'),
              message: h('p', null, message),
              callback: action => {}
            })
          }
        }
      }
    }
  },
  methods: {
    formatDict,
    // 下载补充资料
    downloadFile (row) {
      let keyIds = row.map(item => { return item.fileId })
      console.log(row)
      if (keyIds.length === 1) {
        fileApi.file.download({ keyId: row[0].fileId }).then(res => {
          downFile(res)
        })
      } else {
        fileApi.file.batchDownload({ keyIds: keyIds, fileName: this.$t('feedBackMain.fileOssid') }).then(res => {
          downFile(res)
        })
      }
    },
    // 下载归档资料
    handleDownload (row) {
      let api = 'danganFile'
      this.$confirm(this.$t('common.confirm') + this.$t('common.downLoad'), this.$t('common.tip'), {
        type: 'warning'
      }).then(() => {
        let args = {
          assetInfoIds: [row.assetInfoId]
        }
        let fileTypes = [['0'], '1', ['3']][this.feedbackType - 1]
        // 若为确权文件类型
        if (this.feedbackType === '2') {
          // 总部+确权
          if (this.queryParas.auditFileType === '2001') {
            fileTypes = ['1', '2']
          // 确权
          } else if (this.queryParas.auditFileType === '2002') {
            fileTypes = ['1']
          // 总部
          } else if (this.queryParas.auditFileType === '2003') {
            fileTypes = ['2']
          }
        // 若为其他文件类型需要加fileCode
        } else if (this.feedbackType === '3') {
          args.fileCodes = [this.queryParas.fileId]
        }
        args.fileTypes = fileTypes
        components[api].getDefault(args).then(res => {
          if (res.success && res.data.length > 0) {
            fileApi.file.batchDownload({ keyIds: res.data[0].fileInfos.map(item => { return item.ossId }) }).then(res => {
              downFile(res, `${this.$t('feedBackMain.danganFiles')}(${row.assetCode}).zip`).catch(e => {
                // console.log(e)
              })
            })
          } else {
            this.warning(this.$t('feedBackMain.noFiles'))
          }
        })
      }).catch((e) => {})
    },
    // 获取文件类型
    getFile (e) {
      let test = e.indexOf('.')
      if (test !== -1) {
        e = e.slice(test + 1)
      }
      return e
    },
    // 预览
    preView (type, id) {
      // console.log(type, id)
      this.$nextTick(() => {
        this.$refs.preView.show(type, id)
      })
    },
    // 追加意见
    addSuggestion (e) {
      let list = this.list1[e].feedAuditAssetQstDetailListDtos // 追加列表
      let index = 1
      if (list && list.length > 0) {
        let item = list[list.length - 1].index // 列表末尾项索引值
        index = Number(item) + 1
      }
      list.push({
        index: index,
        extOrgQustionResult: '4',
        feedbackAssetKey: this.list[e].keyId,
        feedbackQuestionContent: ''
      })
      this.isShow = true
      // 表格滚动至底
      this.$nextTick(() => {
        let container = this.$el.querySelector('.dataTable' + e + ' .el-table__body-wrapper')
        container.scrollTop = container.scrollHeight
      })
    },
    // 删除意见
    delSuggestion (pIndex, index) {
      let list = this.list[pIndex].feedAuditAssetQstDetailListDtos // 追加列表
      // 删除选中项
      list.splice(index, 1)
      // 重置问题编号
      for (let index2 in list) {
        if (index2 >= index) {
          list[index2].index--
        }
      }
    },
    // 处理单元格合并参数
    rowspan (e) {
      let list = this.datas.map(item => {
        item.isShow = this.queryParas.freq === '' ? true : (item.feedbackFrequency === this.queryParas.freq.toString() && item.dealEndFlag !== '2' && item.chargeBackStatus !== '2')
        return item
      })
      list.forEach((i, m) => {
        let spanArr = []
        let qusetionNumber = []
        let position = 0
        let position2 = 0
        if (i.feedAuditAssetQstDetailListDtos && i.feedAuditAssetQstDetailListDtos.length > 0) {
          i.feedAuditAssetQstDetailListDtos.forEach((item, index) => {
            if (index === 0) {
              item.index = 1
              spanArr.push(1)
              qusetionNumber.push(1)
              position = 0
              position2 = 0
            } else {
              if (item.qusetionNumber === i.feedAuditAssetQstDetailListDtos[index - 1].qusetionNumber && item.qusetionHistoryNumber === i.feedAuditAssetQstDetailListDtos[index - 1].qusetionHistoryNumber) {
                spanArr[position] += 1
                spanArr.push(0)
                // if (i.feedAuditAssetQstDetailListDtos[index + 1]) {
                //   i.feedAuditAssetQstDetailListDtos[index + 1].index = Number(item.qusetionNumber) + 1
                // }
              } else {
                spanArr.push(1)
                position = index
              }
              if (item.qusetionNumber === i.feedAuditAssetQstDetailListDtos[index - 1].qusetionNumber) {
                if (!item.index) {
                  item.index = i.feedAuditAssetQstDetailListDtos[index - 1].index
                }
                qusetionNumber[position2] += 1
                qusetionNumber.push(0)
              } else {
                if (!item.index) {
                  item.index = i.feedAuditAssetQstDetailListDtos[index - 1].index + 1
                }
                qusetionNumber.push(1)
                position2 = index
              }
            }
          })
        }
        i.spanArr = spanArr
        i.number = qusetionNumber
        i.position = position
        i.position2 = position2
      })
      // this.list = list
      return list
    },
    // 合并单元格；item：卡片对象，{}：表格对象
    objectSpanMethod (item, { row, column, rowIndex, columnIndex }) {
      if (item) {
        let spanArr = item.spanArr ? item.spanArr[rowIndex] : []
        let qusetionNumber = item.number ? item.number[rowIndex] : []
        if (columnIndex === 0 && row.qusetionNumber) {
          // console.log(item.number)
          return {
            rowspan: qusetionNumber,
            colspan: 1
          }
        } else if ((columnIndex === 1 || columnIndex === 4 || columnIndex === 5) && row.qusetionHistoryNumber) {
          return {
            rowspan: spanArr,
            colspan: 1
          }
        } else if ((columnIndex === 5 || columnIndex === 2 || columnIndex === 3 || columnIndex === 4) && !row.qusetionHistoryNumber) {
          return {
            rowspan: 0,
            colspan: 0
          }
        } else if (columnIndex === 1 && !row.qusetionHistoryNumber) {
          return {
            rowspan: 1,
            colspan: 5
          }
        }
      }
    },
    handleOpen (id) {
      this.$emit('handleOpen', id)
    }
  }
}
</script>
<style lang="scss" scoped>
  @import '~@/styles/assetoutfeedback/common.scss'
</style>
