<template>
  <div class="page-container row-container">
    <!-- 左侧区域 -->
    <section class="list-part-container" style="flex: 3">
      <!-- 搜索区 -->
      <el-form class="list-search-container" :model="queryDayworkParams" ref="queryRef" :inline="true"
        style="margin-right: 0px">
        <el-form-item class="section-title" label="生产批次" />
        <el-form-item label="生产计划单号：">
          <el-input placeholder="请输入生产计划单号/批次号" v-model.trim="queryDayworkParams.productionPlanNo"
            @keydown.enter.prevent clearable style="width: 100px" />
        </el-form-item>
        <el-form-item label="产品描述：">
          <el-input placeholder="请输入产品描述" v-model.trim="queryDayworkParams.productDescription" @keydown.enter.prevent
            clearable style="width: 100px" />
        </el-form-item>
        <el-form-item class="section-title" label="请选择当前工段：">
          <el-select-v2 v-model="queryDayworkParams.deptId" :options="deptList" placeholder="请选择工段" style="width: 100px"
            @change="handleDeptChange" />
        </el-form-item>
        <el-form-item class="section-title" label="查询设备：" prop="equipmentDetailCode">
          <el-input placeholder="请输入设备名称" v-model.trim="queryDayworkParams.equipmentDetailCode" @keydown.enter.prevent
            clearable style="width: 100px" />
        </el-form-item>
        <el-form-item style="margin-left: 0">
          <el-button type="info" icon="Search"  :disabled="deptList.length === 0" @click="handleQuery">搜索
          </el-button>
        </el-form-item>
      </el-form>
      <div class="el-table-container">
        <div class="el-table-inner-container">
          <el-table ref="dayworkTable" :data="dayworkList" v-loading="dayworkLoading" highlight-current-row
            height="100%" @current-change="handleDayworkCurrentChange">
            <el-table-column label="客户简称" prop="companyAlias" width="120" align="center" />
            <el-table-column label="生产计划单号" prop="productionPlanNo" width="100" align="center" />
            <el-table-column label="批次号" min-width="120" prop="lotCode" align="center">
              <template #default="scope">
                <el-button link type="primary" v-hasPermi="['business:productionPlan:query']"
                  @click="handleColumnClick(scope.row)"><span>{{ scope.row.lotCode }}</span></el-button>
              </template>
            </el-table-column>
            <el-table-column label="产品描述" prop="productDescription" align="center" />
            <el-table-column label="图纸版本" prop="technologyVersion" width="60" align="center" />
            <el-table-column label="投产量" prop="productionQuantity" width="60" align="center" />
            <el-table-column label="下达日期" prop="createTime" width="100" align="center">
              <template #default="scope">
                <span>{{
        proxy.moment(scope.row.createTime).format("YYYY-MM-DD")
      }}</span>
              </template>
            </el-table-column>
            <el-table-column label="报工总时长" prop="totalWorkingHours" width="150" align="center" />
          </el-table>
        </div>
      </div>
      <!-- 分页 -->
      <pagination v-show="total > 0" :total="total" v-model:page="queryDayworkParams.pageNum"
        v-model:limit="queryDayworkParams.pageSize" @pagination="getDayworks" />
    </section>
    <!-- 右侧区域 -->
    <section class="list-part-container" style="flex: 2">
      <el-form class="list-search-container" :inline="true">
        <el-form-item class="section-title" label="报工信息" />
        <el-form-item class="section-title" label="请选择工序：" prop="processId">
          <el-select-v2 v-model="queryItemParams.processId" clearable :options="processList" placeholder="请选择工序"
            style="width: 100%" @change="handleProcessChange" />
        </el-form-item>
      </el-form>

      <div class="el-table-container">
        <div class="el-table-inner-container">
          <el-table :data="dayworkItemList" v-loading="dayworkItemLoading" height="100%">
            <el-table-column label="操作者" prop="nickName" width="60" align="center" />
            <el-table-column label="工序名称" prop="processAlias" align="center" />
            <el-table-column label="投产量" prop="prodNum" width="60" align="center" />
            <el-table-column label="合格数" prop="qualifiedNum" width="60" align="center" />
            <el-table-column label="废品数" prop="rejectNum" width="60" align="center" />
            <el-table-column label="开始时间" prop="startTime" width="160" align="center" />
            <el-table-column label="结束时间" prop="endTime" width="160" align="center" />
            <el-table-column label="总工时" prop="workingHours" width="160" align="center" />
            <el-table-column label="生产状态" prop="status" width="100" align="center">
              <template #default="scope">
                <dict-tag :options="daywork_status" :value="scope.row.status" />
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" align="center" width="200px">
              <template #default="scope">
                <el-button v-show="scope.row.deptProcessStatus &&
        (scope.row.status == 2 || scope.row.status == 3) &&
        scope.row.id == latestProcessId && scope.row.deptId == latestDeptId && !(lastStatus == 4 || lastStatus == 5 || lastStatus == 7)
        " link type="warning" icon="Edit" @click="handleUpdateDayworkItem(scope.row)">编辑
                </el-button>
                <el-button link type="primary" icon="View" @click="handleCheckDayworkItem(scope.row)">查看
                </el-button>
                <el-button v-show="scope.row.deptProcessStatus &&
        (scope.row.status == 2 || scope.row.status == 3) &&
        scope.row.id == latestProcessId && scope.row.deptId == latestDeptId && !(lastStatus == 4 || lastStatus == 5 || lastStatus == 7) &&
        (scope.row.processStepNumber != lastProcessStepNumber) && currentDaywork.status !=2
        " v-hasPermi="['business:daywork:remove']" link type="danger" icon="Delete"
                  @click="handleDeletedItem(scope.row.id)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!-- 分页 -->
      <pagination v-show="itemTotal > 0" :total="itemTotal" v-model:page="queryItemParams.pageNum"
        v-model:limit="queryItemParams.pageSize" @pagination="getDayworkItems" />
    </section>
    <!-- 报工信息表单 -->
    <daywork-item-form ref="dayworkItemRef" @handleSaveSuccess="handleGetDayworkItems" />
    <!-- 分选报工信息表单 -->
    <sort-item-form ref="sortItemRef" @handleSaveSuccess="handleGetDayworkItems" />
  </div>
