<template>
  <div>
    <avue-crud :option="option" v-model:search="search" :table-loading="loading" :data="data" v-model="form" v-model:page="page" ref="crud"
      @row-del="rowDel" @row-save="rowSave" @row-update="rowUpdate" @search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange"
      @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange" @on-load="onLoad">
      <template #menu-left>
        <el-button type="primary" icon="el-icon-download" @click="handleExport">导出
        </el-button>
        <el-button type="danger" icon="el-icon-delete" @click="handleDelete">删除
        </el-button>
      </template>
      <template #menu-right>
        <el-button type="primary" icon="el-icon-upload" @click="handleImport">导入
        </el-button>
      </template>
      <template #menu> </template>
    </avue-crud>
    <!-- 导入 -->
    <basic-import v-if="isShowImport" title="导入" :isShow="isShowImport"
      templateUrl="/blade-desk/QA/CycleTestItem/download-excel-template" templateName="试验项目模板.xls"
      importUrl="/blade-desk/QA/CycleTestItem/import-excel" @closeDialog="closeDialog"></basic-import>
  </div>
</template>
<script>
import basicImport from '@/components/basic-import/main.vue'
import { pageList, removeItem, saveItem, exportData } from '@/api/energyManagement/bsEnergyQuota';
export default {
  components: {
    basicImport,
  },
  data() {
    return {
      isShowImport: false,
      selectionList: [],
      query: {},
      search: {},
      option: {
        height: "auto",
        calcHeight: 32,
        tip: false,
        simplePage: true,
        searchShow: true,
        searchMenuSpan: 6,
        searchIcon: true,
        searchIndex: 3,
        tree: false,
        border: true,
        index: true,
        selection: true,
        viewBtn: false,
        delBtn: false,
        addBtn: true,
        editBtnText: "修改",
        viewBtnIcon: " ",
        delBtnIcon: " ",
        editBtnIcon: " ",
        viewBtnText: "详情",
        labelWidth: 120,
        menuWidth: 180,
        dialogWidth: 640,
        dialogClickModal: false,
        searchEnter: true,
        excelBtn: false,
        filterBtn: true,
        searchShowBtn: false,
        columnSort: true,
        excelBtn: true,
        columnSort: true,
        index: false,
        showOverflowTooltip: true,
        searchLabelPosition: "left",
        searchLabelPosition: "left",
        searchGutter: 24,
        searchSpan: 6,
        menuAlign: "left",
        gridBtn: false,
        searchMenuPosition: "right",
        addBtnIcon: " ",
        viewBtnIcon: " ",
        delBtnIcon: " ",
        editBtnIcon: " ",
        align: "center",

        column: [
          {
            label: "作业中心",
            prop: "workCenterName",
            sortable: true,
            filter: true,
            span: 24,
            search: true,
            type: "select",
            dicData: [
              { label: "化学镀镍作业中心", value: "化学镀镍作业中心" },
              { label: "电镀作业中心", value: "电镀作业中心" },
              { label: "喷涂作业中心", value: "喷涂作业中心" }],
            rules: [
              {
                required: true,
                message: "请选择作业中心",
                trigger: "blur",
              },
            ],
          },
          {
            label: "设备",
            prop: "equipmentName",
            bind: "equipmentName",
            search: false,
            sortable: true,
            filter: true,
            span: 24,
            type: "select",
            dicData: [
              { label: "化学镀镍", value: "化学镀镍" },
              { label: "电镀设备", value: "电镀设备" },
              { label: "喷涂设备", value: "喷涂设备" },
          ],
              rules: [
                {
                  required: true,
                  message: "请选择设备",
                  trigger: "blur",
                },
              ],
          },
          {
            label: "日期",
            prop: "date",
            search: true,
            sortable: true,
            filter: true,
            span: 24,
            type: 'date',
          
            rules: [
              {
                required: true,
                message: "请输入日期",
                trigger: "blur",
              },
            ],
          },

          {
            label: "自来水用水量(L/d㎡)",
            prop: "tapWaterNum",
            search: false,
            sortable: true,
            filter: true,
            span: 24,
            rules: [
              {
                required: true,
                message: "请输入日期",
                trigger: "blur",
              },
            ],
          },
          {
            label: "纯水用水量(L/d㎡)",
            prop: "pureWaterNum",
            search: false,
            sortable: true,
            filter: true,
            span: 24,
            rules: [
              {
                required: true,
                message: "请输入日期",
                trigger: "blur",
              },
            ],
          },
        ],
      },
      form: {},
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
    };
  },
  methods: {
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },

    closeDialog() {
      this.isShowImport = false
    },
    handleImport() {
      this.isShowImport = true
    },
    handleExport() {
      this.$confirm('是否导出数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.loading = true;
        exportData({}).then(res => {
          const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          link.download = '用水配额数据.xlsx';
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);
          this.$message.success('导出成功');
          this.loading = false;
        }).catch(() => {
          this.loading = false;
        });
      });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        const ids = this.selectionList.map(item => item.id).join(',');
        removeItem(ids).then(() => {
          this.$message.success("删除成功");
          this.onLoad(this.page);
          this.selectionClear();
        });
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        removeItem(row.id).then(() => {
          this.$message.success("删除成功");
          this.onLoad(this.page);
        });
      });
    },
    rowSave(row, done, loading) {
      const submitData = { ...row };
      // 处理日期字段，确保为字符串格式
      if (submitData.date) {
        if (typeof submitData.date === 'object' && submitData.date instanceof Date) {
          // 如果是 Date 对象，转换为 yyyy-MM-dd 格式
          const year = submitData.date.getFullYear();
          const month = String(submitData.date.getMonth() + 1).padStart(2, '0');
          const day = String(submitData.date.getDate()).padStart(2, '0');
          submitData.date = `${year}-${month}-${day}`;
        } else if (typeof submitData.date === 'string') {
          // 如果是字符串，截取前10位 (yyyy-MM-dd)
          submitData.date = submitData.date.substring(0, 10);
        }
      }
      saveItem(submitData).then(() => {
        this.$message.success("新增成功");
        this.onLoad(this.page);
        done();
      }).catch(() => {
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      const submitData = { ...row };
      // 处理日期字段，确保为字符串格式
      if (submitData.date) {
        if (typeof submitData.date === 'object' && submitData.date instanceof Date) {
          // 如果是 Date 对象，转换为 yyyy-MM-dd 格式
          const year = submitData.date.getFullYear();
          const month = String(submitData.date.getMonth() + 1).padStart(2, '0');
          const day = String(submitData.date.getDate()).padStart(2, '0');
          submitData.date = `${year}-${month}-${day}`;
        } else if (typeof submitData.date === 'string') {
          // 如果是字符串，截取前10位 (yyyy-MM-dd)
          submitData.date = submitData.date.substring(0, 10);
        }
      }
      saveItem(submitData).then(() => {
        this.$message.success("修改成功");
        this.onLoad(this.page);
        done();
      }).catch(() => {
        loading();
      });
    },
    // 多选
    selectionChange(list) {
      this.selectionList = list;
    },
  onLoad() {
      this.loading = true;
      pageList(
        this.page.currentPage,
        this.page.pageSize,
        { type: 1 }
      ).then(res => {
        this.data = res.data.data.records;
        this.page.total = res.data.data.total;
        this.loading = false;
        setTimeout(() => {
          this.selectionClear();
        }, 500);
      }).catch(() => {
        this.loading = false;
      });
    },
  },
};
</script>
<style lang="scss" scoped></style>
