<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="年第周" prop="yearWeek">
        <el-input
          v-model="queryParams.yearWeek"
          placeholder="如202501"
          clearable
          style="width: 120px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="周一日期" prop="weekStartDate">
        <el-date-picker clearable
          v-model="queryParams.weekStartDate"
          type="date"
          value-format="yyyy-MM-dd"
          style="width: 150px"
          :picker-options="mondayPickerOptions"
          placeholder="选择周一日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="物料编码" prop="itemCode">
        <el-input
          v-model="queryParams.itemCode"
          placeholder="请输入物料编码"
          clearable
          style="width: 150px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料描述" prop="itemDesc">
        <el-input
          v-model="queryParams.itemDesc"
          placeholder="请输入物料描述"
          clearable
          style="width: 150px"
          @keyup.enter.native="handleQuery"
        />
      </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"
          v-hasPermi="['production:req:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['production:req:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['production:req:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['production:req:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="openExportDialog"
          v-hasPermi="['production:req:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-check"
          size="mini"
          :disabled="!hasChanges"
          @click="handleBatchSave"
          v-hasPermi="['production:req:edit']"
        >保存修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-document-copy"
          size="mini"
          :disabled="multiple"
          @click="openBatchFillDialog"
          v-hasPermi="['production:req:edit']"
        >批量填充</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="reqList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="年第周" align="center" prop="yearWeek" width="90" v-if="columns[0].visible"/>
      <el-table-column label="周一日期" align="center" prop="weekStartDate" width="110" v-if="columns[1].visible">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.weekStartDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="物料编码" align="center" prop="itemCode" width="120" v-if="columns[2].visible"/>
      <el-table-column label="物料描述" align="center" prop="itemDesc" min-width="180" :show-overflow-tooltip="true" v-if="columns[3].visible"/>
      <el-table-column label="周一" align="center" width="90" v-if="columns[4].visible">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.reqMon" :min="0" :precision="0" :controls="false" size="mini" style="width: 70px" :class="{'changed-cell': changedIds.has(scope.row.id)}" @change="markChanged(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="周二" align="center" width="90" v-if="columns[5].visible">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.reqTue" :min="0" :precision="0" :controls="false" size="mini" style="width: 70px" :class="{'changed-cell': changedIds.has(scope.row.id)}" @change="markChanged(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="周三" align="center" width="90" v-if="columns[6].visible">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.reqWed" :min="0" :precision="0" :controls="false" size="mini" style="width: 70px" :class="{'changed-cell': changedIds.has(scope.row.id)}" @change="markChanged(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="周四" align="center" width="90" v-if="columns[7].visible">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.reqThu" :min="0" :precision="0" :controls="false" size="mini" style="width: 70px" :class="{'changed-cell': changedIds.has(scope.row.id)}" @change="markChanged(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="周五" align="center" width="90" v-if="columns[8].visible">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.reqFri" :min="0" :precision="0" :controls="false" size="mini" style="width: 70px" :class="{'changed-cell': changedIds.has(scope.row.id)}" @change="markChanged(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="周六" align="center" width="90" v-if="columns[9].visible">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.reqSat" :min="0" :precision="0" :controls="false" size="mini" style="width: 70px" :class="{'changed-cell': changedIds.has(scope.row.id)}" @change="markChanged(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="周日" align="center" width="90" v-if="columns[10].visible">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.reqSun" :min="0" :precision="0" :controls="false" size="mini" style="width: 70px" :class="{'changed-cell': changedIds.has(scope.row.id)}" @change="markChanged(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="周合计" align="center" width="80" v-if="columns[11].visible">
        <template slot-scope="scope">
          <span>{{ calcRowTotal(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['production:req:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['production:req:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <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="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="年第周" prop="yearWeek">
              <el-input v-model="form.yearWeek" placeholder="如202501" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="周一日期" prop="weekStartDate">
              <el-date-picker clearable
                v-model="form.weekStartDate"
                type="date"
                value-format="yyyy-MM-dd"
                style="width: 100%"
                placeholder="选择周一日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="物料编码" prop="itemCode">
              <el-input v-model="form.itemCode" placeholder="请输入物料编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料描述" prop="itemDesc">
              <el-input v-model="form.itemDesc" placeholder="请输入物料描述" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">每日需求量</el-divider>
        <el-row>
          <el-col :span="6">
            <el-form-item label="周一" prop="reqMon" label-width="50px">
              <el-input-number v-model="form.reqMon" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="周二" prop="reqTue" label-width="50px">
              <el-input-number v-model="form.reqTue" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="周三" prop="reqWed" label-width="50px">
              <el-input-number v-model="form.reqWed" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="周四" prop="reqThu" label-width="50px">
              <el-input-number v-model="form.reqThu" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="周五" prop="reqFri" label-width="50px">
              <el-input-number v-model="form.reqFri" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="周六" prop="reqSat" label-width="50px">
              <el-input-number v-model="form.reqSat" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="周日" prop="reqSun" label-width="50px">
              <el-input-number v-model="form.reqSun" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="合计" label-width="50px">
              <el-input :value="weekTotal" disabled style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="450px" append-to-body>
      <el-form label-width="100px">
        <el-form-item label="周一日期" required>
          <el-date-picker
            v-model="upload.weekStartDate"
            type="date"
            value-format="yyyy-MM-dd"
            :picker-options="mondayPickerOptions"
            placeholder="请选择周一日期"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :data="{ weekStartDate: upload.weekStartDate }"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导出对话框 -->
    <el-dialog title="导出子件物料周需求" :visible.sync="exportOpen" width="450px" append-to-body>
      <el-form label-width="100px">
        <el-form-item label="开始周一" required>
          <el-date-picker
            v-model="exportParams.startDate"
            type="date"
            value-format="yyyy-MM-dd"
            :picker-options="mondayPickerOptions"
            placeholder="选择开始周一日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束周一" required>
          <el-date-picker
            v-model="exportParams.endDate"
            type="date"
            value-format="yyyy-MM-dd"
            :picker-options="mondayPickerOptions"
            placeholder="选择结束周一日期"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleExport">确 定</el-button>
        <el-button @click="exportOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 批量填充对话框 -->
    <el-dialog title="批量填充" :visiblse.sync="batchFillOpen" width="400px" append-to-body>
      <el-form label-width="100px">
        <el-form-item label="已选行数">
          <span class="el-tag el-tag--info">{{ selectedRows.length }} 行</span>
        </el-form-item>
        <el-form-item label="填充列" required>
          <el-checkbox-group v-model="batchFill.columns">
            <el-checkbox label="reqMon">周一</el-checkbox>
            <el-checkbox label="reqTue">周二</el-checkbox>
            <el-checkbox label="reqWed">周三</el-checkbox>
            <el-checkbox label="reqThu">周四</el-checkbox>
            <el-checkbox label="reqFri">周五</el-checkbox>
            <el-checkbox label="reqSat">周六</el-checkbox>
            <el-checkbox label="reqSun">周日</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="填充数值" required>
          <el-input-number v-model="batchFill.value" :min="0" :precision="0" controls-position="right" style="width: 100%" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleBatchFill">确 定</el-button>
        <el-button @click="batchFillOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listReq, getReq, delReq, addReq, updateReq, batchUpdateReq } from "@/api/production/req";
import { getToken } from "@/utils/auth";

export default {
  name: "Req",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 子件物料周需求表格数据
      reqList: [],
      // 已修改的行ID集合
      changedIds: new Set(),
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 导出对话框
      exportOpen: false,
      // 导出参数
      exportParams: {
        startDate: null,
        endDate: null
      },
      // 批量填充对话框
      batchFillOpen: false,
      // 批量填充参数
      batchFill: {
        columns: [],
        value: 0
      },
      // 选中的行数据
      selectedRows: [],
      // 周一日期选择器配置（只能选周一）
      mondayPickerOptions: {
        disabledDate(time) {
          return time.getDay() !== 1;
        }
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        yearWeek: null,
        weekStartDate: null,
        itemCode: null,
        itemDesc: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        yearWeek: [
          { required: true, message: "年第周不能为空", trigger: "blur" }
        ],
        weekStartDate: [
          { required: true, message: "周一日期不能为空", trigger: "blur" }
        ],
        itemCode: [
          { required: true, message: "物料编码不能为空", trigger: "blur" }
        ],
      },
      // 导入参数
      upload: {
        open: false,
        title: "子件物料周需求导入",
        isUploading: false,
        weekStartDate: null,
        headers: { Authorization: "Bearer " + getToken() },
        url: process.env.VUE_APP_BASE_API + "/production/req/importData"
      },
      columns: [
        { key: 0, label: `年第周`, visible: true },
        { key: 1, label: `周一日期`, visible: true },
        { key: 2, label: `物料编码`, visible: true },
        { key: 3, label: `物料描述`, visible: true },
        { key: 4, label: `周一`, visible: true },
        { key: 5, label: `周二`, visible: true },
        { key: 6, label: `周三`, visible: true },
        { key: 7, label: `周四`, visible: true },
        { key: 8, label: `周五`, visible: true },
        { key: 9, label: `周六`, visible: true },
        { key: 10, label: `周日`, visible: true },
        { key: 11, label: `周合计`, visible: true },
      ]
    };
  },
  computed: {
    weekTotal() {
      return (this.form.reqMon || 0) + (this.form.reqTue || 0) + (this.form.reqWed || 0) +
             (this.form.reqThu || 0) + (this.form.reqFri || 0) + (this.form.reqSat || 0) +
             (this.form.reqSun || 0);
    },
    hasChanges() {
      return this.changedIds.size > 0;
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询子件物料周需求列表 */
    getList() {
      this.loading = true;
      this.changedIds = new Set();
      listReq(this.queryParams).then(response => {
        this.reqList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 标记行已修改 */
    markChanged(row) {
      // Vue 2 不支持 Set 的响应式，需要重新赋值触发更新
      const newSet = new Set(this.changedIds);
      newSet.add(row.id);
      this.changedIds = newSet;
    },
    /** 计算行合计 */
    calcRowTotal(row) {
      return (Number(row.reqMon) || 0) + (Number(row.reqTue) || 0) + (Number(row.reqWed) || 0) +
             (Number(row.reqThu) || 0) + (Number(row.reqFri) || 0) + (Number(row.reqSat) || 0) +
             (Number(row.reqSun) || 0);
    },
    /** 批量保存修改 */
    handleBatchSave() {
      const changedRows = this.reqList.filter(row => this.changedIds.has(row.id));
      if (changedRows.length === 0) {
        this.$modal.msgWarning("没有需要保存的修改");
        return;
      }
      this.$modal.confirm('是否确认保存 ' + changedRows.length + ' 条修改的数据？').then(() => {
        batchUpdateReq(changedRows).then(response => {
          this.$modal.msgSuccess(response.msg);
          this.changedIds = new Set();
          this.getList();
        });
      }).catch(() => {});
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        yearWeek: null,
        weekStartDate: null,
        itemCode: null,
        itemDesc: null,
        reqMon: 0,
        reqTue: 0,
        reqWed: 0,
        reqThu: 0,
        reqFri: 0,
        reqSat: 0,
        reqSun: 0
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.selectedRows = selection
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 打开批量填充对话框 */
    openBatchFillDialog() {
      if (this.selectedRows.length === 0) {
        this.$modal.msgWarning("请先选择要填充的行");
        return;
      }
      this.batchFill.columns = [];
      this.batchFill.value = 0;
      this.batchFillOpen = true;
    },
    /** 执行批量填充 */
    handleBatchFill() {
      if (this.batchFill.columns.length === 0) {
        this.$modal.msgWarning("请选择要填充的列");
        return;
      }
      // 填充选中的行和列
      this.selectedRows.forEach(row => {
        this.batchFill.columns.forEach(col => {
          row[col] = this.batchFill.value;
        });
        this.markChanged(row);
      });
      this.batchFillOpen = false;
      this.$modal.msgSuccess(`已填充 ${this.selectedRows.length} 行数据`);
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加子件物料周需求";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getReq(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改子件物料周需求";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateReq(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addReq(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除子件物料周需求编号为"' + ids + '"的数据项？').then(function() {
        return delReq(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 打开导出对话框 */
    openExportDialog() {
      this.exportParams.startDate = null;
      this.exportParams.endDate = null;
      this.exportOpen = true;
    },
    /** 导出按钮操作 */
    handleExport() {
      if (!this.exportParams.startDate || !this.exportParams.endDate) {
        this.$modal.msgWarning("请选择导出的时间范围");
        return;
      }
      if (this.exportParams.startDate > this.exportParams.endDate) {
        this.$modal.msgWarning("开始日期不能大于结束日期");
        return;
      }
      this.exportOpen = false;
      this.download('production/req/export', {
        ...this.queryParams,
        'params[beginWeekStartDate]': this.exportParams.startDate,
        'params[endWeekStartDate]': this.exportParams.endDate
      }, `子件物料周需求_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('production/req/importTemplate', {}, `子件物料周需求模板_${new Date().getTime()}.xlsx`)
    },
    /** 文件上传中处理 */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    /** 文件上传成功处理 */
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    /** 提交上传文件 */
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>

<style scoped>
.changed-cell ::v-deep .el-input__inner {
  background-color: #fffbe6 !important;
  border-color: #faad14 !important;
}
</style>