</template>

<script setup>
import {
  listDaywork,
  listDayworkItem,
  getProcessList,
  delDayworkItem
} from "@/api/business/daywork.js";
import { listDeptProcess } from "@/api/business/deptProcess";
import { getDept } from "@/api/business/planDetailSubDetail.js";
import router from "@/router";
import dayworkItemForm from "./form";
import sortItemForm from "./sortForm"

const { proxy } = getCurrentInstance();

/** 字典 */
const { daywork_status } = proxy.useDict("daywork_status");

/** 生产批次 */
const dayworkList = ref([]);
const dayworkTable = ref(null);
const currentDaywork = ref({});
const dayworkLoading = ref(false);
const total = ref(0);
/**工段 */
const deptList = ref([]);
const loading = ref(false);
/** 报工信息 */
const dayworkItemList = ref([]);
const dayworkItemLoading = ref(false);
const itemTotal = ref(0);
const lastStatus = ref(null)
const latestProcessId = ref(null);
const latestDeptId = ref(null)
const lastProcessStepNumber = ref(null)
const deptProcessList = ref([]);
/**工序 */
const processList = ref([]);
/** 查询对象 */
const queryDayworkParams = ref({
  productDescription: "",
  deptId: "",
  lotCode: "",
  pageNum: 1,
  pageSize: 10,
});
const queryItemParams = ref({
  dayworkId: "0",
  isAmend: 0,
  isWasteRecycling: 0,
  pageNum: 1,
  pageSize: 10,
  technologicalProcessDetailId: null,
});

/***********************  工段相关事件  ****************************/
function getList() {
  loading.value = true;
  getDept().then((response) => {
    deptList.value = response.data;
    loading.value = false;
    if (deptList.value.length > 0) {
      queryDayworkParams.value.deptId = deptList.value[0].value;
      getDayworks();
    } else {
      dayworkList.value = [];
    }
  });
}

//切换工段
function handleDeptChange() {
  getDayworks();
}

/***********************  生产批次相关事件  ****************************/

/** 查询计划明细 */
function getDayworks() {
  dayworkLoading.value = true;
  listDaywork(queryDayworkParams.value).then((res) => {
    dayworkList.value = res.rows;
    for (var i = 0; i < dayworkList.value.length; i++) {
      let timeStamp = dayworkList.value[i].totalWorkingHours;
      let seconds = Math.floor((timeStamp / 1000) % 60);
      let minutes = Math.floor((timeStamp / (1000 * 60)) % 60);
      let hours = Math.floor(timeStamp / (1000 * 60 * 60));
      let time = `${hours}小时${minutes}分钟${seconds}秒`;
      dayworkList.value[i].totalWorkingHours = time;
    }
    total.value = res.total;
    dayworkLoading.value = false;
    // 批次
    if (dayworkList.value.length > 0) {
      proxy.$refs.dayworkTable.setCurrentRow(dayworkList.value[0]);
      console.log(dayworkList.value[0])
    } else {
      dayworkItemList.value = [];
      itemTotal.value = 0;
    }
  });
}

/** 打开批次详情页 */
function handleColumnClick(row) {
  router.push({ path: "/reviseBath/lotFormParticulars/" + row.lotCode });
}

