<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <BreadcrumbBack />
      <span class="breadcrumb-title">查看劳防用品领用</span>
    </header>
    <main class="safety-platform-container__main">
      <el-form v-loading="loading" :model="form" label-width="120px" class="req-form">
        <el-form-item label="职业危害因素" prop="hazardFactor">
          <el-input v-model="form.hazardFactor" disabled />
        </el-form-item>
        <el-form-item label="发放人" prop="issuer">
          <el-select
            v-model="issuerUserId"
            placeholder="请选择发放人"
            filterable
            clearable
            disabled
            style="width: 100%"
          >
            <el-option
              v-for="u in issuerUserList"
              :key="u.id"
              :label="u.realname"
              :value="u.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发放时间" prop="issueTime">
          <el-input v-model="form.issueTime" disabled />
        </el-form-item>
        <el-form-item label="防护用品名称" prop="ppeName">
          <el-input v-model="form.ppeName" disabled />
        </el-form-item>
        <el-form-item label="型号" prop="version">
          <el-input v-model="form.version" disabled />
        </el-form-item>
        <el-form-item label="领用数量" prop="receiveNum">
          <el-input-number
            v-model="form.receiveNum"
            :min="1"
            :precision="0"
            disabled
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="领用人" prop="receiver">
          <el-select
            v-model="receiverUserId"
            placeholder="请选择领用人"
            filterable
            clearable
            disabled
            style="width: 100%"
          >
            <el-option
              v-for="u in receiverUserList"
              :key="u.id"
              :label="u.realname"
              :value="u.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用品状态" prop="status">
          <el-radio-group v-model="form.status" disabled>
            <el-radio :value="true">启用</el-radio>
            <el-radio :value="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="领用备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" disabled />
        </el-form-item>
      </el-form>
    </main>
    <footer class="safety-platform-container__footer">
      <el-button @click="router.back()">返回</el-button>
    </footer>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, computed } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import BreadcrumbBack from '@/components/BreadcrumbBack.vue';
  import { queryPersonalProtectiveEquipmentReceiveDetail } from '@/api/production-safety/personal-protective-equipment-receive';
  import { queryAvailableUserList } from '@/api/production-safety/responsibility-implementation';
  import type { UserLisItem } from '@/api/system/user-operate';

  const router = useRouter();
  const route = useRoute();
  const loading = ref(false);

  const issuerUserList = ref<UserLisItem[]>([]);
  const receiverUserList = ref<UserLisItem[]>([]);
  const issuerUserId = ref<number | null>(null);
  const receiverUserId = ref<number | null>(null);

  const id = computed(() => Number(route.query.id));

  const loadUserList = async () => {
    try {
      const res = await queryAvailableUserList({
        pageNumber: 1,
        pageSize: 9999,
        queryParam: {},
      });
      const list = (res as { records?: UserLisItem[] })?.records ?? [];
      issuerUserList.value = list;
      receiverUserList.value = list;
    } catch (e) {
      console.error('获取用户列表失败:', e);
      issuerUserList.value = [];
      receiverUserList.value = [];
    }
  };

  const syncIssuerReceiverFromForm = () => {
    const foundIssuer = issuerUserList.value.find(
      (x) => x.username === form.issuerCode || x.realname === form.issuerName,
    );
    issuerUserId.value = foundIssuer?.id ?? null;
    const foundReceiver = receiverUserList.value.find(
      (x) => x.username === form.receiverCode || x.realname === form.receiverName,
    );
    receiverUserId.value = foundReceiver?.id ?? null;
  };

  const form = reactive<{
    equipmentId: string;
    version: string;
    ppeName: string;
    hazardFactor: string;
    issuerCode: string;
    issuerName: string;
    issueTime: string;
    receiveNum?: number;
    receiverCode: string;
    receiverName: string;
    status: boolean;
    remark: string;
    createdAt: string;
    updatedAt: string;
  }>({
    equipmentId: '',
    version: '',
    ppeName: '',
    hazardFactor: '',
    issuerCode: '',
    issuerName: '',
    issueTime: '',
    receiveNum: undefined,
    receiverCode: '',
    receiverName: '',
    status: true,
    remark: '',
    createdAt: '',
    updatedAt: '',
  });

  const getDetail = async () => {
    if (!id.value) {
      ElMessage.error('缺少 id');
      return;
    }
    loading.value = true;
    try {
      const res = await queryPersonalProtectiveEquipmentReceiveDetail(id.value);
      if (res) {
        form.equipmentId = res.equipmentId != null ? String(res.equipmentId) : '';
        form.version = res.version ?? '';
        form.ppeName = res.ppeName ?? '';
        form.hazardFactor = res.hazardFactor ?? '';
        form.issuerCode = res.issuerCode ?? '';
        form.issuerName = res.issuerName ?? '';
        form.issueTime = res.issueTime ?? '';
        const rn = res.receiveNum;
        form.receiveNum =
          rn !== '' && rn != null && !Number.isNaN(Number(rn)) ? Number(rn) : undefined;
        form.receiverCode = res.receiverCode ?? '';
        form.receiverName = res.receiverName ?? '';
        form.status = res.status === true || res.status === 'true';
        form.remark = res.remark ?? '';
        form.createdAt = res.createdAt ?? '';
        form.updatedAt = res.updatedAt ?? '';
      }
    } catch (e) {
      console.error('获取领用详情失败:', e);
      ElMessage.error('获取详情失败');
    } finally {
      loading.value = false;
    }
  };

  onMounted(async () => {
    await loadUserList();
    await getDetail();
    syncIssuerReceiverFromForm();
  });
</script>

<style scoped lang="scss">
  @use '@/styles/page-details-layout.scss' as *;
  @use '@/styles/page-main-layout.scss' as *;

  .safety-platform-container__header {
    flex-direction: row !important;
    justify-content: flex-start !important;
    gap: 8px !important;
  }
  .req-form {
    max-width: 600px;
  }
</style>
