<template>
  <el-dialog
    :visible.sync="visible"
    :close-on-click-modal="closeOnClickModal"
    :top="top"
    :title="title"
    :width="width"
    :before-close="handleBeforeClose">
    <div class="sku-batch-import">
      <el-alert
        style="margin-bottom: 18px;"
        type="warning"
        :closable="false"
      >
        <div class="define-title">
          重复上传仅显示最后一次上传的数据！<br />
          只能上传Excel文件<el-button class="download-btn" type="text" @click="downloadXlsx('SKU模版')">下载模版</el-button>
        </div>
      </el-alert>
      <el-form :model="batchImportForm" :rules="batchImportRules" ref="batchImportFormRef" :inline="true">
        <el-form-item prop="day" label="日期:">
          <el-date-picker
            v-model="batchImportForm.day"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item prop="CustomerId" label="客户:">
          <el-select
            v-model="batchImportForm.CustomerId"
            placeholder="选择客户"
            clearable
            filterable
            class="customerId"
          >
            <el-option
              v-for="item in customers"
              :key="item.Id"
              :label="item.CompanyName"
              :value="item.Id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文件上传:">
          <el-upload
            ref="importUploadRef"
            action="/"
            accept=".xlsx"
            :disabled="importStatus"
            :multiple="false"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="uploadSuccess"
          >
            <el-button class="upload-btn" type="success" :loading="importStatus">{{ getImportText }}</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div class="table-list">
        <vxe-table
          border
          show-overflow
          :data="paramsBatchImportList"
          :scroll-y="{enabled: false}"
          :column-config="{ resizable: true }"
          :footer-cell-class-name="footerRowClassName"
          :show-footer="showFooter"
          :footer-method="footerMethod"
          :loading="tableLoading"
          :height="600"
        >
          <vxe-column title="SKU" field="sku" :min-width="300"></vxe-column>
          <vxe-column title="单价" field="avgFee" :min-width="100"></vxe-column>
          <vxe-column title="数量" field="qty" :min-width="100"></vxe-column>
          <vxe-column title="总计" field="total" :min-width="100">
            <template #default="{ row }">
              {{ row | getSumTotal }}
            </template>
          </vxe-column>
        </vxe-table>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleBeforeClose">取 消</el-button>
      <el-button type="primary" :loading="importStatus" @click="handleConfirm">确定上传</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { _getCustomers } from '@/api/baseInfo';
import { deepClone, ceilToDecimals } from '@/utils';
import XLSX from 'xlsx';

