<template>
  <el-dialog
    title="添加非本序废品信息"
    v-model="visible"
    width="1000px"
    append-to-body
    draggable
    v-loading="loading"
  >
    <div class="form-container">
      <div style="padding: 16px 16px 0 16px">
        <el-row :gutter="20">
          <div style="width: 90%">
            <span style="font-weight: bold; font-size: 18px"
              >批次号：{{ detailInfo.lotCode }}</span
            >
          </div>

          <div style="float: right">
            <el-tag
              v-if="detailInfo.status == 0 && detailInfo.id != null"
              class="spacing"
              type="warning"
              >{{ "审核中" }}</el-tag
            >
            <el-tag
              v-if="detailInfo.status == 0 && detailInfo.id == null"
              class="spacing"
              type="primary"
              >{{ "待确认" }}</el-tag
            >
            <el-tag
              v-if="detailInfo.status == 1"
              class="spacing"
              type="success"
              >{{ "已通过" }}</el-tag
            >
            <el-tag
              v-if="detailInfo.status == 2"
              class="spacing"
              type="danger"
              >{{ "已拒绝" }}</el-tag
            >
          </div>
        </el-row>
        <el-row :gutter="20" style="margin-top: 15px">
          <span style="font-weight: bold">基础信息</span>
        </el-row>
        <el-row
          :gutter="20"
          style="
            margin-top: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid #999;
          "
        >
          <el-col :span="11">
            <span class="leftInfo">客户简称</span>
            <span class="rightInfo">{{ detailInfo.companyAlias }}</span>
          </el-col>
          <el-col :span="6">
            <span class="middleInfo">生产计划单号</span>
            <span class="rightInfo">{{ detailInfo.productionPlanNo }}</span>
          </el-col>
          <el-col :span="7">
            <span class="middleInfo">批次号</span>
            <span class="rightInfo">{{ detailInfo.lotCode }}</span>
          </el-col>
        </el-row>
        <el-row
          :gutter="20"
          style="
            margin-top: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid #999;
          "
        >
          <el-col :span="11">
            <span class="leftInfo">产品描述</span>
            <span class="rightInfo">{{ detailInfo.productDescription }}</span>
          </el-col>
          <el-col :span="6">
            <span class="middleInfo">图纸版本</span>
            <span class="rightInfo">{{ detailInfo.technologyVersion }}</span>
          </el-col>
          <el-col :span="7">
            <span class="middleInfo">批次投产量</span>
            <span class="rightInfo">{{ detailInfo.productionQuantity }}</span>
          </el-col>
        </el-row>
        <el-row
          :gutter="20"
          style="
            margin-top: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid #999;
          "
        >
          <el-col :span="11">
            <span class="leftInfo">下达日期</span>
            <span class="rightInfo">{{ detailInfo.createTime }}</span>
          </el-col>
          <!-- <el-col :span="6">
            <span class="middleInfo">当前工段</span>
            <span class="rightInfo">{{ detailInfo.deptName }}</span>
          </el-col> -->
          <!-- <el-col :span="7">
            <span class="middleInfo">当前工序投产量</span>
            <span class="rightInfo">{{
              detailInfo.temporaryProcessQualifiedNum
            }}</span>
          </el-col> -->
        </el-row>
        <el-row :gutter="20" style="margin-top: 20px; margin-bottom: 20px">
          <span style="font-weight: bold">废品信息</span>
        </el-row>
      </div>
      <el-form
        ref="noCurrent"
        v-loading="loading"
        class="master-container"
        :model="detailInfo"
        :rules="rules"
        label-width="80px"
      >
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item
              label="发现工段"
              label-width="80px"
              prop="findDeptName"
            >
              <el-select-v2
                :disabled="
                  detailInfo.status > 0 ||
                  (detailInfo.id != null && isCurrentDept) ||
                  (detailInfo.id != null &&
                    detailInfo.creatorId != useUserStore().user.userId)
                "
                v-model="detailInfo.findDeptName"
                :options="deptList"
                placeholder="请选择工段"
                @change="getFindProcess"
                style="width: 140px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="发现工序"
              label-width="100px"
              prop="findProcessStepNumber"
            >
              <el-select
                :disabled="
                  detailInfo.status > 0 ||
                  (detailInfo.id != null && isCurrentDept) ||
                  (detailInfo.id != null &&
                    detailInfo.creatorId != useUserStore().user.userId)
                "
                v-model="detailInfo.findProcessStepNumber"
                placeholder="请选择工序"
                @change="selectFindProcess"
                style="width: 140px"
              >
                <el-option
                  v-for="(item, index) in findProcessList"
                  :key="item.processStepNumber"
                  :label="item.processAlias"
                  :value="item.processStepNumber"
                >
                  <!-- 自定义选项内容 -->
                  <template #default>
                    <span style="float: left">{{ index + 1 }}</span>
                    <span style="margin-left: 8px">{{
                      item.processAlias
                    }}</span>
                  </template>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="发现人"
              label-width="100px"
              prop="findUserName"
            >
              <el-autocomplete
                v-if="editStatus && type !== 'alterOrder'"
                :fetch-suggestions="querySearchAsync"
                :trigger-on-focus="true"
                style="width: 100%"
                v-model="detailInfo.findUserName"
                placeholder="选择人员"
                popper-class="my-autocomplete"
                :disabled="
                  detailInfo.status > 0 ||
                  (detailInfo.id != null && isCurrentDept) ||
                  (detailInfo.id != null &&
                    detailInfo.creatorId != useUserStore().user.userId)
                "
                @select="handleSelectEmployee"
              >
                <template #default="{ item }">
                  <div
                    style="
                      display: flex;
                      flex-direction: row;
                      justify-content: space-between;
                    "
                  >
                    <div class="name" style="font-size: 12px">
                      {{ item.nickName }}
                    </div>
                    <span
                      class="code"
                      style="font-size: 10px; color: darkgrey"
                      >{{ item.userName }}</span
                    >
                  </div>
                </template>
              </el-autocomplete>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="责任工段" label-width="80px" prop="deptId">
              <el-select-v2
                :disabled="
                  detailInfo.status > 0 ||
                  (detailInfo.id != null && isCurrentDept) ||
                  (detailInfo.id != null &&
                    detailInfo.creatorId != useUserStore().user.userId)
                "
                v-model="detailInfo.deptId"
                :options="deptList"
                placeholder="请选择工段"
                @change="handleChangeDept"
                style="width: 140px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="责任工序"
              label-width="100px"
              prop="processStepNumber"
            >
              <el-select
                :disabled="
                  detailInfo.status > 0 ||
                  (detailInfo.id != null && isCurrentDept) ||
                  (detailInfo.id != null &&
                    detailInfo.creatorId != useUserStore().user.userId)
                "
                v-model="detailInfo.processStepNumber"
                placeholder="请选择工序"
                @change="getFindUser"
                style="width: 140px"
              >
                <el-option
                  v-for="(item, index) in processList"
                  :key="item.processStepNumber"
                  :label="item.processAlias"
                  :value="item.processStepNumber"
                >
                  <!-- 自定义选项内容 -->
                  <template #default>
                    <span style="float: left">{{ index + 1 }}</span>
                    <span style="margin-left: 8px">{{
                      item.processAlias
                    }}</span>
                  </template>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="责任人" label-width="100px">
              <el-select
                :disabled="
                  detailInfo.status > 0 ||
                  (detailInfo.id != null &&
                    detailInfo.creatorId != useUserStore().user.userId &&
                    !isCurrentDept)
                "
                v-if="detailInfo.isWx == 0"
                v-model="detailInfo.userIds"
                multiple
                placeholder="请选择"
              >
                <el-option
                  v-for="item in userList"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId"
                >
                  <template #default>
                    <span style="float: left">{{ item.userName }}</span>
                    <span style="margin-left: 8px">{{ item.nickName }}</span>
                  </template></el-option
                >
              </el-select>
              <el-select
                :disabled="
                  detailInfo.status > 0 ||
                  (detailInfo.id != null &&
                    detailInfo.creatorId != useUserStore().user.userId &&
                    !isCurrentDept)
                "
                v-if="detailInfo.isWx == 1"
                v-model="detailInfo.supplierIds"
                multiple
                placeholder="请选择"
              >
                <el-option
                  v-for="item in userList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                  <template #default>
                    <span style="float: left">{{ item.code }}</span>
                    <span style="margin-left: 8px">{{ item.name }}</span>
                  </template></el-option
                >
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="废品数量" label-width="80px" prop="rejectNum">
              <el-input-number
                :disabled="
                  detailInfo.status > 0 ||
                  (detailInfo.id != null && isCurrentDept) ||
                  (detailInfo.id != null &&
                    detailInfo.creatorId != useUserStore().user.userId)
                "
                v-model="detailInfo.rejectNum"
                :min="1"
                :max="detailInfo.productionQuantity"
                :decimal="false"
                :step="1"
                step-strictly
                label="数量"
                style="width: 140px"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-form-item label="废品原因" label-width="90px" prop="remark">
            <el-input
              :disabled="
                detailInfo.status > 0 ||
                (detailInfo.id != null && isCurrentDept) ||
                (detailInfo.id != null &&
                  detailInfo.creatorId != useUserStore().user.userId)
              "
              type="textarea"
              placeholder="请输入批废原因"
              maxlength="200"
              show-word-limit
              v-model.trim="detailInfo.remark"
              style="width: 495px"
            />
          </el-form-item>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="填写人" label-width="80px" prop="fillName">
              <el-input
                :disabled="true"
                v-model.trim="detailInfo.fillName"
                style="width: 140px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="填写日期" label-width="100px" prop="fillDate">
              <el-date-picker
                v-model="detailInfo.fillDate"
                :disabled="true"
                type="date"
                value-format="YYYY-MM-DD"
                style="width: 150px"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="审核人" label-width="80px" prop="reviewName">
              <el-input
                :disabled="true"
                v-model.trim="detailInfo.reviewName"
                style="width: 140px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item
              label="审核日期"
              label-width="100px"
              prop="reviewDate"
            >
              <el-date-picker
                v-model="detailInfo.reviewDate"
                :disabled="true"
                type="date"
                value-format="YYYY-MM-DD"
                style="width: 150px"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <template #footer>
      <el-button
        v-if="
          (detailInfo.id == null ||
            detailInfo.creatorId == useUserStore().user.userId) &&
          detailInfo.status == 0
        "
        type="primary"
        icon="Check"
        @click="handleSave"
        >保存</el-button
      >
      <el-button
        v-if="detailInfo.id != null && isCurrentDept && detailInfo.status == 0"
        type="success"
        icon="Check"
        @click="handleReview(1)"
        >通过</el-button
      >
      <el-button
        v-if="detailInfo.id != null && isCurrentDept && detailInfo.status == 0"
        type="danger"
        icon="Close"
        @click="handleReview(2)"
        >拒绝</el-button
      >
      <el-button icon="Close" @click="handleCancel">取 消</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { getDeptInfo } from "@/api/business/daywork.js";
