<template>
  <div>
    <div style="display: flex">
      <el-card style="width: 100%">
        <div class="search-container">
          <span class="show-text">任务ID:</span>
          <el-input
            v-model="TaskAID"
            placeholder="请输入任务ID"
            clearable
            style="width: 150px; margin-right: 10px"
            @change="searchTable()"
          />
          <span class="show-text">生产订单:</span>
          <el-input
            v-model="orderNo2"
            placeholder="请输入生产订单"
            clearable
            style="width: 150px; margin-right: 10px"
          />
          <span class="show-text">物料编码:</span>
          <el-input
            v-model="productCode2"
            placeholder="请输入零件编码"
            clearable
            style="width: 150px; margin-right: 10px"
          />
          <span class="show-text">计划号:</span>
          <el-input
            v-model="plannum"
            placeholder="请输入计划号"
            clearable
            style="width: 150px; margin-right: 10px"
          />
          <span class="show-text">销售订单:</span>
          <el-input
            v-model="salenum"
            placeholder="请输入销售订单"
            clearable
            style="width: 150px; margin-right: 10px"
          />
          <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"
          />
          <span class="show-text">任务状态:</span>
          <el-select
            v-model="productionStatus2"
            clearable
            placeholder="请选择状态"
            style="width: 150px; margin-right: 10px"
          >
            <el-option label="全部" value="10" />
            <el-option label="待执行" value="0" />
            <el-option label="可执行" value="1" />
            <el-option label="已开工" value="2" />
            <el-option label="已完成" value="4" />
          </el-select>
          <el-switch
              v-model="stationFilterMode"
              active-text="工位正选"
              inactive-text="工位反选"
              active-value="include"
              inactive-value="exclude"
              style="margin-left: 20px;"
            />
          <el-button
            :disabled="loading"
            icon="el-icon-search"
            plain
            type="primary"
            @click="searchTable()"
            >查询</el-button
          >
          <el-checkbox-group v-model="Doing" @change = "Doingform" style="margin: 20px;">
            <el-checkbox  v-for="item in Doingoptions" :key="item.工位号" :label="item.指南工位号" :value="item.工位号"> </el-checkbox>
          </el-checkbox-group>
          
          
        </div>
        <el-table
          v-loading="loading"
          :data="tableData"
          :height="'72vh'"
          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"
            prop="指派对象"
            label="指派对象"
            width="80"
            fixed
          />
          <el-table-column
            align="center"
            prop="订单号"
            label="生产订单"
            width="80"
            fixed
          />
          
          <el-table-column
            align="center"
            prop="合同号"
            label="销售订单"
            width="80"
            fixed
          />
          <el-table-column
            align="center"
            prop="零件名称"
            label="物料名称"
            width="100"
          />
          <el-table-column
            align="center"
            prop="零件编码"
            label="物料编码"
            width="100"
          />
          <el-table-column align="center" label="顺序" width="50">
            <template slot-scope="scope">{{ scope.row.订单行号 }}</template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="工序名称"
            label="工序名称"
            width="80"
          />
          
          
          <el-table-column
            align="center"
            prop="分配数"
            label="分配数"
            width="60"
          />
          <el-table-column
            align="center"
            prop="上序合格数"
            label="上序合格数"
            width="60"
          />
          
          <el-table-column align="center" label="加工状态" width="80">
            <template slot-scope="scope">
              <div
                :style="getScoreStyle(scope.row.加工状态)"
                class="score-cell"
              >
                {{ scope.row.加工状态 }}
              </div>
            </template>
          </el-table-column>
          <!-- <el-table-column align="center" label="收料状态" width="80">
            <template slot-scope="scope">
              <div
                class="status-light"
                :class="
                  scope.row.收料 > 0
                    ? 'status-light-green'
                    : 'status-light-gray'
                "
              />
            </template>
          </el-table-column> -->
          <el-table-column
            align="center"
            label="加急数量"
            width=" 120"
            v-bind:class="colorstatus"
          >
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="Urgent(scope.row)">{{scope.row.加急总数}}</el-button>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="下序名称"
            label="下序名称"
            width="80"
          />
          <!-- <el-table-column align="center" label="加急" width="60">
            <template slot-scope="scope">
              <div
                class="status-light"
                :class="
                  scope.row.加急 === '加急'
                    ? 'status-light-green'
                    : 'status-light-gray'
                "
              />
            </template>
          </el-table-column> -->
          <!-- <el-table-column align="center" label="优先" width="60">
            <template slot-scope="scope">
              <div
                class="status-light"
                :class="
                  scope.row.优先 === '是'
                    ? 'status-light-green'
                    : 'status-light-gray'
                "
              />
            </template>
          </el-table-column>
          <el-table-column align="center" prop="首检" label="首检" width="60">
            <template slot-scope="scope">
              <div
                class="status-light"
                :class="
                  scope.row.首检 === 'OK'
                    ? 'status-light-green'
                    : 'status-light-gray'
                "
              />
            </template>
          </el-table-column>
          <el-table-column align="center" label="序检" width="60">
            <template slot-scope="scope">
              <div
                class="status-light"
                :class="
                  scope.row.序检 === 'OK'
                    ? 'status-light-green'
                    : 'status-light-gray'
                "
              />
            </template>
          </el-table-column> -->
          <!-- <el-table-column
            align="center"
            prop="订单拆分内码"
            label="内码"
            width="50"
          /> -->
          
          
          
          
          <el-table-column
            align="center"
            prop="完成数量"
            label="完成数"
            width="60"
          />
          <el-table-column
            align="center"
            label="任务状态"
            width="80"
            v-bind:class="colorstatus"
          >
            <template slot-scope="scope">
              <div
                :style="getScoreStyle(scope.row.任务状态)"
                class="score-cell"
              >
                {{ scope.row.任务状态 }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="计划号"
            label="计划号"
            width="80"
          />
          <el-table-column align="center" label="计划开始" width="100">
            <template slot-scope="scope">{{formatDate(scope.row.计划开始)}}</template>
          </el-table-column>
          <el-table-column align="center" label="计划完成" width="100">
            <template slot-scope="scope">{{formatDate(scope.row.计划完成)}}</template>
          </el-table-column>
          <el-table-column align="center" label="开工时间" width="100">
            <template slot-scope="scope">{{formatDate(scope.row.开工时间)}}</template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="派工特殊说明"
            label="备注"
            width="120"
          />
          <el-table-column
            align="center"
            prop="收料"
            label="收料数"
            width="60"
          />
        </el-table>
      </el-card>
    </div>
</div>
</template>
<script>
export default {
  data() {
    return {
      TaskAID:'',
      radio: 1,
      orderNo2: "",
      contractNo: "",
      productCode2: "",
      plannum:"",
      salenum:'',
      process: "",
      processList2: [],
      nature: "",
      productionStatus2: null,
      taskstate: "",
      taskprogress: "0",
      startworktime: 0,
      shift: "白班",
      shiftoptions: [
        
      ],
      Doing: [],
      Doingoptions: [],
      stationFilterMode: 'include',
      // DoingData: {
      //   订单编号: "",
      //   合同号: "",
      //   物料编号: "",
      //   指派数量: "",
      //   完成数量: "",
      // },
      rptDate: [],
      completionTime: [],
      currentTime: "",
      loading: false,
      tableData: [],
      selectedRow: null,
      currentRow: {},
      colorstatus: "",
      assistendData: {},
      assistNumber: 0,
      assistendVisible: false,
      receiveData: {},
      receiveNum: 0,
      receiveVisible: false,
      workStartData: {},
      workStartNum: 0,
      workStartVisible: false,
      firstCheckData: {},
      firstCheckNumber: false,
      firstCheckVisible: false,
      prodReportData: [],
      prodReportDataTop: [],
      proReportNum: 0,
      prodReportVisible: false,
      tableDataBack: [],
      rptDesc: "",
      multipleSelection: "",
      editForm: {
        优先级: "",
        未完成说明: "",
        派工特殊说明: "",
      },
      splitTaskDialogVisible: false,
      splitTaskSubmitLoading: false,
      stationOptions: [],
      splitTaskForm: {
        分配数量: 0,
        指派对象: "",
        指派对象编号: "",
        派工特殊备注: "",
        计划开始时间: "",
        计划结束时间: "",
        最晚开始时间: "",
        任务概述: "",
      },
      tableData2: [], //检验标准数据
      type: "",
      checkForm: {
        检验标准编号: "",
        检验标准名称: "",
        检验项目: "",
        检验内容: "",
        检验比例: "",
        上限值: "",
        下限值: "",
        单位: "",
        检具: "",
        备注: "",
      },
      currentPage: 1, // 当前页码
      inspectionData: [], // 存储所有检测项的二维数组
      pickerOptions: {
        disabledDate(time) {
          // 禁用当前时间之后的日期
          return time.getTime() > Date.now();
        },
      },
      processCheckVisible: false,
      receiveCheckVisible: false,
      checkRecordVisible: false,
      type: "",
      typeList: [],
      operationPerson: "",
      operationPersonList: [],
      operationDate: [],
      inspectionResult: "",
      inspectionResultList: [
        { value: "1", label: "合格" },
        { value: "0", label: "不合格" },
      ],
      checkDetailedVisible: false,
      DetailedVisible: false,
      // 序检自检相关数据
      processCheckData: {
        物料描述: "",
        合同号: "",
        物料编号: "",
        订单编号: "",
        工序名称: "",
        检测数量: 1,
        合格数: 1,
        计划数量: "",
        检验人: "",
        检验时间: "",
        顺序编号: "",
        TaskAID: "",
      },
      betweenProcessTableData: [], // 检验标准数据
      betweenProcessInspectionData: [], // 存储所有检测项的二维数组
      betweenProcessCurrentPage: 1,
      betweenProcessCurrentInspectionItem: 1, // 当前检测零件编号
      
      //currentTask: null,
      currentProcess: null,
      selectProcess: null,
      
      transferForm: {
        newApproverId: '',
        newApproverName: '',
        reason: ''
      },
      
      completeForm: {
        reason: '',
        result: 'completed'
      },
      
      createDialogVisible: false,
      handleDialogVisible: false,
      detailDialogVisible: false,
      submitting: false,
      
      filters: {
        pending: { keyword: '', priority: '', type: '' },
        initiated: { keyword: '', status: '' }
      },
      
      newProcessForm: {
        type: '',
        priority: 'normal',
        title: '',
        description: '',
        approvers: []
      },
      
      formRules: {
        title: [{ required: true, message: '请输入流程标题', trigger: 'blur' }],
        description: [{ required: true, message: '请输入流程描述', trigger: 'blur' }]
      },
      
      handleForm: {
        result: 'approved',
        comment: ''
      },
      
      userList: [],
      
      stats: {
        pending: 0,
        initiated: 0,
        completed: 0,
      },
      
      // 数据
      pendingTasks: [],
      initiatedProcesses: [],
      processedTasks: [],
      users: [],
      Abnormalcontrolpop:false,
      ReturnWarehousepop:false,
      ReturnWarehouseForm:{},
      MaterialRequisitionpop:false,
      MaterialRequisitionForm:{},
      pausePreviousState:{},

      
      pickerOptions: {
        disabledDate(time) {
          // 禁用当前时间之后的日期
          return time.getTime() > Date.now();
        },
      },
      
      // 人员时间记录相关
      userTimeRecords: {}, // 存储用户开始时间记录 { taskAID: { userId: startTime } }
      // 新增相关数据
      orderList: [], // 订单列表
      processList: [], // 工序列表
      seeVisible:false,
      UrgentVisible: false,
      Urgentarr: {},
      selectedOperators:'',
      processname2:'',
      TaskAID2:'',
    };
    
  },
  created() {
    var now = new Date();
    var start = new Date(
      Date.UTC(now.getFullYear() , now.getMonth(), now.getDate()-1, 0, 0, 0)
    )
      .toISOString()
      .replace("T", " ")
      .replace(".000Z", "");
    var end = new Date(
      Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()-1, 23, 59, 59)
    )
      .toISOString()
      .replace("T", " ")
      .replace(".000Z", "");
    this.completionTime = [start, end];
    this.rptDate = end;
    this.getDoing()
  },
  methods: {
    searchTable() {
      this.loading = true;
      this.tableData = [];
      var param = [];
      param.push(["TaskAID", this.TaskAID || 0]);
      param.push(["订单号", this.orderNo2 || 0]);
      param.push(["零件编号", this.productCode2]);
      param.push([
        "计划开工_Start" , this.completionTime ? this.completionTime[0] : '',
      ]);
      param.push([
        "计划开工_End", this.completionTime ? this.completionTime[1] : '',
      ]);

      param.push(["生产状态", this.productionStatus2]||-1);
      param.push(["工位名称", this.Doing]);
      param.push(["工位筛选模式", this.stationFilterMode]);
      param.push(["用户ID" , this.$store.state.user.id])
      param.push(["计划号" , this.plannum])
      param.push(["销售订单" , this.salenum])
      var Data = this.CreateData("11", "异常提醒_及时开工_查询", param);
      this.ExecDatabase(Data)
        .then((response) => {
          this.loading = false;
          
          // 完整的优先级映射
          const priorityLevel = {
            '高': 3,
            '中': 2, 
            '低': 1,
            '是': 1,
            '否': 0,
            '加急': 4,
            '紧急': 4,
            '一般': 2
          };
          
          if (response.data && response.data.length !== 0) {
          
            this.tableData = response.data;
            
            this.tableData.sort((a, b) => {
             // 5. 优先级相同，按订单号排序（安全比较）
              const aOrderNo = String(a.指派对象 || '');
              const bOrderNo = String(b.指派对象 || '');

              if (aOrderNo !== bOrderNo) {
                return aOrderNo.localeCompare(bOrderNo);
              }

              // 4. 按计划开始时间排序（早的在前）
              const aStartTime = a.计划开始 ? new Date(a.计划开始).getTime() : Infinity;
              const bStartTime = b.计划开始 ? new Date(b.计划开始).getTime() : Infinity;

              if (aStartTime !== bStartTime) {
                return aStartTime - bStartTime; // 时间早的在前
              }
            });
            this.tableDataBack = [...this.tableData];
          } else {
            console.log("没有获取到数据");
            this.tableData = [];
            this.tableDataBack = [];
          }
        })
        .catch((error) => {
          this.loading = false;
          console.error("请求失败:", error);
        });
    },
    Doingform(value){
      console.log(value)
      this.station = ''
    },
    getDoing() {
      var Data = this.CreateData("11", "MES_登录_工位与名称_查询");
      this.ExecDatabase(Data).then((response) => {
        this.loading = false;
        if (response.data.length !== 0) {
          this.Doingoptions = response.data;
        }
      });
    },
    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}`;
    },
    getScoreStyle(bgcolor) {
      if (bgcolor == "可执行") {
        return {
          backgroundColor: "#f0f9eb",
          color: "#67c23a",
        };
      } else if (bgcolor == "已完成") {
        return {
          backgroundColor: "#ecf5ff",
          color: "#409eff",
        };
      } else if (bgcolor == "已开工") {
        return {
          backgroundColor: "#fdf6ec",
          color: "#e6a23c",
        };
      } else if (bgcolor == "开始加工"  ||  bgcolor == "辅助开始") {
        return {
          backgroundColor: "#f0f9eb",
          color: "#67c23a",
        };
      }  else if (bgcolor == "暂停") {
        return {
          backgroundColor: "#fdf6ec",
          color: "#e6a23c",
        };
      }else if (bgcolor == "报工" ||  bgcolor == "辅助结束") {
        return {
          backgroundColor: "#ecf5ff",
          color: "#409eff",
        };
      }
    },
    getProcessList() {
      this.processList2 = [];
      var Data = this.CreateData("11", "Prog_MES_LoadProcess");
      this.ExecDatabase(Data).then((response) => {
        for (let i = 0; i < response.data.length; i++) {
          this.processList2.push({
            label: response.data[i].工序名称,
            value: response.data[i].工艺编号,
          });
        }
      });
    },
    getTypeList() {
      this.typeList = [];
      var Data = this.CreateData("11", "查询字典");
      this.ExecDatabase(Data).then((response) => {
        for (let i = 0; i < response.data.length; i++) {
          // 假设 YL_基础表_数据字典 返回的字段是 DictName 和 DictID
          if (response.data[i].数据类别 === "检测类型") {
            this.typeList.push({
              label: response.data[i].词条名称,
              value: response.data[i].词条编号,
            });
          }
        }
      });
    },
    formatDate(date) {
      if (!date) return "";
      return date.split(" ").length > 1 ? date.split(" ")[0] : date;
    },
    logusername() {
      return this.name;
    },
  }
}
</script>