<template>
  <el-row style="margin: 20px;">
    <el-col :span="12">
      <div style="max-height:60vh;overflow:auto;padding-right:8px;">
        <el-form :model="detailForm" :rules="detailRules" ref="detailForm" label-width="80px" style="overflow:visible;">
          <el-form-item label="产线" prop="lineId">
            <el-select v-model="detailForm.lineId" placeholder="请选择产线" filterable @change="onLineChange">
              <el-option v-for="item in productionLineList" :key="item.lineId" :label="item.lineName"
                :value="item.lineId" />
            </el-select>
          </el-form-item>
          <el-form-item label="批次" prop="batchId">
            <!-- <el-select v-model="detailForm.productId" placeholder="请选择产品" filterable>
              <el-option v-for="item in productList" :key="item.productId" :label="item.productName"
                :value="item.productId" />
            </el-select> -->
            <el-select v-model="detailForm.batchId" placeholder="请选择批次" filterable @change="onBatchChange">
              <el-option v-for="item in batchList" :key="item.batchId" :label="item.batchNo" :value="item.batchId" />
            </el-select>
          </el-form-item>
          <el-form-item label="排产数量" prop="quantity">
            <el-input-number v-model="detailForm.quantity" disabled :min="0.01" :step="0.01" style="width:100%" />
          </el-form-item>
          <el-form-item label="计划日期" prop="dateRange">
            <el-date-picker v-model="detailForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" style="width:100%" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="detailForm.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-form>
      </div>
      <el-button type="primary" @click="submitDetailForm">提交排产</el-button>
    </el-col>
    <el-col :span="12">
      <div style="margin: 12px 0; max-width:100%; min-width:600px; height:220px; overflow-x:auto; overflow-y:hidden;">
        <GanttChartEcharts v-if="lineGanttTasks.length > 0 || previewTask"
          :tasks="previewTask ? [...lineGanttTasks, previewTask] : lineGanttTasks"
          style="height:220px; min-width:600px;" />
        <el-empty v-else description="请选择产线以查看排产情况" />
      </div>
    </el-col>
  </el-row>
</template>

<script>
import { listProductionLine } from '@/api/wms/productionLine';
import { ganttProductionLine } from '@/api/wms/productionLine';
import { addSchedulePlanDetail, updateSchedulePlanDetail } from '@/api/wms/schedulePlanDetail';
import { listBatch } from '@/api/wms/batch';

import GanttChartEcharts from '../productionLine/GanttChartEcharts.vue';

export default {
  components: {
    GanttChartEcharts
  },
  data() {
    return {
      detailForm: {
        detailId: undefined,
        planId: undefined,
        lineId: undefined,
        // productId: undefined,
        batchId: undefined,
        quantity: 0,
        dateRange: [],
        startDate: '',
        endDate: '',
        remark: ''
      },
      detailRules: {
        productId: [{ required: true, message: '请选择产品', trigger: 'change' }],
        lineId: [{ required: true, message: '请选择产线', trigger: 'change' }],
        quantity: [{ required: true, message: '请输入排产数量', trigger: 'blur' }],
        dateRange: [{ required: true, type: 'array', len: 2, message: '请选择计划日期区间', trigger: 'change' }]
      },
      lineGanttTasks: [],
      productionLineList: [],
      previewTask: null,
    }
  },
  created() {
    this.fetchBatchList();
    this.fetchProductionLineList();
  },
  methods: {
    fetchProductionLineList() {
      listProductionLine({ pageNum: 1, pageSize: 1000 }).then(res => {
        this.productionLineList = res.rows || [];
      });
    },
    onLineChange(lineId) {
      if (!lineId) {
        this.lineGanttTasks = [];
        return;
      }
      ganttProductionLine({ lineId }).then(res => {
        this.lineGanttTasks = res.data.tasks || [];
        this.updatePreviewTask();
      });
    },
    onBatchChange(batchId) {
      if (batchId) {
        // 从batchList中查找
        const batch = this.batchList.find(item => item.batchId == batchId);
        console.log(batch);
        if (batch) {
          this.detailForm.quantity = batch.totalQuantity;
          this.detailForm.dateRange = [
            batch.estimatedStartTime,
            batch.estimatedEndTime
          ];
        }
      }
    },
    fetchBatchList() {
      listBatch({ pageNum: 1, pageSize: 1000 }).then(res => {
        this.batchList = res.rows || [];
      });
    },
    submitDetailForm() {
      this.$refs.detailForm.validate(valid => {
        if (!valid) return;
        if (this.detailForm.dateRange && this.detailForm.dateRange.length === 2) {
          this.detailForm.startDate = this.detailForm.dateRange[0].replace(' ', "T") + '.000Z';
          this.detailForm.endDate = this.detailForm.dateRange[1].replace(' ', "T") + '.000Z';
        } else {
          this.detailForm.startDate = '';
          this.detailForm.endDate = '';
        }
        const api = this.detailForm.detailId ? updateSchedulePlanDetail : addSchedulePlanDetail;
        const data = Object.assign({}, this.detailForm, { planId: this.planId });
        api(data).then(() => {
          this.$message.success(this.detailForm.detailId ? '修改成功' : '新增成功');
          this.detailDialogVisible = false;
          this.fetchDetailList();
        });
      });
    }
  }
}
</script>