<template>
  <div class="ele-body">
    <el-card shadow="never" v-loading="loading">
      <dailySearch @search="reload" ref="searchRef"> </dailySearch>
      <!-- <seek-page :seekList="seekList" @search="search"></seek-page> -->

      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="datasource"
        cache-key="wanLongDailyList"
        :current.sync="current"
        highlight-current-row
        row-key="id"
        :needPage="false"
        :height="tableHeight"
        :selection.sync="selection"
        @fullscreen-change="fullscreenChange"
      >
        <template v-slot:toolbar>
          <el-button
            size="small"
            type="primary"
            class="ele-btn-icon"
            @click="printData('add')"
          >
            下载
          </el-button></template
        >
        <template slot="subCountAllFirst" slot-scope="{ row }">
          <el-input v-model="row.subCountAllFirst" @change="changeUpate(row)" />
        </template>

        <template slot="subCountSendFirst" slot-scope="{ row }">
          <el-input
            v-model="row.subCountSendFirst"
            @change="changeUpate(row)"
          />
        </template>

        <template slot="difference" slot-scope="{ row }">
          <el-input v-model="row.difference" @change="changeUpate(row)" />
        </template>

        <template slot="remark" slot-scope="{ row }">
          <el-input v-model="row.remark" @change="changeUpate(row)" />
        </template>
      </ele-pro-table>
    </el-card>
  </div>
</template>

