<template>
  <!-- 添加或修改用户信息抽屉 -->
  <el-drawer v-model="visibleProxy" :title="title" size="55%" append-to-body :close-on-click-modal="false" @closed="handleDrawerClosed">
    <el-card shadow="always" class="box-card" style="padding-top: 10px">
      <el-form ref="userFormRef" :model="form" :rules="rules" label-width="100px">
        <!-- 用户状态提示 -->
        <div v-if="isReadOnlyMode" class="user-status-alert">
          <el-alert :title="`该用户为${getUserStatusLabel(form.status)}状态，信息仅供查看`" type="warning" :closable="false" show-icon class="mb-4" />
        </div>

        <div v-if="isBuiltInUserMode" class="user-status-alert">
          <el-alert title="该用户为系统内置用户，仅允许修改部分信息" type="info" :closable="false" show-icon class="mb-4" />
        </div>

        <!-- 基本信息 -->
        <el-divider content-position="left">
          <span class="divider-title">基本信息</span>
        </el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="!form.userId" prop="userName">
              <template #label>
                用户名称
                <el-tooltip content="登录名" placement="top">
                  <el-icon><question-filled /></el-icon>
                </el-tooltip>
              </template>
              <el-input
                :key="`userName-${props.editType}`"
                v-model="form.userName"
                placeholder="请输入用户名称"
                maxlength="30"
                :disabled="isFieldDisabled('userName')"
                @input="handleUsernameChange"
              />
            </el-form-item>
            <el-form-item v-else label="用户名称">
              <el-input v-model="form.userName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input
                :key="`nickName-${props.editType}`"
                v-model="form.nickName"
                placeholder="请输入用户昵称"
                maxlength="30"
                :disabled="isFieldDisabled('nickName')"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item v-if="!form.userId" prop="password">
              <template #label>
                用户密码
                <el-tooltip placement="top" :show-after="100" :hide-after="100">
                  <template #content>
                    <div class="password-tooltip">
                      <div class="tooltip-title">密码要求：</div>
                      <div class="password-rules">
                        <div
                          v-for="rule in passwordRules"
                          :key="rule.key"
                          class="rule-item"
                          :class="{ 'rule-met': rule.valid, 'rule-empty': !form.password }"
                        >
                          <el-icon>
                            <component :is="rule.icon" />
                          </el-icon>
                          <span>{{ rule.label }}</span>
                        </div>
                      </div>
                    </div>
                  </template>
                  <el-icon class="password-help-icon"><QuestionFilled /></el-icon>
                </el-tooltip>
              </template>
              <el-input
                :key="`password-${props.editType}`"
                v-model="form.password"
                type="password"
                placeholder="请输入用户密码"
                maxlength="20"
                show-password
                autocomplete="new-password"
                :disabled="isFieldDisabled('password')"
                @input="handlePasswordInput"
              />

              <!-- 密码强度条 - 简洁版 -->
              <div v-if="!isFieldDisabled('password')" class="password-strength-container">
                <div class="password-strength-header">
                  <span class="strength-label">密码强度</span>
                  <div class="strength-progress">
                    <div class="strength-progress-bg">
                      <div
                        class="strength-progress-fill"
                        :style="{
                          width: strengthScore + '%',
                          backgroundColor: strengthColor
                        }"
                      ></div>
                    </div>
                    <div class="strength-indicators">
                      <div
                        class="strength-dot"
                        :class="{ active: strengthScore >= 30 }"
                        :style="{ backgroundColor: strengthScore >= 30 ? strengthColor : '#e9ecef' }"
                      ></div>
                      <div
                        class="strength-dot"
                        :class="{ active: strengthScore >= 60 }"
                        :style="{ backgroundColor: strengthScore >= 60 ? strengthColor : '#e9ecef' }"
                      ></div>
                      <div
                        class="strength-dot"
                        :class="{ active: strengthScore >= 85 }"
                        :style="{ backgroundColor: strengthScore >= 85 ? strengthColor : '#e9ecef' }"
                      ></div>
                    </div>
                  </div>
                  <span class="strength-level" :style="{ color: strengthColor }">
                    {{ strengthLevel }}
                  </span>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户性别">
              <el-select v-model="form.sex" placeholder="请选择" :disabled="isFieldDisabled('sex')">
                <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <!-- 编辑态：显示输入框 -->
              <el-input
                v-if="!isReadOnlyMode"
                v-model="form.phonenumber"
                placeholder="请输入手机号码"
                maxlength="11"
                :disabled="isFieldDisabled('phonenumber')"
              />
              <!-- 只读态：显示脱敏文本 -->
              <span v-else class="masked-text">
                {{ formatMobile(form.phonenumber) }}
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <!-- 编辑态：显示输入框 -->
              <el-input v-if="!isReadOnlyMode" v-model="form.email" placeholder="请输入邮箱" maxlength="50" :disabled="isFieldDisabled('email')" />
              <!-- 只读态：显示脱敏文本 -->
              <span v-else class="masked-text">
                {{ formatEmail(form.email) }}
              </span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptId">
              <el-tree-select
                v-model="form.deptId"
                :data="props.enabledDeptTree"
                :props="{ value: 'id', label: 'label', children: 'children' }"
                value-key="id"
                placeholder="请选择归属部门"
                check-strictly
                :disabled="isFieldDisabled('deptId')"
                @change="handleDeptChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账号状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择账号状态" :disabled="isFieldDisabled('status')">
                <el-option v-for="dict in availableStatusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
              <div v-if="statusTipText" class="form-tip">
                <small
                  ><el-icon><InfoFilled /></el-icon>{{ statusTipText }}</small
                >
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属机构" prop="manageCom">
              <el-select v-model="form.manageCom" placeholder="请选择">
                <template #header>
                  <el-input v-model="likeName" placeholder="可根据机构编码或名称模糊查询" @input="filterByManageCom"></el-input>
                </template>
                <el-option v-for="dict in filteredManagecom" :key="dict.value" :label="dict.value + '-' + dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 实名信息 -->
        <el-divider content-position="left">
          <span class="divider-title">实名信息</span>
          <el-tag v-if="isEditMode" type="info" size="small" class="ml-2">实名信息不可修改</el-tag>
        </el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="form.realName" placeholder="请输入真实姓名" maxlength="255" :disabled="isEditMode || isFieldDisabled('realName')" />
            </el-form-item>
          </el-col>
          <el-form-item label="证件号码" prop="idNo">
            <!-- 编辑态：显示输入框 -->
            <el-input
              v-if="!isReadOnlyMode"
              v-model="form.idNo"
              placeholder="请输入证件号码"
              maxlength="50"
              :disabled="isEditMode || isFieldDisabled('idNo')"
            />
            <!-- 只读态：显示脱敏文本 -->
            <span v-else class="masked-text">
              {{ formatIdNumber(form.idNo) }}
            </span>
          </el-form-item>
        </el-row>
        <el-row v-if="isEditMode">
          <el-col :span="12">
            <el-form-item label="实名时间">
              <el-input :value="formatAuthTime" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 安全设置 -->
        <el-divider content-position="left">
          <span class="divider-title">安全设置</span>
        </el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="绑定IP" prop="bindIp">
              <el-input v-model="form.bindIp" placeholder="请输入IP地址" maxlength="50" :disabled="isFieldDisabled('bindIp')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账户类型" prop="accType">
              <el-radio-group v-model="form.accType" :disabled="isFieldDisabled('accType')" @change="handleAccTypeChange">
                <el-radio :value="0">长期用户</el-radio>
                <el-radio :value="1">临时用户</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="访问时间" prop="accessTime">
              <el-time-picker
                v-model="form.accessTime"
                is-range
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="HH:mm:ss"
                :disabled="isFieldDisabled('accessTime')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <template #label>
                人脸识别
                <el-tooltip content="开启后，用户登录时需要进行人脸识别验证" placement="top">
                  <el-icon><question-filled /></el-icon>
                </el-tooltip>
              </template>
              <el-switch
                v-model="form.faceAuthRequired"
                active-text="开启"
                inactive-text="关闭"
                active-value="1"
                inactive-value="0"
                :disabled="isFieldDisabled('faceAuthRequired')"
                @change="handleFaceAuthChange"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="form.accType === 1">
          <el-col :span="24">
            <el-form-item label="账户有效期" prop="validDate">
              <el-date-picker
                v-model="form.validDate"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                :disabled="isFieldDisabled('validDate')"
                :disabled-date="disabledValidDate"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 角色权限 -->
        <el-divider content-position="left">
          <span class="divider-title">角色权限</span>
        </el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色类型" prop="roleType">
              <el-select v-model="form.roleType" placeholder="请选择角色类型" :disabled="isFieldDisabled('roleType')" @change="handleRoleTypeChange">
                <el-option v-for="dict in sys_user_role_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="岗位">
              <el-select v-model="form.postIds" multiple placeholder="请选择" :disabled="isFieldDisabled('postIds')">
                <el-option
                  v-for="item in postOptions"
                  :key="item.postId"
                  :label="item.postName"
                  :value="item.postId"
                  :disabled="item.status === '1'"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="角色" prop="roleIds">
              <el-select
                v-model="form.roleIds"
                filterable
                multiple
                placeholder="请选择"
                :disabled="isFieldDisabled('roleIds')"
              >
                <el-option
                  v-for="item in filteredRoleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                  :disabled="item.status === '1'"
                />
              </el-select>
              <div v-if="!form.roleType" class="form-tip">
                <small><el-icon><InfoFilled /></el-icon>请先选择角色类型</small>
              </div>
            </el-form-item>
          </el-col> -->
        </el-row>

        <!-- 备注信息 -->
        <el-divider content-position="left">
          <span class="divider-title">备注信息</span>
        </el-divider>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :disabled="isFieldDisabled('remark')" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <template #footer>
      <div class="dialog-footer">
        <el-button v-if="!isReadOnlyMode" :loading="buttonLoading" type="primary" @click="handleSubmit">
          {{ submitButtonText }}
        </el-button>
        <el-button @click="handleCancel">{{ isReadOnlyMode ? '关 闭' : '取 消' }}</el-button>
      </div>
    </template>
  </el-drawer>

  <!-- 新增：二次验证组件 -->
  <SecondVerify
    v-model:visible="secondVerifyVisible"
    :user-info="currentVerifyUser"
    :title="'修改用户安全验证'"
    :operation-type="'updateUser'"
    @verify-success="handleVerifySuccess"
    @verify-cancel="handleVerifyCancel"
  />
