/*
 * @Author: cclue
 * @Date: 2022-04-28 10:47:35
 * @LastEditTime: 2024-12-16 10:57:06
 * @LastEditors: cclu 1106109051@qq.com
 * @Description: 经营业态管理页面
 * @FilePath: \cloud-platform\src\pages\basicManage\BusinessTrade\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, Avatar, Switch } from 'antd';
import { ModalForm, ProFormText, ProFormDigit, ProFormTextArea, ProFormSelect } from '@ant-design/pro-form';

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

import { getList, delBusinessTrade, updateBusinessTrade } from './service'
import PageTitleBox from '@/components/PageTitleBox';
import { CurrentUser } from 'umi';


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

        hide();
        if (result.Result_Code !== 100) {
            message.error(`${result.Result_Desc}` || `${result.Result_Code}:提交失败`)
            return false
        }
        message.success(fields.AUTOSTATISTICS_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 delBusinessTrade(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 {*} 组件dom
 */
// const BusinessTradeModelTable: React.FC = () => {
const BusinessTradeModelTable: React.FC<{ currentUser: CurrentUser }> = (props) => {
    const { currentUser } = props
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();

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

    const [currentRow, setCurrentRow] = useState<BusinessTradeModel>();// 当前选中行数据

    const [treeSelectOption, setTreeSelectOption] = useState<BusinessTradeModel[]>(); // 可选择项

    const columns: ProColumns<BusinessTradeModel>[] = [
        {
            dataIndex: 'AUTOSTATISTICS_ICO',
            width: 90,
            hideInDescriptions: true,
            render: (_, record) => {
                return <Avatar src={_} size={16} shape="square">{record.AUTOSTATISTICS_NAME.substring(0, 1)}</Avatar>

            }
        },
        {
            title: '业态名称',
            dataIndex: 'AUTOSTATISTICS_NAME',
            hideInDescriptions: true,
            hideInSearch: true,
            render: (dom, entity) => {
                return (
                    <a
                        onClick={() => {
                            setCurrentRow(entity);
                            setShowDetail(true);
                        }}
                    >
                        {dom}
                    </a>
                );
            },
        },

        {
            title: '业态状态',
            dataIndex: 'AUTOSTATISTICS_STATE',
            valueType: 'select',
            valueEnum: { 0: { text: '无效', status: 'error' }, 1: { text: '有效', status: 'success' }, 2: { text: '不可选', status: 'default' } },
            onFilter: true,
            filters: true
        },

        {
            title: '索引',
            dataIndex: 'AUTOSTATISTICS_INDEX',
            hideInSearch: true,
            sorter: (a, b) => b.AUTOSTATISTICS_INDEX - a.AUTOSTATISTICS_INDEX
        },
        {
            title: '所属业主',
            dataIndex: 'OWNERUNIT_NAME',
            sorter: true,
            hideInSearch: true,
        },
        {
            title: '说明',
            dataIndex: 'AUTOSTATISTICS_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.AUTOSTATISTICS_ID)
                    if (sucesse && actionRef.current) {
                        actionRef.current.reload()
                    }
                }}>
                    <a>删除</a>
                </Popconfirm>
            ]
        }
    ]
    return (
        <PageContainer header={{
            title: '',
            breadcrumb: {},
        }}>
            <ProTable<BusinessTradeModel>
                headerTitle={<PageTitleBox props={props} />}
                rowKey="AUTOSTATISTICS_ID"
                search={false}
                actionRef={actionRef}
                request={async (params) => {
                    const data: any = await getList({ BusinessTradeModelPID: -1, ...params })
                    setTreeSelectOption([{ AUTOSTATISTICS_NAME: '默认', AUTOSTATISTICS_ID: -1, children: [...data.data] }])
                    console.log('data', data);

                    return data
                }}

                columns={columns}
                toolbar={{
                    actions: [
                        <Button key="button" icon={<PlusOutlined />} type="primary" onClick={() => { handleModalVisible(true) }}>
                            新建
                        </Button>
                    ]
                }}
            />
            { /* 更新 信息弹出框 */}
            <ModalForm<BusinessTradeModel>
                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 || { AUTOSTATISTICS_TYPE: 2000 })

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

                    if (currentRow) { // 编辑数据
                        newValue = { ...currentRow, ...newValue }
                    }
                    newValue.AUTOSTATISTICS_STATE = values.AUTOSTATISTICS_STATE ? 1 : 0
                    newValue.AUTOSTATISTICS_TYPE = currentRow?.AUTOSTATISTICS_TYPE || 2000
                    const success = await handleAddUpdate(newValue);

                    if (success) {
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                        return true

                    }
                    return false
                }}
            >
                <Row>
                    <Col span={24}>
                        <Form.Item
                            name="AUTOSTATISTICS_PID"
                            label="上级业态"
                            rules={[
                                {
                                    required: true,
                                    message: '请选择上级业态',
                                },
                            ]}
                        >
                            <TreeSelect
                                placeholder="请选择上级业态"
                                dropdownStyle={{ maxHeight: 300, overflow: 'auto' }}
                                treeDefaultExpandedKeys={currentRow ? [currentRow?.AUTOSTATISTICS_PID] : [-1]}
                                // treeDataSimpleMode
                                showArrow={false}
                                treeData={treeSelectOption}
                                fieldNames={{
                                    label: 'AUTOSTATISTICS_NAME',
                                    value: 'AUTOSTATISTICS_ID'
                                }}
                            />
                        </Form.Item>
                        <ProFormText
                            name="AUTOSTATISTICS_NAME"
                            label="业态名称"
                            placeholder="请输入业态名称"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入业态名称',
                                },
                            ]} />


                        <ProFormDigit
                            name="AUTOSTATISTICS_INDEX"
                            label="业态索引"
                            placeholder="请输入业态索引"
                            min={0}
                            max={9999}
                            rules={[
                                {
                                    required: true,
                                    message: '请输入业态索引',
                                },
                            ]}
                            fieldProps={{ precision: 0 }}
                        />

                        <ProFormSelect
                            name="INELASTIC_DEMAND"
                            label="品牌类型"
                            rules={[
                                {
                                    required: true,
                                    message: '请选择品牌类型',
                                },
                            ]}
                            options={[{ label: '刚需', value: 1 }, { label: '半刚需', value: 2 }, { label: '非刚需', value: 3 }]}
                        />


                        {/* 当前依赖包动画过渡有问题 临时采用 Form.Item 方式进行Switch交互 */}
                        <Form.Item
                            name="AUTOSTATISTICS_STATE"
                            label="是否有效"
                        >
                            <Switch
                                checkedChildren="有"
                                unCheckedChildren="无"
                                defaultChecked={currentRow ? !!currentRow.AUTOSTATISTICS_STATE : true}
                            />
                        </Form.Item>
                        {/* <ProFormSwitch 
                            name="AUTOSTATISTICS_STATE"
                            label="是否有效"
                            checkedChildren="有"
                            unCheckedChildren="无"
                           
                        /> */}
                        <ProFormTextArea

                            name="AUTOSTATISTICS_DESC"
                            label="备注说明"
                            placeholder="请输入说明" />
                    </Col>
                </Row>
            </ModalForm>
            {/* 详情抽屉 */}
            <Drawer
                width={600}
                visible={showDetail}
                bodyStyle={{ padding: '24px' }}
                onClose={() => {
                    setCurrentRow(undefined);
                    setShowDetail(false);
                }}
                closable={false}
            >
                {currentRow?.AUTOSTATISTICS_NAME && (
                    <ProDescriptions<BusinessTradeModel>
                        column={2}
                        title={currentRow?.AUTOSTATISTICS_NAME}
                        request={async () => ({
                            data: currentRow || {},
                        })}
                        params={{
                            id: currentRow?.AUTOSTATISTICS_NAME,
                        }}
                        columns={columns as ProDescriptionsItemProps<BusinessTradeModel>[]}
                    />
                )}
            </Drawer>
        </PageContainer >
    )
}

export default BusinessTradeModelTable;