/*
 * @Author: cclu 1106109051@qq.com
 * @Date: 2024-08-21 18:34:38
 * @LastEditors: cclu 1106109051@qq.com
 * @LastEditTime: 2024-09-11 17:08:13
 * @FilePath: \cloud-platform\src\pages\Setting\merchantManagement\index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD
 */
import { connect } from "umi";
import type { CurrentUser } from "umi";
import type { ConnectState } from "@/models/connect";
import React, { useRef, useState } from "react";
import { Button, Drawer, FormInstance, Space, Tooltip, Tree, Typography } from "antd";
import ProTable, { ActionType } from "@ant-design/pro-table";
import ProCard from "@ant-design/pro-card";
import { useRequest } from "ahooks";
import { handleGetSPRegionShopTree, handleGetUserList } from "./service";
import { getMerchantShopTree, getUserSystemRole, getUserTypeTree } from "../Users/service";
import { UserModel } from "../Users/data";
import ProDescriptions, { ProDescriptionsItemProps } from "@ant-design/pro-descriptions";
import Edit from "../Users/components/edit";
import { PlusOutlined } from "@ant-design/icons";
import BusinessManDrawer from "@/pages/basicManage/businessMan/components/businessManDrawer";
import moment from 'moment'
const { Text } = Typography

const merchantManagement: React.FC<{ currentUser: CurrentUser }> = (props) => {
    const { currentUser } = props
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const [treeView, setTreeView] = useState<any>()
    const [showDetail, setShowDetail] = useState<boolean>(false);
    const [createModalVisible, handleModalVisible] = useState<boolean>(false); // 分布更新窗口的弹窗
    const [currentRow, setCurrentRow] = useState<UserModel>(); // 当前选中行
    const [openType, setOpenType] = useState<any>()// 打开是编辑还是新增


    const [showAddDrawer, setShowAddDrawer] = useState<boolean>(false)
    // 根据角色id查询权限树
    const { run: getRoleMenu, data: roleMenuTree } = useRequest(async (SystemRoleId?: number) => {
        const data = await getUserSystemRole(SystemRoleId ? `${SystemRoleId}` : '')
        return data
    }, { manual: true })
    // 根据商家id查询门店列表
    const { run: getShopTree, data: shopTree } = useRequest(async (businessManId?: number) => {
        const data = await getMerchantShopTree({ BusinessManId: businessManId ? `${businessManId}` : currentRow?.BUSINESSMAN_ID })
        return data
    }, { manual: true })


    // 加载服务区树
    const { loading: treeLoading, data: treeViews } = useRequest(async () => {
        const req: any = {
            ProvinceCode: currentUser?.ProvinceCode || '734100',
            ShowWholePower: false
        }
        const data = await handleGetSPRegionShopTree(req)

        setTreeView(data)
        return data
    })
    const { loading: userLoading, data: user } = 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)
                            })
                        }
                    })
                }
            })
        }

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

        setUserTypeObj(obj)
    })

    const { loading: typeLoading, data: userTypeTree } = useRequest(async () => {
        const treeData: any = await getUserTypeTree({ UserTypePattern: 2000 })
        console.log('treeData', treeData);
        let obj: any = {}
        if (treeData && treeData.length > 0) {
            treeData.forEach((item: any) => {
                obj[item.value] = item.label
                if (item.children && item.children.length > 0) {
                    item.children.forEach((subItem: any) => {
                        obj[subItem.value] = subItem.label
                        if (subItem.children && subItem.children.length > 0) {
                            subItem.children.forEach((thirdItem: any) => {
                                obj[thirdItem.value] = thirdItem.label
                            })
                        }
                    })
                }
            })
        }
        setUserTypeTreeObj(obj)
        return treeData
    })
    const [userTypeTreeObj, setUserTypeTreeObj] = useState<any>()
    const [collapsible, setCollapsible] = useState<boolean>(false)

    // 树相关的属性和方法
    const [selectedId, setSelectedId] = useState<string>()
    const [selectedShopId, setSelectedShopId] = useState<string>()
    // 查询的条件
    const [searchParams, setSearchParams] = useState<any>()
    const [userTypeObj, setUserTypeObj] = useState<any>()
    // 商户id给新增的时候默认选上
    const [BUSINESSMAN_ID, setBUSINESSMAN_ID] = useState<any>()
    // 查询的文字
    const [searchText, setSearchText] = useState<string>()
    const [recordColumnsStateMap, setRecordColumnsStateMap] = useState<any>({
        USER_STATUS: { show: false },
    })

    const columns: any = [
        {
            title: '查询账号',
            dataIndex: 'searchKey',
            hideInDescriptions: true,
            hideInTable: true,
            fieldProps: {
                placeholder: '请输入账号/用户名称/业主单位/手机号/经营单位'
            }
        },
        {
            title: '序号',
            width: 80,
            dataIndex: 'index',
            valueType: 'index'
        },
        {
            title: '商户名称',
            width: 300,
            dataIndex: 'BUSINESSMAN_NAME',
            ellipsis: true,
            sorter: (a, b) => {
                return (a.BUSINESSMAN_NAME || '').localeCompare((b.BUSINESSMAN_NAME || ''))
            },
            copyable: true,
            hideInSearch: true,
            render: (_, record) => {
                return record?.USER_NAME ?
                    <Space>
                        <Text copyable={record?.USER_NAME} style={{ cursor: 'pointer', color: '#1890ff' }} onClick={() => {
                            getRoleMenu(record.USER_ID)
                            getShopTree(record?.BUSINESSMAN_ID)
                            setCurrentRow(record)
                            setShowDetail(true)
                        }}>
                            {record?.USER_NAME}
                        </Text>
                    </Space>

                    : record?.BUSINESSMAN_NAME ? <Space>
                        <Text copyable={record?.BUSINESSMAN_NAME} style={{ cursor: 'pointer', color: '#1890ff' }} onClick={() => {
                            console.log('record', record);
                            setCurrentRow({
                                OWNERUNIT_ID: record?.BUSINESSMAN_ID
                            })
                            setShowAddDrawer(true)
                        }}>
                            {record?.BUSINESSMAN_NAME}
                        </Text>
                    </Space>
                        : '-'
            }
        },
        {
            title: '账号',
            width: 150,
            ellipsis: true,
            dataIndex: 'USER_PASSPORT',
            sorter: (a, b) => {
                return (a.USER_PASSPORT.toString() || '').localeCompare((b.USER_PASSPORT.toString() || ''))
            },
            hideInSearch: true,
            render: (_, record) => {
                return handleGetResult(record?.USER_PASSPORT, searchText)
            }
        },
        // {
        //     title: '用户名称',
        //     width: 150,
        //     dataIndex: 'USER_NAME',
        //     ellipsis: true,
        //     hideInDescriptions: true,
        //     sorter: (a, b) => {
        //         return (a.USER_NAME || '').localeCompare((b.USER_NAME || ''))
        //     },
        //     hideInSearch: true,
        //     render: (_, record) => {
        //         return <a onClick={() => {
        //             console.log('record', record);

        //             getRoleMenu(record.USER_ID)
        //             getShopTree(record?.BUSINESSMAN_ID)
        //             setCurrentRow(record)
        //             setShowDetail(true)
        //         }}>{record?.USER_NAME}</a>
        //     }
        // },
        {
            title: '手机号',
            width: 150,
            dataIndex: 'USER_MOBILEPHONE',
            align: 'center',
            sorter: (a, b) => {
                return (a.USER_MOBILEPHONE || '').localeCompare((b.USER_MOBILEPHONE || ''))
            },
            hideInSearch: true,
            render: (_, record) => {
                return handleGetResult(record?.USER_MOBILEPHONE, searchText)
            }
        },

        {
            title: '账号部门',
            width: 150,
            dataIndex: 'USERTYPE_ID',
            hideInSearch: true,
            ellipsis: true,
            align: 'center',
            // valueType: "treeSelect",
            // request: async () => {
            //     return getUserTypeTree({ UserTypePattern: 2000 })
            // },
            fieldProps: {
                // options: userTypeTree,
            },
            render: (_, record) => {
                let str: string = record?.USERTYPE_ID ? userTypeTreeObj[record?.USERTYPE_ID] : ''
                return <Tooltip title={str}>
                    <span style={{ width: '100%', display: 'block', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{str || '-'}</span>
                </Tooltip>
            }
        },

        {
            title: '服务区权限',
            width: 120,
            align: 'center',
            dataIndex: 'ShopNameList',
            hideInSearch: true,
            ellipsis: true,
            render: (_, record) => {
                return record?.ServerpartList && record?.ServerpartList.length > 0 ? record?.ServerpartList.toString() : '-'
            }
        },
        {
            title: '门店权限',
            width: 120,
            align: 'center',
            dataIndex: 'ServerpartList',
            hideInSearch: true,
            hideInDescriptions: true,
            ellipsis: true,
            render: (_, record) => {
                return record?.ShopNameList && record?.ShopNameList.length > 0 ? record?.ShopNameList.toString() : '-'
            }
        },
        {
            title: '操作人',
            width: 140,
            dataIndex: 'STAFF_NAME',
            align: 'center',
            hideInSearch: true,
            ellipsis: true,
        },
        {
            title: '操作时间',
            width: 150,
            dataIndex: 'OPERATE_DATE',
            align: 'center',
            hideInSearch: true,
            render: (_, record) => {
                return record?.OPERATE_DATE ? moment(record?.OPERATE_DATE).format('YYYY-MM-DD HH:mm:ss') : ''
            }
        },
        {
            title: '状态',
            width: 100,
            dataIndex: 'USER_STATUS',
            filters: true,
            align: 'center',
            onFilter: true,
            valueType: 'select',
            initialValue: "1",
            valueEnum: {
                "all": { text: '全部', status: 'Default' },
                "1": { text: '有效', status: 'Processing' },
                "0": { text: '无效', status: 'Default' },
            },
        },
        {
            title: '操作',
            width: 80,
            valueType: 'option',
            align: 'center',
            hideInDescriptions: true,
            // width: 180,
            fixed: 'right',
            render: (_, record) => {
                return record?.USER_ID ?
                    <a
                        key="editable"
                        onClick={() => {
                            handleModalVisible(true);
                            setOpenType('edit')
                            setCurrentRow({ ...record });
                        }}
                    >
                        编辑
                    </a> : <a
                        key="editable"
                        onClick={() => {
                            console.log('record', record);
                            setBUSINESSMAN_ID({
                                label: record?.BUSINESSMAN_NAME,
                                value: record?.BUSINESSMAN_ID
                            })
                            handleModalVisible(true)
                            setOpenType('add')
                        }}
                    >
                        新增
                    </a>
            }
        }
    ]
    const handleGetMerchantTree = () => {
        actionRef.current?.reload()
    }


    // 根据查询的问题 在查出来的结果数据上 添加关键字为金色的效果
    const handleGetResult = (text: string, place?: string) => {
        if (place) {
            // text 原先的文字  place 匹配上的文字
            let indexStr: number = -1
            if (text && text.toString().indexOf(place) !== -1) {
                indexStr = text.indexOf(place)
            }
            if (indexStr > 0) {
                return <span>
                    {text.slice(0, indexStr)}
                    <span style={{ color: '#ffc352' }}>{place}</span>
                    {text.slice(indexStr + (place?.length || 0))}
                </span>
            }
            return <span>{text}</span>
        } else {
            return <span>{text}</span>
        }
    }

    return (
        <div>
            <div style={{ backgroundColor: '#fff', display: 'flex' }}>
                <ProCard
                    style={{ width: !collapsible ? "300px" : "60px" }}
                    className="pageTable-leftnav"
                    bodyStyle={{ padding: 0, paddingTop: 20, paddingLeft: 20, width: !collapsible ? "300px" : "60px" }}
                    colSpan={!collapsible ? "300px" : "60px"}
                    title={!collapsible ? "请选择服务区" : ""}
                    headerBordered
                    collapsed={collapsible}
                >
                    {treeView && treeView.length > 0 ? <Tree
                        checkable
                        treeData={[{
                            label: '全部',
                            value: 0,
                            key: '0-0',
                            children: treeView
                        }]}
                        fieldNames={{
                            title: "label",
                            key: "key"
                        }}
                        blockNode
                        defaultExpandedKeys={['0-0']}
                        onCheck={(checkedKeys: React.Key[] | any, info) => {
                            console.log('info', info);
                            const selectedIds = info.checkedNodes.filter((n: any) => n?.type === 1)
                            const selectedShopIds = info.checkedNodes.filter((n: any) => n?.type === 2)
                            setSelectedId(selectedIds.map(n => n?.value)?.toString() || '')
                            setSelectedShopId(selectedShopIds.map(n => n?.value)?.toString() || '')
                        }}
                    /> : ''}
                </ProCard>
                <div style={{
                    width: !collapsible ? 'calc(100% - 300px)' : 'calc(100% - 60px)',
                    paddingTop: 0,
                    paddingBottom: 0,
                    paddingRight: 0
                }}>
                    <ProTable
                        actionRef={actionRef}
                        formRef={formRef}
                        columns={columns}
                        bordered
                        expandable={{
                            // expandRowByClick: true
                        }}
                        rowKey={(record) => {
                            return `${record?.BUSINESSMAN_ID}-${record?.USER_ID}`
                        }}
                        scroll={{ y: 'calc(100vh - 450px)' }}
                        headerTitle={'商户管理'}
                        search={{ span: 6 }}
                        request={async (params) => {
                            // if (!selectedId) {
                            //     return { data: [], success: true }
                            // }
                            setSearchParams(params)
                            const req: any = {

                                ServerpartId: selectedId,
                                ServerpartShopId: selectedShopId,
                                ProvinceCode: currentUser?.ProvinceCode || '734100',
                                ValidState: params?.USER_STATUS === 'all' ? '' : params?.USER_STATUS === '1' ? 1 : params?.USER_STATUS === '0' ? 0 : '',
                                // ValidState: 1,
                                SearchName: "USER_PASSPORT,USER_NAME,USER_MOBILEPHONE,PROVINCE_UNIT,BUSINESSMAN_NAME",
                                keyWord: {
                                    Key: "USER_PASSPORT,USER_NAME,USER_MOBILEPHONE,PROVINCE_UNIT,BUSINESSMAN_NAME",
                                    Value: params.searchKey
                                }
                            }
                            setSearchText(params.searchKey)
                            const data = await handleGetUserList(req)
                            console.log('data3232', data);
                            if (data && data.length > 0) {
                                data.forEach((item: any) => {
                                    item.USER_PASSPORT = item.children && item.children.length > 0 ? item.children.length : null
                                })
                                return { data, success: true }
                            }
                            return { data: [], success: true }
                        }}
                        columnsState={{
                            value: recordColumnsStateMap,
                            onChange: setRecordColumnsStateMap,
                        }}
                        toolbar={{
                            actions:
                                [
                                    <Button
                                        key="new"
                                        icon={<PlusOutlined />}
                                        type="primary"
                                        onClick={() => {
                                            console.log('currentUser?.UserPattern', currentUser?.UserPattern)
                                            setOpenType('add')
                                            handleModalVisible(true)
                                        }}
                                    >新增商户</Button>,
                                ]
                        }}
                    />
                </div>
            </div>

            <BusinessManDrawer showDrawer={showAddDrawer} setShowDrawer={setShowAddDrawer} setCurrentRow={setCurrentRow} currentRow={currentRow} pageType={'edit'} afterOk={handleGetMerchantTree} />


            {/* 用户详情 */}
            <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('')
                    setBUSINESSMAN_ID(undefined)
                }}
                closable={false}
                bodyStyle={createModalVisible ? { backgroundColor: "#f9f9f9", padding: 16 } : { padding: 16 }}
            >
                {/* 编辑或新增账号 */}
                {createModalVisible && <Edit onShow={showDetail} BUSINESSMAN_ID={BUSINESSMAN_ID} selectTab={2000} tableTab={2000} openType={openType} pageType={"merchantManagement"} detail={currentRow} currentUser={currentUser} reloadTable={(success: boolean, type?: string) => {
                    if (success) {
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                    if (type && type === 'delete') {
                        setCurrentRow(undefined);
                        setShowDetail(false);
                        handleModalVisible(false)
                        setOpenType('')
                        setBUSINESSMAN_ID(undefined)
                    }
                }} />}
                {/* 查看账号详情 */}
                {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.Item label="门店权限">
                        {shopTree?.length ? <Tree
                            style={{ backgroundColor: '#FDFCFC', paddingRight: 24 }}
                            treeData={shopTree}
                            defaultExpandAll={true}
                            fieldNames={
                                { title: "label", key: 'value' }
                            }>
                        </Tree> : '-'}
                    </ProDescriptions.Item>
                </ProDescriptions>
                }
            </Drawer>
        </div>
    )
}

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