<template>
  <el-dialog class="compact-dialog" :model-value="visible" :title="title" width="500px"  @close="close" destroy-on-close>
    <el-form label-position="top" label-width="100px" class="compact-form">
      <el-form-item class="is-required" label="账号名称" prop="accountName">
        <el-input :model-value="form.anotherName" placeholder="请输入" maxlength="50"
          @update:model-value="change($event,'anotherName')" />
      </el-form-item>
      <el-form-item label="登录账号" prop="loginAccount">
        <template #label>
          <div class="inline-flex items-center">
            <span class="text-red-500 mr-4px">*</span>
            <span>登录账号</span>
            <span class="text-gray-500 text-12px">（支持手机号或工号登录，保存后无法修改）</span>
          </div>
        </template>
        <el-input :model-value="form.mobile" placeholder="请输入" maxlength="50" :disabled="disableMobile"
          @update:model-value="change($event,'mobile')" />
      </el-form-item>
      <el-form-item class="is-required" label="手机号" prop="phone">
        <el-input :model-value="form.phone" placeholder="请输入手机号" maxlength="20"
          @update:model-value="change($event,'phone')" />
      </el-form-item>
      <el-form-item label="角色权限" prop="role">
        <el-select filterable clearable multiple :model-value="form.roleIds" class="w-full" placeholder="请选择"
          @update:model-value="change($event,'roleIds')">
          <el-option v-for="item in roles" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="关联人员信息" prop="relatedHlwPeople">
        <el-select clearable filterable teleported :loading="staffLoading" :model-value="form.relatedHlwPeople" class="w-full" placeholder="请选择"
          @update:model-value="change($event,'relatedHlwPeople')">
          <template #empty>
            <div class="flex items-center justify-center">
              <el-empty :image-size="80" description="暂无人员信息">
                <el-button :icon="Plus" type="primary" @click="drawerVisible = true">添加人员</el-button>
                <el-button plain type="primary" :icon="Refresh" :loading="staffLoading"
                  @click="getAllStaff">刷新</el-button>
              </el-empty>
            </div>
          </template>
           <el-option>
            <div class="flex items-center justify-between" @click.stop=" () => {}">
              <div class="text-gray-500">请从列表中选择关联人员</div>
              <div>
                <el-button text type="primary" :icon="Plus" @click.stop="drawerVisible = true">添加人员</el-button>
                <el-button text type="primary" :icon="Refresh" :loading="staffLoading"
                  @click.stop="getAllStaff">刷新</el-button>
              </div>
            </div>
          </el-option>
            <el-option v-for="item in staffList" :key="item.value" :label="item.label" :value="item.value">
              <div class="">
                <span class="mr-10px inline-block min-w-100px">{{ item.label }}</span>
                <span>工号：{{ item.value }}</span>
              </div>
            </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="text-center">
        <el-button class="w-100px" @click="close">取消</el-button>
        <el-button class="w-100px" type="primary" :loading="loading" @click="save">保存</el-button>
      </div>
    </template>
  </el-dialog>
  <hlw-people-drawer :visible="drawerVisible" @close="drawerVisible=false" @change="getAllStaff()" />

</template>
<script setup>
import { ref, watch, computed } from "vue";
import { getRolesList } from '@/api/corp';
import { ElMessage } from "element-plus";
import { getAllDoctorNos } from "@/api/hlw";
import { addCorpAccount, editCorpAccount } from '@/api/account';
import { verifyString } from '@/utils/index'

import { Plus, Refresh } from "@element-plus/icons-vue";
import hlwPeopleDrawer from "@/views/hlw-people-manage/people-drawer.vue";

const props = defineProps({
  visible: { type: Boolean, default: false },
  data: { type: Object, default: () => ({}) },
});
const emits = defineEmits(["close", "change"]);
// const [namePass, name] = verifyString(form.value.name, '名称', 1, 50);
const rules = [
  { key: 'anotherName', test: val => verifyString(val, '账号名称', 1, 50) },
  {
    key: 'mobile', test: val => {
      if (/\W/.test(val)) {
        return [false, '登录账号只能包含字母、数字和下划线'];
      }
      return verifyString(val, '登录账号', 1, 50)
    }
  },
  { key: 'phone', test: val => {
    // 基础非空/长度校验
    const [pass, v] = verifyString(val, '手机号', 1, 20);
    if (!pass) return [false, v];
    const phone = v;
    // 支持中国大陆手机号和带区号的座机号（可带或不带连字符）
    const mobileRegex = /^1[3-9]\d{9}$/;
    const landlineRegex = /^0\d{2,3}-?\d{7,8}$/;
    if (!mobileRegex.test(phone) && !landlineRegex.test(phone)) {
      return [false, '请输入有效的手机号'];
    }
    return [true, phone];
  }, always: true },
  { key: 'roleIds', test: val => [true, Array.isArray(val) ? val : []] },
  { key: 'relatedHlwPeople', test: val => verifyString(val, '关联人员信息', 0, 50) }
]


const loading = ref(false);
const roles = ref([]);
const editForm = ref({});
const propsData = ref({})
const form = computed(() => ({ ...propsData.value, ...editForm.value }));
const disableMobile = computed(() => !!props.data._id && !!props.data.mobile);
const staffLoading = ref(false);
const drawerVisible = ref(false);

const staffList = ref([]);
const title = computed(() => (props.data._id ? "编辑账号" : "新增账号"));

function close() {
  emits("close");
}

function change(value, key) {
  editForm.value[key] = value;
}

async function save() {
  const isEdit = !!props.data._id;
  const data = {}
  for (const rule of rules) {
    // If a rule has `always: true`, validate it even on edit (useful for required fields like phone)
    const shouldTest = isEdit ? (rule.always ? true : (rule.key in editForm.value)) : true;
    if (shouldTest) {
      // 使用合并后的 form 值进行校验：编辑时如果没有在 editForm 中修改对应字段，应使用 propsData 中的原始值
      const currentValue = form.value[rule.key];
      const [pass, val] = rule.test(currentValue);
      if (!pass) {
        ElMessage.error(val);
        return;
      } else {
        data[rule.key] = val;
      }
    }
  }
  if (isEdit) {
    data.id = props.data._id;
  }
  const api = isEdit ? editCorpAccount : addCorpAccount;
  const res = await api(data);
  if (res.success) {
    ElMessage.success(res.message || (isEdit ? "编辑成功" : "新增成功"));
    emits("change");
    close();
  } else {
    ElMessage.error(res.message || "操作失败");
    return;
  }
}

async function getAllRoles() {
  const { success, message, data } = await getRolesList({ showOptions: true });
  roles.value = data && Array.isArray(data.data) ? data.data.map(i => ({
    value: i._id,
    label: i.roleName
  })) : [];
  if (!success) {
    ElMessage.error(message || "获取角色列表失败");
  }
}

async function getAllStaff() {
  staffLoading.value = true;
  const { data } = await getAllDoctorNos({ showAll: true });
  staffList.value = data && data.data && Array.isArray(data.data)
    ? data.data.map((i) => ({ label: i.doctorName, value: i.doctorNo }))
    : [];
  staffLoading.value = false;
}

watch(
  () => props.visible,
  (val) => {
    if (val) {
      propsData.value = { ...props.data };
      editForm.value = {};
      if (roles.value.length === 0) {
        getAllRoles()
      }
      if (staffList.value.length === 0) {
        getAllStaff();
      }

    }
  }
);
</script>
<style scoped>
/* 可根据需要自定义样式 */
</style>

