<template>
  <div>
    <avue-crud
      :option="option"
      :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-plus" @click="handleDelete">申报
            </el-button> -->
        <el-button type="danger" @click="handleDelete">删除 </el-button>
      </template>
      <template #menu-right>
        <el-button type="primary" @click="handleImport">导入 </el-button>
      </template>
      <template #menu> </template>
    </avue-crud>
    <!-- 导入 -->
    <basic-import
      v-if="isShowImport"
      title="导入"
      :isShow="isShowImport"
      templateUrl="/blade-desk/mesOemSpecialPro/downloadExcelTemplate"
      templateName="试验项目模板.xls"
      importUrl="/blade-desk/mesOemSpecialPro/importExcel"
      @closeDialog="closeDialog"
    ></basic-import>
  </div>
</template>
<script>
import basicImport from '@/components/basic-import/main.vue';

import { pageList, saveItem, updateItem, removeItem } from '@/api/oem/oem';
export default {
  components: { basicImport },
  data() {
    return {
      isShowImport: false,
      loading: false,
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 32,
        tip: false,
        // size: 'medium',
        simplePage: true,
        searchShow: true,
        searchMenuSpan: 18,
        searchIcon: true,
        searchIndex: 3,
        tree: false,
        border: true,
        index: true,
        selection: true,
        viewBtn: false,
        delBtn: true,
        addBtn: true,
        editBtnText: '修改',
        addBtnIcon: ' ',
        viewBtnIcon: ' ',
        delBtnIcon: ' ',
        editBtnIcon: ' ',
        viewBtnText: '详情',
        labelWidth: 120,
        menuWidth: 110,
        dialogWidth: 1040,
        dialogClickModal: false,
        searchEnter: true,
        excelBtn: true,
        excelUrl: '/blade-desk/mesOemSpecialPro/export-mesOemSpecialPro',
        filterBtn: true,
        searchShowBtn: false,
        columnSort: true,
        columnSort: true,
        index: false,
        showOverflowTooltip: true,
        gridBtn: false,
        searchMenuPosition: 'right',
        searchLabelPosition: 'left',
        searchLabelPosition: 'left',
        searchGutter: 24,
        searchSpan: 6,
        menuAlign: 'left',
        gridBtn: false,
        searchMenuPosition: 'right',
        align: 'center',
        column: [
          //    {
          //         label: '作业中心',
          //         prop: 'bsWorkCenter.wcName',
          //         search: false,
          //         sortable: true,
          //         filter: true,
          //         span: 12,
          //          headerAlign: 'center',
          //         align: 'left',

          //     },
          // {
          //     label: '产线',
          //     prop: 'bsWorkCenter.wcName',
          //     search: false,
          //     sortable: true,
          //     filter: true,
          //     span: 12,
          //      headerAlign: 'center',
          //     align: 'left',

          // },
          
          {
            label: '外协厂商',
            prop: 'ocId',
             search: true,
            search: true,
            sortable: true,
            filter: true,
            span: 12,
            headerAlign: 'center',
            align: 'left',
            type: 'select',
            dicUrl:"/api/blade-desk/BA/Oem/listForSelect",
            props:{
              label:"ocName",
              value:"id",
              res:"data"
            },
            formatter: (row, value, label, column) => {
              return row.oemName || value || '-';
            }
          },
          {
            label: '确认名称',
            prop: 'proItem',
            search: false,
            sortable: true,
            filter: true,
            span: 12,
            headerAlign: 'center',
            align: 'left',
          },
          {
            label: '确认编号',
            prop: 'condition',
            search: false,
            sortable: true,
            filter: true,
            span: 12,
            headerAlign: 'center',
            align: 'left',
          },
       
          {
            label: '确认到期日期',
            prop: 'lastDueTime',
            search: false,
            sortable: true,
            filter: true,
            span: 12,
              type: 'date',
       
            rules: [{ required: true, message: '请选择发生时间', trigger: 'change' }],
          },
          {
            label: '提醒天数',
            prop: 'remDays',
            search: false,
            sortable: true,
            filter: true,
            span: 12,
            type: 'number',
            headerAlign: 'center',
            align: 'center',
          },
          {
            label: '工艺员',
            prop: 'proMan',
            search: false,
            sortable: true,
            filter: true,
            span: 12,
            headerAlign: 'center',
            align: 'center',
            type: 'select',
            dicUrl: '/blade-system/user/page?size=999999&current=1',
            filterable: true,
            searchLabelWidth: 50,
            props: {
              label: 'realName',
              value: 'id',
              res: 'data.records',
            },
            formatter: (row, value, label, column) => {
              return row.proManName || value || '-';
            },
            rules: [
              {
                required: true,
                message: '请选择工艺员',
                trigger: 'change',
              },
            ],
          },
         
          {
            label: '备注',
            prop: 'remarks',
            search: false,
            sortable: true,
            filter: true,
            span: 12,
            headerAlign: 'center',
            align: 'left',
          },
        ],
      },
      form: {},
      data: [],
      query: {},
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
    };
  },
  methods: {
    // 删除单行
    rowDel(row, index, done) {
      console.log('【删除行】row:', row);
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        return removeItem(String(row.id)).then(() => {
          this.$message.success('删除成功');
          this.onLoad(this.page);
          done();
        });
      }).catch(error => {
        console.error('删除失败:', error);
        this.$message.error('删除失败，请稍后重试');
      });
    },
    // 点击导入按钮
    handleImport() {
      this.isShowImport = true
    },
    // 关闭导入对话框
    closeDialog() {
      this.isShowImport = false;
      this.onLoad(this.page);
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      const ids = this.selectionList.map(item => item.id).join(',');
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        return removeItem(ids).then(() => {
          this.$message.success('删除成功');
          this.selectionClear();
          this.onLoad(this.page);
        });
      }).catch(error => {
        console.error('批量删除失败:', error);
        this.$message.error('删除失败，请稍后重试');
      });
    },
    // 多选
    selectionChange(list) {
      this.selectionList = list;
    },
    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;
      this.onLoad(this.page, this.query);
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page, this.query);
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    onLoad(page, params = {}) {
      this.loading = true;
      pageList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        console.log('API返回数据:', res);

        // 检查返回的数据结构
        if (res.data && res.data.code === 200) {
          const data = res.data.data;
          this.page.total = data.total || 0;
          this.data = data.records || [];
          console.log('设置的数据:', { total: this.page.total, data: this.data });
        } else {
          this.$message.error(res.data.msg || '获取数据失败');
          this.data = [];
        }
        this.loading = false;

      }).catch(error => {
        console.error('获取数据失败:', error);
        this.$message.error('获取数据失败');
        this.data = [];
        this.loading = false;
      });

      setTimeout(() => {
        this.selectionClear();
      }, 500);
    },
    // 格式化日期为 yyyy-MM-dd HH:mm:ss
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      const hours = String(d.getHours()).padStart(2, '0');
      const minutes = String(d.getMinutes()).padStart(2, '0');
      const seconds = String(d.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 新增保存
    rowSave(row, done, loading) {
      console.log('【新增保存】原始row:', row);

      // 复制一份 row 对象，避免修改原对象
      const params = { ...row };

      // 格式化日期字段
      if (params.lastDueTime) {
        params.lastDueTime = this.formatDate(params.lastDueTime);
      }

      // 确保工艺员字段不为空
      console.log('【新增保存】proMan值:', params.proMan);
      if (!params.proMan) {
        this.$message.error('请选择工艺员');
        loading();
        return;
      }

      console.log('【新增保存】处理后params:', params);

      saveItem(params).then(() => {
        this.$message.success('新增成功');
        this.onLoad(this.page);
        done();
      }).catch(error => {
        console.error('新增失败:', error);
        loading();
      });
    },
    // 修改更新
    rowUpdate(row, index, done, loading) {
      console.log('【修改更新】原始row:', row);

      // 复制一份 row 对象，避免修改原对象
      const params = { ...row };

      // 格式化日期字段
      if (params.lastDueTime) {
        params.lastDueTime = this.formatDate(params.lastDueTime);
      }

      // 确保工艺员字段不为空
      console.log('【修改更新】proMan值:', params.proMan);
      if (!params.proMan) {
        this.$message.error('请选择工艺员');
        loading();
        return;
      }

      console.log('【修改更新】处理后params:', params);

      updateItem(params).then(() => {
        this.$message.success('修改成功');
        this.onLoad(this.page);
        done();
      }).catch(error => {
        console.error('修改失败:', error);
        loading();
      });
    },
  },
};
</script>
<style lang="scss" scoped></style>
