<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: 200px" />
        </el-form-item>
        <el-form-item label="产品描述：">
          <el-input placeholder="请输入产品描述" v-model.trim="queryDayworkParams.productDescription" @keydown.enter.prevent
            clearable style="width: 130px" />
        </el-form-item>
        <el-form-item class="section-title" label="请选择当前工段：">
          <el-select-v2 v-model="queryDayworkParams.deptId" :options="deptList" placeholder="请选择工段" style="width: 140px"
            @change="handleDeptChange" />
        </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="70px">
              <template #default="scope">
                <el-button v-if="scope.row.deptProcessStatus &&
        (scope.row.status == 2 || scope.row.status == 3) &&
        scope.row.processId == latestProcessId
        " link type="warning" icon="Edit" @click="handleUpdateDayworkItem(scope.row)">编辑
                </el-button>
                <el-button v-else link type="primary" icon="View" @click="handleCheckDayworkItem(scope.row)">查看
                </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" />
  </div>
</template>

<script setup>
import {
  listDaywork,
  listDayworkItem,
  getProcessList,
} 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";

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 latestProcessId = 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]);
    } 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 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.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;
  proxy.$refs.dayworkItemRef.open(row);
}

//查看报工信息
function handleCheckDayworkItem(row) {
  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;
  //判断是否是当前工段
  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;
  // }
  proxy.$refs.dayworkItemRef.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].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;
      }
    }
    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;
        }
      }
    }
    dayworkItemList.value = res.rows;
    getProcess();
    itemTotal.value = res.total;
    dayworkItemLoading.value = false;
  });
}
//工序信息
function getProcess() {
  //工序下拉框
  getProcessList({
    technologicalProcessId: queryItemParams.value.technologicalProcessId,
  }).then((res) => {
    processList.value = res.data;
  });
}

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

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