/*
 * @Author: cclu
 * @Date: 2021-12-13 11:01:23
 * @LastEditTime: 2024-08-30 18:54:12
 * @LastEditors: cclu 1106109051@qq.com
 * @Description: 账号管理
 * @FilePath: \cloud-platform\src\pages\Setting\Users\index.tsx
 */
import { connect } from "umi";
import React, { useState, useRef } from "react";
import { Button, Drawer, Tree } from 'antd';
import ProTable from "@ant-design/pro-table";
import { PageContainer } from "@ant-design/pro-layout";
import { PlusOutlined } from "@ant-design/icons";

import type { UserModel } 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 Edit from './components/edit';
import ProCard from "@ant-design/pro-card";
import useRequest from "@ahooksjs/use-request";
import ProDescriptions from "@ant-design/pro-descriptions";

import { getUserSystemRole, getUserList, getUserTypeTree } from './service'
import { getOnwer } from "@/services/options";

const UserList: React.FC<{ currentUser: CurrentUser | undefined }> = (props) => {
    const { currentUser } = props
    const actionRef = useRef<ActionType>();
    const [showDetail, setShowDetail] = useState<boolean>(false);
    const [userTypeId, setUserTypeId] = useState<Record<number, []>>();
    const [tableTab, setTableTab] = useState<React.Key>(`${currentUser?.UserPattern}`);
    const [openType, setOpenType] = useState<any>()// 打开是编辑还是新增
    const [collapsible, setCollapsible] = useState<boolean>(false) // 是否显示账号分类查询树
    const [currentRow, setCurrentRow] = useState<UserModel>(); // 当前选中行
    const [createModalVisible, handleModalVisible] = useState<boolean>(false); // 分布更新窗口的弹窗
    const [userTypeObj, setUserTypeObj] = useState<any>()
    const selectTab = useRef(`${currentUser?.UserPattern}`)
    const { loading: treeLoading, data: treeViews } = useRequest(async () => {
        const req: any = {
            ProvinceCode: currentUser?.UserPattern === 2000 ? currentUser?.BusinessManID : currentUser?.ProvinceCode,
        }
        const data = await getUserTypeTree(req)
        let res: any = []
        if (data && data.length > 0) {
            data.forEach((item: any) => {
                res.push(item)
                if (item.children && item.children.length > 0) {
                    item.children.forEach((subItem: any) => {
                        res.push(subItem)
                        if (subItem.children && subItem.children.length > 0) {
                            subItem.children.forEach((thirdItem: any) => {
                                res.push(thirdItem)
                            })
                        }
                    })
                }
            })
        }
        console.log('res', res);

        let obj: any = {}
        if (res && res.length > 0) {
            res.forEach((item: any) => {
                obj[item.value] = item.label
            })
        }
        console.log('obj', obj);

        setUserTypeObj(obj)
    })
    // 请求账号部门tree
    const { run: getUserTypeMenu, loading: typeLoading, data: userTypeTree } = useRequest((type) => getUserTypeTree({ UserTypePattern: type || tableTab, ShowStatus: true }))

    // const [userTypeMenu, setUserTypeMenu] = useState<{1000: {}, 2000: {}}>(()=>getUserTypeTree(tableTab)); // 分布更新窗口的弹窗
    // 根据角色id查询权限树
    const { run: getRoleMenu, data: roleMenuTree } = useRequest(async (SystemRoleId?: number) => {
        const data = await getUserSystemRole(SystemRoleId ? `${SystemRoleId}` : '')
        return data
    }, { manual: true })
    const leftTab = [{ key: `1000`, name: '业主' }, { key: `4000`, name: '供应商' }, { key: `2000`, name: '商户' }, { key: `3000`, name: '游客' }, { key: `9000`, name: '内部' }]
    const ueserCloudTab = currentUser?.UserPattern === 9000 ? leftTab : currentUser?.UserPattern === 1000 ? [{ key: `1000`, name: '业主' }, { key: `4000`, name: '供应商' }] : leftTab.filter(n => n.key === `${currentUser?.UserPattern}`)
    // const ueserCloudTab = leftTab
    // 表格列数据显示配置
    const columns: ProColumns<UserModel>[] = [
        {
            title: '查询账号',
            dataIndex: 'searchKey',
            hideInDescriptions: true,
            hideInTable: true,
            fieldProps: {
                placeholder: '请输入账号/用户名称/业主单位/手机号/经营单位'
            }
        },
        {
            title: '有效状态',
            dataIndex: 'USER_STATUS',
            hideInTable: true,
            valueType: 'select',
            valueEnum: {
                "": "全部",
                "1": "有效",
                "0": "无效"
            },
            initialValue: "1"
        },
        {
            title: '经营单位',
            dataIndex: 'BUSINESSMAN_NAME',
            sorter: (a, b) => {
                return (a.BUSINESSMAN_NAME || '').localeCompare((b.BUSINESSMAN_NAME || ''))
            },
            hideInSearch: true,
            hideInTable: tableTab !== '2000',
            hideInDescriptions: tableTab !== '2000',
        },
        {
            title: '账号部门',
            dataIndex: 'USERTYPE_ID',
            hideInTable: tableTab === '3000' || tableTab === '9000',
            hideInSearch: true,
            hideInDescriptions: true,
            valueType: "treeSelect",
            fieldProps: {
                options: userTypeTree,
            },
        },
        {
            title: '账号',
            dataIndex: 'USER_PASSPORT',
            sorter: (a, b) => {
                return (a.USER_PASSPORT || '').localeCompare((b.USER_PASSPORT || ''))
            },
            hideInSearch: true,
        },
        {
            title: '用户名称',
            dataIndex: 'USER_NAME',
            sorter: (a, b) => {
                return (a.USER_NAME || '').localeCompare((b.USER_NAME || ''))
            },
            hideInDescriptions: true,
            hideInSearch: true,
            render: (_, record) => {

                return <a key="fname" onClick={() => {
                    getRoleMenu(record.USER_ID)
                    setCurrentRow(record)
                    setShowDetail(true)
                }}>{_}</a>
            }
        },
        {
            title: '手机号',
            dataIndex: 'USER_MOBILEPHONE',
            hideInSearch: true
        },
        // {
        //     title: '账号类型',
        //     dataIndex: 'USER_PATTERN',
        //     hideInSearch: true,
        //     valueType: 'select',
        //     valueEnum: {

        //         1000: { text: '业主' },
        //         2000: { text: '商户' },
        //     },
        // },
        {
            title: '状态',
            dataIndex: 'USER_STATUS',
            hideInSearch: true,
            filters: true,
            onFilter: true,
            valueType: 'select',
            initialValue: 1,
            valueEnum: {
                all: { text: '全部', status: 'Default' },
                0: { text: '无效', status: 'Default' },
                1: { text: '有效', status: 'Processing' },
            },

        },
        {
            title: '业主单位',
            dataIndex: 'PROVINCE_UNIT',
            hideInSearch: true,
            sorter: (a, b) => {
                return (a.PROVINCE_UNIT || '').localeCompare((b.PROVINCE_UNIT || ''))
            },
            hideInTable: tableTab === '2000',
            // valueType: "treeSelect",
            valueType: "select",
            request: async () => {
                let data = await getOnwer({ ProvinceCode: "530000", DataType: 1 })
                if (data && data.length > 0) {
                    data.forEach((item: any) => {
                        item.value = item.value.toString()
                    })
                }
                return data
            }
        },
        {
            title: '备注',
            dataIndex: 'USER_DESC',
            hideInSearch: true,
            hideInTable: tableTab === '2000',
            render: (_, record) => {
                return record?.USER_DESC
            }
        },
        {
            title: '操作',
            valueType: 'option',
            hideInDescriptions: true,
            // width: 180,
            render: (text, record) => [
                <a
                    key="editable"
                    onClick={() => {
                        handleModalVisible(true);
                        setOpenType('edit')
                        setCurrentRow({ ...record });
                    }}
                >
                    编辑
                </a>,
            ]
        }
    ]
    return (<PageContainer header={{
        title: '',
        breadcrumb: {},
    }}>
        <ProCard split="vertical" style={{ backgroundColor: '#fff' }}>
            {/* 左侧树筛选 */}
            <ProCard
                className="pageTable-leftnav"
                bodyStyle={{ padding: 0, paddingTop: 20, paddingLeft: 20 }}
                // extra={<MenuFoldOutlined onClick={() => { setCollapsible(!collapsible) }} />}
                colSpan={!collapsible ? "360px" : "60px"}
                // title={!collapsible ? "请选择账号部门" : ""}
                // headerBordered
                // collapsed={collapsible}
                tabs={{
                    activeKey: tableTab,
                    onChange: (key) => {
                        console.log('key', key)
                        setTableTab(key as string);
                        selectTab.current = key
                        getUserTypeMenu(key)
                    },
                }}
            >
                {ueserCloudTab.map(n => {
                    return <ProCard.TabPane key={n.key} tab={n.name}>
                        <Tree
                            checkable
                            style={{ padding: '20px' }}
                            // eslint-disable-next-line no-nested-ternary
                            // 虽然不知道前面为啥要[0].children  但是 领导说 按照下面那行的走 那就遵命
                            // treeData={!typeLoading ? (currentUser?.UserPattern === 9000 ? userTypeTree : userTypeTree[0]?.children) : []}
                            treeData={!typeLoading ? (currentUser?.UserPattern === 9000 ? userTypeTree : userTypeTree) : []}
                            fieldNames={{
                                title: "label",
                                // key: "USERTYPE_ID"
                            }}
                            blockNode
                            // onSelect={onSelect}
                            onCheck={(checkedKeys: React.Key[] | any) => {
                                setUserTypeId({ [n.key]: checkedKeys })
                                if (actionRef.current) {
                                    // actionRef.current?.reset()
                                    actionRef.current?.reload()
                                }
                            }}
                        >
                        </Tree>
                    </ProCard.TabPane>
                })}
            </ProCard>
            {/* 右侧表格主体 */}
            <ProCard bodyStyle={{ paddingTop: 0, paddingBottom: 0, paddingRight: 0 }}>
                <ProTable<UserModel>
                    headerTitle="账号管理"
                    rowKey="USER_ID"
                    actionRef={actionRef}
                    request={async (params, sorter) => {
                        console.log('params', params);

                        const sortstr = Object.keys(sorter).map(n => {
                            const value = sorter[n]
                            return value ? `${n} ${value.replace('end', '')}` : ''
                        })
                        const data = await getUserList({
                            ...params,
                            USER_STATUS: params?.USER_STATUS,
                            USER_PATTERN: tableTab,
                            PROVINCE_UNIT: '911',
                            UserTypeIds: userTypeId && userTypeId[tableTab] ? userTypeId[tableTab].toString() : '',
                            SortStr: sortstr ? sortstr.toString() : 'USER_INDEX',
                            keyWord: params.searchKey ? { key: "USER_PASSPORT,USER_NAME,USER_MOBILEPHONE,PROVINCE_UNIT,BUSINESSMAN_NAME", value: params.searchKey } : null, // 关键词查询
                        })
                        return data
                    }}
                    onReset={() => {
                        actionRef.current?.reload()
                    }}
                    params={{ USER_PATTERN: tableTab }}
                    columns={columns}
                    toolbar={{
                        actions:
                            currentUser?.UserPattern === 1000 || currentUser?.UserPattern === 9000 ?
                                [
                                    <Button
                                        key="new"
                                        icon={<PlusOutlined />}
                                        type="primary"
                                        onClick={() => {
                                            console.log('currentUser?.UserPattern', currentUser?.UserPattern)
                                            handleModalVisible(true)
                                            setOpenType('add')
                                        }}
                                    >账号</Button>,
                                ] : []
                    }}
                    pagination={{ defaultPageSize: 10 }}

                />
            </ProCard>
        </ProCard>
        {/* 用户详情 */}
        <Drawer
            // eslint-disable-next-line no-nested-ternary
            width={showDetail ? 600 : (createModalVisible ? '73%' : undefined)}
            visible={showDetail || createModalVisible}
            onClose={() => {
                setCurrentRow(undefined);
                setShowDetail(false);
                handleModalVisible(false)
                setOpenType('')
            }}
            closable={false}
            bodyStyle={createModalVisible ? { backgroundColor: "#f9f9f9", padding: 0 } : {}}
        >
            {/* 编辑或新增账号 */}
            {createModalVisible && <Edit selectTab={selectTab.current} tableTab={tableTab} openType={openType} detail={currentRow} currentUser={currentUser} reloadTable={(success: boolean) => {
                if (success) {
                    if (actionRef.current) {
                        actionRef.current.reload();
                    }
                }
            }} />}
            {/* 查看账号详情 */}
            {showDetail && <ProDescriptions<UserModel>
                column={1}
                title={currentRow?.USER_NAME}
                request={async () => ({
                    data: currentRow || {},
                })}
                params={{
                    id: currentRow?.USER_NAME,
                }}
                columns={columns as ProDescriptionsItemProps<UserModel>[]}
            >
                <ProDescriptions.Item label="用户角色权限">
                    {roleMenuTree?.length ? <Tree
                        style={{ backgroundColor: '#FDFCFC', paddingRight: 24 }}
                        treeData={roleMenuTree}
                        defaultExpandAll={true}
                        fieldNames={
                            { title: "label", key: 'value' }
                        }>
                    </Tree> : '-'}
                </ProDescriptions.Item>
            </ProDescriptions>
            }
        </Drawer>
    </PageContainer>
    )
}

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

