import { PlusOutlined, SettingOutlined } from '@ant-design/icons';
import {
    ActionType,
    ModalForm,
    ProColumns,
    ProFormDigit,
    ProFormSelect,
    ProFormSwitch,
    ProFormText,
    ProTable,
} from '@ant-design/pro-components';
import { useIntl, FormattedMessage } from '@umijs/max';
import { Button, Tag, theme, Space, message, Typography } from 'antd';
import React, { useRef, useState } from 'react';
import type { AttributeItem } from './data';
import { queryAttributeList, saveAttribute, removeAttribute } from '@/services/product';
import styles from './index.module.css';

const { Text } = Typography;

const ProductAttribute: React.FC = () => {
    const actionRef = useRef<ActionType>();
    const { token } = theme.useToken();
    const intl = useIntl();
    const [modalVisible, setModalVisible] = useState<boolean>(false);
    const [currentRow, setCurrentRow] = useState<AttributeItem | undefined>();

    const columns: ProColumns<AttributeItem>[] = [
        {
            title: intl.formatMessage({ id: 'pages.attribute.columns.name', defaultMessage: '属性名称' }),
            dataIndex: 'name',
            formItemProps: { rules: [{ required: true }] },
            render: (dom) => <Text strong>{dom}</Text>,
        },
        {
            title: intl.formatMessage({ id: 'pages.attribute.columns.code', defaultMessage: '标识符' }),
            dataIndex: 'code',
            render: (dom) => <Tag color="blue">{dom}</Tag>,
        },
        {
            title: intl.formatMessage({ id: 'pages.attribute.columns.type', defaultMessage: '类型' }),
            dataIndex: 'type',
            valueEnum: {
                string: { text: intl.formatMessage({ id: 'common.type.string', defaultMessage: '文本' }), status: 'Default' },
                select: { text: intl.formatMessage({ id: 'common.type.select', defaultMessage: '下拉选择' }), status: 'Processing' },
                boolean: { text: intl.formatMessage({ id: 'common.type.boolean', defaultMessage: '布尔值' }), status: 'Warning' },
                number: { text: intl.formatMessage({ id: 'common.type.number', defaultMessage: '数字' }), status: 'Success' },
            },
        },
        {
            title: intl.formatMessage({ id: 'pages.attribute.columns.isRequired', defaultMessage: '必填' }),
            dataIndex: 'isRequired',
            render: (v) => <Tag color={v ? 'red' : 'default'}>{v ? <FormattedMessage id="common.yes" defaultMessage="是" /> : <FormattedMessage id="common.no" defaultMessage="否" />}</Tag>,
        },
        {
            title: intl.formatMessage({ id: 'pages.attribute.columns.sort', defaultMessage: '排序' }),
            dataIndex: 'sort',
            sorter: true,
            hideInSearch: true,
        },
        {
            title: intl.formatMessage({ id: 'pages.attribute.columns.status', defaultMessage: '状态' }),
            dataIndex: 'status',
            valueEnum: {
                active: { text: intl.formatMessage({ id: 'common.active', defaultMessage: '启用' }), status: 'Success' },
                disabled: { text: intl.formatMessage({ id: 'common.disabled', defaultMessage: '禁用' }), status: 'Error' },
            },
        },
        {
            title: intl.formatMessage({ id: 'pages.attribute.columns.createdAt', defaultMessage: '创建时间' }),
            dataIndex: 'createdAt',
            valueType: 'dateTime',
            hideInSearch: true,
        },
        {
            title: intl.formatMessage({ id: 'pages.product.columns.option', defaultMessage: '操作' }),
            valueType: 'option',
            render: (_, record) => [
                <a key="edit" onClick={() => {
                    setCurrentRow(record);
                    setModalVisible(true);
                }}>
                    <FormattedMessage id="common.edit" defaultMessage="编辑" />
                </a>,
                <a key="del" style={{ color: token.colorError }} onClick={async () => {
                    const hide = message.loading(intl.formatMessage({ id: 'common.loading', defaultMessage: '加载中...' }));
                    await removeAttribute(record.id);
                    hide();
                    message.success(intl.formatMessage({ id: 'common.success.delete', defaultMessage: '删除成功' }));
                    actionRef.current?.reload();
                }}>
                    <FormattedMessage id="common.delete" defaultMessage="删除" />
                </a>,
            ],
        },
    ];

    return (
        <div className={styles.pageContainer} style={{ background: token.colorBgLayout }}>
            <ProTable<AttributeItem>
                headerTitle={
                    <Space>
                        <SettingOutlined style={{ color: token.colorPrimary }} />
                        <span>{intl.formatMessage({ id: 'pages.attribute.title', defaultMessage: '属性管理清单' })}</span>
                    </Space>
                }
                className={styles.proTable}
                actionRef={actionRef}
                rowKey="id"
                search={{
                    labelWidth: 'auto',
                    className: styles.tableSearch
                }}
                rowClassName={styles.tableRow}
                toolBarRender={() => [
                    <Button key="add" icon={<PlusOutlined />} type="primary" onClick={() => setModalVisible(true)}>
                        <FormattedMessage id="pages.attribute.add" defaultMessage="新建属性" />
                    </Button>,
                ]}
                request={queryAttributeList}
                columns={columns}
            />

            <ModalForm
                title={currentRow ? intl.formatMessage({ id: 'common.edit', defaultMessage: '编辑' }) : intl.formatMessage({ id: 'pages.attribute.add', defaultMessage: '新建属性' })}
                open={modalVisible}
                onOpenChange={setModalVisible}
                initialValues={currentRow}
                onFinish={async (values) => {
                    await saveAttribute(values);
                    message.success(intl.formatMessage({ id: 'common.success.update', defaultMessage: '保存成功' }));
                    setModalVisible(false);
                    setCurrentRow(undefined);
                    actionRef.current?.reload();
                }}
                modalProps={{
                    destroyOnHidden: true,
                }}
            >
                <ProFormText name="name" label={<FormattedMessage id="pages.attribute.columns.name" defaultMessage="属性名称" />} rules={[{ required: true }]} />
                <ProFormText name="code" label={<FormattedMessage id="pages.attribute.columns.code" defaultMessage="标识符" />} placeholder="e.g. color" rules={[{ required: true }]} />
                <ProFormSelect
                    name="type"
                    label={<FormattedMessage id="pages.attribute.columns.type" defaultMessage="属性类型" />}
                    options={[
                        { label: intl.formatMessage({ id: 'common.type.string', defaultMessage: '文本' }), value: 'string' },
                        { label: intl.formatMessage({ id: 'common.type.select', defaultMessage: '下拉选择' }), value: 'select' },
                        { label: intl.formatMessage({ id: 'common.type.boolean', defaultMessage: '布尔值' }), value: 'boolean' },
                        { label: intl.formatMessage({ id: 'common.type.number', defaultMessage: '数字' }), value: 'number' },
                    ]}
                />
                <ProFormDigit name="sort" label={<FormattedMessage id="pages.attribute.columns.sort" defaultMessage="排序权重" />} initialValue={0} />
                <ProFormSwitch name="isRequired" label={<FormattedMessage id="pages.attribute.columns.isRequired" defaultMessage="是否必填" />} />
                <ProFormSelect
                    name="status"
                    label={<FormattedMessage id="pages.attribute.columns.status" defaultMessage="状态" />}
                    initialValue="active"
                    options={[
                        { label: intl.formatMessage({ id: 'common.active', defaultMessage: '启用' }), value: 'active' },
                        { label: intl.formatMessage({ id: 'common.disabled', defaultMessage: '禁用' }), value: 'disabled' },
                    ]}
                />
            </ModalForm>
        </div>
    );
};

export default ProductAttribute;