export default {
  name: 'SkuBatchImport',
  props: {
    visible: {
      type: Boolean,
      required: false
    },
    closeOnClickModal: {
      type: Boolean,
      required: false
    },
    top: {
      type: String,
      default: '4vh'
    },
    title: {
      type: String,
      default: '上传SKU'
    },
    width: {
      type: String,
      default: '920px'
    },
    customers: {
      type: Array,
      default: []
    }
  },
  data() {
    return {
      showFooter: true,
      batchImportForm: {
        day: undefined,
        CustomerId: undefined
      },
      batchImportRules: {
        day: [
          { required: true, message: '请选择时间', trigger: 'change' }
        ],
        CustomerId: [
          { required: true, message: '请选择客户', trigger: 'change' }
        ],
      },
      importStatus: false,//导入状态
      oldBatchImportList: [],
      paramsBatchImportList: [],//参数
      tableLoading: false,
    }
  },
  computed: {
    getImportText() {
      return this.importStatus ? '导入中' : '上传表格'
    },
  },
  filters: {
    // 总计
    getSumTotal(row) {
      if (row && row.avgFee >= 0 && row.qty >= 0) {
        const total = row.avgFee * row.qty
        return ceilToDecimals(total, 2)
      }
      return 0
    }
  },
  methods: {
    handleConfirm() {
      this.$refs.batchImportFormRef.validate((valid) => {
        if (valid) {
          this.importStatus = true
          const Items = this.paramsBatchImportList.map(item => ({ sku: item.sku, avgFee: item.avgFee, qty: item.qty }))
          const params = { ...this.batchImportForm, Items }
          this.$emit('onConfirm', params, this.handleBeforeClose, this.updateImportStatus);
        } else {
          return false;
        }
      });
    },
    updateImportStatus() {
      this.importStatus = false
    },
    handleBeforeClose() {
      this.$refs.batchImportFormRef.resetFields();
      this.oldBatchImportList = []
      this.paramsBatchImportList = []
      this.$emit('onClose');
    },
    // 上传xlsx文件
    uploadSuccess(event) {
      const _this = this
      // 处理文件选择的逻辑
      const excelFile = event.raw;
      const isXlsx = excelFile.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
      if (!isXlsx) {
        this.$message({ message: '只能上传 xlsx 文件！', type: 'error' })
        return
      }
      // 导入状态和文件信息
      _this.importStatus = true
      _this.tableLoading = true
      // 构建fileReader对象
      const fileReader = new FileReader()
      // 该事件为读取完成时触发
      fileReader.onload = function (ev) {
        try {
          const data = new Uint8Array(ev.target.result);
          const workbook = XLSX.read(data, { type: 'array' });
          const sheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[sheetName];
          const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1, defval: '' });
          // 规定这个表头
          const headers = jsonData[0]
          const isHead = _this.checkArrayHead(headers)
          if (!isHead) {
            _this.$message({ message: 'Excel表头顺序必须是（SKU、单价、数量）！', type: 'error' })
            return false
          }
          const merges = worksheet['!merges'];
          if (merges) {
            merges.forEach((mergeCell) => {
              const { s, e } = mergeCell;
              const mergedCellValue = jsonData[s.r][s.c]; // 获取合并单元格的值
              // 将合并单元格的值应用到所有合并的单元格中
              for (let row = s.r; row <= e.r; row++) {
                for (let col = s.c; col <= e.c; col++) {
                  jsonData[row][col] = mergedCellValue;
                }
              }
            });
          }
          _this.oldBatchImportList = jsonData
          const paramsBatchImportList = deepClone(jsonData)
          paramsBatchImportList.shift()
          _this.paramsBatchImportList = _this.dealBatchImportList(paramsBatchImportList)
          _this.paramsOldCostList = deepClone(_this.paramsBatchImportList)
        } catch (e) {
          _this.$message({ message: e, type: 'warning' })
        } finally {
          _this.importStatus = false
          _this.tableLoading = false
        }
      }
      // 读取数据
      fileReader.readAsArrayBuffer(excelFile)
    },
    dealBatchImportList(array) {
      console.log(array,":array");
      if (!Array.isArray(array) && array.length === 0) return []
      const result = [];
      // 遍历原始数组
      array.forEach(item => {
        if (item.length === 3) {
          if (item[0] && item[1] && item[2]) {
            result.push({
              sku: item[0],
              avgFee: item[1],
              qty: item[2],
            })
          }
        }
      });
      return result
    },
    // 校验表头
    checkArrayHead(arr) {
      if (arr && arr.length !== 3) return false
      const xlsxHead = ["SKU", "单价", "数量"]//["线路名称", "SKU", "单价", "数量"]
      if (arr.every((item, index) => item === xlsxHead[index])) {
        return true;
      } else {
        return false;
      }
    },
    sumNum(list, field) {
      let count = 0
      if (field === 'total') {
        list.forEach(item => {
          const total = item.avgFee * item.qty
          count += ceilToDecimals(total, 2)
        })
        return count > 0 ? `${count}` : 0
      }
      list.forEach(item => {
        count += Number(item[field])
      })
      return count > 0 ? `${count}` : 0
    },
    footerMethod({ columns, data }) {
      const sums = []
      columns.forEach((column, columnIndex) => {
        if (columnIndex === 0) {
          sums.push('总计')
        } else {
          let sumCell = this.sumNum(data, column.field)
          sums.push(sumCell)
        }
      })
      return [sums]
    },
    footerRowClassName() {
      return 'footer-row'
    },
    downloadXlsx(name) {
      const fileUrl = `/xlsx/${name}.xlsx`
      const link = document.createElement('a')
      link.href = fileUrl
      link.setAttribute('download', `${name}.xlsx`) // 设置下载属性和文件名
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link) // 点击后移除链接
    }
  }
};
</script>

<style scoped>
.sku-batch-import {
  width: 100%;
  display: inline-block;
}
.sku-batch-import .flex {
  display: flex;
}
.sku-batch-import .el-button {
  margin-left: 10px;
}
.sku-batch-import .customerId {
  width: 240px;
}
.sku-batch-import .upload-btn {
  margin-left: 0;
}
.sku-batch-import .table-list {
  padding-top: 6px;
}
.sku-batch-import ::v-deep .footer-row {
  background-color: #F8F8F9 !important;
}
.sku-batch-import .define-title {
  line-height: 1.5;
  font-size: 13px;
}
.sku-batch-import .define-title .download-btn {
  font-size: 13px;
}
</style>
