<template>
  <div class="app-container">
    <el-row :gutter="8">
      <el-col :span="16">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
          label-width="68px">
          <el-form-item label="排产日期" prop="planDate">
            <el-date-picker clearable v-model="queryParams.planDate" type="date" value-format="yyyy-MM-dd"
              placeholder="请选择排产日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="产线名称" prop="lineName">
            <el-input v-model="queryParams.lineName" placeholder="请输入产线名称" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="排产单号" prop="planCode">
            <el-input v-model="queryParams.planCode" placeholder="请输入排产单号" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="排产人" prop="scheduler">
            <el-input v-model="queryParams.scheduler" placeholder="请输入排产人" clearable
              @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-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="planSheetList" height="600px" @row-click="handleRowClick">
          <el-table-column label="排产日期" align="center" prop="planDate" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.planDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="产线ID" align="center" prop="lineId" /> -->
          <el-table-column label="产线名称" align="center" prop="lineName" />
          <el-table-column label="排产单号" align="center" prop="planCode" />
          <!-- <el-table-column label="排产类型" align="center" prop="planType" /> -->
          <el-table-column label="排产人" align="center" prop="scheduler" />
          <el-table-column label="备注" align="center" prop="remark" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <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>
        </el-table>

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

        <PlanDetail v-if="currentPlanSheetId" ref="planDetail" :planSheetId="currentPlanSheetId"
          @change="handlePlanDetailChange" />
        <el-empty v-else class="appempty" description="选择排产单查看详情" />

        <!-- 添加或修改排产单对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="排产日期" prop="planDate">
              <el-date-picker clearable v-model="form.planDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择排产日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="产线名称" prop="lineName">
              <el-select v-model="form.lineName" placeholder="请选择产线名称" filterable clearable>
                <el-option v-for="item in dict.type.sys_lines" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="排产单号" prop="planCode">
              <el-input v-model="form.planCode" placeholder="请输入排产单号" />
            </el-form-item>
            <el-form-item label="排产人" prop="scheduler">
              <el-input v-model="form.scheduler" placeholder="请输入排产人" />
            </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>
      </el-col>

      <el-col :span="8">
        <div class="detail-form-container">
          <div v-if="currentPlanDetail.planDetailId" class="detail-card">
            <div class="card-header">
              <span>排产明细信息</span>
              <el-button type="primary" size="mini" @click="submitDetail">保存变更</el-button>
            </div>
            <div class="card-body">
              <PlanDetailForm v-model="currentPlanDetail" :plan-sheet-id="currentPlanSheetId" />
            </div>
          </div>
          <el-empty v-else description="选择排产单和明细行查看详情" />
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { listPlanSheet, getPlanSheet, delPlanSheet, addPlanSheet, updatePlanSheet } from "@/api/aps/planSheet";
import { updatePlanDetail } from "@/api/aps/planDetail";
import PlanDetail from "@/views/aps/planSheet/detail.vue";
import PlanDetailForm from "@/views/aps/planSheet/PlanDetailForm.vue";

export default {
  name: "PlanSheet",
  dicts: ['sys_lines'],
  components: {
    PlanDetail,
    PlanDetailForm
  },
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 当前选中的排产单ID
      currentPlanSheetId: undefined,
      // 当前选中的明细数据
      currentPlanDetail: {},
      // 排产单表格数据
      planSheetList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planDate: undefined,
        lineId: undefined,
        lineName: undefined,
        planCode: undefined,
        planType: undefined,
        scheduler: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        planSheetId: [
          { required: true, message: "排产单键ID不能为空", trigger: "blur" }
        ],
        planDate: [
          { required: true, message: "排产日期不能为空", trigger: "blur" }
        ],
        lineId: [
          { required: true, message: "产线ID不能为空", trigger: "blur" }
        ],
        lineName: [
          { required: true, message: "产线名称不能为空", trigger: "blur" }
        ],
        planCode: [
          { required: true, message: "排产单号不能为空", trigger: "blur" }
        ],
        planType: [
          { required: true, message: "排产类型不能为空", trigger: "change" }
        ],
        scheduler: [
          { required: true, message: "排产人不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询排产单列表 */
    getList() {
      this.loading = true;
      listPlanSheet(this.queryParams).then(response => {
        this.planSheetList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 点击排产单行，显示详情
    handleRowClick(row) {
      this.currentPlanSheetId = row.planSheetId;
      this.currentPlanDetail = {};
      this.$refs.planDetail.getList();
    },
    // 处理排产明细行点击事件
    handlePlanDetailChange(row) {
      this.currentPlanDetail = row;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 提交排产明细变更
    submitDetail() {
      updatePlanDetail(this.currentPlanDetail).then(response => {
        this.$message({
          message: "变更保存成功",
          type: "success"
        });
        this.handleQuery();
      });
    },
    // 表单重置
    reset() {
      // 日期默认选中今天 yyyy-MM-dd格式，北京时间
      // planCode与日期格式一致，添加-HHmmss
      // 排产人默认当前登录用户 this.$store.getters.nickName
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');

      const dateStr = `${year}-${month}-${day}`;
      const timeStr = `${hours}${minutes}${seconds}`;

      this.form = {
        planSheetId: undefined,
        planDate: dateStr,
        lineId: undefined,
        lineName: undefined,
        planCode: `${dateStr}-${timeStr}`,
        planType: undefined,
        scheduler: this.$store.getters.nickName || undefined,
        remark: undefined,
        delFlag: undefined,
        createBy: undefined,
        updateBy: undefined,
        createTime: undefined,
        updateTime: 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.planSheetId)
      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 planSheetId = row.planSheetId || this.ids
      getPlanSheet(planSheetId).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.planSheetId != null) {
            updatePlanSheet(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addPlanSheet(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const planSheetIds = row.planSheetId || this.ids;
      this.$modal.confirm('是否确认删除排产单编号为"' + planSheetIds + '"的数据项？').then(() => {
        this.loading = true;
        return delPlanSheet(planSheetIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('aps/planSheet/export', {
        ...this.queryParams
      }, `planSheet_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.detail-form-container {
  height: 100%;
  padding: 8px;
}

.detail-card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  padding: 12px 16px;
  border-bottom: 1px solid #ebeef5;
  background-color: #fafafa;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-body {
  padding: 16px;
  flex: 1;
  overflow-y: auto;
}

.appempty {
  margin-top: 20px;
}
</style>
