<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
        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="issuerUserId">
        <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 :label="1">启用</el-radio>
            <el-radio :label="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 } from 'vue';
  import { useRouter } from 'vue-router';
  import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
  import BreadcrumbBack from '@/components/BreadcrumbBack.vue';
  import { savePersonalProtectiveEquipmentReceive } 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 formRef = ref<FormInstance>();
  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?.username ?? '';
    form.issuerName = u?.realname ?? '';
  };

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

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

  const formRules: FormRules = {  };

  onMounted(() => {
    loadUserList();
  });

  const handleSubmit = async () => {
    const valid = await formRef.value?.validate().then(() => true).catch(() => false);
    if (!valid) return;
    submitting.value = true;
    try {
      await savePersonalProtectiveEquipmentReceive({
        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;
    }
  };
</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>
