<script lang="ts" setup>
import type { VxeGridListeners } from '#/adapter/vxe-table';

import { computed, ref } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';

import { Button, Image, message, Avatar } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { TableAction } from '#/components/table-action';
import {
  createAdmin,
  deleteAdmin,
  generateLoginAccount,
  resetPassword,
  updateAdmin,
} from '#/views/system/admin/api';

import { normalizeAdminPayload } from './admin-payload';
import { createAdminModalFormProps } from './form-schemas';
import { createAdminSearchOptions } from './search-config';
import { formatAddressDisplay } from '#/util/address-index';

import { createAdminGridOptions } from './table-config';
import { getRoleMeta } from './role-meta';
import DoctorCardModal from '#/views/doctor/doctor/components/DoctorCardModal.vue';
import { resolveAvatarUrl } from '#/views/system/store-input/utils/inputUser';

function formatAdminRegion(row: {
  province_id?: number;
  city_id?: number;
}): string {
  if (row.province_id && row.city_id) {
    return formatAddressDisplay([row.province_id, row.city_id]);
  }
  return '-';
}

const DEFAULT_AVATAR =
  'https://xiaokang88.oss-cn-hangzhou.aliyuncs.com/xk_upload_20251022/20251022104156946505ca86d97626c08882f31797dbcef49c.png';

const props = defineProps<{
  roleId: number;
}>();

const meta = computed(() => getRoleMeta(props.roleId));

const hasTopTableDropDownActions = ref(false);
const isUpdate = ref(false);
const modalGridApi = ref();

const [Form, formApi] = useVbenForm(
  createAdminModalFormProps(props.roleId, meta.value.formType),
);

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    const e = await formApi.validate();
    if (e.valid) {
      const values = await formApi.getValues();
      const payload = normalizeAdminPayload(
        { ...values, role_id: props.roleId },
        meta.value.formType,
      );
      modalApi.setState({ loading: true, confirmLoading: true });
      const submitApi = isUpdate.value ? updateAdmin : createAdmin;
      submitApi(payload)
        .then(() => {
          message.success('保存成功');
          modalGridApi.value?.reload();
          modalApi.close();
        })
        .finally(() => {
          modalApi.setState({ loading: false, confirmLoading: false });
        });
    }
  },
  onOpenChange(isOpen: boolean) {
    const data = modalApi.getData<Record<string, any>>();
    modalGridApi.value = isOpen ? data?.gridApi : null;
    if (isOpen) {
      const { values = {}, update = false } = data ?? {};
      isUpdate.value = !!update;

      if (update && values?.id) {
        const formValues = { ...values };
        if (formValues.province_id && formValues.city_id) {
          formValues.address = [formValues.province_id, formValues.city_id];
        }
        formValues.role_id = props.roleId;
        formApi.setValues(formValues);
        return;
      }

      isUpdate.value = false;
      formApi.resetForm();
      formApi.setValues({
        role_id: props.roleId,
        avatar: DEFAULT_AVATAR,
      });
    }
  },
});

const [DoctorCardModals, DoctorCardModalApi] = useVbenModal({
  connectedComponent: DoctorCardModal,
});

const openDoctorCard = (row: { doctor_id?: number }) => {
  if (!row.doctor_id) return;
  DoctorCardModalApi.setData({ su_id: row.doctor_id });
  DoctorCardModalApi.open();
};

const gridEvents: VxeGridListeners<any> = {
  checkboxChange() {
    const records = gridApi.grid.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  },
  checkboxAll() {
    const records = gridApi.grid.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: createAdminSearchOptions(),
  gridOptions: createAdminGridOptions(props.roleId, meta.value.formType),
  gridEvents,
});

const showModal = (data: Record<string, any> = {}, update = false) => {
  modalApi.setData({
    values: data,
    update,
    gridApi,
  });
  modalApi.open();
};

const deleteApi = (row: number | false) => {
  let ids: number[] = [];
  if (row) {
    ids.push(row);
  } else {
    ids = gridApi.grid.getCheckboxRecords().map((item) => item.id);
  }
  deleteAdmin({ ids }).then(() => {
    message.success('删除成功!');
    gridApi.query();
  });
};

const resetPasswordApi = (id: number) => {
  resetPassword(id).then(() => {
    message.success('重置成功!');
    gridApi.query();
  });
};

const generateAccountApi = async (row: { id: number }) => {
  try {
    const result = await generateLoginAccount(row.id);
    if (result.login_account) {
      message.success('生成账号成功');
      gridApi.query();
    }
  } catch (error: any) {
    message.error(error.message || '生成账号失败');
  }
};

