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

import { h, ref } from 'vue';
import { useRouter } from 'vue-router';

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

import { message as Message, Modal, Tag } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  postMetersArchivesDown,
  postMetersCreate,
  postMetersDelete,
  postMetersPage,
  postMetersUpdate,
} from '#/api-client';
import { TableAction } from '#/components/table-action';
import { $t } from '#/locales';

import {
  addUserFormSchema,
  editUserFormSchemaEdit,
  meterTypeOptions,
  querySchema,
  rateOptions,
  tableSchema,
} from './schema';

defineOptions({
  name: 'AbpUser',
});

const router = useRouter();
const formOptions: VbenFormProps = {
  schema: querySchema.value,
};
const gridOptions: VxeGridProps<any> = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  columns: tableSchema.value,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  toolbarConfig: {
    custom: true,
  },
  customConfig: {
    storage: true,
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const { data } = await postMetersPage({
          body: {
            pageIndex: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          },
        });
        return data;
      },
    },
  },
};

const [Grid, gridApi] = useVbenVxeGrid({ formOptions, gridOptions });

const editRow: Record<string, any> = ref({});
const [UserModal, userModalApi] = useVbenModal({
  draggable: true,
  onConfirm: submit,
  onBeforeClose: () => {
    editRow.value = {};
    return true;
  },
});

const [AddForm, addFormApi] = useVbenForm({
  // 默认展开
  collapsed: false,
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    labelWidth: 110,
    componentProps: {
      class: 'w-4/5',
    },
  },
  layout: 'horizontal',
  schema: addUserFormSchema.value,
  showCollapseButton: false,
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

const [EditForm, editFormApi] = useVbenForm({
  // 默认展开
  collapsed: false,
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    labelWidth: 110,
    componentProps: {
      class: 'w-4/5',
    },
  },
  // 提交函数
  layout: 'horizontal',
  schema: editUserFormSchemaEdit.value,
  showCollapseButton: false,
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

// 新增和编辑提交的逻辑
async function submit() {
  const isEdit = !!editRow.value.id;
  const formApi = isEdit ? editFormApi : addFormApi;
  const api = isEdit ? postMetersUpdate : postMetersCreate;
  const { valid } = await formApi.validate();
  if (!valid) return;

  const formValues = await formApi.getValues();
  const fetchParams: any = isEdit
    ? {
      id: editRow.value.id,
      ...formValues,
      password: formValues.password || '000000',
    }
    : {
      ...formValues,
      password: formValues.password || '000000',
    };

  try {
    userModalApi.setState({ loading: true, confirmLoading: true });
    const resp = await api({ body: fetchParams });
    if (resp.data) {
      Message.success(
        editRow.value.id ? $t('common.editSuccess') : $t('common.addSuccess'),
      );
      userModalApi.close();
      gridApi.reload();
    } else {
      Message.error(
        editRow.value.id ? $t('common.editFail') : $t('common.addFail'),
      );
    }
  } finally {
    userModalApi.setState({ loading: false, confirmLoading: false });
  }
}

async function onEdit(record: any) {
  editRow.value = record;
  userModalApi.open();
  editFormApi.setValues({ ...record });
}

function onDel(row: any) {
  Modal.confirm({
    title: `${$t('common.confirmDelete')}${row.meterName} ?`,
    onOk: async () => {
      const result = await postMetersDelete({ body: { id: row.id } });
      if (result) {
        gridApi.reload();
        Message.success($t('common.deleteSuccess'));
      } else {
        Message.error($t('common.deleteFail'));
      }
    },
  });
}
const toStatusData = (row: Record<string, any>) => {
  // 或者使用编程式导航
  router.push({
    path: '/iotdb/deviceData',
    query: {
      DeviceType: row.meterType,
      DeviceId: row.meterId,
      FocusAddress: row.focusAddress,
      SystemName: row.businessSystemName,
    },
  });
};
// 档案下发
const archivesIssued = async (row: Record<string, any>) => {
  const result = await postMetersArchivesDown({
    body: {
      meterAddress: row.meterAddress,
      meterType: row.meterType,
      focusAddress: row.focusAddress,
    },
  });
  if (result) {
    gridApi.reload();
    Message.success($t('common.success'));
  } else {
    Message.error($t('common.error'));
  }
};
const openAddModal = async () => {
  editRow.value = {};
  userModalApi.open();
};
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-actions>
        <TableAction :actions="[
          {
            label: $t('common.add'),
            type: 'primary',
            icon: 'ant-design:plus-outlined',
            onClick: openAddModal.bind(null),
            auth: ['AbpIdentity.Users.Create'],
          },
        ]" />
      </template>

      <template #isMeterType="{ row }">
        {{ meterTypeOptions[row.meterType - 1]?.label }}
      </template>
      <template #isSingleRate="{ row }">
        {{rateOptions.find((item) => item.value === row.singleRate)?.label}}
      </template>
      <template #isArchiveStatus="{ row }">
        {{
          row.archiveStatus ? $t('common.Issued') : $t('common.Undistributed')
        }}
      </template>
      <template #isTripState="{ row }">
        {{ row.tripState ? $t('common.SwitchOff') : $t('common.Closing') }}
      </template>
      <template #isHaveValve="{ row }">
        <component :is="h(Tag, { color: row.haveValve ? 'green' : 'red' }, () =>
          row.haveValve ? $t('common.yes') : $t('common.no'),
        )
          " />
      </template>
      <template #isSelfDevelop="{ row }">
        <component :is="h(Tag, { color: row.selfDevelop ? 'green' : 'red' }, () =>
          row.selfDevelop ? $t('common.yes') : $t('common.no'),
        )
          " />
      </template>
      <template #isDynamicPassword="{ row }">
        <component :is="h(Tag, { color: row.dynamicPassword ? 'green' : 'red' }, () =>
          row.dynamicPassword ? $t('common.yes') : $t('common.no'),
        )
          " />
      </template>
      <template #isEnable="{ row }">
        <component :is="h(Tag, { color: row.enabled ? 'green' : 'red' }, () =>
          row.enabled ? $t('common.yes') : $t('common.no'),
        )
          " />
      </template>

      <template #action="{ row }">
        <TableAction :actions="[
          {
            label: $t('common.edit'),
            type: 'link',
            size: 'small',
            auth: ['AbpIdentity.Users.Update'],
            onClick: onEdit.bind(null, row),
          },
        ]" :drop-down-actions="[
            {
              label: $t('common.delete'),
              icon: 'ant-design:delete-outlined',
              type: 'primary',
              auth: ['AbpIdentity.Users.Delete'],
              popConfirm: {
                title: $t('common.askConfirmDelete'),
                confirm: onDel.bind(null, row),
              },
            },
            {
              label: $t('abp.meters.pointData'),
              icon: 'ant-design:profile-outlined',
              type: 'primary',
              auth: ['AbpIdentity.Users.Delete'],
              onClick: toStatusData.bind(null, row),
            },
            {
              label: $t('abp.meters.archivesIssued'),
              icon: 'ant-design:cloud-download-outlined',
              type: 'primary',
              auth: ['AbpIdentity.Users.Delete'],
              onClick: archivesIssued.bind(null, row),
            },
          ]" />
      </template>
    </Grid>
    <UserModal :title="editRow.id ? $t('common.edit') : $t('common.add')" class="w-[800px]">
      <component :is="editRow.id ? EditForm : AddForm" />
    </UserModal>
  </Page>
</template>
