<template>
  <a-card>
    <a-form layout="inline" :class="$style.form">
      <!-- 报表名称 -->
      <a-form-item label="报表名称">
        <a-input v-model="searchData.reportName" allow-clear />
      </a-form-item>
      <a-form-item>
        <!-- 搜索 清除 模板生成 -->
        <a-button :class="$style.btn" type="primary" @click="handlerSearch">搜索</a-button>
        <a-button :class="$style.btn" @click="deleteReport">清除</a-button>
        <a-button :class="$style.btn" @click="modelGenerate">模板生成</a-button>
      </a-form-item>
    </a-form>
    <a-table
      :columns="columns"
      :data-source="dataSource"
      :row-key="(record) => record.id"
      :pagination="pages"
      @change="pagesChange"
    >
      <!-- 任务状态 0 未开始 1 进行中 2 完成 3 失败 -->
      <template slot="status" slot-scope="text, record">
        <span v-if="record.taskStatus === 0">未开始</span>
        <span v-if="record.taskStatus === 1">进行中</span>
        <span v-if="record.taskStatus === 2">完成</span>
        <span v-if="record.taskStatus === 3">失败</span>
      </template>
      <!-- 模板生成 -->
      <template slot="edit" slot-scope="text, record">
        <a-button v-if="record.taskStatus === 2" type="link" @click="downloadTable(record)"
          >下载</a-button
        >
      </template>
    </a-table>
    <a-modal v-model="recordShow" title="模板生成" @ok="generateReport">
      <a-spin :spinning="isshowLoading" tip="正在生成……" size="large">
      <a-form-model
        ref="form"
        :model="form"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        :rules="rules"
      >
        <a-form-model-item label="报表名称" prop="reportName">
          <!-- <a-select v-model="form.reportName">
            <a-select-option v-for="(item, i) in tableOption" :key="i" :value="item.value">{{
              item.label
            }}</a-select-option>
          </a-select> -->
          <a-input v-model="form.reportName" allow-clear />
        </a-form-model-item>
        <a-form-model-item label="公司选择" prop="companyUnit">
          <!-- <SdGroupPicker
            ref="cRelSelect"
            v-model="form.companyUnit"
            :read-only="false"
            @change="changecompany"
          /> -->
          <audit-company-select
            ref="cRelSelect"
            v-model="form.companyUnit"
            :read-only="false"
            @change="changecompany"
          />
        </a-form-model-item>
        <a-form-model-item label="生成年份" prop="time">
          <!-- <a-month-picker v-model="form.time" mode="year" format="YYYY" @change="timeChange" /> -->
          <a-date-picker
            mode="year"
            format="YYYY"
            :allow-clear="false"
            placeholder="选择年份"
            :input-read-only="true"
            :value="form.time"
            @change="panelStartYearChange"
            @panelChange="panelStartYearChange"
          ></a-date-picker>
        </a-form-model-item>
      </a-form-model>
      </a-spin>
    </a-modal>
  </a-card>
</template>

