<template>
  <!-- 添加或修改项目信息对话框 -->
  <el-drawer
    v-model="visible"
    size="80%"
    direction="rtl"
    :close-on-press-escape="false"
  >
    <div class="page-container form-container">
      <div class="form-btns-container">
        <span class="title-label"
          ><el-icon>
            <Document />
          </el-icon>
          报工详情</span
        >

        <el-button
          icon="Close"
          style="margin-left: auto; margin-right: 20px"
          @click="handleCancel"
          >取 消
        </el-button>
      </div>

      <!-- 列表区 -->
      <el-tabs
        v-loading="loading"
        v-model="activeName"
        type="border-card"
        class="demo-tabs"
        @tab-change="handleTabsClick"
      >
        <el-tab-pane label="标准报工" name="0"></el-tab-pane>
        <el-tab-pane label="辅助报工" name="1"></el-tab-pane>
        <div class="el-table-container" style="padding: 0px">
          <el-table
            v-if="activeName == '0'"
            :data="dayworkItemList"
            height="100%"
          >
            <el-table-column label="操作者" prop="nickName" align="center" />
            <el-table-column
              label="设备编号"
              prop="equipmentDetailCode"
              width="100"
              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
              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" align="center" />
            <el-table-column label="结束时间" prop="endTime" align="center" />
            <el-table-column
              label="总工时"
              prop="workingHours"
              align="center"
            />
          </el-table>
          <el-table
            v-if="activeName == '1'"
            :data="auxiliaryItem"
            height="100%"
          >
            <el-table-column label="操作者" prop="nickName" 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
              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" align="center" />
            <el-table-column label="结束时间" prop="endTime" align="center" />
            <el-table-column
              label="总工时"
              prop="workingHours"
              align="center"
            />
          </el-table>
        </div>
      </el-tabs>

      <!-- <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" :pageSizes="[50, 100]"
        v-model:limit="queryParams.pageSize" @pagination="getList" /> -->
    </div>
  </el-drawer>
</template>
<script setup>
import {
  getProcessList,
  getDayworkItemRejectList,
  updateDayworkItemInfoForNum,
  getEquipmentInfo,
  getIsFirstOrder,
  listDayworkItem,
  listDayworkAuxiliaryItem,
} from "@/api/business/daywork.js";
import { ref } from "vue";

const { proxy } = getCurrentInstance();
const emit = defineEmits(["handleSaveSuccess"]);

const { daywork_status } = proxy.useDict("daywork_status");
/** 字典 */
const { daywork_status_edit } = proxy.useDict("daywork_status_edit");
const { daywork_status_first } = proxy.useDict("daywork_status_first");
const { daywork_status_second } = proxy.useDict("daywork_status_second");
const { waste_causes } = proxy.useDict("waste_causes");
const detailInfo = ref({});
const loading = ref(false);
const total = ref(0);
const activeName = ref("0");
const processList = ref([]);
const lotId = ref(null);
const equipmentList = ref([]);
const visible = ref(false);
const isFirst = ref(true); //是否为首序
const editStatus = ref(false);
const currentDept = ref(false);
const rejectAmount = ref(0);
const dynamicOptions = ref([]);
const workingHoursTime = ref("");
const maxQuailifiedNum = ref(0);
const dayworkItemList = ref([]);
const auxiliaryItem = ref([]);
const queryParams = ref({
  pageNum: 1,
  pageSize: 100,
});
const detailsRow = {
  id: null,
  rejectNum: "",
  reason: "",
};
// const validateprodNum = (rule, value, callback) => {
//   if (value <= 0) {
//     callback(new Error("投产量应大于0"));
//   } else {
//     callback();
//   }
// };
const validateWorkingHours = (rule, value, callback) => {
  if (form.value.workHoursTimestamp < 0) {
    callback(new Error("结束时间应晚于开始时间"));
  } else {
    callback();
  }
};
const validateQualifiedNum = (rule, value, callback) => {
  const max = maxQuailifiedNum.value;
  if (value < 0) {
    callback(new Error("合格数量应大于/等于0"));
  } else {
    callback();
  }

  // else if (
  //   value > max &&
  //   detailInfo.value.firstProcessId != form.value.processId
  // ) {
  //   callback(new Error("合格数量不应大于投产量的103%,即" + max));
  // }
};
const validateEndTime = (rule, value, callback) => {
  if (form.value.status > 1) {
    if (form.value.endTime == null) {
      callback(new Error("结束时间不能为空"));
    } else {
      callback();
    }
  } else {
    if (form.value.endTime != null) {
      callback(new Error("该状态结束时间应为空"));
    } else {
      callback();
    }
  }
};
const validateStartTime = (rule, value, callback) => {
  if (form.value.status > 1) {
    if (form.value.startTime == null) {
      callback(new Error("开始时间不能为空"));
    } else {
      callback();
    }
  } else {
    callback();
  }
};
const data = reactive({
  form: {
    groupRejectList: [],
    nickName: "",
    processId: "",
    processAlias: "",
    prodNum: 0,
    qualifiedNum: 0,
    rejectNum: 0,
    startTime: "",
    endTime: "",
    workingHours: 0,
    status: "",
    workHoursTimestamp: 0,
  },
  rules: {
    // prodNum: [
    //   { required: true, message: "投产量不能为空", trigger: "blur" },
    //   { validator: validateprodNum, trigger: "blur" },
    // ],
    startTime: [{ validator: validateStartTime, trigger: "blur" }],
    endTime: [{ validator: validateEndTime, trigger: "blur" }],
    workingHoursTime: [{ validator: validateWorkingHours, trigger: "change" }],
    qualifiedNum: [
      { required: true, message: "合格数量不能为空", trigger: "blur" },
      { validator: validateQualifiedNum, trigger: "blur" },
    ],
  },
});