/** 生产计划明细 current-change 事件 */
function handleDayworkCurrentChange(row) {
  if (row) {
    queryItemParams.value.processId = null;
    currentDaywork.value = row;
    queryItemParams.value.dayworkId = currentDaywork.value.id;
    queryItemParams.value.isAmend = row.isAmend;
    queryItemParams.value.isWasteRecycling = row.isWasteRecycling;
    queryItemParams.value.technologicalProcessDetailId = null;
    queryItemParams.value.technologicalProcessId = row.technologicalProcessId;
    getDayworkItems();
    getProcess();
  } else {
    dayworkItemList.value = [];
    itemTotal.value = 0;
  }
}

/***********************  报工信息相关事件  ****************************/
//查询报工信息数据
function handleGetDayworkItems() {
  dayworkLoading.value = true;
  listDaywork(queryDayworkParams.value).then((res) => {
    dayworkList.value = res.rows;
    for (var i = 0; i < dayworkList.value.length; i++) {
      let timeStamp = dayworkList.value[i].totalWorkingHours;
      let seconds = Math.floor((timeStamp / 1000) % 60);
      let minutes = Math.floor((timeStamp / (1000 * 60)) % 60);
      let hours = Math.floor(timeStamp / (1000 * 60 * 60));
      let time = `${hours}小时${minutes}分钟${seconds}秒`;
      dayworkList.value[i].totalWorkingHours = time;
    }
    total.value = res.total;
    dayworkLoading.value = false;
    if (dayworkList.value.length > 0) {
      for (var i = 0; i < dayworkList.value.length; i++) {
        if (dayworkList.value[i].id == currentDaywork.value.id) {
          var index = i;
          break;
        }
      }
    }
    proxy.$refs.dayworkTable.setCurrentRow(dayworkList.value[index]);
  });
}
//删除报工信息
function handleDeletedItem(id) {
  proxy.$modal
    .confirm("是否确认删除选中的数据项？")
    .then(function () {
      delDayworkItem(id).then(res => {
        if (res.code == 200) {
          proxy.$modal.msgSuccess("删除成功")
          listDaywork(queryDayworkParams.value).then((res) => {
            dayworkList.value = res.rows;
            for (var i = 0; i < dayworkList.value.length; i++) {
              let timeStamp = dayworkList.value[i].totalWorkingHours;
              let seconds = Math.floor((timeStamp / 1000) % 60);
              let minutes = Math.floor((timeStamp / (1000 * 60)) % 60);
              let hours = Math.floor(timeStamp / (1000 * 60 * 60));
              let time = `${hours}小时${minutes}分钟${seconds}秒`;
              dayworkList.value[i].totalWorkingHours = time;
            }
            total.value = res.total;
            // 批次
            proxy.$refs.dayworkTable.setCurrentRow(dayworkList.value[dayworkList.value.findIndex(daywork => daywork.id == currentDaywork.value.id)]);
          });
        }
      })
    })
}
//修改报工信息
function handleUpdateDayworkItem(row) {
  //同工序下状态是否有工序已完成
  let processFinish = false;
  //除了编辑此条以外的同工序合格数
  let totalQuailifiedNum = 0;
  for (let i = 0; i < dayworkItemList.value.length; i++) {
    if (
      row.processId == dayworkItemList.value[i].processId &&
      (dayworkItemList.value[i].status == 2 ||
        dayworkItemList.value[i].status == 3) &&
      row.id != dayworkItemList.value[i].id
    ) {
      totalQuailifiedNum += dayworkItemList.value[i].qualifiedNum;
    }
    if (
      row.processId == dayworkItemList.value[i].processId &&
      dayworkItemList.value[i].status == 3 &&
      row.id != dayworkItemList.value[i].id
    ) {
      processFinish = true;
    }
  }
  let maxQuailifiedNum =
    Math.floor(row.prodNum * 1.03 - totalQuailifiedNum) > 0
      ? Math.floor(row.prodNum * 1.03 - totalQuailifiedNum)
      : 0;
  //该daywork合格数总数不能超过投产数的103%
  row.technologicalProcessId = queryItemParams.value.technologicalProcessId;
  row.deptId = queryDayworkParams.value.deptId;
  row.productionPlanDetailId = currentDaywork.value.productionPlanDetailId;
  row.dayworkId = currentDaywork.value.id;
  row.lotId = currentDaywork.value.lotId;
  row.isAmend = currentDaywork.value.isAmend;
  row.isWasteRecycling = currentDaywork.value.isWasteRecycling;
  row.maxQuailifiedNum = maxQuailifiedNum;
  row.totalQuailifiedNum = totalQuailifiedNum;
  //判断是否是当前工段
  if (row.deptId == currentDaywork.value.deptId) {
    row.currentDept = true;
  } else {
    row.currentDept = false;
  }
  //修改向form表单传一个状态值
  row.editStatus = true;
  //如果为true，则同工序已有工序已完成
  row.processFinish = processFinish;
  if(row.isSort == 0){
    proxy.$refs.dayworkItemRef.open(row);
  }else{
    proxy.$refs.sortItemRef.open(row);
  }
  
}

