/*
 * @Author: your name
 * @Date: 2022-04-28 10:47:35
 * @LastEditTime: 2022-04-28 16:45:52
 * @LastEditors: Please set LastEditors
 * @Description: 商品类别管理
 * @FilePath: \cloud-platform\src\pages\basicManage\Commdity\Attribute\index.tsx
 */

import ProTable from '@ant-design/pro-table';
import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProDescriptions from '@ant-design/pro-descriptions';
import { PlusOutlined } from '@ant-design/icons';
import { Button, message, TreeSelect, Form, Drawer, Popconfirm, Row, Col, Switch } from 'antd';
import { ModalForm, ProFormText, ProFormDigit, ProFormTextArea, ProFormSwitch } from '@ant-design/pro-form';

import type { FormInstance } from 'antd';
import type { CommodityType } from '../data';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import type { TreeSelectModel } from '@/utils/format';

import { getTreeSelectOption } from '@/utils/format';
import { getList, delCommdityType, updateCommodityType } from './service'


/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAddUpdate = async (fields: CommodityType) => {
    const hide = message.loading('正在提交...');
    try {
        const result: any = await updateCommodityType({ ...fields })

        hide();
        if (result.Result_Code !== 100) {
            message.error(`${result.Result_Desc}` || `${result.Result_Code}:提交失败`)
            return false
        }
        message.success(fields.COMMODITYTYPE_ID ? "更新成功！" : "新建成功！")
        return true
    } catch (error) {
        hide();
        message.error("提交失败")
        return false
    }
}
/**
 * @en-US delete node
 * @zh-CN 删除节点
 * @param fields
 */
const handleDelete = async (nodeId: number) => {
    const hide = message.loading('正在删除...');
    try {
        const result = await delCommdityType(nodeId)

        hide();
        if (result.Result_Code !== 100) {
            message.error(`${result.Result_Code}:删除失败`)
            return false
        }
        message.success("删除成功！")
        return true
    } catch (error) {
        hide();
        message.error("删除失败")
        return false
    }
}

/**
 * @description:  商品类别组件
 * @param {*}
 * @return {*}
 */