<script>
  import { getDailyList, updateDaily } from '@/api/wanLong/index';
  import dailySearch from './components/dailySearch.vue';
  import * as XLSX from 'xlsx';
  import { saveAs } from 'file-saver';

  export default {
    name: 'wanLongIndex',

    components: {
      dailySearch
    },

    data() {
      return {
        loading: false,
        current: null,
        selection: [],
        tableHeight: 'calc(100vh - 320px)',
        dynamicColumns: [], // 保存 taskList 动态列
        taskNames: [], // taskName 列名数组
        timeDate: ''
        // categoryData: [],
        // categoryType: [],

        // orderStatus: [
        //   {
        //     value: 4,
        //     label: '待生产'
        //   },
        //   {
        //     value: 5,
        //     label: '生产中'
        //   },
        //   {
        //     value: 6,
        //     label: '已完成'
        //   },
        //   {
        //     value: 7,
        //     label: '已延期'
        //   },
        //   {
        //     value: 9,
        //     label: '暂停'
        //   },
        //   {
        //     value: 10,
        //     label: '终止'
        //   }
        // ]
      };
    },

    computed: {
      // seekList() {
      //   const today = new Date();
      //   const year = today.getFullYear();
      //   const month = String(today.getMonth() + 1).padStart(2, '0');
      //   const day = String(today.getDate()).padStart(2, '0');

      //   const dateStr = `${year}-${month}-${day}`;

      //   return [
      //     {
      //       label: '选择日期:',
      //       value: 'startTime',
      //       type: 'date',
      //       dateType: 'date',
      //       placeholder: '',
      //       defaultValue: dateStr,
      //       clearable: false,
      //       width: 220
      //     },
      //     {
      //       label: '物品分类:',
      //       value: 'categoryLevelId',
      //       type: 'select',
      //       placeholder: '',
      //       planList: this.categoryType
      //     },
      //     {
      //       label: '工单状态:',
      //       value: 'workOrderStatusList',
      //       type: 'select',
      //       placeholder: '',
      //       multiple: true,
      //       planList: this.orderStatus
      //     }
      //   ];
      // },

      columns() {
        const baseColumns = [
          {
            columnKey: 'selection',
            type: 'selection',
            width: 45,
            align: 'center'
          },
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            label: '物品名称',
            prop: 'categoryName',
            width: 150,
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            label: '物品编码',
            prop: 'categoryCode',
            width: 160,
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            label: '图号',
            prop: 'imgCode',
            width: 160,
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            label: '图纸版本',
            prop: 'version',
            width: 160,
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            label: '重量',
            prop: 'productUnitWeight',
            width: 120,
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            label: '型号',
            prop: 'modelType',
            width: 120,
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            label: '规格',
            prop: 'specification',
            width: 120,
            showOverflowTooltip: true,
            align: 'center'
          },

          {
            label: '中间状态数量',
            prop: 'middleNum',
            width: 120,
            showOverflowTooltip: true,
            align: 'center',
            sortable: 'custom'
          },
          {
            label: '库存数量',
            prop: 'availableCountBase',
            width: 120,
            showOverflowTooltip: true,
            align: 'center'
          },

          {
            label: '下料初始值',
            prop: 'subCountAllFirst',
            width: 120,
            slot: 'subCountAllFirst',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            label: '下料总数量',
            prop: 'subCountAll',
            width: 120,
            showOverflowTooltip: true,
            align: 'center'
          },

          {
            label: '送货初始值',
            prop: 'subCountSendFirst',
            width: 120,
            slot: 'subCountSendFirst',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            label: '送货数量',
            prop: 'subCountSend',
            width: 120,
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            label: '固配与活配差异',
            prop: 'difference',
            slot: 'difference',
            width: 120,
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            label: '备注',
            prop: 'remark',
            slot: 'remark',
            width: 120,
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            label: '日期',
            prop: 'date',
            width: 100,
            showOverflowTooltip: true,
            align: 'center'
          }
        ];

        return baseColumns.concat(this.dynamicColumns);
      }
    },

    created() {},

    methods: {
      datasource({ page, limit, where }) {
        if (Object.keys(where).length == 0) {
          const today = new Date();
          const year = today.getFullYear();
          const month = String(today.getMonth() + 1).padStart(2, '0');
          const day = String(today.getDate()).padStart(2, '0');

          const dateStr = `${year}-${month}-${day}`;
          where.startTime = dateStr + ' 00:00:00';
          where.endTime = dateStr + ' 23:59:59';
        }
        this.timeDate = where.startTime.split(' ')[0];
        return getDailyList({
          pageNum: page,
          size: -1,
          ...where
        }).then((res) => {
          const data = res.data || [];

          if (data.length) {
            const firstItem = data[0];
            if (firstItem.taskList && firstItem.taskList.length) {
              this.taskNames = firstItem.taskList.map((t) => t.taskName);
              this.dynamicColumns = firstItem.taskList.map((t) => ({
                label: t.taskName,
                prop: `task_${t.taskName}`,
                width: 100,
                align: 'center'
              }));
            }
          }

          const tableData = data.map((item) => {
            const taskFields = {};
            if (item.taskList && item.taskList.length) {
              item.taskList.forEach((t) => {
                taskFields[`task_${t.taskName}`] = t.quantity;
              });
            }
            return Object.assign({}, item, taskFields);
          });

          return tableData;
        });
      },

      reload(where) {
        this.$nextTick(() => {
          this.$refs.table.reload({ page: 1, where });
        });
      },

      async changeUpate(item) {
        const filteredData = Object.keys(item).reduce((acc, key) => {
          if (!key.startsWith('task_')) {
            acc[key] = item[key];
          }
          return acc;
        }, {});
        await updateDaily(filteredData);
      },

      fullscreenChange(fullscreen) {
        this.tableHeight = fullscreen
          ? 'calc(100vh - 120px)'
          : 'calc(100vh - 320px)';
      },

      formatDate(date) {
        const d = new Date(date);
        const yyyy = d.getFullYear();
        const mm = String(d.getMonth() + 1).padStart(2, '0');
        const dd = String(d.getDate()).padStart(2, '0');
        const hh = String(d.getHours()).padStart(2, '0');
        const mi = String(d.getMinutes()).padStart(2, '0');
        const ss = String(d.getSeconds()).padStart(2, '0');
        return `${yyyy}-${mm}-${dd} ${hh}:${mi}:${ss}`;
      },
      async printData() {
        try {
          const tableData = this.$refs.table?.getData?.() || [];
          if (!tableData.length) {
            this.$message.warning('当前表格没有数据可导出');
            return;
          }

          const allColumns = this.columns
            .concat(this.dynamicColumns)
            .filter(
              (col) =>
                col.columnKey !== 'selection' && col.columnKey !== 'index'
            );

          const exportData = tableData.map((row) => {
            const obj = {};
            allColumns.forEach((col) => {
              const key = col.prop || col.columnKey;
              if (key) {
                obj[col.label] = row[key] ?? '';
              }
            });
            return obj;
          });

          const ws = XLSX.utils.json_to_sheet(exportData);

          const wb = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(wb, ws, '表格数据');
          const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
          saveAs(
            new Blob([wbout], { type: 'application/octet-stream' }),
            `${this.timeDate}生产日报.xlsx`
          );

          this.$message.success('导出成功');
        } catch (err) {
          console.error(err);
          this.$message.error('导出 Excel 失败，请检查控制台');
        }
      }
    }
  };
</script>

<style scoped>
  .clickable {
    cursor: pointer;
    color: #409eff;
  }
</style>
