<template>
  <main class="safety-platform-container__main">
    <BasicForm
      ref="basicFormRef"
      :formData="ruleFormData"
      :formRules="isViewMode ? undefined : formRules"
      :formConfig="computedFormConfig"
    >
      <template #status>
        <el-radio-group v-model="ruleFormData.status" :disabled="isViewMode">
          <el-radio label="ENABLE">启用</el-radio>
          <el-radio label="DISABLE">禁用</el-radio>
        </el-radio-group>
      </template>
      <template #deductionReason>
        <el-input
          v-model="ruleFormData.deductionReason"
          type="text"
          :disabled="isViewMode"
          placeholder="请输入扣分原因"
        />
        <!-- 原扣分原因下拉选择（隐患台账） -->
        <!-- <el-select
          :disabled="isViewMode"
          v-model="ruleFormData.hiddenDangerId"
          placeholder="请选择扣分原因"
          filterable
          clearable
          style="width: 100%"
          @change="onDeductionReasonChange"
        >
          <el-option
            v-for="item in hiddenDangerOptions"
            :key="item.id"
            :label="item.deductionReason ?? item.dangerProblem"
            :value="item.id"
          />
        </el-select> -->
      </template>
    </BasicForm>
  </main>
  <footer class="safety-platform-container__footer">
    <el-button @click="router.back()">返回</el-button>
    <el-button v-if="!isViewMode" type="primary" @click="handleSubmit">
      {{ isCreateMode ? '提交' : '保存' }}
    </el-button>
  </footer>
</template>

<script setup lang="ts">
  import { computed, onMounted, ref } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import BasicForm from '@/components/BasicForm.vue';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { POINT_DEDUCTION_FORM_CONFIG, POINT_DEDUCTION_FORM_DATA, POINT_DEDUCTION_FORM_RULES } from '../configs/form';
  import { saveMonthlyDeduction, updateMonthlyDeduction, queryDeductionDetail } from '@/api/pointDeduction';
  // import { queryHiddenDangerPage } from '@/api/hiddenDanger';
  // import type { HiddenDangerItem } from '@/api/hiddenDanger';

  const router = useRouter();
  const route = useRoute();

  const operate = computed(() => (route.query.operate as string) || 'pointDeduction-create');
  const currentId = computed(() => Number(route.query.id));

  const isCreateMode = computed(() => operate.value === 'pointDeduction-create');
  const isEditMode = computed(() => operate.value === 'pointDeduction-edit');
  const isViewMode = computed(() => operate.value === 'pointDeduction-view');

  const { ruleFormData, formRules, ruleFormConfig, cloneRuleFormData } = useFormConfigHook(
    POINT_DEDUCTION_FORM_CONFIG,
    POINT_DEDUCTION_FORM_DATA,
    POINT_DEDUCTION_FORM_RULES,
  );

  // 查看模式下，所有字段设为只读
  const viewFormConfig = ref(
    POINT_DEDUCTION_FORM_CONFIG.map((item) => ({
      ...item,
      componentProps: {
        ...item.componentProps,
        disabled: true,
      },
    })),
  );

  const computedFormConfig = computed(() => {
    if (isViewMode.value) {
      return viewFormConfig.value;
    }
    return ruleFormConfig.value;
  });

  const basicFormRef = ref<InstanceType<typeof BasicForm>>();

  // 扣分原因下拉选项（来自隐患台账 productionHiddenDanger/queryPage）- 已改为文本输入，保留注释
  // const hiddenDangerOptions = ref<HiddenDangerItem[]>([]);
  // const loadHiddenDangerOptions = async () => {
  //   try {
  //     const res = await queryHiddenDangerPage({
  //       pageNumber: 1,
  //       pageSize: 500,
  //       queryParam: {},
  //     });
  //     if (res?.records?.length) {
  //       hiddenDangerOptions.value = res.records;
  //     }
  //   } catch (e) {
  //     console.error('获取扣分原因选项失败:', e);
  //   }
  // };
  // 选择扣分原因时同步名称到 deductionReason
  // const onDeductionReasonChange = (hiddenDangerId: number | undefined) => {
  //   if (hiddenDangerId == null) {
  //     ruleFormData.deductionReason = '';
  //     return;
  //   }
  //   const option = hiddenDangerOptions.value.find((item) => item.id === hiddenDangerId);
  //   ruleFormData.deductionReason = option ? (option.deductionReason ?? option.dangerProblem) : '';
  // };

  const handleValidate = async () => {
    if (!basicFormRef.value) return;
    const res = await basicFormRef.value.validateForm();
    if (!res) return false;
    // 扣分原因改为文本输入后校验 deductionReason
    if (!ruleFormData.deductionReason?.trim()) {
      ElMessage.error('请输入扣分原因');
      return false;
    }
    return true;
  };

  const getDetail = async () => {
    if (!currentId.value) return;
    try {
      const res = await queryDeductionDetail(currentId.value);
      if (res) {
        ruleFormData.deductionTitle = res.deductionTitle;
        ruleFormData.deductionDate = res.deductionDate;
        ruleFormData.deductionValue = res.deductionScore;
        ruleFormData.departmentName = res.departmentName;
        ruleFormData.hiddenDangerId = res.hiddenDangerId;
        ruleFormData.deductionReason = res.deductionReason ?? '';
        ruleFormData.status = res.status ? 'ENABLE' : 'DISABLE';
      }
      cloneRuleFormData();
    } catch (e) {
      console.error('获取月度扣分详情失败:', e);
      ElMessage.error(e?.message || e?.data || '获取详情失败');
    }
  };

  const handleSubmit = async () => {
    const res = await handleValidate();
    if (!res) return;
    try {
      const basePayload = {
        // 扣分标题沿用扣分原因，后端若需要标题字段可复用
        deductionTitle: ruleFormData.deductionReason,
        deductionDate: ruleFormData.deductionDate,
        deductionScore: ruleFormData.deductionValue,
        departmentName: ruleFormData.departmentName,
        hiddenDangerId: ruleFormData.hiddenDangerId,
        deductionReason: ruleFormData.deductionReason,
        status: ruleFormData.status === 'ENABLE',
      };

      if (isCreateMode.value) {
        await saveMonthlyDeduction(basePayload);
        ElMessage.success('创建成功');
      } else if (isEditMode.value && currentId.value) {
        await updateMonthlyDeduction({
          id: currentId.value,
          ...basePayload,
        });
        ElMessage.success('保存成功');
      }

      router.back();
    } catch (e) {
      console.error('保存月度扣分失败:', e);
      ElMessage.error(e?.message || e?.data || '保存失败，请重试');
    }
  };

  onMounted(() => {
    cloneRuleFormData();
    // loadHiddenDangerOptions();
    if (isEditMode.value || isViewMode.value) {
      getDetail();
    }
  });
</script>

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