<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="日期" prop="calendarDate">
        <el-date-picker
          v-model="queryParams.calendarDate"
          type="date"
          placeholder="选择日期"
          value-format="yyyy-MM-dd"
          clearable
        />
      </el-form-item>
      <el-form-item label="产线" prop="lineId">
        <el-select v-model="queryParams.lineId" placeholder="请选择产线" clearable filterable style="width: 180px">
          <el-option
            v-for="line in lineOptions"
            :key="line.lineId"
            :label="line.lineName"
            :value="line.lineId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="班次" prop="shiftId">
        <el-select v-model="queryParams.shiftId" placeholder="请选择班次" clearable filterable style="width: 180px">
          <el-option
            v-for="shift in shiftOptions"
            :key="shift.shiftId"
            :label="shift.shiftName"
            :value="shift.shiftId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable>
          <el-option label="停用" :value="0" />
          <el-option label="启用" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <el-col :span="3">
        <el-button type="info" plain icon="el-icon-date" size="mini" @click="handleGenerateYearWorkday">一键生成全年工作日</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <KLPTable v-loading="loading" :data="calendarShiftList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="日期" align="center" prop="calendarDate" width="120" />
      <el-table-column label="产线" align="center" prop="lineName" width="150" />
      <el-table-column label="班次" align="center" prop="shiftName" width="150" />
      <el-table-column label="计划工时" align="center" prop="plannedHours" width="100" />
      <el-table-column label="状态" align="center" prop="statusName" width="80" />
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </KLPTable>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改日历班次配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="日期" prop="calendarDate">
          <el-date-picker
            v-model="form.calendarDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="产线" prop="lineId">
          <el-select v-model="form.lineId" placeholder="请选择产线" filterable style="width: 100%">
            <el-option
              v-for="line in lineOptions"
              :key="line.lineId"
              :label="line.lineName"
              :value="line.lineId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="班次" prop="shiftId">
          <el-select v-model="form.shiftId" placeholder="请选择班次" filterable style="width: 100%">
            <el-option
              v-for="shift in shiftOptions"
              :key="shift.shiftId"
              :label="shift.shiftName"
              :value="shift.shiftId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="计划工时" prop="plannedHours">
          <el-input-number v-model="form.plannedHours" :min="0" :precision="2" :step="0.5" style="width: 100%" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">停用</el-radio>
            <el-radio :label="1">启用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCalendarShift, getCalendarShift, delCalendarShift, addCalendarShift, updateCalendarShift, exportCalendarShift, listShiftTemplate, generateCalendarShiftWorkdayYear } from "@/api/aps/aps";
import { listProductionLine } from "@/api/wms/productionLine";

export default {
  name: "ApsCalendarShift",
  data() {
    return {
      buttonLoading: false,
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      calendarShiftList: [],
      lineOptions: [],
      shiftOptions: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        calendarDate: undefined,
        lineId: undefined,
        shiftId: undefined,
        status: undefined
      },
      form: {},
      generateYear: new Date().getFullYear(),
      rules: {
        calendarDate: [{ required: true, message: "日期不能为空", trigger: "change" }],
        lineId: [{ required: true, message: "产线不能为空", trigger: "change" }],
        shiftId: [{ required: true, message: "班次不能为空", trigger: "change" }]
      }
    };
  },
  created() {
    this.getList();
    this.loadLines();
    this.loadShifts();
  },
  methods: {
    getList() {
      this.loading = true;
      listCalendarShift(this.queryParams).then(response => {
        this.calendarShiftList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    loadLines() {
      listProductionLine({ pageNum: 1, pageSize: 1000 }).then(response => {
        this.lineOptions = response.rows || [];
      });
    },
    loadShifts() {
      listShiftTemplate({ pageNum: 1, pageSize: 1000 }).then(response => {
        this.shiftOptions = response.rows || [];
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        configId: undefined,
        calendarDate: undefined,
        lineId: undefined,
        shiftId: undefined,
        plannedHours: 0,
        status: 1,
        remark: undefined
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.configId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加日历班次配置";
    },
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const configId = row.configId || this.ids[0];
      getCalendarShift(configId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改日历班次配置";
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.configId != null) {
            updateCalendarShift(this.form).then(() => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addCalendarShift(this.form).then(() => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    handleDelete(row) {
      const configIds = row.configId || this.ids;
      this.$modal.confirm('是否确认删除选中的日历班次配置数据？').then(() => {
        this.loading = true;
        return delCalendarShift(configIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {}).finally(() => {
        this.loading = false;
      });
    },
    handleExport() {
      this.download('aps/calendar-shift/export', {
        ...this.queryParams
      }, `calendar_shift_${new Date().getTime()}.xlsx`);
    },
    handleGenerateYearWorkday() {
      this.$prompt('请输入要生成的年份（例如 2026）', '一键生成全年工作日', {
        confirmButtonText: '下一步',
        cancelButtonText: '取消',
        inputValue: String(this.generateYear),
        inputPattern: /^(20\d{2}|2100)$/,
        inputErrorMessage: '请输入 2000-2100 的年份'
      }).then(({ value }) => {
        const year = Number(value)
        this.$confirm('是否覆盖已有配置？\n- 选“是”：将已有记录强制改为工作日\n- 选“否”：仅补齐缺失记录', '覆盖选项', {
          confirmButtonText: '是（覆盖）',
          cancelButtonText: '否（仅补齐）',
          distinguishCancelAndClose: true,
          type: 'warning'
        }).then(() => {
          this.loading = true
          return generateCalendarShiftWorkdayYear(year, true).then(res => {
            this.generateYear = year
            this.$modal.msgSuccess(`生成完成（覆盖模式），处理记录 ${res.data || 0} 条`)
            this.getList()
          }).finally(() => {
            this.loading = false
          })
        }).catch(action => {
          if (action === 'cancel') {
            this.loading = true
            return generateCalendarShiftWorkdayYear(year, false).then(res => {
              this.generateYear = year
              this.$modal.msgSuccess(`生成完成（仅补齐），处理记录 ${res.data || 0} 条`)
              this.getList()
            }).finally(() => {
              this.loading = false
            })
          }
        })
      }).catch(() => {})
    }
  }
};
</script>

<style scoped lang="scss">
.app-container {
  padding: 10px;
}

::v-deep .el-table,
::v-deep .el-table--border,
::v-deep .el-table--group {
  border-color: #eef2f7;
}

::v-deep .el-table td,
::v-deep .el-table th.is-leaf {
  border-bottom: 1px solid #f3f5f8;
}

::v-deep .el-dialog {
  border-radius: 8px;
}
</style>
