<template>
  <div>
    <el-card>
      <div>
        <el-menu mode="horizontal" :default-active="activeIndex" router>
          <!-- <el-menu-item index="/QualityManagement/CheckTask/firstSpecial"
            >首检专检</el-menu-item
          >
          <el-menu-item index="/QualityManagement/CheckTask/processSpecial"
            >序检专检</el-menu-item
          > -->
          <el-menu-item index="/QualityManagement/CheckTask/final"
            >终检</el-menu-item
          >
          <el-menu-item index="/QualityManagement/CheckTask/purchaseIncoming"
            >采购入库检</el-menu-item
          >
          <el-menu-item index="/QualityManagement/CheckTask/salesReturn"
            >销售退货检</el-menu-item
          >
          <el-menu-item index="/QualityManagement/CheckTask/materialReturn"
            >原材料退库检</el-menu-item
          >
          <el-menu-item index="/QualityManagement/CheckTask/OtherInbound"
            >其他入库检</el-menu-item
          >
          <el-menu-item index="/QualityManagement/CheckTask/processReceive"
            >序检收检</el-menu-item
          >
        </el-menu>
      </div>
    </el-card>
    <el-card>
      <div class="search-container">
        <span class="show-text">生产订单:</span>
        <el-input
          v-model="orderNo"
          placeholder="请输入生产订单"
          clearable
          style="width: 150px; margin-right: 10px"
        />
        <span class="show-text">物料名称:</span>
        <el-input
          v-model="partName"
          placeholder="请输入物料名称"
          clearable
          style="width: 150px; margin-right: 10px"
        />
        <span class="show-text">物料编码:</span>
        <el-input
          v-model="partNo"
          placeholder="请输入物料编号"
          clearable
          style="width: 150px; margin-right: 10px"
        />
        <span class="show-text">检测日期:</span>
        <el-date-picker
          v-model="inspectionDate"
          :clearable="false"
          end-placeholder="结束时间"
          format="yyyy-MM-dd"
          range-separator="-"
          start-placeholder="开始时间"
          style="width: 280px; vertical-align: top"
          type="datetimerange"
          value-format="yyyy-MM-dd"
        />
        <!--  <span class="show-text">计划完工日期:</span>
        <el-date-picker
          v-model="completionTime"
          :clearable="false"
          end-placeholder="结束时间"
          format="yyyy-MM-dd"
          range-separator="-"
          start-placeholder="开始时间"
          style="width: 280px; vertical-align: top"
          type="datetimerange"
          value-format="yyyy-MM-dd"
        /> -->

        <br />
        <br />

        <span class="show-text">检测结果</span>
        <el-select
          v-model="inspectionResult"
          clearable
          style="width: 150px; margin-right: 10px"
          filterable
        >
          <el-option label="合格" value="1" />
          <el-option label="不合格" value="0" />
        </el-select>
        <span class="show-text">检测人:</span>
        <el-select
          v-model="checker"
          placeholder="请选择检测人"
          clearable
          style="width: 150px; margin-right: 10px"
          filterable
        >
          <el-option
            v-for="item in checkerList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <!--  <span class="show-text">检测类别:</span>
        <el-select
          v-model="type"
          placeholder="请选择检测类别"
          clearable
          style="width: 150px; margin-right: 10px"
          filterable
        >
          <el-option
            v-for="item in typeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select> -->
        <el-button
          :disabled="loading"
          icon="el-icon-search"
          plain
          type="primary"
          @click="searchTable()"
          >查询
        </el-button>
        <!-- <el-button
          type="success"
          icon="el-icon-download"
          plain
          :disabled="tableData.length === 0"
          @click="exportToExcel"
          >导出</el-button
        > -->
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        :height="'67vh'"
        border
        element-loading-background="rgba(0, 0, 0, 0.2)"
        element-loading-spinner="el-icon-loading"
        highlight-current-row
        size="mini"
        style="width: 100%; margin-top: 20px"
        tooltip-effect="dark"
      >
        <el-table-column
          align="center"
          label="序号"
          type="index"
          width="50"
          fixed
        />
        
        <el-table-column
          align="center"
          label="生产订单"
          width="80"
          prop="订单编号"
        />
        <el-table-column
          align="center"
          label="物料名称"
          width="150"
          prop="物料名称"
        />
        <el-table-column
          align="center"
          label="物料编码"
          width="150"
          prop="物料编码"
        />
        
        <!-- <el-table-column
          align="center"
          label="采购数"
          width="80"
          prop="计划生产数"
        /> -->

        <el-table-column
          align="center"
          label="检验数量"
          width="80"
          prop="入库数量"
        />
        <el-table-column
          align="center"
          label="合格数"
          width="80"
          prop="合格数"
        />
        <el-table-column
          align="center"
          label="不合格数"
          width="80"
          prop="不合格数"
        />
        <el-table-column
          align="center"
          label="检验人"
          width="100"
          prop="检测人"
        />

        <el-table-column
          align="center"
          label="检验时间"
          width="150"
          prop="检验时间"
        />
        <el-table-column
          align="center"
          label="备注"
          width="150"
          prop="备注"
        />
        <el-table-column label="操作" align="center" width="250">
          <template slot-scope="scope">
            <el-button
              class="operation-btn"
              type="primary"
              size="mini"
              @click="receiveCheck(scope.row)"
              >退货检</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 收检对话框 -->
    <el-dialog
      title="退货检"
      :visible.sync="receiveCheckVisible"
      width="60%"
      style="text-align: center"
    >
      <el-form
        ref="receiveCheckForm"
        :model="receiveCheckData"
        label-position="right"
        label-width="140px"
        size="mini"
      >
        <div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">物料名称</span>
              <span class="info-value">{{ receiveCheckData.零件名称 }}</span>
            </div>
          
            <div class="info-item">
              <span class="info-label">物料编码</span>
              <span class="info-value">{{ receiveCheckData.零件编码 }}</span>
            </div>
            
          </div>
        </div>
        <div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">生产订单</span>
              <span class="info-value">{{ receiveCheckData.计划号 }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">采购数</span>
              <span class="info-value">{{ receiveCheckData.计划生产数 }}</span>
            </div>
          </div>
        </div>
        <div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label"> 送检数量</span>
              <span class="info-value">{{ receiveCheckData.检测数量 }}</span>
            </div>
            <div class="info-item">
              <span class="info-label"> 合格数</span>
              <span class="info-value">{{receiveCheckData.检测数量 - receiveCheckData.不合格数 }}</span>
            </div>
          </div>
        </div>
        <div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label"> 不合格数</span>
              <el-input-number
                v-model="receiveCheckData.不合格数"
                size="mini"
                :min="0"
                :max="receiveCheckData.检测数量"
                style="width: 200px"
                @change="handleQualifiedChange"
              />
              
            </div>
            <div class="info-item">
              <span class="info-label"> 检验人</span>
              <el-select
                v-model="receiveCheckData.检测人"
                placeholder="请选择检验人"
                clearable
                style="width: 200px"
                filterable
              >
                <el-option
                  v-for="item in checkerList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                />
              </el-select>
            </div>
          </div>
        </div>
        <div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label"> 检验时间</span>

              <el-date-picker
                v-model="receiveCheckData.检测时间"
                type="datetime"
                placeholder="选择检验时间"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 120px"
                class="info-value"
              />
            </div>
            <div class="info-item">
              <span class="info-label"> 检测说明</span>

              <el-input
                v-model="receiveCheckData.检测说明"
                type="textarea"
                :rows="2"
                placeholder="请输入检测说明"
                style="width: 120px"
                class="info-value"
              />
            </div>
          </div>
        </div>
      </el-form>

      <div slot="footer">
        <el-button type="primary" @click="confirmReceiveCheck">确 定</el-button>
        <el-button @click="receiveCheckVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入xlsx库
import * as XLSX from "xlsx";

export default {
  data() {
    return {
      contractNo: "",
      orderNo: "",
      partNo: "",
      partName: "",
      completionTime: "",
      inspectionDate: "",
      type: "",
      typeList: [],
      checker: "",
      checkerLabel: "",
      checkerList: [],
      inspectionResult: "",
      tableData: [],
      loading: false,
      selectedRow: null,
      receiveCheckVisible: false,
      receiveCheckData: {
        // 基本信息（从行数据获取）
        零件名称: "",
        内部合同号: "",
        零件编码: "",
        计划号: "",
        工序名称: "",
        计划完成时间: "",
        计划生产数: 0,
        TaskAID: "",

        // 收检数据（用户输入）
        检测数量: 0,
        合格数: 0,
        不合格数: 0,
        检测人: "",
        检测时间: "",
        检测说明: "",
      },
    };
  },
  created() {
    this.getTypeList();
    this.getCheckerList();
    this.searchTable();
    this.getCurrentTime();
    setInterval(this.getCurrentTime, 1000);
  },
  computed: {
    activeIndex() {
      return this.$route.path;
    },
  },
  methods: {
    getTypeList() {
      this.typeList = [];
      var Data = this.CreateData("11", "查询字典");
      this.ExecDatabase(Data).then((response) => {
        for (let i = 0; i < response.data.length; i++) {
          if (response.data[i].数据类别 === "检测类型") {
            this.typeList.push({
              label: response.data[i].词条名称,
              value: response.data[i].词条编号,
            });
          }
        }
      });
    },
    getCheckerList() {
      this.checkerList = [];
      var Data = this.CreateData("11", "人员管理_人员信息查询_质检部门_查询");
      this.ExecDatabase(Data).then((response) => {
        for (let i = 0; i < response.data.length; i++) {
          this.checkerList.push({
            label: response.data[i].Personnel_Name,
            value: response.data[i].Personnel_Number,
          });
        }
      });
    },

    searchTable() {
      // 开始加载状态，清空表格数据和选中行
      this.loading = true;
      this.tableData = [];

      // 构建基础查询参数
      var param = [];
      param.push(["订单号", this.orderNo]);
      param.push(["零件编号", this.partNo]);
      param.push(["零件名称", this.partName]);
      // 添加检测日期范围参数
      param.push([
        "检测日期_Start",
        this.inspectionDate ? this.inspectionDate[0] : "",
      ]);
      param.push([
        "检测日期_End",
        this.inspectionDate ? this.inspectionDate[1] : "",
      ]);
      param.push(["检测结果", this.inspectionResult]);
      const selectedChecker = this.checkerList.find(
        (item) => item.value === this.checker
      );
      param.push(["检测人", selectedChecker ? selectedChecker.label : ""]);

      // 调用封装方法生成请求数据 - 使用新的存储过程名称
      var Data = this.CreateData(
        "11",
        "质量管理_质量检验_退货质检任务_查询",
        param
      );

      // 执行数据库请求
      this.ExecDatabase(Data)
        .then((response) => {
          this.loading = false;
          console.log(response.data);
          if (response.data && response.data.length !== 0) {
            this.tableData = response.data;
          } else {
            this.tableData = [];
            this.$message.info("未查询到相关数据");
          }
        })
        .catch((error) => {
          this.loading = false;
          console.error("查询失败:", error);
          this.$message.error("查询失败");
        });
    },

    receiveCheck(row) {
      // 打开收检对话框并填充数据
      this.receiveCheckVisible = true;
      console.log(row)
      // 从行数据填充基本信息
      this.receiveCheckData = {
        // 基本信息（从行数据获取）
        零件名称: row.物料名称 || "",
        零件编码: row.物料编码 || "",
        计划号: row.订单编号 || "",
        行号: row.行号 || 0,
        订单类型: row.订单类型 || "",
        // 收检数据（用户输入）
        检测数量: row.入库数量 || 0,
        合格数: row.入库数量 || 0,
        不合格数: row.不合格数 || 0,
        检测人: row.检测人 || "",
        检测时间: this.formatDateTime(new Date()),
        检测说明: "",
      };
      console.log(this.receiveCheckData);
    },

    handleQualifiedChange(value) {
      // 自动计算不合格数
      this.receiveCheckData.合格数 = this.receiveCheckData.检测数量 - value;
    },

    confirmReceiveCheck() {
      // 验证表单
      if (
        !this.receiveCheckData.检测数量 ||
        this.receiveCheckData.检测数量 <= 0
      ) {
        this.$message.warning("请输入有效的检测数量");
        return;
      }

      if (!this.receiveCheckData.检测人) {
        this.$message.warning("请选择检验人");
        return;
      }

      if (!this.receiveCheckData.检测时间) {
        this.$message.warning("请选择检验时间");
        return;
      }
      if (!this.receiveCheckData.检测数量 == this.receiveCheckData.合格数 + this.receiveCheckData.不合格数) {
        this.$message.warning("合格数加不合格数必须等于检测数量");
        return;
      }
      // 调用存储过程保存数据
      this.saveReceiveCheck();
    },
    getCurrentTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0"); // 月份从0开始，需要加1
      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");
      this.currentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    saveReceiveCheck() {
      var param = [];
      param.push(["检测类型编号", 5]);
      param.push(["质检类型", "来料检验"]);
      param.push(["零件名称", this.receiveCheckData.零件名称]);
      param.push(["零件编码", this.receiveCheckData.零件编码]);
      param.push(["计划号", this.receiveCheckData.计划号]);
      param.push(["检测数量", this.receiveCheckData.检测数量]);
      param.push(["合格数", this.receiveCheckData.合格数]);
      param.push(["不合格数", this.receiveCheckData.不合格数]);
      param.push(["检测人", this.receiveCheckData.检测人]);
      param.push(["检测时间", this.receiveCheckData.检测时间]);
      param.push(["检测说明", this.receiveCheckData.检测说明]);
      param.push(["行号", this.receiveCheckData.行号]);
      param.push(["订单类型", this.receiveCheckData.订单类型]);
      console.log(param);
      var Data = this.CreateData("12", "质量管理_销售退货检_更新", param);

      this.ExecDatabase(Data)
        .then((response) => {
          if (
            response.data &&
            response.data[0] &&
            response.data[0].result === "1"
          ) {
            this.$message.success("销售退货操作成功");
            this.receiveCheckVisible = false;
            // 刷新表格数据
            this.searchTable();
            // this.submitMaterialRequisition();
          } else {
            this.$message.error("销售退货操作失败");
          }
        })
        .catch((error) => {
          console.error("销售退货操作失败:", error);
          this.$message.error("销售退货操作失败");
        });
    },
    async submitMaterialRequisition() {
          var params = []
          var param = []
          var param2 = [];
          param.push(["doc_date", this.formatDate(this.currentTime)]);
          param.push(["doc_type", "202-59"]);
          param.push(["external_num", this.receiveCheckData.计划号]);
          param.push(["task_items", param2]);
          param2.push(["base_type", "202"]);
          param2.push(["external_num", this.receiveCheckData.计划号])
          param2.push(["item_code", this.receiveCheckData.零件编码]);
          param2.push(["item_name", this.receiveCheckData.零件名称]);
          param2.push(["whs_code", ""]);
          param2.push(["manage_type", 'B']);
          param2.push(["price", 0]);
          param2.push(["quantity", this.receiveCheckData.合格数]);
          param2.push(["base_line_num",this.receiveCheckData.行号]);
          param2.push(["base_entry", this.receiveCheckData.计划号]);
          params.push(param)

        const result = this.transformData(params);
        // const jsonString = JSON.stringify(result, null, 2);
        // console.log(jsonString);
        const result2 = await posttm('/stocktask/task/issueordertask',result)
        console.log(result2)
    },
    transformData(rawArray) {
      console.log("原始数据:", rawArray);
      
      // 初始化结果对象
      const result = {
        doc_date: "",
        doc_type: "",
        external_num: 0,
        task_items: []
      };
      
      // 遍历所有文档，合并 task_items
      for (const docArray of rawArray) {
        // 将单个文档的二维数组转换为对象
        const map = {};
        for (const [key, value] of docArray) {
          map[key] = value;
        }

        // 设置文档级别信息（使用第一个文档的信息）
        if (result.task_items.length === 0) {
          result.doc_date = map.doc_date;
          result.doc_type = map.doc_type;
          result.external_num = map.external_num;
        }

        // 处理 task_items
        const taskItemsArray = map.task_items;
        
        console.log("当前文档的 task_items:", taskItemsArray);
        
        if (Array.isArray(taskItemsArray)) {
          // 将 task_items 的二维数组转换为对象
          const taskMap = {};
          for (const [k, v] of taskItemsArray) {
            taskMap[k] = v;
          }
          
          // 将每个文档的 task_item 添加到结果中
          result.task_items.push({
            base_line_num: taskMap.base_line_num,
            base_entry: taskMap.base_entry,
            base_type: taskMap.base_type,
            external_num: taskMap.external_num,
            item_code: taskMap.item_code,
            item_name: taskMap.item_name,
            whs_code: '', // 原值被清空
            manage_type: taskMap.manage_type,
            price: taskMap.price,
            quantity: taskMap.quantity,
          });
        }
      }

      return result;
    },
    formatDateTime(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    // 导出Excel功能
    exportToExcel() {
      if (this.tableData.length === 0) {
        this.$message.warning("没有数据可导出");
        return;
      }

      try {
        // 准备导出数据
        const exportData = this.tableData.map((item, index) => {
          return {
            序号: index + 1,
            合同号: item.内部合同号 || "",
            订单编号: item.计划号 || "",
            零件名称: item.零件名称 || "",
            零件编码: item.零件编码 || "",
            工序名称: item.工序名称 || "",
            计划生产数: item.计划生产数 || 0,
            检验数量: item.检验数量 || 0,
            检验合格数量: item.合格数 || 0,
            检验不合格数量: item.不合格数 || 0,
            检验操作人: item.检测人 || "",
            检验时间: item.检测时间 || "",
          };
        });

        // 创建工作簿
        const wb = XLSX.utils.book_new();

        // 创建工作表
        const ws = XLSX.utils.json_to_sheet(exportData);

        // 设置列宽
        const colWidth = [
          { wch: 8 }, // 序号
          { wch: 15 }, // 合同号
          { wch: 15 }, // 订单编号
          { wch: 20 }, // 零件名称
          { wch: 15 }, // 零件编码
          { wch: 12 }, // 工序名称
          { wch: 12 }, // 计划生产数
          { wch: 10 }, // 检验数量
          { wch: 15 }, // 检验合格数量
          { wch: 15 }, // 检验不合格数量
          { wch: 12 }, // 检验操作人
          { wch: 20 }, // 检验时间
        ];
        ws["!cols"] = colWidth;

        // 将工作表添加到工作簿
        XLSX.utils.book_append_sheet(wb, ws, "序检收检记录");

        // 生成文件名（包含当前时间）
        const fileName = `序检收检记录_${this.formatDateForFileName(
          new Date()
        )}.xlsx`;

        // 导出文件
        XLSX.writeFile(wb, fileName);

        this.$message.success("导出成功");
      } catch (error) {
        console.error("导出失败:", error);
        this.$message.error("导出失败");
      }
    },

    // 格式化日期用于文件名
    formatDateForFileName(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");
      return `${year}${month}${day}_${hours}${minutes}${seconds}`;
    },
  },
};
</script>

<style>
.search-container {
  margin-bottom: 20px;
}
.show-text {
  margin-right: 5px;
  line-height: 32px;
}
.operation-cell {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.operation-btn {
  flex: 1;
  margin: 0 5px;
  padding: 0;
  min-width: 0;
}
.active {
  color: skyblue;
  margin-left: 5px;
}

.info-container {
  border: 1px solid #ccc;
  display: flex;
}

.info-item {
  display: flex;
  flex: 1;
  border-right: 1px solid #ccc;
}

.info-item:last-child {
  border-right: none;
}

.info-label {
  width: 30%;
  padding: 8px;
  background-color: #f5f7fa;
  border-right: 1px solid #ccc;
}

.info-value {
  flex: 1;
  padding: 5px;
}

.info-label,
.info-value {
  display: flex;
  align-items: center;
}
</style>