<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { EmployeeFamilyMembersVo } from '#/api/hr/employeeModel';

import { nextTick, ref, watch } from 'vue';

import { cloneDeep } from '@vben/utils';

import { Button, Space } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';

defineOptions({ name: 'FamilyMembersTable', inheritAttrs: false });

const props = withDefaults(
  defineProps<{
    modelValue?: EmployeeFamilyMembersVo[];
  }>(),
  {
    modelValue: () => [],
  },
);

const emit = defineEmits<{
  change: [EmployeeFamilyMembersVo[]];
  'update:modelValue': [EmployeeFamilyMembersVo[]];
}>();

type FamilyRow = EmployeeFamilyMembersVo & { _rid: number };

const relationOptions = [
  { label: '父亲', value: '父亲' },
  { label: '母亲', value: '母亲' },
  { label: '夫妻', value: '夫妻' },
  { label: '儿子', value: '儿子' },
  { label: '女儿', value: '女儿' },
  { label: '哥哥', value: '哥哥' },
  { label: '弟弟', value: '弟弟' },
  { label: '姐姐', value: '姐姐' },
  { label: '妹妹', value: '妹妹' },
];

// const yesNoTagOptions = [
//   { color: 'success', label: '是', value: 'Y' },
//   { color: 'default', label: '否', value: 'N' },
// ];

const tableData = ref<FamilyRow[]>(
  props.modelValue.map((r) => ({ ...r, _rid: Date.now() + Math.random() })),
);
let ridSeed = Date.now();

const skipReload = ref(false);

watch(
  () => props.modelValue,
  (val) => {
    if (skipReload.value) return;
    const rows = (val || []).map((r) => ({ ...r, _rid: ++ridSeed }));
    tableData.value = rows;
    reloadGridAndSyncRadio();
  },
);

function emitChange() {
  skipReload.value = true;
  const sanitized = tableData.value.map(({ _rid, ...rest }) => rest);
  emit('update:modelValue', sanitized as EmployeeFamilyMembersVo[]);
  emit('change', sanitized as EmployeeFamilyMembersVo[]);
  nextTick(() => {
    skipReload.value = false;
  });
}

function createDefaultRow(): FamilyRow {
  ridSeed += 1;
  return {
    // 新增行不带后端ID，后端根据是否存在ID判断新增/编辑
    id: undefined as unknown as number,
    relation: '父亲',
    name: '',
    birthDate: '',
    companyAndJob: '',
    contact: '',
    emergencyFlag: 'N',
    _rid: ridSeed,
  } as FamilyRow;
}

function reloadGridAndSyncRadio() {
  gridApi.grid?.loadData(tableData.value);
  if (tableData.value && tableData.value.length > 0) {
    const emergency = tableData.value.find((r) => r.emergencyFlag === 'Y');
    if (emergency) {
      nextTick(() => gridApi.grid?.setRadioRow(emergency));
    } else {
      nextTick(() => gridApi.grid?.clearRadioRow());
    }
  }
}