const { form, rules } = toRefs(data);

/***********************  方法区  ****************************/
/** 打开抽屉 */
const open = (row) => {
  reset();
  dayworkItemList.value = [];
  auxiliaryItem.value = [];
  loading.value = true;
  // if (row.id) {
  //查询是否为首序
  queryParams.value.dayworkId = row.dayworkId;
  queryParams.value.processStepNumber = row.processStepNumber;
  tabs(activeName.value);
  visible.value = true;
  // }
};

function tabs(tab) {
  if (tab == "0") {
    listDayworkItem(queryParams.value).then((res) => {
      dayworkItemList.value = res.rows;
      console.log(res);
      for (var i = 0; i < dayworkItemList.value.length; i++) {
        // console.log(i, dayworkItemList.value[i], dayworkItemList.value[i].daywork)
        let timeStamp = dayworkItemList.value[i].workingHours
          ? dayworkItemList.value[i].workingHours
          : 0;
        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}秒`;
        dayworkItemList.value[i].workingHours = time;
      }
      total.value = res.total;
      loading.value = false;
    });
  } else if (tab == "1") {
    listDayworkAuxiliaryItem(queryParams.value).then((res) => {
      auxiliaryItem.value = res.data;
      console.log(res);
      for (var i = 0; i < auxiliaryItem.value.length; i++) {
        // console.log(i, dayworkItemList.value[i], dayworkItemList.value[i].daywork)
        let timeStamp = auxiliaryItem.value[i].workingHours
          ? auxiliaryItem.value[i].workingHours
          : 0;
        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}秒`;
        auxiliaryItem.value[i].workingHours = time;
      }
      console.log("auxiliaryItem", auxiliaryItem.value);
      // total.value = res.total;
      loading.value = false;
    });
  }
}

function handleTabsClick() {
  loading.value = true;
  tabs(activeName.value);
}

