<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"
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="120px"
        class="req-form"
      >
        <el-form-item label="职业危害因素" prop="hazardFactor">
          <el-input v-model="form.hazardFactor" placeholder="请输入职业危害因素" clearable />
        </el-form-item>
        <el-form-item label="发放人" prop="issuerCode">
          <el-select
            v-model="issuerUserId"
            placeholder="请选择发放人"
            filterable
            clearable
            style="width: 100%"
            @change="onIssuerChange"
          >
            <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-date-picker
            v-model="form.issueTime"
            type="date"
            placeholder="选择发放时间"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="防护用品名称" prop="ppeName">
          <el-input v-model="form.ppeName" placeholder="请输入防护用品名称" clearable />
        </el-form-item>
        <el-form-item label="型号" prop="version">
          <el-input v-model="form.version" placeholder="请输入型号" clearable />
        </el-form-item>
        <el-form-item label="领用数量" prop="receiveNum">
          <el-input-number
            v-model="form.receiveNum"
            :min="1"
            :precision="0"
            placeholder="领用数量"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="领用人" prop="receiverUserId">
          <el-select
            v-model="receiverUserId"
            placeholder="请选择领用人"
            filterable
            clearable
            style="width: 100%"
            @change="onReceiverChange"
          >
            <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">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="领用备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入领用备注"
            :rows="3"
            clearable
          />
        </el-form-item>
      </el-form>
    </main>
    <footer class="safety-platform-container__footer">
      <el-button @click="router.back()">返回</el-button>
      <el-button type="primary" :loading="submitting" @click="handleSubmit">保存</el-button>
    </footer>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, computed } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
  import BreadcrumbBack from '@/components/BreadcrumbBack.vue';
  import {
    queryPersonalProtectiveEquipmentReceiveDetail,
    updatePersonalProtectiveEquipmentReceive,
  } 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 formRef = ref<FormInstance>();
  const loading = ref(false);
  const submitting = ref(false);

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

  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 onIssuerChange = (userId: number | null) => {
    const u = issuerUserList.value.find((x) => x.id === userId);
    form.issuerCode = u?.id ?? '';
    form.issuerName = u?.realname ?? '';
  };

  const onReceiverChange = (userId: number | null) => {
    const u = receiverUserList.value.find((x) => x.id === userId);
    form.receiverCode = u?.id ?? '';
    form.receiverName = u?.realname ?? '';
  };

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

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

  const form = reactive({
    id: undefined as number | undefined,
    equipmentId: '',
    version: '',
    ppeName: '',
    hazardFactor: '',
    issuerCode: '',
    issuerName: '',
    issueTime: '',
    receiveNum: undefined as number | undefined,
    receiverCode: '',
    receiverName: '',
    status: 1 as number,
    remark: '',
  });

  const formRules: FormRules = { 
        hazardFactor: [{ required: true, message: '请输入职业危害因素', trigger: 'blur' }],
        issuerCode: [{ required: true, message: '请选择发放人', trigger: 'blur' }],
        issueTime: [{ required: true, message: '请选择发放时间', trigger: 'blur' }],
        receiveNum: [{ required: true, message: '请输入领用数量', trigger: 'blur' }],
        ppeName: [{ required: true, message: '请输入防护用品名称', trigger: 'blur' }],
        version: [{ required: true, message: '请输入型号', trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'blur' }],
        remark: [{ required: true, message: '请输入备注', trigger: 'blur' }],
   };

  const getDetail = async () => {
    if (!id.value) {
      ElMessage.error('缺少 id');
      return;
    }
    loading.value = true;
    try {
      const res = await queryPersonalProtectiveEquipmentReceiveDetail(id.value);
      if (res) {
        form.id = res.id;
        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 === 1 || res.status === '1' ? 1 : 0;
        form.remark = res.remark ?? '';
      }
    } catch (e) {
      console.error('获取领用详情失败:', e);
      ElMessage.error('获取详情失败');
    } finally {
      loading.value = false;
    }
  };

  const handleSubmit = async () => {
    const valid = await formRef.value?.validate().then(() => true).catch(() => false);
    if (!valid) return;
    if (!form.id) {
      ElMessage.error('缺少 id');
      return;
    }
    submitting.value = true;
    try {
      await updatePersonalProtectiveEquipmentReceive({
        id: form.id,
        equipmentId: form.equipmentId || undefined,
        version: form.version || undefined,
        ppeName: form.ppeName || undefined,
        hazardFactor: form.hazardFactor || undefined,
        issuerCode: form.issuerCode || undefined,
        issuerName: form.issuerName || undefined,
        issueTime: form.issueTime || undefined,
        receiveNum: form.receiveNum,
        receiverCode: form.receiverCode || undefined,
        receiverName: form.receiverName || undefined,
        status: form.status,
        remark: form.remark || undefined,
      });
      ElMessage.success('保存成功');
      router.back();
    } catch (e) {
      console.error('编辑领用记录失败:', e);
      ElMessage.error('保存失败，请重试');
    } finally {
      submitting.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>