import { getDayworkProcessList } from "@/api/business/daywork.js";
import { lotParticulars } from "@/api/business/technologicalAmend.js";
import {
  selectUserList,
  getInfo,
  getUserByProcessStepNumber,
} from "@/api/business/noCurrentReject";
import { getDeptList } from "@/api/business/planDetailSubDetail.js";
import useUserStore from "@/store/modules/user";
import { ref } from "vue";
import { save, updateReject } from "../../../api/business/noCurrentReject";
import { has } from "lodash-es";
import { use } from "vxe-table";
const { proxy } = getCurrentInstance();
const emit = defineEmits(["handleSaveSuccess"]);
/** 字典数组区 */
const { is_allow_more } = proxy.useDict("is_allow_more");
/** 废批*/
const deptList = ref([]);
const detailInfo = ref({});
const processList = ref([]);
const findProcessList = ref([]);
const isCurrentDept = ref(false); //是否可以审核
const currentDeptList = ref([]);
const userList = ref([]);
const loading = ref(false);
const editStatus = ref(true);
const visible = ref(false);
const data = reactive({
  form: {},
  rules: {
    deptId: [
      { required: true, message: "责任工段不能为空", trigger: "change" },
    ],
    technologicalProcessName: [
      { required: true, message: "责任工序不能为空", trigger: "change" },
    ],
    findDeptName: [
      { required: true, message: "发现工段不能为空", trigger: "change" },
    ],
    findUserName: [
      { required: true, message: "发现人不能为空", trigger: "change" },
    ],
    findTechnologicalProcessName: [
      { required: true, message: "发现工序不能为空", trigger: "change" },
    ],
    processStepNumber: [
      { required: true, message: "责任工序不能为空", trigger: "change" },
    ],
    findProcessStepNumber: [
      { required: true, message: "发现工序不能为空", trigger: "change" },
    ],
    remark: [{ required: true, message: "废品原因不能为空", trigger: "blur" }],
    rejectNum: [{ required: true, message: "废品不能为空", trigger: "blur" }],
  },
});
const { form, rules } = toRefs(data);

