import {
  MyButtons,
  MyColumns,
  MyImportModal,
  MyProTableProps,
  useCurrentPermissions,
} from '@/common';
import { Apis } from '@/gen/Apis';
import { ProTable } from '@ant-design/pro-components';
import { useNavigate } from '@umijs/max';
import { Dropdown, Space } from 'antd';

import { MyExport } from '@/components/MyExport';
import { Selects } from '@/components/Select';
import {
  HouseMetersMeterTypeEnum,
  HouseMetersUsageTypeEnum,
} from '@/gen/Enums';
import dayjs from 'dayjs';
import { useState } from 'react';
import ChargingStandard from './modals/ChargingStandard';
import Create from './modals/Create';
import MeterHasOne from './modals/MeterHasOne';
import Update from './modals/Update';

export default function HouseMeter({ title = '房屋表' }) {
  const navigate = useNavigate();
  const [getParams, setParams] = useState({});

  const getCurrentPermissions = useCurrentPermissions();
  let toolBarRender = (action: any) => {
    return getCurrentPermissions({
      create: (
        <Create
          key="Create"
          reload={action?.reload}
          item={{ meter_type: 'HouseMeter' }}
          title={title}
        />
      ),
      importmeter: (
        <MyImportModal
          key="ImportMeter"
          title="导入"
          type="default"
          size="middle"
          templateApi={Apis.Meter.HouseMeters.DownloadTemplate}
          importApi={Apis.Meter.HouseMeters.Import}
          reload={action?.reload}
        />
      ),
      importhouse: (
        <MyImportModal
          key="ImportHouse"
          title="仪表绑房"
          type="default"
          size="middle"
          templateApi={Apis.Meter.HouseMeterHasHouses.DownloadTemplate}
          importApi={Apis.Meter.HouseMeterHasHouses.Import}
          reload={action?.reload}
        />
      ),
      export: (
        <MyExport
          key="export"
          item={getParams}
          download={Apis.Meter.HouseMeters}
        />
      ),
    });
  };
  let tableRender = (item: any, action: any) => {
    let permissions = getCurrentPermissions({
      view: (
        <MyButtons.View
          title="查看"
          onClick={() => {
            navigate(`/meter/readings/show/${item.id}`);
          }}
        />
      ),
      has: (
        <MeterHasOne
          item={{ ...item, size: 'small' }}
          reload={action?.reload}
          title="绑房"
        />
      ),
    });

    let permissionsSpace = getCurrentPermissions({
      update: {
        key: '1',
        label: <Update item={item} reload={action?.reload} title={title} />,
      },
      delete: {
        key: '2',
        label: (
          <MyButtons.Delete
            onConfirm={() =>
              Apis.Meter.HouseMeters.Delete({ id: item.id }).then(() =>
                action?.reload(),
              )
            }
          />
        ),
      },
    });

    let Others = (
      <Dropdown menu={{ items: permissionsSpace }} trigger={['click']}>
        <MyButtons.Default title="更多" />
      </Dropdown>
    );
    return [...permissions, ...[Others]];
  };
  return (
    <ProTable
      {...MyProTableProps.props}
      headerTitle="仪表列表"
      request={async (params, sort) => {
        setParams(params);
        return MyProTableProps.request(
          { ...params, meter_type: HouseMetersMeterTypeEnum.HouseMeter.value },
          sort,
          Apis.Meter.HouseMeters.List,
        );
      }}
      toolBarRender={(action) => [toolBarRender(action)]}
      columns={[
        MyColumns.ID({
          search: false,
        }),
        Selects?.AssetProjects({
          title: '选择项目',
          key: 'asset_projects_id',
          hidden: true,
        }),
        {
          title: '项目名称',
          dataIndex: ['asset_project', 'name'],
          // search: { transform: (value) => ({ project_name: value }) }
          search: false,
        },
        {
          title: '房屋',
          render: (_, item: any) => {
            return item.house_meter_has_houses?.map(
              (res: { full_name: string }) => {
                return res?.full_name;
              },
            );
          },
        },
        {
          title: '仪表编号',
          dataIndex: 'name',
        },
        MyColumns.EnumTag({
          title: '仪表类型',
          dataIndex: 'meter_type',
          valueEnum: HouseMetersMeterTypeEnum,
          search: false,
        }),
        MyColumns.EnumTag({
          title: '使用类型',
          dataIndex: 'usage_type',
          valueEnum: HouseMetersUsageTypeEnum,
          // search: false,
        }),

        {
          title: '收费标准',
          dataIndex: ['charge_standard', 'name'],
          search: false,
          render: (_, item: any) => {
            return item.charge_standard ? (
              <ChargingStandard item={item} />
            ) : (
              '-'
            );
          },
        },
        {
          title: '绑定房屋',
          dataIndex: 'house_meter_has_houses_count',
          search: false,
        },
        // {
        //   title: '初始抄表读数',
        //   dataIndex: 'initial_value',
        //   search: false,
        // },
        {
          title: '最新抄表读数',
          dataIndex: 'latest_value',
          search: false,
        },
        // {
        //   title: '初始抄表日期',
        //   dataIndex: 'initial_time',
        //   search: false,
        //   render: (renderValue: any) =>
        //     renderValue ? dayjs(renderValue).format('YYYY-MM-DD') : '-',
        // },
        {
          title: '最新抄表日期',
          dataIndex: 'latest_time',
          search: false,
          render: (renderValue: any) =>
            renderValue ? dayjs(renderValue).format('YYYY-MM-DD') : '-',
        },
        {
          title: '距离上次抄表',
          dataIndex: 'latest_time',
          search: false,
          render: (renderValue: any) =>
            renderValue ? dayjs().diff(renderValue, 'day') + '天' : '-',
        },
        // {
        //   title: '备注',
        //   dataIndex: 'remark',
        //   search: false,
        // },
        // MyColumns.SoftDelete({
        //   onRestore: Apis.Meter.HouseMeters.Restore,
        //   onSoftDelete: Apis.Meter.HouseMeters.SoftDelete,
        //   search: false,
        //   setPermissions: getCurrentPermissions({
        //     enableDisable: true,
        //   }),
        // }),
        // MyColumns.CreatedAt(),
        MyColumns.Option({
          render: (_, item: any, index, action) => (
            <Space key={index}>
              <>{tableRender(item, action)}</>
            </Space>
          ),
        }),
      ]}
    />
  );
}
