<template>
  <el-dialog v-model="visible" :title="dialogTitle" width="640px" destroy-on-close>
    <div class="dialog-form">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="150px" label-suffix="：">
        <el-form-item label="律所名称" prop="firmName">
          <el-input v-model="form.firmName" placeholder="请输入律所名称" clearable />
        </el-form-item>
        <el-form-item label="负责人姓名" prop="directorName">
          <el-input v-model="form.directorName" placeholder="请输入负责人姓名" clearable />
        </el-form-item>
        <el-form-item label="律所位置" prop="address">
          <el-input v-model="form.address" placeholder="请输入律所位置" clearable />
        </el-form-item>
        <el-form-item label="社会统一信用代码" prop="creditCode">
          <el-input v-model="form.creditCode" placeholder="请输入社会统一信用代码" clearable />
        </el-form-item>
        <el-form-item label="信息服务费" prop="platformCommissionRatio">
          <el-input-number v-model="form.platformCommissionRatio" :min="1" :max="99" :step="1" controls-position="right" />
          <span class="form-tip">仅支持 1 - 99 的整数</span>
        </el-form-item>
        <el-form-item label="收款账号" prop="paymentAccount">
          <div class="bank-card-input">
            <el-input v-model="bankCardDisplay" placeholder="请输入银行卡号" maxlength="23" clearable :disabled="isEditMode" />
          </div>
        </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 } from "vue";
import { ElMessage, type FormInstance } from "element-plus";

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

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: "",
  firmName: "",
  directorName: "",
  address: "",
  creditCode: "",
  paymentAccount: "",
  platformCommissionRatio: 3
});
const bankCardInput = ref("");
const bankCardReg = /^([1-9]\d{15}|\d{17}|\d{18}|\d{19})$/;

const validateServiceFee = (_rule: any, value: number | string, callback: (err?: Error) => void) => {
  if (value === undefined || value === null || value === "") {
    callback(new Error("请输入信息服务费"));
    return;
  }
  const numericValue = Number(value);
  if (!Number.isFinite(numericValue) || !Number.isInteger(numericValue)) {
    callback(new Error("信息服务费需为整数"));
    return;
  }
  if (numericValue < 1 || numericValue > 99) {
    callback(new Error("信息服务费范围为 1-99"));
    return;
  }
  callback();
};

const rules = reactive({
  firmName: [{ required: true, message: "请输入律所名称", trigger: "blur" }],
  directorName: [{ required: true, message: "请输入负责人姓名", trigger: "blur" }],
  address: [{ required: true, message: "请输入律所位置", trigger: "blur" }],
  creditCode: [{ required: true, message: "请输入社会统一信用代码", trigger: "blur" }],
  paymentAccount: [
    { required: true, message: "请输入收款账号", trigger: "blur" },
    {
      validator: (_rule, _value, callback) => {
        const card = bankCardInput.value.trim();
        if (!card) {
          callback(new Error("请输入收款账号"));
        } else if (!bankCardReg.test(card)) {
          callback(new Error("请输入正确的银行卡号"));
        } else {
          callback();
        }
      },
      trigger: "change"
    }
  ],
  platformCommissionRatio: [
    { required: true, message: "请输入信息服务费", trigger: "change" },
    { validator: validateServiceFee, trigger: "change" }
  ]
});

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

const resetForm = () => {
  form.id = "";
  form.firmName = "";
  form.directorName = "";
  form.address = "";
  form.creditCode = "";
  form.paymentAccount = "";
  form.platformCommissionRatio = 3;
  bankCardInput.value = "";
};

const open = (payload: DialogOptions) => {
  resetForm();
  options.value = payload;
  if (payload.row) {
    Object.assign(form, payload.row);
    bankCardInput.value = (form.paymentAccount || "").replace(/\s+/g, "");
    form.platformCommissionRatio = Number(payload.row.platformCommissionRatio ?? 3);
    form.creditCode = payload.row.creditCode || "";
  } else {
    form.platformCommissionRatio = 3;
    form.creditCode = "";
    bankCardInput.value = "";
    form.paymentAccount = "";
  }
  visible.value = true;
  nextTick(() => formRef.value?.clearValidate());
};

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

const isEditMode = computed(() => !!form.id);

const bankCardDisplay = computed({
  get: () => formatCard(bankCardInput.value),
  set: val => {
    bankCardInput.value = val.replace(/\s+/g, "");
    form.paymentAccount = bankCardInput.value;
    formRef.value?.validateField("paymentAccount").catch(() => {});
  }
});

const formatCard = (card: string) => {
  return card
    .replace(/\s+/g, "")
    .replace(/(.{4})/g, "$1 ")
    .trim();
};

const handleSubmit = () => {
  form.paymentAccount = bankCardInput.value;
  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: 560px;
  margin: 0 auto;
}
.bank-card-input {
  display: flex;
  gap: 12px;
  align-items: stretch;
  margin-bottom: 8px;
}
.bank-card-input .el-input {
  flex: 1;
}
.bank-card-tags {
  display: flex;
  flex-wrap: wrap;
}
.bank-card-tip {
  display: flex;
  padding-bottom: 0;
  margin-left: 4px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}
.form-tip {
  margin-left: 12px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}
</style>
