<template>
  <div class="body">
    <!-- <div v-for="(box, index) in drawingData" :key="index" class="suit-box">
        <div class="pdf-box">
          <PDFView
            :need-to-show-pdf="true"
            :pdf-source="baseUrl + box.pdfPath"
          />
        </div>
        <div class="suit-title">{{ box?.drawingTitle }}</div>
        <div class="suit-desc">{{ box?.created }}</div>
      </div> -->
    <div v-if="!checkName" class="checkBody">
      <div class="titleText" style="text-align: center; margin-bottom: 20px">
        请先扫描铭牌或输入工牌号：
      </div>
      <ScanCodeInput v-model="inputValue" @keyup.enter="handleSubmit" />
    </div>
    <div v-else class="checkForm">
      <div v-if="!editStatus" class="headerName">
        <div class="titleText">当前检验人：{{ checkName }}</div>
        <div
          class="titleText"
          style="margin-right: 15%; display: flex; align-items: center"
        >
          检验类型：
          <el-select
            v-model="checkType"
            placeholder="Select"
            style="width: 100px; font-size: 16px"
            @change="
              search.page = 1;
              getPagination();
            "
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              style="color: black; font-size: 16px"
            />
          </el-select>
        </div>

        <div
          class="titleText"
          style="color: red; cursor: pointer"
          @click="logOff"
        >
          注销
        </div>
      </div>
      <div v-if="!editStatus" class="content">
        <div>
          <el-button
            class="sureBtn"
            style="margin-bottom: 10px"
            type="success"
            @click="addCheck"
            >新 增
          </el-button>
        </div>
        <el-table
          :data="dataList"
          style="height: calc(100vh - 250px); border-radius: 16px"
        >
          <el-table-column label="序号" type="index" width="80" />
          <el-table-column label="检验项名称" prop="checkName" />
          <el-table-column label="检验项内容" prop="checkContent" />
          <el-table-column label="流转卡号" prop="seqNo" />
          <el-table-column label="备注" prop="remark" />
          <el-table-column label="附件" prop="filePath">
            <template #default="scope">
              <span
                v-if="scope.row.filePath"
                class="opera"
                @click="downLoad(scope.row.filePath)"
                >下载</span
              >
              <span v-else>无附件</span>
            </template>
          </el-table-column>
          <el-table-column label="结果" prop="result">
            <template #default="scope">
              <span
                :style="{ color: scope.row.result == '1' ? 'green' : 'red' }"
                >{{ scope.row.result == "1" ? "合格" : "不合格" }}</span
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <span class="opera" @click="editCheck(scope.row)">编辑</span>
              <span
                class="opera"
                style="color: red"
                @click="deleteCheck(scope.row.id)"
                >删除</span
              >
            </template>
          </el-table-column>
          <template #empty>
            <div class="empty">
              <Empty />
            </div>
          </template>
        </el-table>
        <Pagination
          :limit="search.limit"
          :page="search.page"
          :position="'right'"
          :total="search.total"
          @pagination="getPagination"
        />
      </div>
      <div v-if="editStatus" class="headerName">
        <div class="titleText">当前检验人：{{ checkName }}</div>
        <div
          class="titleText"
          style="margin-right: 15%; display: flex; align-items: center"
        >
          操作类型：{{ editType == "add" ? "新增" : "修改" }}
        </div>
        <div></div>
      </div>
      <div v-if="editStatus" class="content">
        <div class="form">
          <div class="formContent">
            <el-scrollbar style="height: calc(100vh - 200px); padding: 20px">
              <CheckForm ref="formRef" v-model="formData" />
            </el-scrollbar>
          </div>
          <div class="btns">
            <el-button class="sureBtn" type="primary" @click="submit"
              >提 交
            </el-button>
            <el-button class="sureBtn" type="info" @click="toBack"
              >返 回
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {
  addCheckList,
  checkUser,
  deleteCheckList,
  editCheckList,
  getCheckList,
} from "@/api/inspect";
import { useProcessStore } from "@/store/modules/processView";
import { useInspectStore } from "@/store/modules/inspect";
import { downloadFile } from "@/utils/downLoad";
import CheckForm from "./components/checkForm.vue";

