<template>
  <main class="safety-platform-container__main">
    <BasicForm
      ref="basicFormRef"
      :formData="ruleFormData"
      :formRules="isViewMode ? undefined : formRules"
      :formConfig="computedFormConfig"
    >
      <template #categoryName>
        <el-select v-model="ruleFormData.categoryName" placeholder="请选择分类名称" :disabled="isViewMode">
          <el-option v-for="item in classifyNameOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </template>
      <template #responsibleDeptId>
        <el-cascader
          v-model="ruleFormData.responsibleDeptId"
          :options="deptTree"
          :props="responsibleDeptCascaderProp"
          clearable
          :show-all-levels="false"
          placeholder="请选择责任部门"
          style="width: 100%"
          :disabled="isViewMode"
        />
      </template>
      <template #cooperateDeptIds>
        <el-cascader
          v-model="ruleFormData.cooperateDeptIds"
          :options="deptTree"
          :props="cooperateDeptCascaderProp"
          clearable
          collapse-tags
          :show-all-levels="false"
          :max-collapse-tags="3"
          popper-class="cascader-popper--custom"
          placeholder="请选择配合部门"
          style="width: 100%"
          :disabled="isViewMode"
        />
      </template>
      <template #responsiblePersonId>
        <el-select
          v-model="ruleFormData.responsiblePersonId"
          placeholder="请选择责任人"
          :disabled="isViewMode"
          filterable
        >
          <el-option
            v-for="user in responsiblePersonOptions"
            :key="user.value"
            :label="user.label"
            :value="user.value"
          />
        </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 UploadFiles from '@/components/UploadFiles/UploadFiles.vue';
  // import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
  import '@wangeditor/editor/dist/css/style.css';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { ACADEMY_FILE_FORM_CONFIG, ACADEMY_FILE_FORM_DATA, ACADEMY_FILE_FORM_RULES } from '../configs/form';
  import {
    querySafetyCultureActivityDetail,
    addSafetyCultureActivityManagement,
    updateSafetyCultureActivity,
    getAllDepartments,
  } from '@/api/safety-culture';
  import { queryAvailableUserList } from '@/api/system/person-group';
  import type { addSafetyCultureFilePageQuery } from '@/api/safety-culture';
  import type { DeptTree } from '@/types/dept/type';

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

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

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

  const { ruleFormData, formRules, ruleFormConfig, cloneRuleFormData } = useFormConfigHook(
    ACADEMY_FILE_FORM_CONFIG,
    ACADEMY_FILE_FORM_DATA,
    ACADEMY_FILE_FORM_RULES,
  );

  const viewFormConfig = ref(
    ACADEMY_FILE_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>>();

  const responsibleDeptCascaderProp = {
    expandTrigger: 'hover' as const,
    checkStrictly: true,
    emitPath: false,
    value: 'id',
    label: 'deptName',
  };

  const cooperateDeptCascaderProp = {
    multiple: true,
    expandTrigger: 'hover' as const,
    checkStrictly: true,
    emitPath: false,
    value: 'id',
    label: 'deptName',
  };

  const deptTree = ref<DeptTree[]>([]);
  const loadDeptTreeData = async () => {
    const result = await getAllDepartments();
    deptTree.value = result?.[0]?.children || [];
  };

  const classifyNameOptions = ref<Array<{ label: string; value: string }>>([
    { label: '安全综合工作', value: '安全综合工作' },
    { label: '生产安全工作', value: '生产安全工作' },
  ]);

  const responsiblePersonOptions = ref<Array<{ label: string; value: number }>>([]);
  const loadResponsiblePersonOptions = async () => {
    const result = await queryAvailableUserList({
      pageNumber: 1,
      pageSize: 1000,
      queryParam: {},
    });
    responsiblePersonOptions.value = (result.records || []).map((item) => ({
      label: item.realname || item.staffNo,
      value: item.id,
    }));
  };

  const normalizeToNumberArray = (value: unknown): number[] => {
    if (Array.isArray(value)) {
      return value.map((item) => Number(item)).filter((item) => Number.isFinite(item));
    }

    if (value == null || value === '') {
      return [];
    }

    if (typeof value === 'string' && value.includes(',')) {
      return value
        .split(',')
        .map((item) => Number(item.trim()))
        .filter((item) => Number.isFinite(item));
    }

    const numericValue = Number(value);
    return Number.isFinite(numericValue) ? [numericValue] : [];
  };

  const normalizeCooperateDeptIds = (value: unknown): string => {
    return normalizeToNumberArray(value)
      .map((item) => String(item))
      .join(',');
  };

  const buildPayload = (): addSafetyCultureFilePageQuery => {
    const responsibleDeptId = Number(ruleFormData.responsibleDeptId);
    const responsiblePersonId = Number(ruleFormData.responsiblePersonId);

    return {
      planName: String(ruleFormData.planName || ''),
      actionContent: String(ruleFormData.actionContent || ''),
      categoryName: String(ruleFormData.categoryName || ''),
      responsibleDeptId,
      responsiblePersonId,
      cooperateDeptIds: normalizeCooperateDeptIds(ruleFormData.cooperateDeptIds),
    };
  };

  const handleValidate = async () => {
    if (!basicFormRef.value) return;
    const res = await basicFormRef.value.validateForm();
    return res;
  };

  const getDetail = async () => {
    if (!currentId.value) return;
    try {
      const res = await querySafetyCultureActivityDetail(currentId.value);
      if (res) {
        ruleFormData.planName = res.planName || '';
        ruleFormData.actionContent = res.actionContent || '';
        ruleFormData.categoryName = res.categoryName != null ? String(res.categoryName) : '';
        ruleFormData.responsibleDeptId = res.responsibleDeptId != null ? Number(res.responsibleDeptId) : undefined;
        ruleFormData.responsiblePersonId =
          res.responsiblePersonId != null ? Number(res.responsiblePersonId) : undefined;
        ruleFormData.cooperateDeptIds = normalizeToNumberArray(res.cooperateDeptIds);
      }
      cloneRuleFormData();
    } catch (e) {
      console.error('获取安全文化活动详情失败:', e);
      ElMessage.error('获取详情失败');
    }
  };

  const handleSubmit = async () => {
    const res = await handleValidate();
    if (!res) return;

    console.log('ruleFormData', ruleFormData);
    try {
      const payload = buildPayload();
      if (isCreateMode.value) {
        await addSafetyCultureActivityManagement(payload);
        ElMessage.success('创建成功');
      } else if (isEditMode.value && currentId.value) {
        await updateSafetyCultureActivity({
          id: currentId.value,
          ...payload,
        });
        ElMessage.success('保存成功');
      }

      router.back();
    } catch (e) {
      console.error('保存安全文化活动失败:', e);
      ElMessage.error('保存失败，请重试');
    }
  };

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

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

  .editor-container {
    width: 100%;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
  }

  .content-display {
    min-height: 200px;
    padding: 12px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    background-color: #f5f7fa;
  }

  .file-display {
    .file-link {
      color: #409eff;
      text-decoration: none;

      &:hover {
        text-decoration: underline;
      }
    }
  }

  .no-file {
    color: rgba(0, 0, 0, 0.65);
  }

  .image-uploader {
    :deep(.el-upload--picture-card) {
      width: 80px !important;
      height: 80px !important;
      line-height: 80px;
    }

    :deep(.el-upload-list--picture-card .el-upload-list__item) {
      width: 80px !important;
      height: 80px !important;
    }
  }
</style>
