<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 type="primary" icon="Check" style="margin-right: 10px" @click="handleSave">保 存
        </el-button>
        <el-button icon="Close" @click="handleCancel">取 消
        </el-button>
      </div>
      <!-- 主表 -->
      <el-form ref="dayworkItemRef" class="master-container" :model="form" :rules="rules" :show-message="true">
        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="开始时间：" prop="startTime">
              <el-date-picker v-model="form.startTime" :disabled="!editStatus" type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss" :clearable="false" :editable="false" placeholder="请选择开始时间"
                @change="handleTotalTime" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生产工序：" prop="processId" label-width="90px">
              {{ form.processAlias }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="辅助工序：" prop="processId" label-width="90px">
              {{ form.auxiliaryProcessAlias }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="生产状态：" prop="status" align="center">
              <el-select v-model="form.status" placeholder="请选择生产状态" :disabled="true" style="width: 220px"
                @change="handleChangeStatus">
                <el-option v-for="dict in dynamicOptions" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结束时间：" prop="endTime" label-width="90px">
              <el-date-picker v-model="form.endTime" :disabled="!editStatus" type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss" :editable="false" :clearable="false" placeholder="请选择结束时间"
                @change="handleTotalTime" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="操作者:" prop="nickName" label-width="82px">
              <el-input v-model.trim="form.nickName" placeholder="请输入操作者" readonly :clearable="true"
                style="width: 220px; margin-left: 8px">
                <template #append>
                  <el-button icon="Search" @click="handleSelectUserSingle" />
                </template></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="投产数量：" prop="endTime">
              <div>{{ form.prodNum }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合格数量：" prop="endTime" label-width="90px">
              <el-input-number :disabled="!editStatus" v-model="form.qualifiedNum" style="width: 220px;" :step="1"
                step-strictly :controls="false" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="废品数量：" prop="endTime" label-width="90px">
              <el-input-number :disabled="true" v-model="form.rejectNum" :step="1" style="width: 220px;" step-strictly
                :controls="false" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 搜索区域 -->
      <el-form class="list-search-container" :inline="true">
        <el-form-item class="section-title" label="废品信息" />
      </el-form>
      <!-- 列表区 -->
      <div class="el-table-container">
        <el-table ref="dayworkItemRejectTable" v-loading="loading" row-key="id" :data="form.groupRejectList"
          height="100%" @row-click="showRejectList">
          <el-table-column type="index" label="行号" width="60" align="center">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="dayworkItem.nickName" label="生产工序加工人" align="center"></el-table-column>
          <el-table-column prop="dayworkItem.startTime" label="开始时间" align="center"></el-table-column>
          <el-table-column prop="dayworkItem.endTime" label="结束时间" align="center"></el-table-column>
          <el-table-column prop="rejectNum" label="废品数量" align="center">
            <template #default="scope">
              <div v-if="!editStatus"> {{ scope.row.rejectNum }}</div>
              <!-- <el-input-number v-else v-model="scope.row.rejectNum" style="width: 100px" :step="1" step-strictly
                :controls="false" @change="handleChangeRejectNum(scope.row)" /> -->
              <el-button v-else type="primary" link > {{ scope.row.rejectNum
                }}</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="qualifiedNum" label="合格数量" align="center"></el-table-column>
          <!-- <el-table-column fixed="right" label="操作" align="center">
            <template #default="scope">
              <el-button link type="danger" icon="Delete" :disabled="!editStatus"
                @click="handleDeleteReject(scope.row)">删除
              </el-button>
            </template>
          </el-table-column> -->
        </el-table>
      </div>
      <!-- 搜索人员弹窗 -->
      <dialog-person ref="dialogPersonRef" :single-selected="handleGetUser" />
      <reject-edit-dialog ref="rejectEditDialogRef" @submit="refreshHandle" />
    </div>
  </el-drawer>
</template>
<script setup>
import {
  getDayworkItemInfo,
  updateDayworkItemInfo
} from "@/api/business/dayworkAuxiliaryItem.js";
import { ref } from "vue";
import dialogPerson from "./person.vue"
import rejectEditDialog from "./RejectEditDialog.vue";
import { isStaticProperty } from "@vue/compiler-sfc";

const { proxy } = getCurrentInstance();
const emit = defineEmits(["handleSaveSuccess"]);
/** 字典 */
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 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 rejectEditDialogRef = ref(null)
const detailsRow = {
  id: null,
  rejectNum: "",
  reason: "",
};
// const validateprodNum = (rule, value, callback) => {
//   if (value <= 0) {
//     callback(new Error("投产量应大于0"));
//   } else {
//     callback();
//   }
// };

function refreshHandle() {
  loading.value = true;
  if (form.value.id) {
    getDayworkItemInfo(form.value.id).then(
      (response) => {
        loading.value = false;
        if (response.code == 200) {
          // for (let i = 0; i < response.data.length; i++) {
          //   response.data[i].rejectNum = parseInt(response.data[i].rejectNum);
          // }
          form.value = response.data
          form.value.groupRejectList = response.data.rejectList
          console.log(form.value)
          if (form.value.status == '3') {
            editStatus.value = true
          } else {
            editStatus.value = false
          }
        }
      }
    );
  }
}

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();
  loading.value = true;
  dynamicOptions.value = daywork_status_first.value;
  console.log(daywork_status_first)
  console.log(daywork_status_second)
  console.log(daywork_status_edit)
  if (row.id) {
    getDayworkItemInfo(row.id).then(
      (response) => {
        if (response.code == 200) {
          // for (let i = 0; i < response.data.length; i++) {
          //   response.data[i].rejectNum = parseInt(response.data[i].rejectNum);
          // }
          form.value = response.data
          form.value.groupRejectList = response.data.rejectList
          console.log(form.value)
          if (form.value.status == '3') {
            editStatus.value = true
          } else {
            editStatus.value = false
          }
        }
      }
    );
    loading.value = false;
    visible.value = true;
  }
};
//操作者人员带回
function handleGetUser(selection) {
  form.value.nickName = selection.nickName;
  form.value.userId = selection.userId;
  form.value.userName = selection.userName;
}
function handleSelectUserSingle() {
  proxy.$refs.dialogPersonRef.open()
}

function handleChangeRejectNum(row) {
  let sumReject = 0;
  form.value.groupRejectList.forEach(t => {
    sumReject += t.rejectNum
  })
  form.value.rejectNum = sumReject
}
/**
 * 对话框关闭 事件
 */
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;

      form.value.workingHours = form.value.workHoursTimestamp;
      if (flag) {
        updateDayworkItem();
      }
    }
  });
};

//页面提交方法
function updateDayworkItem() {
  updateDayworkItemInfo(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;
  reset();
}

const showRejectList = (row) => {
  console.log(row)
  rejectEditDialogRef.value.open({ ...row, lotId: form.value.lotId, productionPlanDetailId: form.value.productionPlanDetailId })
}

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