function getList() {
  loading.value = true;
  listDayworkItem(queryParams).then((res) => {
    dayworkItemList.value = res.rows;
    for (var i = 0; i < dayworkItemList.value.length; i++) {
      let timeStamp = dayworkItemList.value[i].workingHours
        ? dayworkItemList.value[i].workingHours
        : 0;
      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}秒`;
      dayworkItemList.value[i].workingHours = time;
    }
    total.value = res.total;
    loading.value = false;
  });
}
function handleSelectUserSingle() {}
/**
 * 对话框关闭 事件
 */
function close() {
  reset();
  visible.value = false;
}

/** 表单重置 */
function reset() {
  form.value = {
    groupRejectList: [],
    nickName: "",
    processId: null,
    processAlias: "",
    prodNum: 0,
    qualifiedNum: 0,
    rejectNum: 0,
    startTime: "",
    endTime: "",
    workingHours: 0,
  };
  proxy.resetForm("dayworkItemRef");
}

/** 提交按钮 */
const handleSave = () => {
  proxy.$refs["dayworkItemRef"].validate((valid) => {
    if (valid) {
      rejectAmount.value = 0;
      var reasonList = [];
      var flag = true;
      for (let i = 0; i < form.value.groupRejectList.length; i++) {
        rejectAmount.value += form.value.groupRejectList[i].rejectNum;
        if (form.value.groupRejectList[i].rejectNum <= 0) {
          flag = false;
          proxy.$modal.msgError("第" + (i + 1) + "废品数应大于0");
          return;
        }
        if (!form.value.groupRejectList[i].reason) {
          flag = false;
          proxy.$modal.msgError("第" + (i + 1) + "行废品原因不能为空");

          return;
        }
        if (reasonList.indexOf(form.value.groupRejectList[i].reason) >= 0) {
          flag = false;
          proxy.$modal.msgError(
            "第" +
              (i + 1) +
              "行废品原因与" +
              (reasonList.indexOf(form.value.groupRejectList[i].reason) + 1) +
              "行相同"
          );
          return;
        }
        reasonList.push(form.value.groupRejectList[i].reason);
      }
      if (rejectAmount.value > form.value.prodNum) {
        flag = false;
        proxy.$modal.msgError(
          "废品总数不能超过投产数，当前废品总数为" + rejectAmount.value
        );
      }

      form.value.workingHours = form.value.workHoursTimestamp;
      //设备id和code
      for (let i = 0; i < equipmentList.value.length; i++) {
        if (form.value.equipmentDetailId == equipmentList.value[i].value) {
          form.value.equipmentDetailCode = equipmentList.value[i].label;
        }
      }
      if (flag) {
        if (form.value.groupRejectList.length > 0) {
          form.value.groupRejectList.forEach((item) => {
            item.deptId = detailInfo.value.deptId;
            item.processId = detailInfo.value.processId;
          });
        }
        form.value.dayworkId = detailInfo.value.dayworkId;
        //同工序的所有合格数
        form.value.temporaryProcessQualifiedNum =
          detailInfo.value.totalQuailifiedNum + form.value.qualifiedNum;
        //如果状态从工序已完成改成结束报工，传给后端一个标记，如果为true，则删除中间表对应的数据
        if (detailInfo.value.status == 3 && form.value.status == 2) {
          form.value.dayworkId = detailInfo.value.dayworkId;
          form.value.flag = true;
        }
        let data = form.value;
        data.lotId = lotId.value;

        const max = maxQuailifiedNum.value;
        let sunm =
          detailInfo.value.totalQuailifiedNum + form.value.qualifiedNum; //计算总合格数
        let num = sunm - form.value.prodNum; //多出来的数量
        let percent = (sunm / form.value.prodNum) * 100; //合格率
        percent = Math.ceil(percent * 100) / 100; //只入不舍
        //判断是否超过投产量
        if (sunm > form.value.prodNum) {
          //判断是否为首序
          if (isFirst.value) {
            // 弹出确认对话框
            proxy.$modal
              .confirm(
                "合格数为投产量" +
                  percent +
                  "%,超出投产量" +
                  num +
                  "。 是否继续保存！"
              )
              .then(function () {
                updateDayworkItem();
              })
              .then(() => {
                return;
              })
              .catch(() => {
                return;
              });
          } else {
            if (form.value.qualifiedNum <= max) {
              updateDayworkItem();
            } else {
              proxy.$modal.msgError(
                "合格数不能超过投产量的103%,最大合格数为" + max
              );
            }
          }
        } else {
          updateDayworkItem();
        }
      }
    }
  });
};

//页面提交方法
function updateDayworkItem() {
  updateDayworkItemInfoForNum(form.value).then((res) => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess("保存成功！");
      visible.value = false;
      emit("handleSaveSuccess");
    } else {
      proxy.$modal.msgError("保存失败！");
    }
  });
}

//删除废弃信息
function handleDeleteReject(row) {
  form.value.groupRejectList.splice(form.value.groupRejectList.indexOf(row), 1);
}

//添加废弃信息
function handleAddReject() {
  const newDetail = JSON.parse(JSON.stringify(detailsRow));
  newDetail.rejectNum = 0;
  newDetail.dayworkId = detailInfo.value.dayworkId;
  newDetail.dayworkItemId = detailInfo.value.id;
  newDetail.lotId = detailInfo.value.lotId;
  form.value.groupRejectList.push(newDetail);
}

//计算总工时
function handleTotalTime() {
  if (form.value.endTime == null) {
    workingHoursTime.value = "0小时0分钟0秒";
    form.value.workHoursTimestamp = 0;
  } else {
    form.value.workHoursTimestamp =
      new Date(form.value.endTime) - new Date(form.value.startTime);
    let seconds = Math.floor((form.value.workHoursTimestamp / 1000) % 60);
    let minutes = Math.floor(
      (form.value.workHoursTimestamp / (1000 * 60)) % 60
    );
    let hours = Math.floor(form.value.workHoursTimestamp / (1000 * 60 * 60));
    let time = `${hours}小时${minutes}分钟${seconds}秒`;
    workingHoursTime.value = time;
  }
}

//当生产状态为未开始、生产中时，结束时间为空，合格数为0，废弃信息为空
function handleChangeStatus() {
  if (form.value.status == 1) {
    form.value.endTime = null;
    workingHoursTime.value = "0小时0分钟0秒";
    form.value.workingHours = 0;
    form.value.groupRejectList = [];
    form.value.qualifiedNum = 0;
  }
  if (form.value.status == 0) {
    form.value.endTime = null;
    form.value.startTime = null;
    workingHoursTime.value = "0小时0分钟0秒";
    form.value.workingHours = 0;
    form.value.groupRejectList = [];
    form.value.qualifiedNum = 0;
    form.value.equipmentDetailId = null;
    form.value.equipmentDetailCode = null;
  }
}

/** 取消按钮 */
const handleCancel = () => {
  visible.value = false;
  dayworkItemList.value = [];
  reset();
};

/** 暴露给父组件的方法 */
defineExpose({
  open,
});
</script>
<style scoped>
.el-select-v2__placeholder {
  display: flex !important;
}
</style>
