import {
  stockcontrollerCreatestockpoint,
  stockcontrollerDelstockpoints,
  stockcontrollerGetstockpoints,
  stockcontrollerUpdatestockpoint,
} from '@/servers/api/stock';
import { EditOutlined, PlusOutlined } from '@ant-design/icons';
import {
  ActionType,
  DrawerForm,
  PageContainer,
  ProColumns,
  ProForm,
  ProFormSelect,
  ProFormText,
  ProTable,
} from '@ant-design/pro-components';
import { request } from '@umijs/max';
import { App, Button, Divider, Popconfirm, Space, Tag } from 'antd';
import { useRef } from 'react';

// 区域数据项类型
interface AreaItem {
  code: string;
  name: string;
}

const ListPage: React.FC = () => {
  const { message } = App.useApp();
  const actionRef = useRef<ActionType>();
  const columns: ProColumns<API.StockPoint>[] = [
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '地址',
      dataIndex: 'location',
    },
    {
      title: '联系人',
      dataIndex: 'contactPerson',
    },
    {
      title: '联系电话',
      dataIndex: 'contactPhone',
    },
    {
      title: '区域',
      dataIndex: 'areas',
      render: (_, record: any) => {
        if (!record.areas || record.areas.length === 0) {
          return <Tag color="blue">全球</Tag>;
        }
        return (
          <Space wrap>
            {record.areas.map((area: any) => (
              <Tag key={area.code}>{area.name}</Tag>
            ))}
          </Space>
        );
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      valueType: 'dateTime',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <UpdateForm tableRef={actionRef} values={record} />
          <Divider type="vertical" />
          <Popconfirm
            title="删除"
            description="确认删除?"
            onConfirm={async () => {
              try {
                const { success, message: errMsg } =
                  await stockcontrollerDelstockpoints({
                    id: record.id as number,
                  });
                if (!success) {
                  throw new Error(errMsg);
                }
                actionRef.current?.reload();
              } catch (error: any) {
                message.error(error.message);
              }
            }}
          >
            <Button type="primary" danger>
              删除
            </Button>
          </Popconfirm>
        </>
      ),
    },
  ];

  return (
    <PageContainer ghost>
      <ProTable<API.StockPoint>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        request={async (params) => {
          const { data, success } = await stockcontrollerGetstockpoints(params);
          return {
            total: data?.total || 0,
            data: data?.items || [],
            success,
          };
        }}
        columns={columns}
        toolBarRender={() => [<CreateForm tableRef={actionRef} />]}
        search={false}
      />
    </PageContainer>
  );
};

const CreateForm: React.FC<{
  tableRef: React.MutableRefObject<ActionType | undefined>;
}> = ({ tableRef }) => {
  const { message } = App.useApp();
  return (
    <DrawerForm<API.CreateStockPointDTO>
      title="新建"
      trigger={
        <Button type="primary">
          <PlusOutlined />
          新建
        </Button>
      }
      autoFocusFirstInput
      drawerProps={{
        destroyOnHidden: true,
      }}
      onFinish={async (values) => {
        try {
          const { success, message: errMsg } =
            await stockcontrollerCreatestockpoint(values);
          if (!success) {
            throw new Error(errMsg);
          }
          tableRef.current?.reload();
          message.success('提交成功');
          return true;
        } catch (error: any) {
          message.error(error.message);
        }
      }}
    >
      <ProForm.Group>
        <ProFormText
          name="name"
          label="名称"
          width="lg"
          placeholder="请输入名称"
          rules={[{ required: true, message: '请输入名称' }]}
        />
        <ProFormText
          name="location"
          label="地址"
          width="lg"
          placeholder="请输入地址"
          rules={[{ required: true, message: '请输入地址' }]}
        />
        <ProFormText
          name="contactPerson"
          label="联系人"
          width="lg"
          placeholder="请输入联系人"
          rules={[{ required: true, message: '请输入联系人' }]}
        />
        <ProFormText
          name="contactPhone"
          label="联系电话"
          width="lg"
          placeholder="请输入联系电话"
          rules={[{ required: true, message: '请输入联系电话' }]}
        />
        <ProFormSelect
          name="areas"
          label="区域"
          width="lg"
          mode="multiple"
          placeholder="留空表示全球"
          request={async () => {
            try {
              const resp = await request('/area', {
                method: 'GET',
                params: { pageSize: 1000 },
              });
              if (resp.success) {
                return resp.data.list.map((area: AreaItem) => ({
                  label: area.name,
                  value: area.code,
                }));
              }
              return [];
            } catch (e) {
              return [];
            }
          }}
        />
      </ProForm.Group>
    </DrawerForm>
  );
};

const UpdateForm: React.FC<{
  tableRef: React.MutableRefObject<ActionType | undefined>;
  values: API.StockPoint;
}> = ({ tableRef, values: initialValues }) => {
  const { message } = App.useApp();
  return (
    <DrawerForm<API.UpdateStockPointDTO>
      title="编辑"
      initialValues={{
        ...initialValues,
        areas: ((initialValues as any).areas?.map((area: any) => area.code) ?? []),
      }}
      trigger={
        <Button type="primary">
          <EditOutlined />
          编辑
        </Button>
      }
      autoFocusFirstInput
      drawerProps={{
        destroyOnHidden: true,
      }}
      onFinish={async (values) => {
        try {
          const { success, message: errMsg } =
            await stockcontrollerUpdatestockpoint(
              { id: initialValues.id as number },
              values,
            );
          if (!success) {
            throw new Error(errMsg);
          }
          message.success('提交成功');
          tableRef.current?.reload();
          return true;
        } catch (error: any) {
          message.error(error.message);
        }
      }}
    >
      <ProForm.Group>
        <ProFormText
          name="name"
          label="名称"
          width="lg"
          placeholder="请输入名称"
          rules={[{ required: true, message: '请输入名称' }]}
        />
        <ProFormText
          name="location"
          label="地址"
          width="lg"
          placeholder="请输入地址"
          rules={[{ required: true, message: '请输入地址' }]}
        />
        <ProFormText
          name="contactPerson"
          label="联系人"
          width="lg"
          placeholder="请输入联系人"
          rules={[{ required: true, message: '请输入联系人' }]}
        />
        <ProFormText
          name="contactPhone"
          label="联系电话"
          width="lg"
          placeholder="请输入联系电话"
          rules={[{ required: true, message: '请输入联系电话' }]}
        />
        <ProFormSelect
          name="areas"
          label="区域"
          width="lg"
          mode="multiple"
          placeholder="留空表示全球"
          request={async () => {
            try {
              const resp = await request('/area', {
                method: 'GET',
                params: { pageSize: 1000 },
              });
              if (resp.success) {
                return resp.data.list.map((area: AreaItem) => ({
                  label: area.name,
                  value: area.code,
                }));
              }
              return [];
            } catch (e) {
              return [];
            }
          }}
        />
      </ProForm.Group>
    </DrawerForm>
  );
};

export default ListPage;