const CommodityTypeTable: React.FC = () => {
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();

    const [createModalVisible, handleModalVisible] = useState<boolean>(false); // 新建窗口的弹窗
    const [showDetail, setShowDetail] = useState<boolean>();

    const [currentRow, setCurrentRow] = useState<CommodityType>();

    const [treeSelectOption, setTreeSelectOption] = useState<TreeSelectModel[]>();

    const columns: ProColumns<CommodityType>[] = [
        {
            title: '类别名称',
            dataIndex: 'COMMODITYTYPE_NAME',
            hideInSearch: true,
            render: (dom, entity) => {
                return (
                    <a
                        onClick={() => {
                            setCurrentRow(entity);
                            setShowDetail(true);
                        }}
                    >
                        {dom}
                    </a>
                );
            },
        },
        // {
        //     title: '类别名称',
        //     dataIndex: 'CommodityTypePID',
        //     hideInTable: true,
        //     hideInDescriptions: true,
        //     colSize: 1.5,
        //     renderFormItem: () => {
        //         return (
        //             <TreeSelect
        //                 key="selectCate"
        //                 placeholder="请选择类别名称"
        //                 dropdownStyle={{ maxHeight: 300, overflow: 'auto' }}
        //                 treeData={treeSelectOption}
        //                 treeDefaultExpandAll
        //                 treeDataSimpleMode
        //             />)
        //     }
        // },

        {
            title: '类别编码',
            dataIndex: 'COMMODITYTYPE_CODE',
            hideInSearch: true
        },
        {
            title: '类别状态',
            dataIndex: 'COMMODITYTYPE_VALID',
            valueType: 'select',
            valueEnum: { 0: { text: '无效', status: 'error' }, 1: { text: '有效', status: 'success' } }
        },
        {
            title: '香烟类别',
            dataIndex: 'CIGARETTE_TYPE',
            valueType: 'select',
            hideInSearch: true,
            valueEnum: { 0: { text: '否' }, 1: { text: '是' } }
        },
        {
            title: '索引',
            dataIndex: 'COMMODITYTYPE_INDEX',
            hideInSearch: true
        },
        {
            title: '说明',
            dataIndex: 'COMMODITYTYPE_DESC',
            hideInSearch: true
        },

        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            hideInDescriptions: true,
            render: (_, record) => [
                <a
                    key="edit"
                    onClick={() => {
                        setCurrentRow(record);
                        handleModalVisible(true);
                    }}
                >
                    编辑
                </a>,
                <Popconfirm title="确认删除该商品类别及以下子类别吗?" onConfirm={async () => {

                    const sucesse = await handleDelete(record.COMMODITYTYPE_ID)
                    if (sucesse && actionRef.current) {
                        actionRef.current.reload()
                    }
                }}>
                    <a>删除</a>
                </Popconfirm>


            ]
        }

    ]

    return (
        <PageContainer>
            <ProTable<CommodityType>
                headerTitle="商品类别管理"
                rowKey="COMMODITYTYPE_ID"
                search={false}
                actionRef={actionRef}
                request={async (params) => {
                    const data: any = await getList({ CommodityTypePID: -1, ...params })
                    return data
                }}
                onLoad={async (data) => {
                    const keys: TreeSelectModel = { title: 'COMMODITYTYPE_NAME', value: 'COMMODITYTYPE_ID', id: 'COMMODITYTYPE_ID', pId: 'COMMODITYTYPE_PID' }
                    const top: TreeSelectModel[] = await getTreeSelectOption(keys, data)
                    const topSelect: TreeSelectModel = { title: '默认类别', value: -1, pId: "", id: -1 }
                    top.unshift(topSelect)
                    setTreeSelectOption(top)
                }}
                columns={columns}
                toolbar={{
                    actions: [
                        <Button key="button" icon={<PlusOutlined />} type="primary" onClick={() => { handleModalVisible(true) }}>
                            新建
                        </Button>
                    ]
                }}
            />
            <ModalForm<CommodityType>
                layout={'horizontal'}
                wrapperCol={{ span: 16 }}
                labelCol={{ span: 6 }}
                width={600}
                title={currentRow ? '更新商品类别' : '新建商品类别'}
                visible={createModalVisible}
                formRef={formRef}
                onVisibleChange={(value) => {
                    handleModalVisible(value)
                    if (!value) {

                        formRef.current?.resetFields();
                        setCurrentRow(undefined);
                    } else {
                        formRef.current?.setFieldsValue(currentRow || { CIGARETTE_TYPE: 0, COMMODITYTYPE_VALID: 1 })

                    }
                }}
                onFinish={async (values) => {
                    let newValue: any = { ...values }

                    if (currentRow) { // 编辑数据
                        newValue = { ...currentRow, ...newValue }
                    }
                    newValue.CIGARETTE_TYPE = values.CIGARETTE_TYPE ? 1 : 0
                    newValue.COMMODITYTYPE_VALID = values.COMMODITYTYPE_VALID ? 1 : 0
                    const success = await handleAddUpdate(newValue as CommodityType);

                    if (success) {
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                        handleModalVisible(false);
                    }
                }}
            >
                <Row>
                    <Col span={24} >

                        <Form.Item
                            name="COMMODITYTYPE_PID"
                            label="上级类别"
                            rules={[
                                {
                                    required: true,
                                    message: '请选择上级类别',
                                },
                            ]}
                        >
                            <TreeSelect
                                placeholder="请选择上级类别"
                                dropdownStyle={{ maxHeight: 300, overflow: 'auto' }}
                                treeDefaultExpandAll
                                treeDataSimpleMode
                                treeData={treeSelectOption}
                            />

                        </Form.Item>
                        <ProFormText
                            name="COMMODITYTYPE_NAME"
                            label="类别名称"
                            placeholder="请输入类别名称"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入类别名称',
                                },
                            ]} />

                        <ProFormText
                            name="COMMODITYTYPE_CODE"
                            label="类别编码"
                            placeholder="请输入类别编码"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入类别编码',
                                },
                            ]} />
                        <ProFormDigit
                            name="COMMODITYTYPE_INDEX"
                            label="类别索引"
                            placeholder="请输入类别索引"
                            min={0}
                            max={9999}
                            rules={[
                                {
                                    required: true,
                                    message: '请输入类别索引',
                                },
                            ]}
                            fieldProps={{ precision: 0 }}
                        />
                        <Row>
                            <Col span={12} >
                                {/* 当前依赖包动画过渡有问题 临时采用 Form.Item 方式进行Switch交互 */}
                                <Form.Item
                                    name="CIGARETTE_TYPE"
                                    label="香烟类别"
                                    rules={[
                                        {
                                            required: true,
                                            message: '香烟类别',
                                        },
                                    ]}
                                >
                                    <Switch
                                        checkedChildren="是"
                                        unCheckedChildren="否"
                                        defaultChecked={currentRow ? !!currentRow.CIGARETTE_TYPE : true}
                                    />
                                </Form.Item>
                                {/* <ProFormSwitch

                                    name="CIGARETTE_TYPE"
                                    label="香烟类别"
                                    checkedChildren="是"
                                    unCheckedChildren="否"
                                    wrapperCol={{ span: 6 }}
                                    labelCol={{ span: 12 }}
                                /> */}
                            </Col>
                            <Col span={12} >
                                {/* 当前依赖包动画过渡有问题 临时采用 Form.Item 方式进行Switch交互 */}
                                <Form.Item
                                    name="COMMODITYTYPE_VALID"
                                    label="是否有效"
                                    rules={[
                                        {
                                            required: true,
                                            message: '是否无效',
                                        },
                                    ]}
                                >
                                    <Switch
                                        checkedChildren="有"
                                        unCheckedChildren="无"
                                        defaultChecked={currentRow ? !!currentRow.COMMODITYTYPE_VALID : true}
                                    />
                                </Form.Item>
                                {/* <ProFormSwitch
                                    name="COMMODITYTYPE_VALID"
                                    label="是否有效"
                                    checkedChildren="有"
                                    unCheckedChildren="无"
                                    wrapperCol={{ span: 6 }}
                                    labelCol={{ span: 10 }}
                                /> */}
                            </Col>
                        </Row>
                        <ProFormTextArea

                            name="COMMODITYTYPE_DESC"
                            label="备注说明"
                            placeholder="请输入说明" />
                    </Col>
                </Row>
            </ModalForm>
            <Drawer
                width={600}
                visible={showDetail}
                onClose={() => {
                    setCurrentRow(undefined);
                    setShowDetail(false);
                }}
                closable={false}
            >
                {currentRow?.COMMODITYTYPE_NAME && (
                    <ProDescriptions<CommodityType>
                        column={2}
                        title={currentRow?.COMMODITYTYPE_NAME}
                        request={async () => ({
                            data: currentRow || {},
                        })}
                        params={{
                            id: currentRow?.COMMODITYTYPE_NAME,
                        }}
                        columns={columns as ProDescriptionsItemProps<CommodityType>[]}
                    />
                )}
            </Drawer>
        </PageContainer >
    )
}

export default CommodityTypeTable;