<template>
    <el-drawer v-model="visible" :title="dialogTitle" width="500px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <div class="form-title">账号信息</div>
        <!-- 账号 -->
        <el-form-item label="账号" required>
          <el-input v-model="form.account" :disabled="!isAdd" placeholder="请输入账号" />
        </el-form-item>
  
        <!-- 密码 -->
        <el-form-item label="密码" prop="password" v-if="isAdd" required>
          <el-input
            v-model="form.password"
            type="password"
            autocomplete="new-password"
            show-password
            :placeholder="isAdd ? '请输入密码（至少6位）' : '留空则不修改密码'"
          />
        </el-form-item>
  
        <!-- 确认密码 -->
        <el-form-item label="确认密码" prop="confirmPassword" v-if="isAdd" required>
          <el-input
            v-model="form.confirmPassword"
            type="password"
            autocomplete="new-password"
            show-password
            :placeholder="isAdd ? '请再次输入密码' : '留空则不修改密码'"
          />
        </el-form-item>
  
        <el-divider></el-divider>

        <div class="form-title">个人信息</div>
        <!-- 姓名 -->
        <el-form-item label="姓名" required>
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
  
        <!-- 性别 -->
        <el-form-item label="性别" required>
          <el-radio-group v-model="form.sex" placeholder="请选择性别">
            <el-radio-button label="未知" :value="0" />
            <el-radio-button label="男" :value="1" />
            <el-radio-button label="女" :value="2" />
          </el-radio-group>
        </el-form-item>
  
        <!-- 生日 -->
        <el-form-item label="生日" required>
          <el-date-picker
            v-model="form.birthday"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择生日"
          />
        </el-form-item>
  
        <!-- 隶属单位 -->
        <el-form-item label="隶属单位" required>
          <el-select v-model="form.affiliate_unit" placeholder="请选择隶属单位" clearable style="width: 100%">
            <el-option v-for="item in companyList" :key="item.id" :label="item.org_name" :value="String(item.id)" />
          </el-select>
        </el-form-item>
  
        <!-- 部门 -->
        <el-form-item label="部门" required>
          <el-select v-model="form.department" placeholder="请先选择隶属单位" clearable style="width: 100%" :disabled="!form.affiliate_unit">
            <el-option v-for="item in departmentList" :key="item.id" :label="item.org_name" :value="String(item.id)" />
          </el-select>
        </el-form-item>

        <!-- 职位 -->
        <el-form-item label="职位" required>
          <el-input v-model="form.position" placeholder="请输入职位" />
        </el-form-item>

        <!-- 学历 -->
        <el-form-item label="学历">
          <el-input v-model="form.education" placeholder="请输入学历" />
        </el-form-item>

        <!-- 民族 -->
        <el-form-item label="民族" required>
          <el-input v-model="form.nation" placeholder="请输入民族" />
        </el-form-item>
  
        <!-- 手机 -->
        <el-form-item label="手机" required>
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
  
        <!-- 微信 -->
        <el-form-item label="微信">
          <el-input v-model="form.wechat" placeholder="请输入微信" />
        </el-form-item>
  
        <!-- 邮箱 -->
        <el-form-item label="邮箱" required>
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
  
        <!-- 家庭住址 -->
        <el-form-item label="家庭住址" required>
          <el-input v-model="form.home_address" placeholder="请输入家庭住址" />
        </el-form-item>
  
        <!-- 状态 -->
        <el-form-item label="状态">
          <el-select
            v-model="form.account_status"
            placeholder="请选择状态"
            style="width: 100%"
          >
            <el-option label="离职" :value="2" v-if="!isAdd" />
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
  
      <!-- 对话框脚部 -->
      <template #footer>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </template>
    </el-drawer>
  </template>
  
  <script setup lang="ts">