//查看报工信息
function handleCheckDayworkItem(row) {
  row.technologicalProcessId = queryItemParams.value.technologicalProcessId;
  row.deptId = queryDayworkParams.value.deptId;
  row.productionPlanDetailId = currentDaywork.value.productionPlanDetailId;
  row.isAmend = currentDaywork.value.isAmend;
  row.isWasteRecycling = currentDaywork.value.isWasteRecycling;
  row.dayworkId = currentDaywork.value.id;
  row.lotId = currentDaywork.value.lotId;
  //判断是否是当前工段
  if (row.deptId == currentDaywork.value.deptId) {
    row.currentDept = true;
  } else {
    row.currentDept = false;
  }
  //修改向form表单传一个状态值
  row.editStatus = false;
  // row.returnFlag = false;
  // //如果是最新工序的已接收，则传一个状态值，给form表单一个退回按钮
  // if (row.processId == latestProcessId.value && row.status == 7) {
  //   row.returnFlag = true;
  // }
  if(row.isSort == 0){
    proxy.$refs.dayworkItemRef.open(row);
  }else{
    proxy.$refs.sortItemRef.open(row);
  }
}

/**切换工序 */
function handleProcessChange() {
  getDayworkItems();
}

/** 报工详情列表 */
function getDayworkItems() {
  dayworkItemLoading.value = true;
  //查询该工段在工段资源分配时绑定的工序，传一个flag，如果flag有值则后端查询不分页
  listDeptProcess({ deptId: queryDayworkParams.value.deptId, flag: 1 }).then(
    (res) => {
      deptProcessList.value = res.rows;
      listDayworkItem(queryItemParams.value).then((res) => {
        console.log(currentDaywork.value);
        for (let i = 0; i < res.rows.length; i++) {
          //如果时首序，投产数是单批数
          if (res.rows[i].processStepNumber === res.others.isFirst && res.rows[i].prodNum == 0) {
            if (currentDaywork.value.isLast == 1) {
              res.rows[i].prodNum = currentDaywork.value.lastLotQuantity;
            } else {
              res.rows[i].prodNum = currentDaywork.value.oneLotQuantity;
            }
          }
          //拿到最新一条报工信息的工序id，只能编辑当前序
          // if (res.rows[i] == res.rows[res.rows.length - 1]) {
          //   latestProcessId.value = res.rows[i].processId;
          // }
        }
        if (res.others != null && res.others.latestProcessId != null) {
          latestProcessId.value = res.others.latestProcessId
        }
        if (res.others != null && res.others.lastItem != null) {
          latestDeptId.value = res.others.lastItem.deptId
          lastStatus.value = res.others.lastItem.status
        }
        for (var i = 0; i < res.rows.length; i++) {
          let timeStamp = res.rows[i].workingHours;
          let seconds = Math.floor((timeStamp / 1000) % 60);
          let minutes = Math.floor((timeStamp / (1000 * 60)) % 60);
          let hours = Math.floor(timeStamp / (1000 * 60 * 60));
          let time = `${hours}小时${minutes}分钟${seconds}秒`;
          res.rows[i].workingHours = time;
          res.rows[i].deptProcessStatus = false;
          //报工记录的工序id是该工段绑定的工序时，允许编辑
          for (var item = 0; item < deptProcessList.value.length; item++) {
            if (res.rows[i].processId == deptProcessList.value[item].processId) {
              res.rows[i].deptProcessStatus = true;
            }
          }
          console.log(res.rows[i].deptProcessStatus)
        }
        dayworkItemList.value = res.rows;
        getProcess();
        itemTotal.value = res.total;
        dayworkItemLoading.value = false;
      });
    }
  );
}
//工序信息
function getProcess() {
  //工序下拉框
  getProcessList({
    technologicalProcessId: queryItemParams.value.technologicalProcessId,
    isWasteRecycling: currentDaywork.value.isWasteRecycling,
    isAmend: currentDaywork.value.isAmend,
    lotId: currentDaywork.value.lotId,
  }).then((res) => {
    processList.value = res.data;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  getDayworks();
}

onMounted(() => {
  getList();
});
</script>
<style scoped>
.el-form--inline .el-form-item {
  margin-right: 20px;
}
</style>
