<template>
  <el-dialog v-model="visible" :title="dialogTitle" width="760px" destroy-on-close>
    <div class="dialog-form">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" label-suffix="：">
        <el-form-item label="律师姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入律师姓名" clearable />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" clearable />
        </el-form-item>
        <el-form-item label="从业时间" prop="practiceStartDate">
          <el-date-picker
            v-model="form.practiceStartDate"
            type="date"
            placeholder="请选择从业时间"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <!-- <el-form-item label="专业领域" prop="expertiseAreaInfo">
          <el-select v-model="form.expertiseAreaInfo" placeholder="请选择专业领域" filterable style="width: 100%">
            <el-option v-for="item in props.professionalOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="法律场景" prop="firstLevelScenario">
          <el-tree-select
            v-model="form.firstLevelScenario"
            :data="props.sceneOptions"
            :props="sceneTreeProps"
            check-strictly
            placeholder="请选择法律场景"
            style="width: 100%"
            clearable
          />
        </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="lawFirmId">
          <el-select
            v-model="form.lawFirmId"
            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="paymentNum">
          <el-select
            v-model="form.paymentNum"
            placeholder="请选择所属律所后选择收款账号"
            :disabled="paymentOptions.length === 0"
            filterable
            clearable
          >
            <el-option
              v-for="item in paymentOptions"
              :key="item.id ?? item.paymentAccount"
              :label="item.paymentAccount"
              :value="item.paymentAccount"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <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 { ref, reactive, computed, nextTick, watch } from "vue";
import type { FormInstance } from "element-plus";

interface DialogOptions {
  title: string;
  row?: Record<string, any>;
  onSubmit: (params: Record<string, any>) => Promise<any>;
}

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

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

const form = reactive({
  id: "",
  name: "",
  phone: "",
  practiceStartDate: "",
  // expertiseAreaInfo: "",
  firstLevelScenario: "",
  status: 1,
  paymentNum: "",
  lawFirmId: ""
});

const rules = reactive({
  name: [{ required: true, message: "请输入律师姓名", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    { pattern: /^1\d{10}$/, message: "请输入正确手机号", trigger: "blur" }
  ],
  practiceStartDate: [{ required: true, message: "请输入从业时间", trigger: "blur" }],
  // expertiseAreaInfo: [{ required: true, message: "请输入专业领域", trigger: "blur" }],
  firstLevelScenario: [{ required: true, message: "请选择法律场景", trigger: "change" }],
  paymentNum: [{ required: true, message: "请选择收款账号", trigger: "change" }],
  lawFirmId: [{ required: true, message: "请选择所属律所", trigger: "change" }]
});

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

const resetForm = () => {
  form.id = "";
  form.name = "";
  form.phone = "";
  form.practiceStartDate = "";
  // form.expertiseAreaInfo = "";
  form.firstLevelScenario = "";
  form.status = 1;
  form.paymentNum = "";
  form.lawFirmId = "";
};

const sceneTreeProps = { value: "id", label: "name", children: "children" };

const paymentOptions = computed(() => {
  const target = props.lawFirmOptions.find(option => option.value === form.lawFirmId);
  return target?.paymentList || [];
});

const initializingFirm = ref(false);

const open = (payload: DialogOptions) => {
  resetForm();
  options.value = payload;
  initializingFirm.value = true;
  if (payload.row) {
    Object.assign(form, payload.row);
    if (payload.row.firmId && !payload.row.lawFirmId) {
      form.lawFirmId = payload.row.firmId;
    }
  }
  props.fetchLawFirms?.(payload.row?.firmName || "");
  visible.value = true;
  nextTick(() => {
    formRef.value?.clearValidate();
    initializingFirm.value = false;
  });
};

watch(
  () => form.lawFirmId,
  () => {
    if (initializingFirm.value) return;
    form.paymentNum = "";
    formRef.value?.validateField("paymentNum").catch(() => {});
  }
);

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

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

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

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

defineExpose({
  open
});
</script>

<style scoped lang="scss">
.dialog-form {
  max-width: 640px;
  margin: 0 auto;
}
</style>
