<template>
  <el-dialog v-model="visible" :title="dialogTitle" width="640px" destroy-on-close>
    <el-form ref="formRef" class="dialog-form" :model="form" :rules="rules" label-width="100px" label-suffix="：">
      <el-form-item label="登录账号" prop="userName">
        <el-input v-model="form.userName" placeholder="请输入登录账号" clearable />
      </el-form-item>
      <el-form-item label="关联律所" prop="roleId">
        <el-select
          v-model="form.roleId"
          placeholder="请选择关联律所"
          remote
          filterable
          reserve-keyword
          :remote-method="handleFirmRemote"
          :loading="props.lawFirmLoading"
          @visible-change="handleFirmDropdown"
        >
          <el-option v-for="item in lawFirmOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="登录密码" prop="userPassword">
        <el-input v-model="form.userPassword" placeholder="请输入登录密码" type="userPassword" show-user-password />
      </el-form-item>
      <el-form-item label="账号状态" prop="status">
        <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入备注信息" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false"> 取 消 </el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit"> 保 存 </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, computed, nextTick, watch } from "vue";
import type { FormInstance } from "element-plus";
import type { User } from "@/api/interface";

interface DialogOptions {
  title: string;
  mode: "add" | "edit";
  row?: Partial<User.ResUserList>;
  onSubmit: (params: Record<string, any>) => Promise<any>;
}

const props = defineProps<{
  lawFirmOptions: { label: string; value: string | number }[];
  lawFirmLoading?: boolean;
  fetchLawFirms?: (keyword?: string) => Promise<void>;
}>();

const visible = ref(false);
const loading = ref(false);
const formRef = ref<FormInstance>();
const options = ref<DialogOptions>({
  title: "",
  mode: "add",
  onSubmit: async () => Promise.resolve()
});

const form = reactive({
  id: "",
  userName: "",
  roleId: "",
  userPassword: "",
  status: 1,
  remark: "",
  roleName: ""
});

const dialogTitle = computed(() => options.value.title);

const rules = reactive({
  userName: [{ required: true, message: "请输入登录账号", trigger: "blur" }],
  roleId: [{ required: true, message: "请选择关联律所", trigger: "change" }],
  userPassword: [
    {
      validator: (_: any, value: string, callback: (error?: Error) => void) => {
        if (options.value.mode === "add" && !value) return callback(new Error("请输入登录密码"));
        callback();
      },
      trigger: "blur"
    }
  ]
});

const resetForm = () => {
  form.id = "";
  form.userName = "";
  form.roleId = "";
  form.userPassword = "";
  form.status = 1;
  form.remark = "";
  form.roleName = "";
};

const open = (payload: DialogOptions) => {
  resetForm();
  options.value = payload;
  if (payload.row) {
    Object.assign(form, payload.row);
    form.roleId = (payload.row?.roleId as string) || "";
  }
  const keyword = payload.row?.roleName || "";
  if (!props.lawFirmOptions.length || keyword) {
    props.fetchLawFirms?.(keyword);
  }
  visible.value = true;
  nextTick(() => formRef.value?.clearValidate());
};

watch(
  () => props.lawFirmOptions,
  list => {
    if (!form.roleId) return;
    const target = list.find(item => item.value === form.roleId);
    if (target) form.roleName = target.label;
  },
  { immediate: true }
);

const emits = defineEmits<{
  success: [];
}>();

const buildPayload = () => {
  const payload: Record<string, any> = {
    id: form.id,
    userName: form.userName,
    roleId: form.roleId,
    status: form.status,
    remark: form.remark
  };
  if (!payload.id) delete payload.id;
  if (form.userPassword) {
    payload.userPassword = form.userPassword;
  }
  return payload;
};

const handleSubmit = () => {
  formRef.value?.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      const payload = buildPayload();
      await options.value.onSubmit(payload);
      emits("success");
      visible.value = false;
    } finally {
      loading.value = false;
    }
  });
};

const handleFirmRemote = (keyword = "") => {
  props.fetchLawFirms?.(keyword.trim());
};

const handleFirmDropdown = (visible: boolean) => {
  if (visible && !props.lawFirmOptions.length) {
    props.fetchLawFirms?.("");
  }
};

defineExpose({
  open
});
</script>

<style scoped lang="scss">
.dialog-form {
  max-width: 520px;
  margin: 0 auto;
}
.form-tip {
  display: inline-block;
  margin-left: 12px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}
</style>
