<script setup lang="ts">
import { Page, useVbenModal, type VbenFormProps } from '@vben/common-ui';
import { getVxePopupContainer } from '@vben/utils';
import { Modal, Popconfirm, Space } from 'ant-design-vue';
import {
  useVbenVxeGrid,
  vxeCheckboxChecked,
  type VxeGridProps
} from '#/adapter/vxe-table';
import {onMounted} from "vue";
import {
  contingenPlanExport,
  contingenPlanList,
  contingenPlanRemove,
  contingenPlanUpdate
} from '#/api/property/customerService/contingenPlan';
import type { ContingenPlanForm } from '#/api/property/customerService/contingenPlan/model';
import { commonDownloadExcel } from '#/utils/file/download';

import contingenPlanModal from './contingenPlan-modal.vue';
import contingenPlanDetail from './contingenPlan-detail.vue';
import { columns, querySchema } from './data';
import {personList} from "#/api/property/resident/person";
import {renderDictValue} from "#/utils/render";

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
  },
  columns,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        return await contingenPlanList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  // 表格全局唯一表示 保存列配置需要用到
  id: 'system-contingenPlan-index'
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

const [ContingenPlanModal, modalApi] = useVbenModal({
  connectedComponent: contingenPlanModal,
});

const [contingenPlanDetailModal, contingenPlanDetailApi] = useVbenModal({
  connectedComponent: contingenPlanDetail,
});

async function handleInfo(row: Required<ContingenPlanForm>) {
  contingenPlanDetailApi.setData({ id: row.id });
  contingenPlanDetailApi.open();
}

function handleAdd() {
  modalApi.setData({});
  modalApi.open();
}

async function handleEdit(row: Required<ContingenPlanForm>) {
  modalApi.setData({ id: row.id });
  modalApi.open();
}

async function handleDelete(row: Required<ContingenPlanForm>) {
  await contingenPlanRemove(row.id);
  await tableApi.query();
}

async function handleExamine(row: Required<ContingenPlanForm>) {
  row.status = '1'
  await contingenPlanUpdate(row);
  await tableApi.query();
}

function handleMultiDelete() {
  const rows = tableApi.grid.getCheckboxRecords();
  const ids = rows.map((row: Required<ContingenPlanForm>) => row.id);
  Modal.confirm({
    title: '提示',
    okType: 'danger',
    content: `确认删除选中的${ids.length}条记录吗？`,
    onOk: async () => {
      await contingenPlanRemove(ids);
      await tableApi.query();
    },
  });
}

function handleDownloadExcel() {
  commonDownloadExcel(contingenPlanExport, '应急预案管理数据', tableApi.formApi.form.values, {
    fieldMappingTime: formOptions.fieldMappingTime,
  });
}

async function queryPersonData() {
  let params = {
    pageSize: 1000,
    pageNum: 1,
  }
  const res = await personList(params);
  const options = res.rows.map((user) => ({
    label: user.userName + '-' + renderDictValue(user.gender, 'sys_user_sex') + '-' + user.phone,
    value: user.id,
  }));
  tableApi.formApi.updateSchema([
    {
      componentProps: () => ({
        options: options,
        showSearch:true,
        filterOption: filterOption
      }),
      fieldName: 'dutyPersion',
    }
  ])
}

const filterOption = (input: string, option: any) => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

onMounted(async () => {
  await queryPersonData()
})
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="应急预案管理列表">
      <template #toolbar-tools>
        <Space>
          <a-button
            v-access:code="['system:contingenPlan:export']"
            @click="handleDownloadExcel"
          >
            {{ $t('pages.common.export') }}
          </a-button>
          <a-button
            :disabled="!vxeCheckboxChecked(tableApi)"
            danger
            type="primary"
            v-access:code="['system:contingenPlan:remove']"
            @click="handleMultiDelete">
            {{ $t('pages.common.delete') }}
          </a-button>
          <a-button
            type="primary"
            v-access:code="['system:contingenPlan:add']"
            @click="handleAdd"
          >
            {{ $t('pages.common.add') }}
          </a-button>
        </Space>
      </template>
      <template #action="{ row }">
        <Space>
          <Popconfirm
            v-if="row.status === '0'"
            :get-popup-container="getVxePopupContainer"
            placement="left"
            title="确认审核？"
            @confirm="handleExamine(row)"
          >
            <ghost-button
              @click.stop=""
            >
              {{ '审核' }}
            </ghost-button>
          </Popconfirm>
          <ghost-button
            @click.stop="handleInfo(row)"
          >
            {{ $t('pages.common.info') }}
          </ghost-button>
          <ghost-button
            v-if="row.status === '0'"
            v-access:code="['system:contingenPlan:edit']"
            @click.stop="handleEdit(row)"
          >
            {{ $t('pages.common.edit') }}
          </ghost-button>
          <Popconfirm
            :get-popup-container="getVxePopupContainer"
            placement="left"
            title="确认删除？"
            @confirm="handleDelete(row)"
          >
            <ghost-button
              danger
              v-access:code="['system:contingenPlan:remove']"
              @click.stop=""
            >
              {{ $t('pages.common.delete') }}
            </ghost-button>
          </Popconfirm>
        </Space>
      </template>
    </BasicTable>
    <ContingenPlanModal @reload="tableApi.query()" />
    <contingenPlanDetailModal/>
  </Page>
</template>
