<template>
  <div>
    <slot></slot>
    <a-button v-if="vIf" :class="classStyle" @click="showImportPanel">
      {{ Title }}
    </a-button>
    <a-modal
      :title="Title"
      :visible="modalImport.visible"
      :width="width"
      destroy-on-close
      :mask-closable="false"
      @cancel="handleCancel"
    >
      <slot name="modalimport">
        <a-form>
          <!-- 前置按钮插槽 -->
          <slot name="beforeimport"></slot>
          <a-form-item>
            <sd-attachment
              :max="1"
              :group-id="groupId"
              accept=".xls,.xlsx,.zip"
              @change="fnchangefile"
            >
            </sd-attachment>
          </a-form-item>
          <a-form-item style="text-align: center"></a-form-item>
          <!-- 后置按钮插槽 -->
          <slot name="afterimport"></slot>
          <a-form-item>
            <span v-if="Message !== ''" style="padding: 0 15px">
              {{ Message }}
            </span>
            <br v-if="Message !== '' && mblink && !hasattach" />
            <a-button v-if="!templategroupId && mblink" type="link" @click="fnDownloadTemplate">
              导入模板.xls
            </a-button>
            <sd-attachment
              v-if="templategroupId && mblink && !hasattach"
              :group-id="templategroupId"
              read-only
            />
            <a-button
              v-if="templategroupId && mblink && !hasattach"
              style="padding-left: 0;"
              icon="sd-download"
              type="link"
              @click="fnDownloadFile"
            >
              下载模板
            </a-button>
          </a-form-item>
        </a-form>
      </slot>
      <template slot="footer">
        <span :class="[$style.footerbtnsxm]"
          ><a-button :class="$style.buttonStyle" @click="handleCancel">取消</a-button></span
        >
        <span :class="[$style.footerbtnsxm]"
          ><a-button type="primary" :class="$style.buttonStyle" @click="importfromfile"
            >确定</a-button
          ></span
        >
      </template>
    </a-modal>
    <a-modal
      v-model="isErrorInfo"
      title="错误信息"
      :width="700"
      @ok="isErrorInfo = false"
      @cancel="isErrorInfo = false"
    >
      <!-- <table>
        <tr v-for="(item, index) in errorInfo" :key="index"
          ><td>{{ item }}</td></tr
        >
      </table> -->
      <a-descriptions bordered :class="$style.advancedimport">
        <a-descriptions-item :label="null">
          <p v-for="(item, index) in errorInfo" :key="index">{{ item }}</p>
        </a-descriptions-item>
      </a-descriptions>
      <!--  {{ errorInfo }} -->
      <!-- <a-descriptions-item v-for="(item, index) in errorInfo" :key="index" bordered>
        <a-descriptions-item label="">

        </a-descriptions-item>
        <p>{{ item }}</p
        ><br /> -->
      <!-- </a-descriptions-item> -->
    </a-modal>
  </div>
</template>

<script>
import axios from '@/common/services/axios-instance'
import { Message } from 'ant-design-vue'
import AuditAdvancedImportService from './audit-advanced-import-service'
import components from './_import-components/audit-advanced-import-import'
import download from '@/common/services/download'