const formRef = ref(null);
const formData = ref({});
const checkName = ref(null);
const checkType = ref("first_check");
const editStatus = ref(false);
const editCheck = async (row) => {
  editStatus.value = true;
  editType.value = "edit";
  formData.value = row;
  if (row.filePath) {
    setTimeout(() => {
      formRef.value.setFileList([{ name: row.fileName }]);
    }, 0);
  }
};
const search = ref({
  limit: 10,
  page: 1,
  total: 0,
});
const downLoad = async (url) => {
  let resUrl = url;
  await downloadFile(resUrl, "附件");
};
const addCheck = () => {
  formData.value = { ...checkObj };
  editStatus.value = true;
  editType.value = "add";
};
const check = () => {
  return new Promise(async (resolve, reject) => {
    await formRef.value.formRef.validate((valid) => {
      if (valid) {
        resolve();
      } else {
        ElMessage.error("请检查表单");
        reject();
      }
    });
  });
};
const reset = () => {
  formData.value = {};
  editStatus.value = false;
  editType.value = "add";
  getPagination();
};
const addCheckAsync = async () => {
  const { data, code } = await addCheckList({
    ...formData.value,
    checkType: checkType.value,
    operationId: processStore.odersData.operationId,
    workOrderCode: processStore.odersData.workOrderCode,
    operator: checkName.value,
    processId: processStore.scanInfo.id,
    fileName: fileName.value,
    operationName: processStore.scanInfo.operationName,
  });
  if (code == "200") {
    ElMessage.success("操作成功！");
  }
};
const deleteCheck = (id) => {
  deleteCheckAsync(id);
};
const deleteCheckAsync = async (id) => {
  const { data, code } = await deleteCheckList({
    id,
  });
  if (code == "200") {
    ElMessage.success("操作成功！");
    getPagination();
  }
};
const editCheckAsync = async () => {
  const { data, code } = await editCheckList({
    ...formData.value,
    checkType: checkType.value,
    operationId: processStore.odersData.operationId,
    workOrderCode: processStore.odersData.workOrderCode,
    operator: checkName.value,
    processId: processStore.scanInfo.id,
    fileName: fileName.value,
    operationName: processStore.scanInfo.operationName,
  });
  if (code == "200") {
    ElMessage.success("操作成功！");
  }
};
const fileName = ref("");
provide("fileName", fileName);
const submit = async () => {
  check().then(async () => {
    if (editType.value == "add") {
      await addCheckAsync();
      reset();
    } else {
      await editCheckAsync();
      reset();
    }
  });
};
const checkObj = {
  checkContent: "",
  checkName: "",
  checkType: "",
  filePath: "",
  result: "",
  seqNoList: [],
};
const dataList = ref([]);
const getPagination = async () => {
  const { data } = await getCheckList({
    checkType: checkType.value,
    pageNo: search.value.page,
    pageSize: search.value.limit,
    operationId: processStore.odersData.operationId,
    workOrderCode: processStore.odersData.workOrderCode,
    seqNo: processStore.useSeqNo,
    operationName: processStore.scanInfo.operationName,
  });
  search.value.total = data.totalCount;
  dataList.value = data.records;
};
const inspectStore = useInspectStore();
const processStore = useProcessStore();
const editType = ref("add");
const toBack = () => {
  editStatus.value = false;
};
//add 或者edit
const options = [
  {
    value: "first_check",
    label: "首检",
  },
  {
    value: "inspection",
    label: "巡检",
  },
  {
    value: "self_check",
    label: "自检",
  },
  {
    value: "special_inspection",
    label: "专检",
  },
  {
    value: "mutual_inspection",
    label: "互检",
  },
];
const inputValue = ref("");
const handleSubmit = () => {
  inputValue.value = inputValue.value.trim();
  checkUserVal();
};
const logOff = () => {
  checkName.value = "";
  inspectStore.checkName = "";
};

// const drawingData = ref<any>([]);
const checkUserVal = async () => {
  setTimeout(() => {
    inputValue.value = "";
  }, 0);
  const { data, code, msg } = await checkUser({
    employeeCode: inputValue.value,
  });
  if (code == "200") {
    ElMessage.success("记录成功！请开展检验操作");
    inspectStore.checkName = data.userName;
    checkName.value = data.userName;
  } else {
    ElMessage.error(msg);
  }
};
// const baseUrl = import.meta.env.VITE_APP_UPLOAD_URL;

onMounted(() => {
  if (inspectStore.checkName) {
    checkName.value = inspectStore.checkName;
  }
});
watch(checkName, (val) => {
  if (val !== "") {
    getPagination();
  }
});
onUnmounted(() => {
  inspectStore.checkName = "";
});
</script>

<style lang="scss" scoped>
.opera {
  font-size: 20px;
  margin-right: 10px;
  cursor: pointer;
  color: rgb(64, 158, 255);
}

.sureBtn {
  border-radius: 16px;
  font-size: 16px;
  font-size: 500;
}

.body {
  width: 100vw;
  height: calc(100vh - 120px);
  display: flex;
  align-items: center;
  justify-content: center;

  .checkBody {
    width: 30vw;
    align-items: center;
    justify-content: center;
  }

  .checkForm {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;

    .headerName {
      width: 100%;
      height: 40px;
      background-color: white;
      border-radius: 20px;
      lighting-color: 40px;
      padding: 0 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .content {
      flex: 1;
      padding: 20px;

      .form {
        width: 800px;
        height: 100%;
        margin: 0 auto;
        background-color: white;
        border-radius: 16px;
        display: flex;
        flex-direction: column;

        .formContent {
          flex: 1;
        }

        .btns {
          width: 100%;
          height: 60px;
          display: flex;
          align-items: center;
          padding: 0 20%;
          justify-content: space-evenly;
        }
      }
    }
  }
}
</style>