import { ref, computed, watch, nextTick } from "vue";
  import { ElMessage } from "element-plus";
  import { createEmployee, editEmployee, getEmployeeDetail, getCompanys, getDepartments } from "@/api/erp";

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
    statusDict: {
      type: Array,
      default: () => [],
    },
  });
  
  const emit = defineEmits(["update:modelValue", "submit", "close"]);

  const visible = ref(false);
  const formRef = ref<any>(null);
  const isAdd = ref(false);
  const companyList = ref<any[]>([]);
  const departmentList = ref<any[]>([]);
  const isHydratingUserData = ref(false);

  // 获取公司列表
  const loadCompanyList = async () => {
    try {
      const res = await getCompanys();
      companyList.value = res.data || res || [];
    } catch (e) {
      console.error("获取公司列表失败", e);
    }
  };


  // 获取部门列表
  const loadDepartments = async (parentId?: number) => {
    try {
      const res = await getDepartments(parentId);
      departmentList.value = res.data || res || [];
    } catch (e) {
      console.error("获取部门列表失败", e);
    }
  };

  const form = ref<any>({
    id: null,
    tid: 1,
    tenant_id: 1,
    account: "",
    name: "",
    phone: "",
    qq: "",
    sex: 0,
    birthday: "",
    affiliate_unit: "",
    department: "",
    position: "",
    education: "",
    nation: "",
    wechat: "",
    home_address: "",
    password: "",
    confirmPassword: "",
    email: "",
    account_status: 1,
    status: 1,
  });

  // 监听隶属单位变化，加载对应部门
  watch(() => form.value.affiliate_unit, (newVal) => {
    if (isHydratingUserData.value) {
      return;
    }
    form.value.department = "";
    departmentList.value = [];
    if (newVal) {
      loadDepartments(Number(newVal));
    }
  });

  const dialogTitle = computed(() => {
    return isAdd.value ? "添加用户" : "编辑用户";
  });
  
  // 密码验证规则
  const validatePassword = (rule: any, value: any, callback: any) => {
    if (isAdd.value) {
      // 新增用户时，密码必填
      if (!value) {
        callback(new Error("请输入密码"));
        return;
      }
      if (value.length < 6) {
        callback(new Error("密码长度不能少于6位"));
        return;
      }
    } else {
      // 编辑用户时，如果填写了密码，则必须符合规则
      if (value && value.length < 6) {
        callback(new Error("密码长度不能少于6位"));
        return;
      }
    }
    callback();
  };
  
  // 确认密码验证规则
  const validateConfirmPassword = (rule: any, value: any, callback: any) => {
    if (isAdd.value) {
      // 新增用户时，确认密码必填
      if (!value) {
        callback(new Error("请再次输入密码"));
        return;
      }
      if (value !== form.value.password) {
        callback(new Error("两次输入的密码不一致"));
        return;
      }
    } else {
      // 编辑用户时，如果填写了密码，则确认密码必须一致
      if (form.value.password && value !== form.value.password) {
        callback(new Error("两次输入的密码不一致"));
        return;
      }
      // 如果填写了确认密码但没填密码，提示错误
      if (value && !form.value.password) {
        callback(new Error("请先输入密码"));
        return;
      }
    }
    callback();
  };
  
  // 表单验证规则
  const rules = {
    account: [
      { required: true, message: "请输入账号", trigger: "blur" },
      { min: 3, max: 20, message: "账号长度在 3 到 20 个字符", trigger: "blur" },
    ],
    name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
    password: [{ validator: validatePassword, trigger: "blur" }],
    confirmPassword: [{ validator: validateConfirmPassword, trigger: "blur" }],
    email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }],
  };
  
  // 监听 modelValue
  watch(
    () => props.modelValue,
    (newVal) => {
      visible.value = newVal;
    }
  );
  
  // 监听 visible 变化
  watch(visible, (newVal) => {
    if (!newVal) {
      emit("update:modelValue", false);
    }
  });
  
  // 监听 statusDict 变化，用于调试
  watch(
    () => props.statusDict,
    (newVal) => {},
    { immediate: true, deep: true }
  );
  
  const loadUserData = async (user: any) => {
    try {
      // 处理两种调用方式：传递用户对象或用户 ID
      const userId = typeof user === "number" ? user : user?.id || user?.userId;
      if (!userId) {
        throw new Error("未提供有效的用户 ID");
      }
  
      const res = await getEmployeeDetail(userId);
  
      const data = res.data || res;
  
      // 确保 sex 和 status 都是数字类型
      const sexValue =
        data.sex !== undefined && data.sex !== null
          ? Number(data.sex)
          : data.gender !== undefined && data.gender !== null
            ? Number(data.gender)
            : 0;
  
      const statusValue =
        data.account_status !== undefined && data.account_status !== null
          ? Number(data.account_status)
          : data.status !== undefined && data.status !== null
            ? Number(data.status)
            : 1;

      const affiliateUnitValue =
        data.affiliate_unit !== undefined && data.affiliate_unit !== null
          ? String(data.affiliate_unit)
          : "";
      const departmentValue =
        data.department !== undefined && data.department !== null
          ? String(data.department)
          : "";

      isHydratingUserData.value = true;
      form.value = {
        id: data.id,
        tid: data.tid || data.tenant_id || 1,
        tenant_id: data.tenant_id || data.tid || 1,
        account: data.account || "",
        name: data.name || "",
        phone: data.phone || "",
        qq: data.qq || "",
        sex: sexValue,
        birthday: data.birthday || "",
        affiliate_unit: affiliateUnitValue,
        department: departmentValue,
        position: data.position || "",
        education: data.education || "",
        nation: data.nation || data.nationality || "",
        wechat: data.wechat || "",
        home_address: data.home_address || "",
        password: "",
        confirmPassword: "",
        email: data.email || "",
        account_status: statusValue,
        status: statusValue,
      };

      await nextTick();

      departmentList.value = [];
      if (form.value.affiliate_unit) {
        await loadDepartments(Number(form.value.affiliate_unit));
      }
      form.value.department = departmentValue;
      isHydratingUserData.value = false;
    } catch (e: any) {
      console.error("Failed to load user data:", e);
      const errorMsg = e?.response?.data?.message || e?.message || "加载用户失败";
      ElMessage.error(errorMsg);
      throw e;
    }
  };
  
  const handleCancel = () => {
    visible.value = false;
  };
  
  const handleSubmit = async () => {
    // 表单验证
    if (!formRef.value) {
      return;
    }
  
    try {
      await formRef.value.validate();
    } catch (error) {
      ElMessage.warning("请检查表单填写是否正确");
      return;
    }
  
    // 验证密码一致性
    if (isAdd.value) {
      // 新增用户时，密码必填
      if (!form.value.password) {
        ElMessage.error("请输入密码");
        return;
      }
      if (form.value.password !== form.value.confirmPassword) {
        ElMessage.error("两次输入的密码不一致");
        return;
      }
    } else {
      // 编辑用户时，如果填写了密码，则必须填写确认密码且一致
      if (form.value.password) {
        if (form.value.password !== form.value.confirmPassword) {
          ElMessage.error("两次输入的密码不一致");
          return;
        }
      }
    }
  
    try {
      if (isAdd.value) {
        // 新增用户
        const submitData: any = {
          tid: form.value.tid,
          tenant_id: form.value.tenant_id,
          account: form.value.account,
          name: form.value.name,
          phone: form.value.phone,
          qq: form.value.qq,
          sex: form.value.sex,
          birthday: form.value.birthday,
          affiliate_unit: form.value.affiliate_unit,
          department: form.value.department,
          position: form.value.position,
          education: form.value.education,
          nation: form.value.nation,
          wechat: form.value.wechat,
          email: form.value.email,
          home_address: form.value.home_address,
          account_status: form.value.account_status,
          status: form.value.account_status,
          password: form.value.password,
        };

        await createEmployee(submitData);
        ElMessage.success("添加成功");
      } else {
        // 编辑用户
        if (!form.value.id || form.value.id === 0) {
          ElMessage.error("用户ID不能为空");
          return;
        }

        const submitData: any = {
          id: form.value.id,
          tid: form.value.tid,
          tenant_id: form.value.tenant_id,
          account: form.value.account,
          name: form.value.name,
          phone: form.value.phone,
          qq: form.value.qq,
          sex: form.value.sex,
          birthday: form.value.birthday,
          affiliate_unit: form.value.affiliate_unit,
          department: form.value.department,
          position: form.value.position,
          education: form.value.education,
          nation: form.value.nation,
          wechat: form.value.wechat,
          email: form.value.email,
          home_address: form.value.home_address,
          account_status: form.value.account_status,
          status: form.value.account_status,
        };
  
        // 只有在填写了密码时才添加到提交数据中
        if (form.value.password) {
          submitData.password = form.value.password;
        }
  
        await editEmployee(form.value.id, submitData);
        ElMessage.success("更新成功");
      }
  
      visible.value = false;
      emit("submit");
    } catch (e: any) {
      const errorMsg = e?.response?.data?.message || e?.message || "操作失败";
      ElMessage.error(errorMsg);
    }
  };
  
  // 暴露方法给父组件
  defineExpose({
    loadUserData,
    openAdd: () => {
      isAdd.value = true;
      form.value = {
        id: 0,
        tid: 1,
        tenant_id: 1,
        account: "",
        name: "",
        phone: "",
        qq: "",
        sex: 0,
        birthday: "",
        affiliate_unit: "",
        department: "",
        position: "",
        education: "",
        nation: "",
        wechat: "",
        home_address: "",
        password: "",
        confirmPassword: "",
        email: "",
        account_status: 1,
        status: 1,
      };
      loadCompanyList();
      visible.value = true;
      // 清除表单验证
      if (formRef.value) {
        formRef.value.clearValidate();
      }
    },
    openEdit: (user: any) => {
      isAdd.value = false;
      loadCompanyList();
      visible.value = true;
      // 清除表单验证
      if (formRef.value) {
        formRef.value.clearValidate();
      }
      // 异步加载用户详细信息
      loadUserData(user);
    },
    open: (user?: any) => {
      loadCompanyList();
      if (user) {
        isAdd.value = false;
        loadUserData(user);
      } else {
        isAdd.value = true;
        form.value = {
          id: 0,
          tid: 1,
          tenant_id: 1,
          account: "",
          name: "",
          phone: "",
          qq: "",
          sex: 0,
          birthday: "",
          affiliate_unit: "",
          department: "",
          position: "",
          education: "",
          nation: "",
          wechat: "",
          home_address: "",
          password: "",
          confirmPassword: "",
          email: "",
          account_status: 1,
          status: 1,
        };
      }
      visible.value = true;
      // 清除表单验证
      if (formRef.value) {
        formRef.value.clearValidate();
      }
    },
  });
  </script>
  
  <style lang="less" scoped>
  .form-title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 20px;
  }
  </style>