export default {
  name: 'AuditAdvancedImport',
  metaInfo: {
    title: 'AuditAdvancedImport',
  },
  components,
  props: {
    classStyle: {
      type: Array,
      default: null,
    },
    /**
     * 判断导入按钮 显示条件，为true 则显示
     */
    vIf: {
      Type: Boolean,
      defalt: false,
    },
    /**
     * 导入弹出框大小设定，默认650
     */
    width: {
      Type: Number,
      defalt: 650,
    },
    /**
     * 文字说明提示
     */
    Message: {
      type: String,
      default: '',
    },
    /**
     *  标题
     */
    Title: {
      type: String,
      default: '导入',
    },
    /**
     * 导入具体方法
     */
    ImportFun: {
      type: Function,
      default: null,
    },
    /**
     * 显示模板样例
     */
    mblink: {
      type: Boolean,
      default: true,
    },
    /**
     * 配置表id
     */
    configId: {
      type: String,
      default: '',
    },
    /**
     * 父分类ID
     */
    relevantColumn: {
      type: Number,
      default: null,
    },
    /**
     * 刷新表名
     */
    tableId: {
      type: String,
      default: '',
    },
    /**
     * 样例接口参数
     */
    templateparam: {
      type: Array,
      default: null,
    },
  },
  data() {
    return {
      modalImport: {
        title: '导入',
        visible: false,
      },
      errorInfo: [],
      isErrorInfo: false,
      groupId: Math.round(Math.random() * 100000000000000000).toString(),
      templategroupId: null,
      templatepath: null,
      hasattach: false,
    }
  },
  mounted() {
    this.getTemplate(this.configId)
    this.hasattach = false
  },
  created() {
    this.hasattach = false
  },
  methods: {
    showImportPanel() {
      this.modalImport.visible = true
      this.groupId = Math.round(Math.random() * 100000000000000000).toString()
    },
    handleCancel() {
      this.modalImport.visible = false
      this.hasattach = false
      this.$emit('importHandleCancel') // 调用取消回调函数
    },
    importfromfile(data) {
      if (!this.hasattach) {
        Message.warn('请先上传附件')
        return
      }
      this.$emit('changeSpinning', false) // 修改Spinning显示状态
      let params = {
        groupId: this.groupId,
        configId: this.configId,
        relevantColumn: this.relevantColumn,
      }
      if (this.ImportFun !== null) {
        params = this.ImportFun(params)
      }
      AuditAdvancedImportService.Import(params)
        .then((res) => {
          this.$emit('changeSpinning', true) // 修改Spinning显示状态
          if (res.data.flag === false) {
            Message.error('导入数据失败！')
            this.isErrorInfo = true
            this.errorInfo = res.data.data
            console.log(this.errorInfo)
            return false
          } else {
            Message.success('导入成功！')
            this.$emit('importfromfileAfter') // 调用导入成功回调函数
            if (this.$parent.$parent.$refs[`${this.tableId}`]) {
              this.$parent.$parent.$refs[`${this.tableId}`].refresh()
            }
          }
        })
        .catch((err) => {
          this.$emit('changeSpinning', true) // 修改Spinning显示状态
          // Message.error(err)
          if (err.response.data.message === '字段被审计单位：auditedUnit不能为空') {
            Message.error('被审计单位名称填写错误，请核对后导入')
          } else {
            Message.error(err)
          }
        })
      this.modalImport.visible = false
      this.hasattach = false
    },
    fnDownloadTemplate() {
      AuditAdvancedImportService.downloadTemplateExcel(this.templatepath, this.templateparam).then(
        (res) => {
          const url = URL.createObjectURL(res.data)
          const fname = '导入模板.xls'
          download(url, fname)
        }
      )
    },
    getTemplate(configId) {
      AuditAdvancedImportService.getTemplate(configId).then((res) => {
        this.templategroupId = res.data.groupId
        this.templatepath = res.data.templateUrl
      })
    },
    fnDownloadFile() {
      return axios
        .get('api/framework/v1/attachment-extend/attachments-info/' + this.templategroupId)
        .then((res) => {
          const code = res.data[0]?.code
          if (code) {
            const fname = res.data[0].name
            const url = `${location.origin}${location.pathname}api/framework/v1/task-form-process/download-attachments/${code}`
            download(url, fname)
          }
        })
    },
    fnchangefile(attach) {
      if (attach.length > 0) {
        this.hasattach = true
      } else {
        this.hasattach = false
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;

.footerbtnsxm {
  padding: 0 5px;
}

:global(.ant-upload.ant-upload-drag .ant-upload) {
  padding: 0 0;
}

:global(.ant-form-item) {
  margin: 0 0;
}

.advancedimport {
  :global(.ant-descriptions-item-no-label) {
    display: none;
  }
}
</style>