</template>

<script setup lang="ts">
import api from '@/api/system/user';
import { optionselectByUserRoleType } from '@/api/system/role';
import {
  getBuiltInUserEditableFields,
  getUserRoleTypeLabel,
  getUserStatusLabel,
  isBuiltInUser,
  isCancelledUser,
  UserForm,
  UserRoleType,
  UserVO,
  VerifyResult,
  canRoleHaveBranch,
  isSystemAdmin
} from '@/api/system/user/types';
import { DeptTreeVO } from '@/api/system/dept/types';
import { RoleVO } from '@/api/system/role/types';
import { PostVO } from '@/api/system/post/types';
import { optionselect } from '@/api/system/post';
import { useUserStore } from '@/store/modules/user';
import { InfoFilled, QuestionFilled } from '@element-plus/icons-vue';
import { usePasswordStrength } from './composables/usePasswordStrength';
import SecondVerify from './secondVerify.vue';
import { getConfigKey } from '@/api/system/config';
import { formatEmail, formatIdNumber, formatMobile } from '@/api/system/anonymization';

// ======================== Props & Emits ========================
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  editType: {
    type: String,
    default: 'add'
  },
  rowData: {
    type: Object as PropType<UserVO | null>,
    default: null
  },
  enabledDeptTree: {
    type: Array as PropType<DeptTreeVO[]>,
    default: () => []
  }
});