const copyToClipboard = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text);
    message.success('复制成功');
  } catch {
    const textArea = document.createElement('textarea');
    textArea.value = text;
    textArea.style.position = 'fixed';
    textArea.style.left = '-999999px';
    document.body.appendChild(textArea);
    textArea.select();
    try {
      document.execCommand('copy');
      message.success('复制成功');
    } catch {
      message.error('复制失败');
    }
    document.body.removeChild(textArea);
  }
};
</script>

<template>
  <Page auto-content-height :title="meta.title">
    <Modal
      :title="`${isUpdate ? '编辑' : '新增'}${meta.title}`"
      class="w-[60%]"
    >
      <Form />
    </Modal>
    <DoctorCardModals />
    <Grid>
      <template #toolbar-buttons>
        <TableAction
          :actions="[
            {
              label: '新增',
              type: 'primary',
              icon: 'ant-design:plus-outlined',
              onClick: () => showModal({}, false),
            },
          ]"
          :drop-down-actions="[
            {
              label: '删除',
              icon: 'ant-design:delete-outlined',
              ifShow: hasTopTableDropDownActions,
              popConfirm: {
                title: '确定删除吗？',
                confirm: deleteApi.bind(null, false),
              },
            },
          ]"
        >
          <template #more>
            <Button style="margin-left: 16px">
              批量操作
              <Icon icon="ant-design:down-outlined" />
            </Button>
          </template>
        </TableAction>
      </template>
      <template #avatar="{ row }">
        <Image :src="row.avatar" height="30" width="30" />
      </template>
      <template #nick_name="{ row }">
        <Button
          v-if="meta.formType === 'doctor' && row.doctor_id"
          type="link"
          size="small"
          @click="openDoctorCard(row)"
        >
          {{ row.nick_name }}
        </Button>
        <span v-else>{{ row.nick_name }}</span>
      </template>
      <template #region="{ row }">
        {{ formatAdminRegion(row) }}
      </template>
      <template #store_name="{ row }">
        <div v-if="row.store?.name" class="flex items-center gap-2">
          <Avatar
            :src="resolveAvatarUrl(row.store?.pic)"
            :size="28"
            shape="square"
          >
            {{ (row.store.name || '?').charAt(0) }}
          </Avatar>
          <div class="min-w-0">
            <div class="truncate">{{ row.store.name }}</div>
            <div class="text-xs text-gray-400">ID: {{ row.store_id }}</div>
          </div>
        </div>
        <span v-else-if="row.store_id">诊所 #{{ row.store_id }}</span>
        <span v-else>-</span>
      </template>
      <template #doctor_profile="{ row }">
        <Button
          v-if="row.doctor_profile?.name || row.doctor_id"
          type="link"
          size="small"
          class="!h-auto !p-0"
          @click="openDoctorCard(row)"
        >
          <div class="flex items-center gap-2 text-left">
            <Avatar
              :src="resolveAvatarUrl(row.doctor_profile?.avatar)"
              :size="28"
            >
              {{ (row.doctor_profile?.name || '?').charAt(0) }}
            </Avatar>
            <div class="min-w-0">
              <div class="truncate text-[#1677ff]">
                {{ row.doctor_profile?.name || `su_id: ${row.doctor_id}` }}
              </div>
              <div v-if="row.doctor_profile?.mobile" class="text-xs text-gray-400">
                {{ row.doctor_profile.mobile }}
              </div>
            </div>
          </div>
        </Button>
        <span v-else>-</span>
      </template>
      <template #login_account="{ row }">
        <span v-if="row.login_account">
          <Button
            type="link"
            size="small"
            @click="copyToClipboard(row.login_account)"
          >
            {{ row.login_account }}
          </Button>
        </span>
        <Button
          v-else
          type="link"
          size="small"
          @click="generateAccountApi(row)"
        >
          生成账号
        </Button>
      </template>
      <template #action="{ row }">
        <TableAction
          :actions="[
            {
              label: '编辑',
              type: 'link',
              icon: 'uil:edit',
              size: 'small',
              onClick: showModal.bind(null, row, true),
            },
            {
              label: '删除',
              type: 'link',
              icon: 'ant-design:delete-outlined',
              size: 'small',
              popConfirm: {
                title: '确定删除吗？',
                confirm: deleteApi.bind(null, row.id),
              },
            },
          ]"
          :drop-down-actions="[
            {
              label: '重置密码',
              type: 'link',
              icon: 'bitcoin-icons:refresh-filled',
              size: 'small',
              popConfirm: {
                title: '确定重置密码吗？',
                confirm: resetPasswordApi.bind(null, row.id),
              },
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
