<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">
          <span style="font-weight: bold; font-size: 18px">批次号：{{ detailInfo.lotCode }}</span>
        </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 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="findTechnologicalProcessName">
              <el-select-v2 v-model="detailInfo.findTechnologicalProcessName" :options="findProcessList"
                @change="selectFindProcess" placeholder="请选择工序" :disabled="detailInfo.findDeptId == null"
                style="width: 140px">
                <template #default="{ index, item }">
                  <span style="float: left">{{ index + 1 }}</span>
                  <span style="margin-left: 8px">{{ item.label }}</span>
                </template>
              </el-select-v2>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发现人" label-width="100px">
              <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" @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-select
                v-model="detailInfo.findUserId"
                filterable
                remote
                reserve-keyword
                placeholder="请选发现人"
                collapse-tags-tooltip
                collapse-tags
                :remote-method="(arg) => selectUsere(arg)"
                :loading="loadingCarrier"
                @change="handleselectUsereChange"
              >
                <el-option
                  v-for="dict in userList"
                  :key="dict.userid"
                  :label="dict.userName"
                >
                  <template #suffix>
                    <span>{{ dict.userName }} - {{ dict.nickName }}</span>
                  </template>
                </el-option>
              </el-select> -->
            </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 v-model="detailInfo.deptName" :options="deptList" placeholder="请选择工段" @change="getProcess"
                style="width: 140px" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="责任工序" label-width="100px" prop="technologicalProcessName">
              <el-select-v2 v-model="detailInfo.technologicalProcessName" :options="processList" placeholder="请选择工序"
                :disabled="detailInfo.deptId == null" @change="selectProcess" style="width: 140px">
                <template #default="{ index, item }">
                  <span style="float: left">{{ index + 1 }}</span>
                  <span style="margin-left: 8px">{{ item.label }}</span>
                </template>
              </el-select-v2>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="废品数量" label-width="100px" prop="rejectNum">
              <el-input-number 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 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" placeholder="请输入填写人" 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"
                placeholder="请选择填写时间" style="width: 150px" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <template #footer>
      <el-button type="primary" icon="Check" @click="handleSave">保存</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 } from "@/api/business/noCurrentReject";
import useUserStore from "@/store/modules/user";
import { ref } from "vue";
import { save } from "../../../api/business/noCurrentReject";
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 userList = ref([]);
const loading = ref(false);
const editStatus = ref(true);
const visible = ref(false);
const data = reactive({
  form: {},
  rules: {
    deptId: [{ required: true, message: "责任工段不能为空", trigger: "blur" }],
    technologicalProcessName: [
      { required: true, message: "责任工序不能为空", trigger: "blur" },
    ],
    findDeptName: [
      { required: true, message: "发现工段不能为空", trigger: "blur" },
    ],
    findTechnologicalProcessName: [
      { 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) {
    // getInfo(row.id).then((res) => {
    //   if (res.code == 200) {
    //     detailInfo.value = res.data;
    //     getProcess(detailInfo.value.deptId)
    //     getFindProcess(detailInfo.value.findDeptId)
    //   }
    // });
    // //查工段
    // getDeptInfo({ dayworkId: row.dayworkId }).then((res) => {
    //   deptList.value = res.data;
    //   console.log("deptList.value", deptList.value);
    // });
    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
        getProcess(detailInfo.value.deptId)
        getFindProcess(detailInfo.value.findDeptId)
      }
    })


    visible.value = true;
  }
};

const add = (row) => {
  reset();
  if (row.id) {
    lotParticulars(row.lotCode).then((res) => {
      if (res.code == 200) {
        detailInfo.value = res.data;
        detailInfo.value.companyAlias = detailInfo.value.daywork.companyAlias;
        detailInfo.value.productDescription =
          detailInfo.value.daywork.productDescription;
        detailInfo.value.productionPlanNo =
          detailInfo.value.daywork.productionPlanNo;
        // detailInfo.value.deptName = detailInfo.value.daywork.deptName;
        detailInfo.value.dayworkId = row.id;
        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;
      }
    });

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

    visible.value = true;
  }
};

/** 输入框输出建议 */
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 getProcess(value) {
  detailInfo.value.technologicalProcessId = null;

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

  detailInfo.value.deptId = foundProcess.value;
  detailInfo.value.deptName = foundProcess.label;

  getDayworkProcessList({
    id: detailInfo.value.dayworkId,
    deptId: detailInfo.value.deptId,
  }).then((response) => {
    processList.value = response.data;
  });
}

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.value === value
  );
  detailInfo.value.findTechnologicalProcessId = foundProcess.value;
  detailInfo.value.findTechnologicalProcessName = foundProcess.label;
}

//获得工序
function getFindProcess(value) {
  detailInfo.value.findTechnologicalProcessId = 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,
  };
  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>