const emit = defineEmits(['update:visible', 'save']);

// ======================== 基础设置 ========================
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const userStore = useUserStore();

// 字典数据
const { sys_user_sex, branchtype, sys_user_role_type, sys_user_status, sys_managecom } = toRefs<any>(
  proxy?.useDict('sys_user_sex', 'branchtype', 'sys_user_role_type', 'sys_user_status', 'sys_managecom')
);

// ======================== 响应式数据 ========================
const userFormRef = ref<ElFormInstance>();
const postOptions = ref<PostVO[]>([]);
const roleOptions = ref<RoleVO[]>([]);
const filteredRoleOptions = ref<RoleVO[]>([]);
const initPassword = ref<string>('');
const buttonLoading = ref(false);
const filteredManagecom = ref([]);
const likeName = ref('');

// 临时用户有效期配置
const tempUserValidityDays = ref<number>(90);

// 二次验证相关状态
const secondVerifyVisible = ref(false);
const currentVerifyUser = ref<Partial<UserVO>>({});
const pendingFormData = ref<UserForm | null>(null);

// 表单数据
const form = ref<UserForm>({
  userId: undefined,
  deptId: undefined,
  userName: '',
  nickName: '',
  password: '',
  phonenumber: '',
  email: '',
  sex: undefined,
  status: '2',
  remark: '',
  postIds: [],
  roleIds: [],
  roleType: '',
  branchType: '',
  idNo: '',
  bindIp: '',
  accessTime: undefined,
  accType: 0,
  validDate: undefined,
  realName: '',
  sysType: 'N',
  manageCom: '',
  authTime: '',
  faceAuthRequired: '0'
});

