import InternationalPhoneInput from '@/components/InternationalPhoneInput';
import {
  logisticscontrollerCreateshippingaddress,
  logisticscontrollerDelshippingaddress,
  logisticscontrollerGetshippingaddresslist,
  logisticscontrollerUpdateshippingaddress,
} from '@/servers/api/logistics';
import { stockcontrollerGetallstockpoints } from '@/servers/api/stock';
import { EditOutlined, PlusOutlined } from '@ant-design/icons';
import {
  ActionType,
  DrawerForm,
  PageContainer,
  ProColumns,
  ProForm,
  ProFormItem,
  ProFormSelect,
  ProFormText,
  ProTable,
} from '@ant-design/pro-components';
import { App, Button, Divider, Popconfirm } from 'antd';
import { useRef } from 'react';

const ListPage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const { message } = App.useApp();

  const columns: ProColumns<API.ShippingAddress>[] = [
    {
      title: '仓库点',
      dataIndex: 'stockPointId',
      hideInSearch: true,
      valueType: 'select',
      request: async () => {
        const { data = [] } = await stockcontrollerGetallstockpoints();
        return data.map((item) => ({
          label: item.name,
          value: item.id,
        }));
      },
    },
    {
      title: '地区',
      dataIndex: ['address', 'region'],
      hideInSearch: true,
    },
    {
      title: '城市',
      dataIndex: ['address', 'city'],
      hideInSearch: true,
    },
    {
      title: '邮编',
      dataIndex: ['address', 'postal_code'],
      hideInSearch: true,
    },
    {
      title: '详细地址',
      dataIndex: ['address', 'address_line_1'],
      hideInSearch: true,
    },
    {
      title: '联系电话',
      render: (_, record) =>
        `+${record.phone_number_extension} ${record.phone_number}`,
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <UpdateForm tableRef={actionRef} value={record} />
          <Divider type="vertical" />
          <Popconfirm
            title="删除"
            description="确认删除?"
            onConfirm={async () => {
              try {
                const { success, message: errMsg } =
                  await logisticscontrollerDelshippingaddress({
                    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
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        toolBarRender={() => [<CreateForm tableRef={actionRef} />]}
        request={async () => {
          const { data, success } =
            await logisticscontrollerGetshippingaddresslist();
          if (success) {
            return {
              data: data,
            };
          }
          return {
            data: [],
          };
        }}
        columns={columns}
      />
    </PageContainer>
  );
};

const region = {
  AB: 'Alberta',
  BC: 'British',
  MB: 'Manitoba',
  NB: 'New',
  NL: 'Newfoundland',
  NS: 'Nova',
  ON: 'Ontario',
  PE: 'Prince',
  QC: 'Quebec',
  SK: 'Saskatchewan',
  NT: 'Northwest',
  NU: 'Nunavut',
  YT: 'Yukon',

  // 美国州名
  // AL: 'Alabama',
  // AK: 'Alaska',
  // AZ: 'Arizona',
  // AR: 'Arkansas',
  // CA: 'California',
  // CO: 'Colorado',
  // CT: 'Connecticut',
  // DE: 'Delaware',
  // FL: 'Florida',
  // GA: 'Georgia',
  // HI: 'Hawaii',
  // ID: 'Idaho',
  // IL: 'Illinois',
  // IN: 'Indiana',
  // IA: 'Iowa',
  // KS: 'Kansas',
  // KY: 'Kentucky',
  // LA: 'Louisiana',
  // ME: 'Maine',
  // MD: 'Maryland',
  // MA: 'Massachusetts',
  // MI: 'Michigan',
  // MN: 'Minnesota',
  // MS: 'Mississippi',
  // MO: 'Missouri',
  // MT: 'Montana',
  // NE: 'Nebraska',
  // NV: 'Nevada',
  // NH: 'New Hampshire',
  // NJ: 'New Jersey',
  // NM: 'New Mexico',
  // NY: 'New York',
  // NC: 'North Carolina',
  // ND: 'North Dakota',
  // OH: 'Ohio',
  // OK: 'Oklahoma',
  // OR: 'Oregon',
  // PA: 'Pennsylvania',
  // RI: 'Rhode Island',
  // SC: 'South Carolina',
  // SD: 'South Dakota',
  // TN: 'Tennessee',
  // TX: 'Texas',
  // UT: 'Utah',
  // VT: 'Vermont',
  // VA: 'Virginia',
  // WA: 'Washington',
  // WV: 'West Virginia',
  // WI: 'Wisconsin',
  // WY: 'Wyoming',
};
const CreateForm: React.FC<{
  tableRef: React.MutableRefObject<ActionType | undefined>;
}> = ({ tableRef }) => {
  const { message } = App.useApp();
  return (
    <DrawerForm
      title="新建"
      trigger={
        <Button type="primary">
          <PlusOutlined />
          新建
        </Button>
      }
      autoFocusFirstInput
      drawerProps={{
        destroyOnHidden: true,
      }}
      onFinish={async (values) => {
        const { contact, ...params } = values;
        try {
          const { success, message: errMsg } =
            await logisticscontrollerCreateshippingaddress({
              ...params,
              phone_number: contact?.phone,
              phone_number_extension: contact?.extension,
              phone_number_country: contact?.country,
            } as API.ShippingAddress);
          if (!success) {
            throw new Error(errMsg);
          }
          tableRef.current?.reload();
          message.success('提交成功');
          return true;
        } catch (error: any) {
          message.error(error.message);
        }
      }}
    >
      <ProFormText
        name="name"
        label="名称"
        width="lg"
        placeholder="请输入名称"
        required
        rules={[{ required: true, message: '请输入名称' }]}
      />
      <ProFormSelect
        name="stockPointId"
        width="lg"
        label="仓库点"
        placeholder="请选择仓库点"
        required
        rules={[{ required: true, message: '请选择仓库点' }]}
        request={async () => {
          const { data = [] } = await stockcontrollerGetallstockpoints();
          return data.map((item) => ({
            label: item.name,
            value: item.id,
          }));
        }}
      />
      <ProForm.Group title="地址">
        <ProFormText
          name={['address', 'country']}
          label="国家"
          initialValue={'CA'}
          hidden
        />
        <ProFormSelect
          name={['address', 'region']}
          label="地区"
          placeholder={'请选择地区'}
          showSearch
          required
          valueEnum={region}
          rules={[{ required: true, message: '请选择地区' }]}
        />
        <ProFormText
          name={['address', 'city']}
          label="城市"
          placeholder="请输入城市"
          required
          rules={[{ required: true, message: '请输入城市' }]}
        />
        <ProFormText
          name={['address', 'postal_code']}
          label="邮编"
          placeholder="请输入邮编"
          required
          rules={[{ required: true, message: '请输入邮编' }]}
        />
        <ProFormText
          name={['address', 'address_line_1']}
          label="详细地址"
          placeholder="请输入详细地址"
          width="lg"
          required
          rules={[{ required: true, message: '请输入详细地址' }]}
        />
      </ProForm.Group>
      <ProFormItem
        name="contact"
        label="联系电话"
        required
        rules={[
          {
            required: true,
            async validator(_, value) {
              if (!value?.phone) {
                return Promise.reject('请输入联系电话');
              }
              return Promise.resolve();
            },
          },
        ]}
      >
        <InternationalPhoneInput />
      </ProFormItem>
    </DrawerForm>
  );
};

const UpdateForm: React.FC<{
  tableRef: React.MutableRefObject<ActionType | undefined>;
  value: API.ShippingAddress;
}> = ({ tableRef, value }) => {
  const { message } = App.useApp();
  const {
    id,
    phone_number,
    phone_number_country,
    phone_number_extension,
    ...initialValue
  } = value;
  return (
    <DrawerForm
      title="编辑"
      trigger={
        <Button type="primary">
          <EditOutlined />
          编辑
        </Button>
      }
      autoFocusFirstInput
      drawerProps={{
        destroyOnHidden: true,
      }}
      onFinish={async (values) => {
        const { contact, ...params } = values;
        try {
          const { success, message: errMsg } =
            await logisticscontrollerUpdateshippingaddress(
              { id: id as number },
              {
                ...params,
                phone_number: contact?.phone,
                phone_number_extension: contact?.extension,
                phone_number_country: contact?.country,
              } as API.ShippingAddress,
            );
          if (!success) {
            throw new Error(errMsg);
          }
          tableRef.current?.reload();
          message.success('提交成功');
          return true;
        } catch (error: any) {
          message.error(error.message);
        }
      }}
      initialValues={{
        ...initialValue,
        contact: {
          phone: phone_number,
          extension: phone_number_extension,
          country: phone_number_country,
        },
      }}
    >
      <ProFormText
        name="name"
        label="名称"
        width="lg"
        placeholder="请输入名称"
        required
        rules={[{ required: true, message: '请输入名称' }]}
      />
      <ProFormSelect
        name="stockPointId"
        width="lg"
        label="仓库点"
        placeholder="请选择仓库点"
        required
        rules={[{ required: true, message: '请选择仓库点' }]}
        request={async () => {
          const { data = [] } = await stockcontrollerGetallstockpoints();
          return data.map((item) => ({
            label: item.name,
            value: item.id,
          }));
        }}
      />
      <ProFormText
          name={['email']}
          label="邮箱"
          placeholder="请输入邮箱"
          required
          rules={[{ required: true, message: '请输入邮箱' }]}
        />
      <ProForm.Group title="地址">
        <ProFormText
          name={['address', 'country']}
          label="国家"
          initialValue={'CA'}
          hidden
        />
        <ProFormSelect
          name={['address', 'region']}
          label="地区"
          placeholder={'请选择地区'}
          showSearch
          required
          valueEnum={region}
          rules={[{ required: true, message: '请选择地区' }]}
        />
        <ProFormText
          name={['address', 'city']}
          label="城市"
          placeholder="请输入城市"
          required
          rules={[{ required: true, message: '请输入城市' }]}
        />
        <ProFormText
          name={['address', 'postal_code']}
          label="邮编"
          placeholder="请输入邮编"
          required
          rules={[{ required: true, message: '请输入邮编' }]}
        />
        <ProFormText
          name={['address', 'address_line_1']}
          label="详细地址"
          placeholder="请输入详细地址"
          width="lg"
          required
          rules={[{ required: true, message: '请输入详细地址' }]}
        />

         
      </ProForm.Group>
      <ProFormItem
        name="contact"
        label="联系电话"
        required
        rules={[
          {
            required: true,
            async validator(_, value) {
              if (!value?.phone) {
                return Promise.reject('请输入联系电话');
              }
              return Promise.resolve();
            },
          },
        ]}
      >
        <InternationalPhoneInput />
      </ProFormItem>
    </DrawerForm>
  );
};

export default ListPage;