const gridOptions: VxeGridProps<FamilyRow> = {
  columns: [
    { title: '序号', type: 'seq', width: 60 },
    {
      type: 'radio',
      width: 110,
      title: '是否紧急联系人',
    },
    {
      editRender: { name: 'select', options: relationOptions },
      field: 'relation',
      title: '关系',
      minWidth: 120,
    },
    {
      editRender: { name: 'input' },
      field: 'name',
      title: '姓名',
      minWidth: 140,
    },
    {
      editRender: {
        name: 'input',
        props: { placeholder: 'YYYY-MM-DD' },
      },
      field: 'birthDate',
      title: '出生日期',
      minWidth: 140,
    },
    {
      editRender: { name: 'input' },
      field: 'companyAndJob',
      title: '工作单位职务',
      minWidth: 200,
    },
    {
      editRender: {
        name: 'input',
        props: { placeholder: '手机或座机' },
      },
      field: 'contact',
      title: '联系方式',
      minWidth: 160,
    },
    // {
    //   field: 'emergencyFlag',
    //   title: '是否紧急联系人',
    //   cellRender: { name: 'CellTag', options: yesNoTagOptions },
    //   minWidth: 140,
    // },
    { slots: { default: 'action' }, title: '操作', width: 120 },
  ],
  data: tableData.value,
  editConfig: { mode: 'row', trigger: 'click' },
  // editRules: {
  //   name: [{ required: true, message: '姓名不能为空' }],
  //   relation: [{ required: true, message: '关系不能为空' }],
  //   contact: [
  //     {
  //       validator({ cellValue }) {
  //         if (isValidContact(cellValue)) {
  //           return new Error('联系方式格式不正确');
  //         }
  //       },
  //     },
  //   ],
  // },
  height: 'auto',
  keepSource: true,
  radioConfig: { strict: true },
  rowConfig: { keyField: '_rid' },
  pagerConfig: { enabled: false },
  toolbarConfig: { enabled: true, refresh: false, custom: false, zoom: false },
  showOverflow: true,
};

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions,
  gridEvents: {
    radioChange: onRadioChange,
    editClosed: onEditClosed,
  },
});

function onRadioChange() {
  const record = gridApi.grid.getRadioRecord();
  const rid = record?._rid;
  tableData.value.forEach((r) => {
    r.emergencyFlag = r._rid === rid ? 'Y' : 'N';
  });
  emitChange();
}

// function isValidContact(value: string) {
//   const mobile = /^1[3-9]\d{9}$/;
//   const landline = /^0\d{2,3}-\d{7,8}$/;
//   return mobile.test(value) || landline.test(value);
// }

async function onEditClosed() {
  // const row = params?.row;
  // if (row) {
  //   const errors: string[] = [];
  //   if (!row.relation) errors.push('请填写关系');
  //   if (!row.name) errors.push('请填写姓名');
  //   if (row.contact && !isValidContact(row.contact))
  //     errors.push('联系方式格式不正确');
  //   if (errors.length > 0) {
  //     message.warning(errors.join('、'));
  //     nextTick(() => gridApi.grid?.setEditRow(row));
  //     return;
  //   }
  // }
  // const errMap = await gridApi.grid?.validate();
  // if (errMap) {
  //   message.warning('校验不通过');
  // }

  tableData.value = await gridApi.grid.getFullData();
  emitChange();
}

async function handleAdd() {
  await gridApi.grid?.clearEdit();
  const row = createDefaultRow();
  tableData.value.push(row);
  gridApi.grid?.loadData(tableData.value);
  nextTick(() => gridApi.grid?.setEditRow(row));
  emitChange();
}

function handleDelete(row: FamilyRow) {
  tableData.value = tableData.value.filter((r) => r._rid !== row._rid);
  gridApi.grid?.loadData(tableData.value);
  emitChange();
}

defineExpose({
  getData: () => {
    const sanitized = tableData.value.map(({ _rid, ...rest }) => rest);
    return cloneDeep(sanitized) as EmployeeFamilyMembersVo[];
  },
  setData: (rows: EmployeeFamilyMembersVo[]) => {
    const mapped = (rows || []).map((r) => ({ ...r, _rid: ++ridSeed }));
    tableData.value = mapped;
    reloadGridAndSyncRadio();
    emitChange();
  },
  resetData: () => {
    tableData.value = [];
    reloadGridAndSyncRadio();
    emitChange();
  },
});
</script>
<template>
  <div class="flex h-full flex-col" id="family-members-table">
    <Grid table-title="家庭成员信息">
      <template #toolbar-tools>
        <Space>
          <Button type="primary" @click="handleAdd">新增成员</Button>
        </Space>
      </template>
      <template #action="{ row }">
        <Button danger @click.stop="handleDelete(row)">删除</Button>
      </template>
    </Grid>
  </div>
</template>