// ======================== 密码强度管理 ========================
const {
  strengthScore,
  strengthLevel,
  strengthColor,
  passwordRules,
  allBasicRulesMet,
  configLoaded,
  checkPasswordStrengthForUI,
  createBasicPasswordRules,
  resetPasswordStrength
} = usePasswordStrength({
  username: computed(() => form.value.userName || ''),
  showStrengthMeter: true,
  showTooltip: true
});

// ======================== 用户状态判断 ========================
const isEditMode = computed(() => props.editType === 'edit');
const isReadOnlyMode = computed(() => {
  return isEditMode.value && props.rowData && isCancelledUser(props.rowData);
});
const isBuiltInUserMode = computed(() => {
  return isEditMode.value && props.rowData && isBuiltInUser(props.rowData);
});
const builtInEditableFields = computed(() => {
  return getBuiltInUserEditableFields();
});

// 判断字段是否禁用
const isFieldDisabled = (fieldName: string): boolean => {
  if (isReadOnlyMode.value) return true;
  if (isBuiltInUserMode.value) {
    return !builtInEditableFields.value.includes(fieldName);
  }
  return false;
};

// ======================== 权限相关计算属性 ========================
// 检查当前用户是否有渠道设置
const currentUser = computed(() => userStore.userInfo?.user);
const currentUserHasBranch = computed(() => currentUser.value?.branchType);

const visibleProxy = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
});

const title = computed(() => {
  if (isReadOnlyMode.value) {
    return '查看用户信息';
  }
  return isEditMode.value ? '修改用户' : '添加用户';
});

const formatAuthTime = computed(() => {
  return form.value.authTime ? proxy?.parseTime(form.value.authTime) : '';
});

// 提交按钮文案
const submitButtonText = computed(() => {
  if (isReadOnlyMode.value) return '关 闭';
  if (isEditMode.value) return '保存修改';
  return '确 定';
});

// 状态选项控制
const availableStatusOptions = computed(() => {
  if (!sys_user_status.value) return [];

  if (isEditMode.value) {
    if (props.rowData?.status === '2') {
      return sys_user_status.value;
    } else {
      return sys_user_status.value.filter((dict: any) => dict.value !== '2');
    }
  } else {
    return sys_user_status.value.filter((dict: any) => dict.value === '2');
  }
});

// 状态提示文本
const statusTipText = computed(() => {
  if (isEditMode.value && props.rowData?.status === '2') {
    return '用户当前为待激活状态，可修改其他信息或保持当前状态';
  }
  if (isEditMode.value) {
    return '';
  }
  return '新增用户只能为待激活状态';
});

const isBranchDisabled = computed(() => {
  if (!form.value.roleType) return true;
  const needsBranch = canRoleHaveBranch(form.value.roleType);
  if (!needsBranch) return true;

  // 如果当前用户有渠道设置，且不是在编辑模式，则限制只能设置为当前用户的渠道
  if (currentUserHasBranch.value && !isEditMode.value) {
    return true; // 禁用下拉框，将自动设置为当前用户渠道
  }

  return false;
});

const availableBranches = computed(() => {
  if (!branchtype.value) return [];

  // 如果当前用户有渠道设置，只显示当前用户的渠道选项
  if (currentUserHasBranch.value) {
    return branchtype.value.filter((item: any) => item.value === currentUser.value?.branchType);
  }

  return branchtype.value;
});

