<template>
  <el-dialog v-model="visible" title="新增开票信息" width="800px" @close="handleClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="纳税人识别号" prop="taxId">
            <el-input v-model="form.taxId" placeholder="" disabled>
              <!-- <template #append>
                <el-button @click="handleResetTaxId">还原</el-button>
              </template> -->
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="开户行行号" prop="bankCode">
            <el-input v-model="form.bankCode" placeholder="请输入开户行行号" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="开户行名称" prop="bankId">
            <el-select v-model="form.bankId" placeholder="请选择" class="w-full" filterable @change="handleBankChange">
              <el-option v-for="bank in bankList" :key="bank.id" :label="`${bank.bnId} , ${bank.bnName}`" :value="bank.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="银行账户" prop="bankAccount">
            <el-input v-model="form.bankAccount" placeholder="请输入银行账户" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="电话" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入电话" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="地址" prop="address">
            <el-input v-model="form.address" placeholder="" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="是否主账号" prop="isPrimaryAccount">
            <el-radio-group v-model="form.isPrimaryAccount">
              <el-radio v-for="dict in sys_platform_yes_no" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确认</el-button>
        <el-button @click="handleClose">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import type { InvoiceInfoForm } from '@/api/customer/customerFile/invoiceInfo/types';
import { listBank } from '@/api/company/bank';
import { BankVO } from '@/api/company/bank/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_platform_yes_no } = toRefs<any>(proxy?.useDict('sys_platform_yes_no'));

const bankList = ref<BankVO[]>([]);
interface Props {
  modelValue: boolean;
  editData?: InvoiceInfoForm;
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void;
  (e: 'confirm', data: InvoiceInfoForm): void;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  editData: undefined
});

const emit = defineEmits<Emits>();

const formRef = ref<any>(null);

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

const form = reactive<InvoiceInfoForm>({
  taxId: undefined,
  bankCode: '',
  bankId: undefined,
  bankName: '',
  bankAccount: '',
  phone: '',
  address: '',
  isPrimaryAccount: '0',
  status: '0',
  remark: ''
});

const rules = {
  bankCode: [
    { required: true, message: '请输入开户行行号', trigger: 'blur' },
    { pattern: /^[0-9]+$/, message: '开户行行号只能包含数字', trigger: 'blur' }
  ],
  bankId: [{ required: true, message: '请选择开户行名称', trigger: 'change' }],
  bankAccount: [
    { required: true, message: '请输入银行账户', trigger: 'blur' },
    { pattern: /^[0-9]+$/, message: '银行账户只能包含数字', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' } // 去掉 as RegExp
  ]
};

const handleBankChange = (bankId: string | number) => {
  const bank = bankList.value.find((b) => b.id === bankId);
  form.bankName = bank?.bnName || '';
};

const handleResetTaxId = () => {
  form.taxId = undefined;
};

// 监听编辑数据
watch(
  () => props.editData,
  (newVal) => {
    if (newVal) {
      Object.assign(form, newVal);
    }
  },
  { immediate: true, deep: true }
);

// 确认
const handleConfirm = async () => {
  try {
    await formRef.value?.validate();
    emit('confirm', { ...form });
    handleClose();
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

// 获取银行列表
const getBankList = async () => {
  try {
    const res = await listBank({ pageNum: 1, pageSize: 9999, isShow: '0' });
    bankList.value = res.rows || [];
  } catch (error) {
    console.error('获取银行列表失败', error);
  }
};
onMounted(() => {
  getBankList();
});
// 关闭
const handleClose = () => {
  formRef.value?.resetFields();
  Object.assign(form, {
    taxId: undefined,
    bankCode: '',
    bankId: undefined,
    bankName: '',
    bankAccount: '',
    phone: '',
    address: '',
    isPrimaryAccount: '0',
    status: '0',
    remark: ''
  });
  emit('update:modelValue', false);
};
</script>