/***********************  方法区  ****************************/
/** 打开抽屉 */
const open = (row) => {
  reset();
  console.log("row", row);
  if (row.id) {
    Promise.all([
      getInfo(row.id),
      getDeptInfo({ dayworkId: row.dayworkId }),
    ]).then((res) => {
      if (res[0].code == 200 && res[1].code == 200) {
        deptList.value = res[1].data;
        detailInfo.value = res[0].data;
        userList.value =
          res[0].data.supplierList && res[0].data.supplierList.length > 0
            ? res[0].data.supplierList
            : res[0].data.dayworkItemList &&
              res[0].data.dayworkItemList.length > 0
            ? res[0].data.dayworkItemList
            : [];
        console.log(userList.value);
        getDeptList().then((response) => {
          currentDeptList.value = response.data.rows;
          //判断是否显示审核按钮
          hasCurrentDept();
        });
        getProcessList();

        // handleChangeDept(detailInfo.value.deptId);
        // getFindProcess(detailInfo.value.findDeptId)
      }
    });

    visible.value = true;
  }
};
//获取工序集合
function getProcessList() {
  getDayworkProcessList({
    id: detailInfo.value.dayworkId,
    deptId: detailInfo.value.deptId,
  }).then((response) => {
    processList.value = response.data;
  });
  getDayworkProcessList({
    id: detailInfo.value.dayworkId,
    deptId: detailInfo.value.findDeptId,
  }).then((response) => {
    findProcessList.value = response.data;
  });
}
const add = (row) => {
  console.log("uwer", useUserStore().user);
  reset();
  if (row.id) {
    lotParticulars(row.lotCode).then((res) => {
      if (res.code == 200) {
        detailInfo.value = res.data;
        detailInfo.value.companyAlias =
          detailInfo.value.productionPlanDetail.companyAlias;
        detailInfo.value.productDescription =
          detailInfo.value.productionPlanDetail.productDescription;
        detailInfo.value.productionPlanNo =
          detailInfo.value.productionPlanDetail.productionPlanNo;
        // detailInfo.value.deptName = detailInfo.value.daywork.deptName;
        detailInfo.value.dayworkId = row.id;
        detailInfo.value.status = 0;
        detailInfo.value.isWx = 0;
        detailInfo.value.technologicalProcessId = null;
        detailInfo.value.deptId = null;
        detailInfo.value.fillDate = proxy.moment().format("YYYY-MM-DD");
        detailInfo.value.fillName = useUserStore().user.nickName;
        detailInfo.value.id = null;
        console.log(detailInfo.value, "999");
      }
    });

    //查工段
    getDeptInfo({ dayworkId: row.id }).then((res) => {
      deptList.value = res.data;
      console.log("deptList.value", deptList.value);
    });

    visible.value = true;
  }
};
//审核
function handleReview(value) {
  //审核责任人不能为空
  console.log(detailInfo.value);
  if (
    (detailInfo.value.userIds && detailInfo.value.userIds.length == 0) ||
    (detailInfo.value.supplierIds && detailInfo.value.supplierIds.length == 0)
  ) {
    proxy.$modal.msgError("责任人不能为空");
    return;
  }
  detailInfo.value.status = value;
  detailInfo.value.reviewDate = proxy.moment().format("YYYY-MM-DD");
  detailInfo.value.reviewName = useUserStore().user.nickName;
  detailInfo.value.reviewId = useUserStore().user.userId;
  updateReject(detailInfo.value).then((res) => {
    proxy.$modal.msgSuccess("审核成功");
    visible.value = false;
    emit("handleSaveSuccess");
  });
}
//获取责任用户
function getUser() {
  getUserByProcessStepNumber({
    dayworkId: detailInfo.value.dayworkId,
    processStepNumber: detailInfo.value.processStepNumber,
    isWx: detailInfo.value.isWx,
  }).then((res) => {
    userList.value = res.data;
  });
}
//责任人下拉框
function getFindUser() {
  detailInfo.value.userIds = [];
  detailInfo.value.supplierIds = [];
  const foundProcess = processList.value.find(
    (process) =>
      process.processStepNumber === detailInfo.value.processStepNumber
  );
  detailInfo.value.technologicalProcessId = foundProcess.processId;
  detailInfo.value.technologicalProcessName = foundProcess.processAlias;
  getUser();
}