// ======================== 临时用户有效期日期限制 ========================
const disabledValidDate = (time: Date): boolean => {
  if (form.value.accType !== 1 || tempUserValidityDays.value <= 0) {
    return false;
  }

  const today = new Date();
  today.setHours(0, 0, 0, 0);

  // 禁用过去的日期
  if (time < today) {
    return true;
  }

  // 禁用超过最大有效期的日期
  const maxDate = new Date();
  maxDate.setDate(today.getDate() + tempUserValidityDays.value);

  return time > maxDate;
};

// ======================== 表单验证规则 ========================
const rules = ref({
  userName: [
    { required: true, message: '用户名称不能为空', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
  ],
  nickName: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
  password: [],
  email: [
    { required: true, message: '邮箱不能为空', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  phonenumber: [
    { required: true, message: '手机号码不能为空', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  manageCom: [{ required: true, message: '所属机构不能为空', trigger: 'blur' }],
  deptId: [{ required: true, message: '归属部门不能为空', trigger: 'change' }],
  realName: [{ required: true, message: '真实姓名不能为空', trigger: 'blur' }],
  idNo: [
    { required: true, message: '证件号码不能为空', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号码', trigger: 'blur' }
  ],
  // roleIds: [{ required: true, message: '用户角色不能为空', trigger: 'blur' }],
  roleType: [{ required: true, message: '请选择角色类型', trigger: 'change' }],
  bindIp: [{ pattern: /^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/, message: '请输入正确的IP地址', trigger: 'blur' }],
  validDate: [
    {
      validator: (rule, value, callback) => {
        if (form.value.accType === 1 && (!value || value.length < 2)) {
          callback(new Error('临时用户必须设置有效期'));
        } else if (value && value.length === 2) {
          const diff = new Date(value[1]).getTime() - new Date(value[0]).getTime();
          const diffDays = Math.ceil(diff / (1000 * 60 * 60 * 24));

          if (diffDays < 1) {
            callback(new Error('账户有效期至少1天'));
          } else if (tempUserValidityDays.value > 0 && diffDays > tempUserValidityDays.value) {
            callback(new Error(`账户有效期不能超过${tempUserValidityDays.value}天`));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ]
});

// 监听配置加载状态，更新密码验证规则
watch(
  configLoaded,
  (loaded) => {
    if (loaded) {
      rules.value.password = createBasicPasswordRules({ fieldName: '用户密码' });
      nextTick(() => {
        if (userFormRef.value) {
          userFormRef.value.clearValidate();
        }
      });
    }
  },
  { immediate: true }
);

// ======================== 角色过滤相关方法 ========================
const filterRolesByUserRoleType = async (userRoleType: string) => {
  if (!userRoleType) {
    filteredRoleOptions.value = [];
    return;
  }

  try {
    const response = await optionselectByUserRoleType(userRoleType);
    filteredRoleOptions.value = response.data || [];
  } catch (error) {
    filteredRoleOptions.value = [];
    proxy?.$modal.msgError('获取角色列表失败');
  }
};

// ======================== 配置获取方法 ========================
const loadTempUserValidityDays = async () => {
  try {
    const res = await getConfigKey('sys.user.temp.validity.days');
    tempUserValidityDays.value = res?.data === undefined ? 90 : parseInt(res.data) || 90;
  } catch (error) {
    tempUserValidityDays.value = 90;
  }
};

// ======================== 事件处理方法 ========================
const handleUsernameChange = () => {
  if (form.value.password) {
    checkPasswordStrengthForUI(form.value.password);
  }
};

const handlePasswordInput = () => {
  checkPasswordStrengthForUI(form.value.password);
};

const handleFaceAuthChange = (value: string) => {
  const statusText = value === '1' ? '开启' : '关闭';
};

const handleAccTypeChange = (value: number) => {
  if (value === 0) {
    // 长期用户，清空有效期
    form.value.validDate = undefined;
  }
  // 清除验证
  if (userFormRef.value) {
    userFormRef.value.clearValidate('validDate');
  }
};

const handleRoleTypeChange = async (val: string) => {
  const needsBranch = canRoleHaveBranch(val);

  if (!needsBranch) {
    form.value.branchType = '';
  } else if (currentUserHasBranch.value) {
    // 如果当前用户有渠道设置，自动设置为当前用户的渠道
    form.value.branchType = currentUser.value?.branchType || '';
  }

  await filterRolesByUserRoleType(val);
  form.value.roleIds = [];
};

const handleDeptChange = async (value: number | string) => {
  const selectedDept = findDeptById(props.enabledDeptTree, value);
  if (selectedDept) {
    form.value.manageCom = selectedDept.manageCom;
  }
};

const handleDrawerClosed = () => {
  resetForm();
};

const handleCancel = () => {
  visibleProxy.value = false;
};

// ======================== 二次验证相关方法 ========================

// 二次验证成功处理
const handleVerifySuccess = async (result: VerifyResult): Promise<void> => {
  if (!result.success) return;

  try {
    await executeSubmit();
  } finally {
    handleVerifyCancel();
  }
};

// 二次验证取消处理
const handleVerifyCancel = (): void => {
  secondVerifyVisible.value = false;
  currentVerifyUser.value = {};
  pendingFormData.value = null;
};

// ======================== 工具方法 ========================
const getBranchTypeName = (branchTypeValue: string) => {
  if (!branchTypeValue) return '未设置';
  const branch = branchtype.value?.find((item: any) => item.value === branchTypeValue);
  return branch ? branch.label : branchTypeValue;
};

const getRoleTypeName = (roleType: string) => {
  return getUserRoleTypeLabel(roleType);
};

const findDeptById = (deptTree: DeptTreeVO[], id: string | number): DeptTreeVO | null => {
  for (const dept of deptTree) {
    if (dept.id === id) return dept;
    if (dept.children?.length) {
      const found = findDeptById(dept.children, id);
      if (found) return found;
    }
  }
  return null;
};

/** 模糊查询 */
const filterByManageCom = () => {
  if (likeName.value) {
    filteredManagecom.value = sys_managecom.value.filter((item) => {
      return item.label.includes(likeName.value) || item.value.includes(likeName.value);
    });
  } else {
    filteredManagecom.value = sys_managecom.value;
  }
};

// ======================== 表单操作方法 ========================
const resetForm = () => {
  form.value = {
    userId: undefined,
    deptId: undefined,
    userName: '',
    nickName: '',
    password: '',
    phonenumber: '',
    email: '',
    sex: undefined,
    status: '2',
    remark: '',
    postIds: [],
    roleIds: [],
    roleType: '',
    branchType: '',
    idNo: '',
    bindIp: '',
    accessTime: undefined,
    accType: 0,
    validDate: undefined,
    realName: '',
    sysType: 'N',
    manageCom: '',
    authTime: '',
    faceAuthRequired: '0'
  };

  filteredRoleOptions.value = [];
  resetPasswordStrength();

  // 重置验证相关状态
  secondVerifyVisible.value = false;
  currentVerifyUser.value = {};
  pendingFormData.value = null;

  nextTick(() => {
    if (userFormRef.value) {
      userFormRef.value.resetFields();
      setTimeout(() => {
        userFormRef.value?.clearValidate();
      }, 100);
    }

    if (configLoaded.value) {
      rules.value.password = createBasicPasswordRules({ fieldName: '用户密码' });
      setTimeout(() => {
        userFormRef.value?.clearValidate();
      }, 150);
    }
  });
};

const loadFormData = async () => {
  if (!isEditMode.value) {
    const { data: userData } = await api.getUser();
    roleOptions.value = userData.roles;
    form.value.password = initPassword.value || '';

    form.value.status = '2';

    // 如果当前用户有渠道设置，默认设置角色类型和渠道
    if (currentUserHasBranch.value) {
      // 默认设置为业务操作员
      form.value.roleType = UserRoleType.BUSINESS_OPERATOR;
      form.value.branchType = currentUser.value?.branchType || '';
      await filterRolesByUserRoleType(UserRoleType.BUSINESS_OPERATOR);
    }
  } else {
    const { data: userData } = await api.getUser(props.rowData!.userId);
    Object.assign(form.value, userData.user);

    if (userData.user.accessStartTime && userData.user.accessEndTime) {
      form.value.accessTime = [userData.user.accessStartTime, userData.user.accessEndTime];
    }
    if (userData.user.validStartDate && userData.user.validEndDate) {
      form.value.validDate = [userData.user.validStartDate, userData.user.validEndDate];
    }

    form.value.faceAuthRequired = userData.user.faceAuthRequired || '0';

    roleOptions.value = userData.roles;
    form.value.postIds = userData.postIds;
    form.value.roleIds = userData.roleIds;

    if (form.value.roleType) {
      await filterRolesByUserRoleType(form.value.roleType);
    }
  }

  nextTick(() => {
    if (userFormRef.value) {
      userFormRef.value.clearValidate();
    }
  });
};

// ======================== 验证方法 ========================

// ======================== 修改后的提交处理 ========================
const handleSubmit = () => {
  if (isReadOnlyMode.value) return;

  userFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) return;

    if (isEditMode.value) {
      // 保存表单数据，等待验证成功后使用
      pendingFormData.value = { ...form.value };
      // 设置验证用户信息
      currentVerifyUser.value = {
        userId: form.value.userId,
        userName: form.value.userName,
        phonenumber: form.value.phonenumber,
        email: form.value.email
      };
      // 显示二次验证对话框
      secondVerifyVisible.value = true;
    } else {
      // 新增用户直接保存
      await executeSubmit();
    }
  });
};

const executeSubmit = async (): Promise<void> => {
  buttonLoading.value = true;
  try {
    const submitData = pendingFormData.value || form.value;

    if (submitData.userId) {
      await api.updateUser(submitData);
      proxy?.$modal.msgSuccess('修改成功');
    } else {
      await api.addUser(submitData);
      proxy?.$modal.msgSuccess('新增成功');
    }

    emit('save');
    visibleProxy.value = false;
  } catch (error) {
    proxy?.$modal.msgError('保存失败');
  } finally {
    buttonLoading.value = false;
  }
};

// ======================== 生命周期 ========================
const initForm = async () => {
  const response = await optionselect('86', undefined);
  postOptions.value = response.data;

  if (!userStore.userInfo) {
    await userStore.getInfo();
  }

  // 加载临时用户有效期配置
  await loadTempUserValidityDays();
  filteredManagecom.value = sys_managecom.value;
};

watch(
  () => props.visible,
  async (visible) => {
    if (visible) {
      resetForm();
      await nextTick();
      await loadFormData();
    }
  }
);

onMounted(() => {
  initForm();
});
</script>

<style scoped>
:deep(.el-select) {
  width: 100%;
}

.divider-title {
  font-size: 16px;
  font-weight: 600;
  color: #409eff;
}

:deep(.el-divider__text) {
  background-color: transparent;
  padding: 0 20px;
}

:deep(.el-divider--horizontal) {
  margin: 20px 0;
}

.form-tip .el-icon {
  margin-right: 4px;
  vertical-align: middle;
}

.user-status-alert {
  margin-bottom: 20px;
}

.user-status-alert .mb-4 {
  margin-bottom: 16px !important;
}

.password-strength-container {
  margin-top: 8px;
}

.password-strength-header {
  display: flex;
  align-items: center;
  gap: 10px;
}

.strength-label {
  font-size: 12px;
  color: #606266;
  white-space: nowrap;
  font-weight: 500;
}

.strength-progress {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 8px;
}

.strength-progress-bg {
  flex: 1;
  height: 4px;
  background-color: #e9ecef;
  border-radius: 2px;
  overflow: hidden;
}

.strength-progress-fill {
  height: 100%;
  border-radius: 2px;
  transition:
    width 0.3s ease,
    background-color 0.3s ease;
}

.strength-indicators {
  display: flex;
  gap: 3px;
}

.strength-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #e9ecef;
  transition: all 0.3s ease;
}

.strength-dot.active {
  transform: scale(1.2);
}

.strength-level {
  font-size: 12px;
  font-weight: 500;
  min-width: 20px;
  text-align: center;
}

.password-help-icon {
  color: #909399;
  cursor: help;
  margin-left: 4px;
}

.password-help-icon:hover {
  color: #409eff;
}

.password-tooltip {
  max-width: 280px;
}

.tooltip-title {
  font-weight: 600;
  margin-bottom: 8px;
  color: #fff;
}

.password-rules {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.rule-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #d1d5db;
  transition: color 0.3s ease;
}

.rule-item.rule-met {
  color: #10b981;
}

.rule-item.rule-empty {
  color: #9ca3af;
}

.rule-item .el-icon {
  width: 14px;
  height: 14px;
  flex-shrink: 0;
}
</style>