<script>
import components from './_import-components/audit-report-list-import'
import auditPreReport from './audit-pre-report'
import auditCompanySelect from './audit-company-select'
import moment from 'moment'
export default {
  name: 'AuditPreReport',
  metaInfo: {
    title: '模型信息管理',
  },
  components: {
    ...components,
    auditCompanySelect,
  },
  filters: {
    // 时间格式化
    dateFormat(value) {
      return value
    },
  },
  data() {
    return {
      searchData: {
        reportName: '',
      },
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      isshowLoading: false,
      form: {
        reportName: '',
        time: '',
        companyUnit: '',
        year: '',
      },
      dataSource: [],
      //       createTime
      // creator
      // creatorId
      // fileUrl
      // id
      // tableName
      // tableYear
      // taskStatus

      rules: {
        reportName: [{ required: true, message: '请输入报表名称', trigger: 'blur' }],
        companyUnit: [{ required: true, message: '请选择公司', trigger: 'blur' }],
        time: [{ required: true, message: '请选择年份', trigger: 'change' }],
      },
      columns: [
        // 序号 ，报表名称，时间，生成状态 操作
        {
          title: '序号',
          dataIndex: 'index',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          title: '报表名称',
          dataIndex: 'tableName',
        },
        {
          title: '时间',
          dataIndex: 'createTime',
          // sdRender: TableColumnTypes.date,
          customRender: (text) => this.$options.filters.dateFormat(text),
        },
        {
          title: '生成状态',
          dataIndex: 'taskStatus',
          scopedSlots: { customRender: 'status' },
        },
        // fileUrl

        {
          title: '操作',
          dataIndex: 'id',
          scopedSlots: { customRender: 'edit' },
        },
      ],
      recordShow: false,
      pages: {
        current: 1,
        total: 0,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: (total) => `共 ${total} 条`,
      },
      tableOption: [],
      okFlag: false,
    }
  },
  computed: {
    rowSelection() {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
        },
        type: 'radio',
      }
    },
  },
  created() {
    this.initTable()
  },
  methods: {
    handlerSearch() {
      this.initTable()
    },
    pagesChange(value) {
      this.pages.current = value.current
      this.pages.pageSize = value.pageSize
      this.initTable()
    },
    panelStartYearChange(value) {
      console.log('🚀 ~ panelStartYearChange ~ value:', value)
      this.form.time = value
      this.form.year = moment(value).format('YYYY')
      console.log('🚀 ~ panelStartYearChange ~ this.form:', this.form)
    },
    downloadTable(record) {
      const url = record.downloadUrl
      // 根据该路径下载文件
      const a = document.createElement('a')
      a.href = url
      a.download = ''
      a.click()
      a.remove()
    },
    deleteReport() {
      this.searchData.reportName = ''
      this.initTable()
    },
    modelGenerate() {
      this.recordShow = true
    },
    // 单位 选择
    changecompany(val) {},
    // 初始化table
    initTable() {
      const data = {
        year: '',
        tableName: this.searchData.reportName,
        size: this.pages.pageSize,
        page: this.pages.current,
      }
      auditPreReport.getTable(data).then((res) => {
        if (res.data.code + '' === '200') {
          const { records, total, size, current } = res.data.data
          this.dataSource = records
          this.pages.total = total
          this.pages.pageSize = size
          this.pages.current = current
        }
      })
    },
    // // 初始化所有报表
    // initAllTable() {
    //   const data = {
    //     size: 999,
    //     page: 1,
    //   }
    //   auditPreReport.getTable(data).then((res) => {
    //     if (res.data.code === 200) {
    //       const { records } = res.data.data
    //       this.tableOption = records.map((item) => {
    //         return {
    //           label: item.tableName,
    //           value: item.tableName,
    //         }
    //       })
    //     }
    //   })
    // },
    timeChange(val) {
      // 生成年份 如2024
    },
    // 生成报表
    generateReport() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.okFlag) {
            return
          }
          this.okFlag = true
          this.isshowLoading = true
          const comp = (this.form.companyUnit || []).map((item) => {
            return {
              orgCode: item.orgCode,
              companyName: item.name,
            }
          })
          const data = {
            // 公司列表
            companies: comp,
            // 选择年
            year: this.form.year,
            // 报表名称
            tableName: this.form.reportName,
          }
          auditPreReport
            .generateReportData(data)
            .then((res) => {
              this.recordShow = false
              this.okFlag = false
              // 清空表单
              this.form = {
                reportName: '',
                time: '',
                companyUnit: '',
                year: '',
              }
              this.initTable()
              this.isshowLoading = false
            })
            .catch(() => {
              this.okFlag = false
              this.isshowLoading = false
            })
        }
      })
    },
  },
}
</script>

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

.btn {
  margin-left: 10px;
}

.form {
  margin-bottom: 20px;
}
</style>
