<template>
  <el-dialog
    :title="`训练消耗指标数据 - 出入库明细`"
    :visible.sync="dialogVisible"
    custom-class="new-edition-dialog"
    width="50%"
    @closed="closed"
    @open="open"
  >
    <div class="detailed-container">
      <el-form
        v-model="queryParam.querys"
        :inline="true"
        class="search-form"
        size="small"
      >
        <el-form-item label="出入库：">
          <el-select
            v-model="queryParam.querys[1].value"
            clearable
            placeholder="请选择出入库"
          >
            <el-option
              v-for="item in getDictionaryByCode('crklx')"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-upload
            ref="upload"
            :action="actionUrl"
            :before-upload="beforeUpload"
            :headers="headers"
            :multiple="false"
            :on-error="handleError"
            :on-success="handleSuccess"
            :show-file-list="false"
            class="avatar-uploader"
          >
            <el-button
              v-charge
              :loading="uploadLoading"
              icon="el-icon-download"
              style="margin-right: 10px;"
              type="primary"
            >
              导入
            </el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-download" type="primary" @click="exportFile"
            >导出
          </el-button>
          <el-button icon="el-icon-download" type="info" @click="downModelTep"
            >模板下载
          </el-button>
          <el-button icon="el-icon-search" type="primary" @click="handleSearch"
            >搜索
          </el-button>
          <el-button icon="el-icon-refresh" @click="resetSearch">
            重置
          </el-button>
        </el-form-item>
      </el-form>
      <el-table
        ref="multipleSelection"
        v-loading="loading"
        :cell-style="{'text-align': 'center'}"
        :data="tableData"
        :header-cell-style="{'text-align': 'center'}"
        :max-height="500"
        :style="{width: '100%'}"
        size="mini"
        @selection-change="handleSelectionChange"
        @sort-change="sortChange"
      >
        <el-table-column
          :index="
            index =>
              index +
              1 +
              (queryParam.pageBean.page - 1) * queryParam.pageBean.pageSize
          "
          fixed
          label="序号"
          type="index"
          width="55"
        />
        <el-table-column
          :formatter="({name}) => name || '-'"
          label="指标名称"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          :formatter="
            ({operateType}) => dictionaryEscape('crklx', operateType) || '-'
          "
          label="出入库"
          show-overflow-tooltip
        />
        <el-table-column
          :formatter="({number}) => (isNotEmpty(number) ? number : '-') || '-'"
          label="出入库数量"
          show-overflow-tooltip
        />
        <el-table-column
          :formatter="({unit}) => dictionaryEscape('jldw', unit) || '-'"
          label="计量单位"
          show-overflow-tooltip
        />
        <el-table-column
          :formatter="({createTime}) => createTime || '-'"
          label="出入库时间"
          min-width="150"
          prop="createTime"
          show-overflow-tooltip
          sortable="custom"
        />
      </el-table>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-pagination
        :current-page="queryParam.pageBean.page"
        :page-size="queryParam.pageBean.pageSize"
        :page-sizes="[20, 30, 40, 50]"
        :total="queryParam.pageBean.total"
        align="right"
        background
        layout="prev, pager, next,total, sizes, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </span>
  </el-dialog>
</template>

<script>
import * as api from '@/api/examDataMenu/examSafeguardData/examIndexData.js'
import {
  getSorterDirection,
  refineRequestBody,
  setQueryValue
} from '@/utils/requestWrappers'

import {TableMixin} from '@/mixins/tableMixin'
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'
import {isNotEmpty} from '@/utils/helpers'
import {mapState} from 'vuex'
export default {
  name: 'DetailedDialog',
  mixins: [TableMixin],
  props: {
    value: {
      type: Boolean,
      default: false
    },
    rowDetails: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      queryParam: {
        pageBean: {pageSize: 20, page: 1, total: 0},
        querys: [{property: 'index_id_'}, {property: 'operateType'}],
        sorter: [{direction: 'DESC', property: 'createTime'}]
      },
      tableData: [],
      noLoadData: true,
      isCalcTableHeight: false,
      uploadLoading: false
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    },
    id() {
      return this.rowDetails?.id || ''
    },
    actionUrl: _ => window.context.portal + '/biz/training/data/importExcel',
    ...mapState({
      headers: state => ({
        Authorization: `Bearer ${state.login.currentUser.token}`
      })
    })
  },
  created() {},
  methods: {
    isNotEmpty,
    dictionaryEscape,
    getSorterDirection,
    getDictionaryByCode,
    // 导出数据
    async exportFile() {
      await api.exportDataMx({
        querys: this.queryParam.querys,
        pageBean: {
          pageSize: -1
        }
      })
    },
    // 模板下载
    async downModelTep() {
      await api.downModelMx()
    },
    //  导入文件上传前
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        this.uploadLoading = true
        const {size, name} = file
        let passedOrNot = true // 是否通过验证
        const maxSize = 500 * 1024 * 1024 // 20MB
        const typeRegular = /\.(xls|xlsx)$/i
        const verification = [
          {
            condition: !typeRegular.test(name),
            result: () => this.$message.error('只能上传xls或xlsx文件类型')
          }
        ]
        verification.forEach(item => {
          if (item.condition) {
            item.result()
            passedOrNot = false
            this.uploadLoading = false
          }
        })

        passedOrNot ? resolve() : reject()
      })
    },

    // 导入文件上传成功
    async handleSuccess() {
      this.$message.success('数据导入成功')
      this.uploadLoading = false
      await this.loadData()
    },
    // 导入文件上传失败
    handleError() {
      this.$message.error('数据导入失败，请重试')
      this.uploadLoading = false
    },

    // 打开弹层
    open() {
      if (this.id) {
        this.saveLoading = true
        setQueryValue(this.queryParam, 'index_id_', this.id)
        const {prop, order} = getSorterDirection(this.queryParam, true)
        this.$nextTick(() => this.$refs.multipleSelection?.sort(prop, order))
      }
    },

    // 关闭弹层后
    closed() {
      // 重置组件数据
      Object.assign(this.$data, this.$options.data.call(this))
    },

    // 获取表格数据
    async loadData() {
      try {
        this.loading = true
        const {total = 0, rows = []} = await api.detailed(
          refineRequestBody(this.queryParam)
        )
        this.queryParam.pageBean.total = total
        const {name, unit} = this.rowDetails
        this.tableData = rows.map(i => ({...i, name, unit}))
      } finally {
        this.loading = false
      }
    },

    // 重置搜索
    resetSearch() {
      this.queryParam = this.$options.data().queryParam
      setQueryValue(this.queryParam, 'index_id_', this.id)
      this.loadData()
    }
  }
}
</script>

<style lang="scss" scoped></style>