/** 输入框输出建议 */
function querySearchAsync(queryString, cb) {
  if (queryString) {
    selectUserList(queryString).then((res) => {
      cb(res.rows);
    });
  }
}
/** 输入框输出选择 */
function handleSelectEmployee(item) {
  detailInfo.value.findUserName = item.nickName;
  detailInfo.value.findUserId = item.userId;
}
//责任工段切换
function handleChangeDept(value) {
  detailInfo.value.technologicalProcessId = null;
  detailInfo.value.processStepNumber = null;
  detailInfo.value.supplierIds = [];
  detailInfo.value.userIds = [];
  userList.value = [];
  const foundProcess = deptList.value.find(
    (process) => process.value === value
  );
  detailInfo.value.deptName = foundProcess.label;
  if (foundProcess.isOutsourcing == 1 || foundProcess.code == "170000") {
    detailInfo.value.isWx = 1;
  } else {
    detailInfo.value.isWx = 0;
  }
  //判断是否显示审核按钮
  hasCurrentDept();
  getDayworkProcessList({
    id: detailInfo.value.dayworkId,
    deptId: detailInfo.value.deptId,
  }).then((response) => {
    processList.value = response.data;
  });
}
//获得工序
function getProcess() {
  detailInfo.value.technologicalProcessId = null;

  const foundProcess = deptList.value.find(
    (process) => process.value === value
  );

  detailInfo.value.deptId = foundProcess.value;
  detailInfo.value.deptName = foundProcess.label;
  //判断是否显示审核按钮
  hasCurrentDept();
  getDayworkProcessList({
    id: detailInfo.value.dayworkId,
    deptId: detailInfo.value.deptId,
  }).then((response) => {
    processList.value = response.data;
  });
}
function hasCurrentDept() {
  console.log(currentDeptList.value);
  console.log(detailInfo.value);
  //管理员
  if (useUserStore().user.userId == 1) {
    isCurrentDept.value = true;
  } else {
    currentDeptList.value.forEach((item) => {
      console.log(item.value, detailInfo.value.deptId);
      if (item.value == detailInfo.value.deptId) {
        isCurrentDept.value = true;
      }
    });
    console.log(isCurrentDept.value);
  }
}

