/*
 * @Author: cclu lkrnchocolateaaron@gmail.com
 * @Date: 2022-02-17 13:53:19
 * @LastEditors: cclu lkrnchocolateaaron@gmail.com
 * @LastEditTime: 2022-05-07 11:24:37
 * @FilePath: \cloud-platform\src\pages\Setting\UserType\index.tsx
 * @Description: 账号部门管理
 */
import React, { useState, useRef } from "react";
import useRequest from "@ahooksjs/use-request";
import { PlusOutlined } from "@ant-design/icons";
import { PageContainer } from "@ant-design/pro-layout";
import ProTable from "@ant-design/pro-table";
import ProDescriptions from "@ant-design/pro-descriptions";
import { Badge, Button, Drawer, Form, message,  Switch,  TreeSelect } from 'antd';
import { ModalForm, ProFormDigit, ProFormSelect,  ProFormText, ProFormTextArea } from "@ant-design/pro-form";

import type { FormInstance } from 'antd';
import type { UserTypeModel } from "./data";
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import type { ProDescriptionsItemProps } from "@ant-design/pro-descriptions"
import type { ConnectState } from "@/models/connect";
import type { CurrentUser } from '@/models/user';


import { getMerchantTree, getOnwer } from "@/services/options";
import { getUserTypeList, delUserType, updataUserType, getUserTypeCount } from './service'
import { connect } from "umi";

/**
    * @en-US add or update node
    * @zh-CN 新增或更新分类数据
    * @param fields 分类数据对象
    */
const handleAddUpdate = async (fields: UserTypeModel) => {
    const hide = message.loading('正在提交...')

    const result = await updataUserType(fields)
    hide()
    if (result.Result_Code !== 100) {
        message.error(`${result.Result_Desc}` || `${result.Result_Code}:提交失败`)
        return false
    }
    message.success(fields.USERTYPE_ID ? "更新成功！" : "新建成功！")
    return true
}

/**
 * @description: 删除分类
 * @param {nodeId} 分类id
 * @return {boolean} 是否执行成功
 */
