<template>
  <div class="app-container">
    <el-card>
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="88px"
      >
        <el-form-item label="生产类型" prop="productionType">
          <el-select
            v-model="queryParams.productionType"
            placeholder="请选择生产类型"
            clearable
            filterable
          >
            <el-option
              v-for="item in dict.type.inventory_production_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="生产车间" prop="productionWorkshop">
          <el-select
            v-model="queryParams.productionWorkshop"
            placeholder="请选择生产车间"
            clearable
            filterable
          >
            <el-option
              v-for="item in productionPlantList"
              :key="item.productionPlantNo"
              :label="item.productionPlantName"
              :value="item.productionPlantNo"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="生产日期" prop="productionDateRange">
          <el-date-picker
            v-model="queryParams.productionDateRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </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-row>
    </el-card>
    <br />
    <el-card>
      <el-table
        border
        stripe
        v-loading="loading"
        :data="list"
      >
        <el-table-column label="生产完工报告号" align="center" prop="reportNumber" min-width="180" />
        <el-table-column label="生产类型" align="center" prop="productionType" min-width="120">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.inventory_production_type" :value="scope.row.productionType" />
          </template>
        </el-table-column>
        <el-table-column label="生产车间" align="center" prop="productionWorkshop" min-width="140">
          <template slot-scope="scope">
            <span>{{ getProductionWorkshopLabel(scope.row.productionWorkshop) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="生产车间完工日期" align="center" prop="completionDate" min-width="160" />
        <el-table-column label="单据状态" align="center" prop="documentStatus" min-width="120">
          <template slot-scope="scope">
            <el-tag v-if="String(scope.row.documentStatus) === '0'" type="info">草稿</el-tag>
            <el-tag v-else-if="String(scope.row.documentStatus) === '1'" type="warning">已提交</el-tag>
            <el-tag v-else-if="String(scope.row.documentStatus) === '2'" type="success">已完工</el-tag>
            <el-tag v-else type="default">{{ getDocumentStatusLabel(scope.row.documentStatus) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="详细" align="center" min-width="120">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="180" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看详情</el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" style="margin-right: 8px">编辑</el-button>
            <el-popconfirm :title="'确定要删除这条数据吗？'" @confirm="handleDelete(scope.row)">
              <el-button size="mini" type="text" slot="reference" icon="el-icon-delete">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

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


    <!-- 新增/编辑弹框 -->
    <el-dialog :title="title" :visible.sync="open" fullscreen append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="生产完工报告号" prop="reportNumber">
              <el-input v-model="form.reportNumber" placeholder="请输入生产完工报告号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生产类型" prop="productionType">
              <el-select v-model="form.productionType" placeholder="请选择生产类型" clearable filterable style="width: 100%;">
                <el-option
                  v-for="item in dict.type.inventory_production_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生产车间" prop="productionWorkshop">
              <el-select v-model="form.productionWorkshop" placeholder="请选择生产车间" clearable filterable style="width: 100%;">
                <el-option
                  v-for="item in productionPlantList"
                  :key="item.productionPlantNo"
                  :label="item.productionPlantName"
                  :value="item.productionPlantNo"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="生产车间完工日期" prop="completionDate">
              <el-date-picker
                v-model="form.completionDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择完工日期"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单据状态" prop="documentStatus">
              <el-select v-model="form.documentStatus" placeholder="请选择单据状态" clearable style="width: 100%;">
                <el-option label="草稿" value="0" />
                <el-option label="已提交" value="1" />
                <el-option label="已完工" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-divider content-position="left">明细</el-divider>
          <el-form-item label-width="0" prop="goods">
            <el-table :data="form.goods" style="width: 100%;" border stripe>
              <el-table-column label="生产计划单号" prop="productionPlanNumber" min-width="220" fixed>
                <template slot-scope="{ row, $index }">
                  <el-form-item
                    :prop="`goods.${$index}.productionPlanNumber`"
                    :rules="tableRules.productionPlanNumber"
                    class="table-form-item"
                  >
                    <el-input v-model="row.productionPlanNumber" placeholder="请输入生产计划单号" @change="handleGoodsEdit($index, 'productionPlanNumber', row.productionPlanNumber)">
                      <template #append>
                        <el-tooltip class="item" effect="dark" content="查询" placement="top">
                          <el-button type="success" icon="el-icon-search" circle size="mini" @click="openPlanQuery($index)"></el-button>
                        </el-tooltip>
                      </template>
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column label="物料编码" prop="materialCode" min-width="140">
                <template slot-scope="{ row, $index }">
                  <el-input v-model="row.materialCode" placeholder="物料编码" @change="handleGoodsEdit($index, 'materialCode', row.materialCode)" />
                </template>
              </el-table-column>
              <el-table-column label="物料名称" prop="materialName" min-width="180">
                <template slot-scope="{ row, $index }">
                  <el-input v-model="row.materialName" placeholder="物料名称" @change="handleGoodsEdit($index, 'materialName', row.materialName)" />
                </template>
              </el-table-column>
              <el-table-column label="规格型号" prop="specificationModel" min-width="160">
                <template slot-scope="{ row, $index }">
                  <el-input v-model="row.specificationModel" placeholder="规格型号" @change="handleGoodsEdit($index, 'specificationModel', row.specificationModel)" />
                </template>
              </el-table-column>
              <el-table-column label="品种种类" prop="varietyCategory" min-width="120">
                <template slot-scope="{ row, $index }">
                  <el-input v-model="row.varietyCategory" placeholder="品种种类" @change="handleGoodsEdit($index, 'varietyCategory', row.varietyCategory)" />
                </template>
              </el-table-column>
              <el-table-column label="品类级别" prop="categoryGrade" min-width="120">
                <template slot-scope="{ row, $index }">
                  <el-input v-model="row.categoryGrade" placeholder="品类级别" @change="handleGoodsEdit($index, 'categoryGrade', row.categoryGrade)" />
                </template>
              </el-table-column>
              <el-table-column label="批次" prop="batchNumber" min-width="160">
                <template slot-scope="{ row, $index }">
                  <el-input v-model="row.batchNumber" placeholder="批次" @change="handleGoodsEdit($index, 'batchNumber', row.batchNumber)" />
                </template>
              </el-table-column>

              <el-table-column label="数量" prop="quantity" min-width="110">
                <template slot-scope="{ row, $index }">
                  <decimal-input v-model="row.quantity" :precision="2" placeholder="数量" @blur="handleGoodsEdit($index, 'quantity', row.quantity)" />
                </template>
              </el-table-column>
              <el-table-column label="计量单位" prop="measurementUnit" min-width="110">
                <template slot-scope="{ row, $index }">
                  <el-input v-model="row.measurementUnit" placeholder="计量单位" @change="handleGoodsEdit($index, 'measurementUnit', row.measurementUnit)" />
                </template>
              </el-table-column>
              <el-table-column label="辅助数量" prop="auxiliaryQuantity" min-width="120">
                <template slot-scope="{ row, $index }">
                  <decimal-input v-model="row.auxiliaryQuantity" :precision="2" placeholder="辅助数量" @blur="handleGoodsEdit($index, 'auxiliaryQuantity', row.auxiliaryQuantity)" />
                </template>
              </el-table-column>
              <el-table-column label="辅助计量单位" prop="auxiliaryMeasurementUnit" min-width="160">
                <template slot-scope="{ row, $index }">
                  <el-input v-model="row.auxiliaryMeasurementUnit" placeholder="辅助计量单位" @change="handleGoodsEdit($index, 'auxiliaryMeasurementUnit', row.auxiliaryMeasurementUnit)" />
                </template>
              </el-table-column>

              <el-table-column label="合格数量" prop="qualifiedQuantity" min-width="120">
                <template slot-scope="{ row, $index }">
                  <decimal-input v-model="row.qualifiedQuantity" :precision="2" placeholder="合格数量" @blur="handleGoodsEdit($index, 'qualifiedQuantity', row.qualifiedQuantity)" />
                </template>
              </el-table-column>
              <el-table-column label="不合格数量" prop="unqualifiedQuantity" min-width="130">
                <template slot-scope="{ row, $index }">
                  <decimal-input v-model="row.unqualifiedQuantity" :precision="2" placeholder="不合格数量" @blur="handleGoodsEdit($index, 'unqualifiedQuantity', row.unqualifiedQuantity)" />
                </template>
              </el-table-column>
              <el-table-column label="仓库" prop="warehouse" min-width="160">
                <template slot-scope="{ row, $index }">
                  <el-input v-model="row.warehouse" placeholder="仓库" @change="handleGoodsEdit($index, 'warehouse', row.warehouse)" />
                </template>
              </el-table-column>
              <el-table-column label="入库数量" prop="warehousingQuantity" min-width="120">
                <template slot-scope="{ row, $index }">
                  <decimal-input v-model="row.warehousingQuantity" :precision="2" placeholder="入库数量" @blur="handleGoodsEdit($index, 'warehousingQuantity', row.warehousingQuantity)" />
                </template>
              </el-table-column>
              <el-table-column label="入库辅助数量" prop="warehousingAuxiliaryQuantity" min-width="170">
                <template slot-scope="{ row, $index }">
                  <decimal-input v-model="row.warehousingAuxiliaryQuantity" :precision="2" placeholder="入库辅助数量" @blur="handleGoodsEdit($index, 'warehousingAuxiliaryQuantity', row.warehousingAuxiliaryQuantity)" />
                </template>
              </el-table-column>

              <el-table-column label="操作" width="80" align="center" fixed="right">
                <template slot-scope="{ $index }">
                  <el-button type="text" icon="el-icon-delete" @click="handleDeleteGoodsRow($index)" />
                </template>
              </el-table-column>
            </el-table>

            <div style="margin-top: 10px; text-align: center;">
              <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAddGoodsRow">添加</el-button>
            </div>
          </el-form-item>
        </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>

    <unfinished-data-query-dialog
      ref="unfinishedDialog"
      :production-plant-list="productionPlantList"
      :production-type-default="form.productionType"
      :production-workshop-default="form.productionWorkshop"
      @selectList="getSelectList"
    />
  </div>
</template>

<script>
import DecimalInput from "@/views/components/DecimalInput.vue";
import UnfinishedDataQueryDialog from "@/views/components/UnfinishedDataQueryDialog.vue";
import { getProductionPlantList } from "../../../api/production/productionPlant";
import { getProductionCompletePage, getProductionCompleteById, addProductionComplete, editProductionComplete, deleteProductionComplete } from "../../../api/production/complete";
export default {
  name: "ProductionComplete",
  dicts: ["inventory_production_type"],
  components: { DecimalInput, UnfinishedDataQueryDialog },
  data() {
    return {
      showSearch: true,
      loading: false,
      total: 0,
      list: [],
      queryOpen: false,
      open: false,
      title: "",
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productionType: null,
        productionWorkshop: null,
        productionDateRange: [],
        startDate: null,
        endDate: null,
      },
      // 生产车间（与 production/plan/index.vue 保持一致的写法）
      productionPlantList: [],
      queryDialogForm: {
        reportNumber: null,
        productionType: null,
        productionWorkshop: null,
        completionDate: null,
        documentStatus: null,
      },
      form: {
        id: null,
        reportNumber: null,
        productionType: null,
        productionWorkshop: null,
        completionDate: null,
        documentStatus: null,
        goods: [
          {
            productionPlanNumber: null,
            materialCode: null,
            materialName: null,
            specificationModel: null,
            varietyCategory: null,
            categoryGrade: null,
            batchNumber: null,
            quantity: null,
            measurementUnit: null,
            auxiliaryQuantity: null,
            auxiliaryMeasurementUnit: null,
            qualifiedQuantity: null,
            unqualifiedQuantity: null,
            warehouse: null,
            warehousingQuantity: null,
            warehousingAuxiliaryQuantity: null,
          },
        ],
      },
      rules: {
        reportNumber: [{ required: true, message: "请输入生产完工报告号", trigger: "blur" }],
        productionType: [{ required: true, message: "请选择生产类型", trigger: "change" }],
        productionWorkshop: [{ required: true, message: "请选择生产车间", trigger: "change" }],
        completionDate: [{ required: true, message: "请选择生产车间完工日期", trigger: "change" }],
        documentStatus: [{ required: true, message: "请选择单据状态", trigger: "change" }],
      },
      tableRules: {
        productionPlanNumber: [{ required: true, message: "生产计划单号不能为空", trigger: "blur" }],
      },
      goodsIndex: null,
  
    };
  },
  watch: {
    "queryParams.productionDateRange": {
      handler(newVal) {
        console.log(newVal)
        if (newVal && newVal.length === 2) {
          this.queryParams.startDate = newVal[0];
          this.queryParams.endDate = newVal[1];
        } else {
          this.queryParams.startDate = null;
          this.queryParams.endDate = null;
        }
        console.log(this.queryParams)
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    // 页面初始化时加载生产车间下拉数据
    this.getProductionPlant();
    const range = [this.getTomorrowDate(), this.getTomorrowDate()];
    // 同步把起止日期写入，避免 watch 尚未执行导致 startDate/endDate 仍为空
    this.queryParams.productionDateRange = range;
    this.queryParams.startDate = range[0];
    this.queryParams.endDate = range[1];
    this.handleQuery();
  },
  methods: {
    /** 生产车间 value -> label（用于列表展示） */
    getProductionWorkshopLabel(val) {
      const key = val == null ? "" : String(val);
      const hit = (this.productionPlantList || []).find(x => x && String(x.productionPlantNo) === key);
      return hit ? hit.productionPlantName : (val ?? "-");
    },
    /** 单据状态 value -> label（用于列表展示） */
    getDocumentStatusLabel(val) {
      const v = String(val);
      if (v === "0") return "草稿";
      if (v === "1") return "已提交";
      if (v === "2") return "已完工";
      return val ?? "-";
    },
    /** 获取明天日期（yyyy-MM-dd） */
    getTomorrowDate() {
      const date = new Date();
      date.setDate(date.getDate() + 1);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    /** 生产车间下拉数据：从接口拉取 */
    getProductionPlant() {
      getProductionPlantList({})
        .then((res) => {
          const data = res && res.data ? res.data : res;
          this.productionPlantList = Array.isArray(data) ? data : [];
        })
        .catch(() => {
          this.productionPlantList = [];
        });
    },
    getList() {
      getProductionCompletePage(this.queryParams).then(res => {
        this.list = res.data.records;
        this.total = res.data.total;
        this.loading = false;
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        productionType: null,
        productionWorkshop: null,
        productionDateRange: null,
        startDate: null,
        endDate: null,
      };
      this.handleQuery();
    },
    handleView(row) {
      let parmas = {
        id: row.id
      }
          getProductionCompleteById(parmas).then(res => {
            this.form = res.data;
            this.open = true;
            this.isView = true;
            this.title = "查看";
          })
          .catch(() => {
            this.$modal.msgError("查看失败");
          })
    },
    handleUpdate(row) {
      this.handleUpdateDialog(row);
    },
    handleDelete(row) {
      let parmas = {
        ids: row.id
      }
      deleteProductionComplete(parmas).then(res => {
        this.$modal.msgSuccess("删除成功");
        this.getList();
      }).catch(() => {
        this.$modal.msgError("删除失败");
      })
    },
    handleAdd() {
      this.handleAddDialog();
    },
    openQueryDialog() {
      this.queryOpen = true;
    },
    cancelQueryDialog() {
      this.queryOpen = false;
    },
    confirmQueryDialog() {
      // TODO: 这里可以把弹框表单值合并到 queryParams 再请求
      // Object.assign(this.queryParams, this.queryDialogForm)
      this.queryOpen = false;
      this.getList();
    },
    reset() {
      this.form = {
        id: null,
        reportNumber: null,
        productionType: null,
        productionWorkshop: null,
        completionDate: null,
        documentStatus: null,
        goods: [
          {
            productionPlanNumber: null,
            materialCode: null,
            materialName: null,
            specificationModel: null,
            varietyCategory: null,
            categoryGrade: null,
            batchNumber: null,
            quantity: null,
            measurementUnit: null,
            auxiliaryQuantity: null,
            auxiliaryMeasurementUnit: null,
            qualifiedQuantity: null,
            unqualifiedQuantity: null,
            warehouse: null,
            warehousingQuantity: null,
            warehousingAuxiliaryQuantity: null,
          },
        ],
      };
      this.$nextTick(() => {
        if (this.$refs.form) this.$refs.form.clearValidate();
      });
    },
    handleAddDialog() {
      this.reset();
      this.title = "新增";
      this.open = true;
    },
    handleUpdateDialog(row) {
      this.reset();
      if (row) {
        this.title = "编辑";
        getProductionCompleteById(row.id).then(res => {
          this.form = res.data;
          this.open = true; 
          this.isView = false;
        }).catch(() => {
          this.$modal.msgError("编辑失败");
        })
      } else {
        this.handleAddDialog();
      }
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (!valid) return;
        // TODO: 接口：新增/编辑
        if (this.form.id) { 
          editProductionComplete(this.form).then(res => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
            }).catch(() => {
              this.$modal.msgError("修改失败");
            }) } else {
             addProductionComplete(this.form).then(res => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;    
              this.getList();
            }).catch(() => {
              this.$modal.msgError("新增失败"); 
            }) }
      });
    },
    handleAddGoodsRow() {
      this.form.goods.push({
        productionPlanNumber: null,
        materialCode: null,
        materialName: null,
        specificationModel: null,
        varietyCategory: null,
        categoryGrade: null,
        batchNumber: null,
        quantity: null,
        measurementUnit: null,
        auxiliaryQuantity: null,
        auxiliaryMeasurementUnit: null,
        qualifiedQuantity: null,
        unqualifiedQuantity: null,
        warehouse: null,
        warehousingQuantity: null,
        warehousingAuxiliaryQuantity: null,
      });
    },
    handleDeleteGoodsRow(index) {
      this.form.goods.splice(index, 1);
      if (this.form.goods.length === 0) {
        this.handleAddGoodsRow();
      }
    },
    handleGoodsEdit(index, field, value) {
      if (this.$refs.form) {
        this.$refs.form.validateField(`goods.${index}.${field}`);
      }
    },
    openPlanQuery(index) {
      this.goodsIndex = index;
      this.$refs.unfinishedDialog.openDialog();
    },
    getSelectList(list) {
      if (!list || list.length === 0) return;
      const mapRow = (x) => ({
        productionPlanNumber: x.productionPlanNumber ?? x.planNum ?? null,
        materialCode: x.goodsNum ?? null,
        materialName: x.materialName ?? null,
        specificationModel: x.specificationModel ?? x.specModel ?? null,
        varietyCategory: x.varietyCategory ?? null,
        categoryGrade: x.categoryGrade ?? x.categoryLevel ?? null,
        batchNumber: x.batchNumber ?? x.batch ?? null,
        quantity: x.quantity ?? x.qty ?? null,
        measurementUnit: x.measurementUnit ?? x.unit ?? null,
        auxiliaryQuantity: x.auxiliaryQuantity ?? x.auxQty ?? null,
        auxiliaryMeasurementUnit: x.auxiliaryMeasurementUnit ?? x.auxUnit ?? null,
        qualifiedQuantity: x.qualifiedQuantity ?? x.qualifiedQty ?? null,
        unqualifiedQuantity: x.unqualifiedQuantity ?? x.unqualifiedQty ?? null,
        warehouse: x.warehouse ?? null,
        warehousingQuantity: x.warehousingQuantity ?? x.inQty ?? null,
        warehousingAuxiliaryQuantity: x.warehousingAuxiliaryQuantity ?? x.inAuxQty ?? null,
      });

      this.form.goods.splice(this.goodsIndex, 1, mapRow(list[0]));
      for (let i = 1; i < list.length; i++) {
        this.form.goods.push(mapRow(list[i]));
      }
    },
  },
};
</script>

<style scoped lang="scss">
.table-form-item {
  margin-bottom: 0;
}

.table-form-item ::v-deep .el-form-item__content {
  margin-left: 0 !important;
  line-height: normal;
}

.el-table .el-input,
.el-table .el-input-number {
  width: 100%;
}
</style>