function selectProcess(value) {
  const foundProcess = processList.value.find(
    (process) => process.value === value
  );

  detailInfo.value.technologicalProcessId = foundProcess.value;
  detailInfo.value.technologicalProcessName = foundProcess.label;
}

function selectFindProcess(value) {
  const foundProcess = findProcessList.value.find(
    (process) =>
      process.processStepNumber === detailInfo.value.findProcessStepNumber
  );
  detailInfo.value.findTechnologicalProcessId = foundProcess.processId;
  detailInfo.value.findTechnologicalProcessName = foundProcess.processAlias;
}

//获得工序
function getFindProcess(value) {
  console.log(value);
  detailInfo.value.findTechnologicalProcessId = null;
  detailInfo.value.findProcessStepNumber = null;
  const foundProcess = deptList.value.find(
    (process) => process.value === value
  );
  console.log("foundProcess", foundProcess);
  detailInfo.value.findDeptId = foundProcess.value;
  detailInfo.value.findDeptNmae = foundProcess.label;
  getDayworkProcessList({
    id: detailInfo.value.dayworkId,
    deptId: detailInfo.value.findDeptId,
  }).then((response) => {
    findProcessList.value = response.data;
  });
}

/** 取消按钮 */
function handleCancel() {
  visible.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  detailInfo.value = {
    id: null,
    technologicalProcessId: null,
    reason: "",
    deptId: null,
    fillDate: null,
    fillName: null,
    userIds: [],
  };
  isCurrentDept.value = false;
  deptList.value = [];
  userList.value = [];
  findProcessList.value = [];
  processList.value = [];
  proxy.resetForm("noCurrent");
}

/** 提交按钮 */
function handleSave() {
  console.log("detailInfo", detailInfo.value);
  proxy.$refs["noCurrent"].validate((valid) => {
    if (valid) {
      save(detailInfo.value).then((res) => {
        if (res.code == 200) {
          proxy.$message({
            message: "保存成功",
            type: "success",
          });
          visible.value = false;
          emit("handleSaveSuccess");
        }
      });
    }
  });
}

/** 暴露给父组件的方法 */
defineExpose({
  open,
  add,
});
</script>
<style scoped>
.leftInfo {
  color: #999;
  font-size: 16px;
  width: 120px;
  /* display: inline-block; */
}

.middleInfo {
  color: #999;
  font-size: 16px;
  width: 120px;
  display: inline-block;
}

.rightInfo {
  font-size: 16px;
  padding-left: 20px;
}
</style>