const handleDelete = async (nodeId: number) => {
    const hide = message.loading('正在删除...');
    try {
        const result = await delUserType(nodeId)

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

// 数字角标生成
const renderBadge = (count: number, active = false) => {
    return (
        <Badge
            count={count}
            style={{
                marginTop: -2,
                marginLeft: 4,
                color: active ? '#1890FF' : '#999',
                backgroundColor: active ? '#E6F7FF' : '#eee',
            }}
        />
    );
};

const UserTypeList: React.FC<{ currentUser: CurrentUser | undefined }> = (props) => {
    const { currentUser } = props
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const [showDetail, setShowDetail] = useState<boolean>(false); // 是否显示详情
    const [currentRow, setCurrentRow] = useState<UserTypeModel>(); // 当前选中行
    const [createModalVisible, handleModalVisible] = useState<boolean>(false); // 发布分类更新窗口的弹窗

    const [userTypeTree, setUserTypeTree] = useState<[]>(); // 树结构数据分类 用于弹出编辑时选择上级
    const [activeKey, setActiveKey] = useState<React.Key>(`${currentUser?.UserPattern===9000?'1000':currentUser?.UserPattern}`); // 树结构数据分类 用于弹出编辑时选择上级

    // 查询可选商家
    const { data: merchantTree } = useRequest(async () => {
        return await getMerchantTree({MerchantPid:currentUser?.BusinessManID||''})
    })
    // 查询可选商家
    const {loading: typeCountLoading,data: typeCount } = useRequest(getUserTypeCount)

    // 表格数据配置 <UserTypeModel|SystemMenuModel>
    const columns: ProColumns<UserTypeModel>[] = [
        {
            title: '分类名称',
            dataIndex: 'USERTYPE_NAME',
            hideInDescriptions: true,
            render: (_, record) => {

                return <a key="fname" onClick={() => {
                    setCurrentRow(record)
                    setShowDetail(true)
                }}>{record?.USERTYPE_NAME}</a>
            }
        },
        {
            title: '状态',
            dataIndex: 'USERTYPE_STATUS',
            hideInSearch: true,
            filters: true,
            valueType: 'select',
            initialValue: 1,
            valueEnum: {
                all: { text: '全部', status: 'Default' },
                0: { text: '无效', status: 'Default' },
                1: { text: '有效', status: 'Processing' },
            },

        },
        {
            title: '所属业主',
            dataIndex: 'USERTYPE_PROVINCE',
            hideInSearch: true,
            hideInTable: activeKey==='2000',
            valueType: "select",
            request: async () => {
                const options = await getOnwer()
                return options;
            },
        },
        {
            title: '所属商户',
            dataIndex: 'USERTYPE_PROVINCE',
            hideInSearch: true,
            hideInTable: activeKey==='1000',
            valueType: "treeSelect",
            fieldProps: {
                options: merchantTree
            },

        },
        {
            title: '索引',
            dataIndex: 'USERTYPE_INDEX',
            hideInSearch: true
        },

        {
            title: '说明',
            dataIndex: 'USERTYPE_DESC',
            hideInSearch: true
        },
        {
            title: '操作',
            valueType: 'option',
            dataIndex: 'option',
            hideInDescriptions: true,
            render: (text, record) => [
                <a
                    key="editable"
                    onClick={() => {

                        handleModalVisible(true);
                        if (showDetail) {
                            setShowDetail(false);
                        }

                        setCurrentRow({ ...record });
                    }}
                >
                    编辑
                </a>,
                // <Popconfirm  // 删除按钮功能
                //     title="确认删除该项菜单吗?"
                //     onConfirm={async () => {
                //         if (record) {
                //             const { USERTYPE_ID } = record
                //             const success = (USERTYPE_ID ? await handleDelete(USERTYPE_ID) : false)
                //             if (success) {
                //                 if (actionRef.current) {
                //                     actionRef.current.reload();
                //                 }
                //             }
                //         }
                //     }}
                // >
                //     <a>无效</a>
                // </Popconfirm>
            ]
        }

    ]

    return (<PageContainer header={{
        title: '',
        breadcrumb: {},
    }}>

        <ProTable<UserTypeModel>

            rowKey="USERTYPE_ID"
            actionRef={actionRef}
            request={async (params) => {
              console.log('params',params)
                const data = await getUserTypeList({ ...params })
                setUserTypeTree(data)
                return { data, success: true }
            }}
            search={false}
            params={{ UserTypePattern: activeKey }}
            columns={columns}
            toolbar={{
                actions: [
                    <Button
                        key="new"
                        icon={<PlusOutlined />}
                        type="primary"
                        onClick={() => {
                            handleModalVisible(true)
                        }}
                    >部门</Button>,
                ],
                menu: {
                    type: 'tab',
                    activeKey,
                    items: currentUser?.UserPattern===9000 ? [
                        {
                            key: '1000',
                            label: <span>业主{renderBadge(!typeCountLoading ? typeCount?.OwnerUnitCount: '', activeKey === '1000')}</span>,
                        },
                        {
                          key: '4000',
                          label: <span>供应商{renderBadge(!typeCountLoading ?typeCount?.SupplierCount:'', activeKey === '4000')}</span>,
                        },
                        {
                            key: '2000',
                            label: <span>商户{renderBadge(!typeCountLoading ?typeCount?.MerchantCount:'', activeKey === '2000')}</span>,
                        }
                    ]:currentUser?.UserPattern===1000 ?[
                        {
                          key: '1000',
                          label: <span>业主{renderBadge(!typeCountLoading ? typeCount?.OwnerUnitCount: '', activeKey === '1000')}</span>,
                        },
                        {
                          key: '4000',
                          label: <span>供应商{renderBadge(!typeCountLoading ?typeCount?.SupplierCount:'', activeKey === '4000')}</span>,
                        },
                    ]:[],
                    onChange: (key) => {
                        setActiveKey(key as string);
                    },
                },
            }}
            pagination={{ defaultPageSize: 10 }}
        />

        {/* 编辑新增分类弹出框 */}
        <ModalForm
            layout={'horizontal'}
            wrapperCol={{ span: 16 }}
            labelCol={{ span: 6 }}
            title={currentRow ? '分类编辑' : '分类新增'}
            width={600}
            visible={createModalVisible}
            formRef={formRef}
            onVisibleChange={(value) => {
                handleModalVisible(value)
                if (value) {
                    formRef.current?.setFieldsValue(
                        currentRow ? {
                            ...currentRow, USERTYPE_STATUS: !!currentRow.USERTYPE_STATUS,
                            USERTYPE_PID: currentRow.USERTYPE_PID !== -1 ? currentRow.USERTYPE_PID : ''
                        } : { USERTYPE_STATUS: 1,USERTYPE_PATTERN:activeKey },
                    );
                } else {
                    formRef.current?.resetFields();
                    setCurrentRow(undefined);
                }
            }}
            onFinish={async (value) => {
                let newValue: any = { ...value , USERTYPE_PATTERN:activeKey}
                if (currentRow) { // 编辑数据
                    newValue = { ...currentRow, ...newValue }
                }

                newValue.USERTYPE_STATUS = value.USERTYPE_STATUS ? 1 : 0
                newValue.USERTYPE_PID = value.USERTYPE_PID ? value.USERTYPE_PID : -1
                const success = await handleAddUpdate(newValue as UserTypeModel)

                if (success) {
                    if (actionRef.current) {
                        actionRef.current.reload();
                    }
                    // handleModalVisible(false)
                    return true
                }
                return false
            }}
        >

            <ProFormText
                name="USERTYPE_NAME"
                label="分类名称"
                placeholder="请输入分类名称"
                rules={[
                    {
                        required: true,
                        message: '请输入分类名称',
                    },
                ]}
            />
            <Form.Item
                name="USERTYPE_PID"
                label="上级分类"
            >
                <TreeSelect
                    placeholder="请选择上级分类"
                    dropdownStyle={{ maxHeight: 300, overflow: 'auto' }}
                    // treeDefaultExpandAll
                    treeData={userTypeTree}
                    fieldNames={{
                        label: 'USERTYPE_NAME',
                        value: "USERTYPE_ID",
                        children: "children"
                    }}
                >
                </TreeSelect >
            </Form.Item>
            {activeKey === '1000' ||activeKey === '4000'
              ?<ProFormSelect
                name="USERTYPE_PROVINCE"
                label="业主单位"
                placeholder="请选择业主单位"
                rules={[
                    {
                        required: true,
                        message: '请选择业主单位',
                    },
                ]}
                request={async () => {
                    const options = await getOnwer()
                    return options;
                }}
                fieldProps={{
                    fieldNames: {
                        title: 'label',
                        // key: "value"
                    },

                }}
            />:''}
            {activeKey === '2000' &&
                <Form.Item
                    name="USERTYPE_PROVINCE"
                    label="所属商家"
                    // rules={[
                    //     {
                    //         required: true,
                    //         message: '请选择所属商家',
                    //     }
                    // ]}
                >
                    <TreeSelect
                        treeData={merchantTree}
                        treeDefaultExpandAll
                        showSearch
                        treeNodeFilterProp="label"
                        allowClear
                    />
                </Form.Item>}
            {/* <ProFormSwitch // 当前组件依赖临时过渡使用form.item
                name="USERTYPE_STATUS"
                label="是否有效"
                checkedChildren="有"
                unCheckedChildren="无"

            /> */}
            <Form.Item
                name="USERTYPE_STATUS"
                label="是否有效"
            >
                <Switch
                    checkedChildren="有"
                    unCheckedChildren="无"
                    defaultChecked={currentRow ? !!currentRow.USERTYPE_STATUS : true}
                />
            </Form.Item>

            <ProFormDigit
                name="USERTYPE_INDEX"
                label="索引"
                placeholder="请输入索引"

                min={0}
                max={9999}
                fieldProps={{ precision: 0 }}
            />

            <ProFormTextArea
                name="USERTYPE_DESC"
                label="备注说明"
                placeholder="请输入说明"
            />

        </ModalForm>
        {/* 分类详情 */}
        <Drawer
            width={600}
            visible={showDetail}
            onClose={() => {
                setCurrentRow(undefined);
                setShowDetail(false);
            }}
            closable={false}
        >
            {currentRow?.USERTYPE_NAME && (
                <ProDescriptions<UserTypeModel>
                    column={1}
                    title={currentRow?.USERTYPE_NAME}
                    request={async () => ({
                        data: currentRow || {},
                    })}
                    params={{
                        id: currentRow?.USERTYPE_ID,
                    }}
                    columns={columns as ProDescriptionsItemProps<UserTypeModel>[]}
                />
            )}
        </Drawer>
    </PageContainer>
    )
}

export default connect(({ user }: ConnectState) => ({
    currentUser: user.currentUser,

}))(UserTypeList);

