
import useRequest from '@ahooksjs/use-request';
import IconFont from '@/components/IconFont';
import { useState } from 'react';
import { GridContent } from '@ant-design/pro-layout';
import { Row, Col, Card, Divider, Typography, Descriptions, Alert } from 'antd';
import { ContactsOutlined, ClusterOutlined, HomeOutlined, MobileOutlined } from '@ant-design/icons';
import { connect, Link } from 'umi';

import type { FC } from 'react';
import type { ConnectState } from '@/models/connect';
import type { CurrentUser } from '@/models/user';

import { getMyShopList } from './sevice';
import { getServerpartTree, getUserShopTree } from '@/services/options';
import { getUserSystemRole } from '@/pages/Setting/Users/service';
import { getRoleList } from '@/pages/Setting/Roles/service';
import styles from './center.less'

import ServerpartCardList from './components/MyServerpart';
import ShopCardList from './components/Myshop';
import MyPemission from './components/Permission';

type TabKeyProp = 'myserverpart' | 'myshop' | 'permission'  // 权限类型

/**
 * @description: 个人中心页面
 * @param {*} currentUser 用户信息
 * @return {*}
 */
const Center: FC<{ currentUser: CurrentUser | undefined }> = ({ currentUser }) => {
	const [activeTabKey, setActiveTabKey] = useState<TabKeyProp>(currentUser?.UserPattern === 2000 || currentUser?.UserPattern === 3000 ? 'myshop' : 'myserverpart') // 默认显示我的门店

	// 获取用户所有服务区
	const { loading: serverpartloading, data: myServerpartList = [] } = useRequest(async () => {
		if (currentUser?.CityAuthority) {
			return getServerpartTree(currentUser?.ProvinceCode, currentUser?.CityAuthority)
		}
		return []
	})

	// 获取服务区-门店树结构
	const { loading: shopLoading, data: shopTree } = useRequest(async () => {
		const data = await getUserShopTree(currentUser?.ID)
		if (data.length === 1) {
			return data[0].children
		}
		return []
	})

	// 获取用户所有门店
	const { loading, data: myshopList = [] } = useRequest(async () => {
		if (currentUser?.ServerpartShopIds) {
			return getMyShopList({ SERVERPARTSHOP_IDS: currentUser?.ServerpartShopIds })
		}
		return []
	})

	// 获取用户权限 根据用户userid查询角色树
	const { run: getRoleMenu, loading: myRoleLoading, data: myRoleTree } = useRequest((SystemId?: number) => {
		return getUserSystemRole(SystemId ? `${SystemId}` : '')
		// return data
	}, { manual: true })

	// 查询角色树
	const { run: getParentRoles, data: roleTree } = useRequest(async () => {
		return await getRoleList({ SystemRolePID: currentUser?.TopSystemRoleId })
	}, { manual: true })

	// 右侧用户头部tabs生成
	const renderTabList = ([serverpartCout = 0, shopCout = 0]) => {
		return [
			currentUser?.UserPattern === 1000 || currentUser?.UserPattern === 9000 ? ({
				key: 'myserverpart',
				tab: (
					<span>
						我的服务区<span style={{ fontSize: 14 }}>({serverpartCout})</span>
					</span>
				),
			}) : '',
			currentUser?.UserPattern === 2000 || currentUser?.UserPattern === 9000 ? ({
				key: 'myshop',
				tab: (
					<span>
						我的门店<span style={{ fontSize: 14 }}>({shopCout})</span>
					</span>
				),
			}) : '',
			{
				key: 'permission',
				tab: (
					<span>
						我的权限
					</span>
				),
			},
		]
	}

	// 用户基本信息
	const renderUserInfo = ({ ProvinceUnit, DepartmentName, BusinessManName, UserPattern, UserName, UserMobilephone }: Partial<CurrentUser>) => {
		return (
			<Descriptions className={styles.detail} column={2}>
				<Descriptions.Item span={1} contentStyle={{ alignItems: "center" }}>
					<ContactsOutlined style={{ marginRight: 8, }} />
					<Typography.Text >{UserName}</Typography.Text>
				</Descriptions.Item>
				<Descriptions.Item span={1} contentStyle={{ alignItems: "center" }}>
					<MobileOutlined style={{ marginRight: 8, }} />
					{UserMobilephone}
				</Descriptions.Item>
				<Descriptions.Item span={2} contentStyle={{ alignItems: "center" }}>
					<ClusterOutlined style={{ marginRight: 8, }} />
					{UserPattern === 1000 ? DepartmentName : BusinessManName}
					{/* { ProvinceUnit } */}
				</Descriptions.Item>
				<Descriptions.Item span={2} contentStyle={{ alignItems: "center" }}>
					<HomeOutlined
						style={{ marginRight: 8, }} />
					{ProvinceUnit}
				</Descriptions.Item>
			</Descriptions>
		)
	}
	return (
		<GridContent>
			{/* UserPattern 3000 游客身份，如果是游客 提示用户完善公司信息 */}
			{currentUser?.UserPattern === 3000 && <Alert style={{ marginBottom: 24 }}
				message={<Typography.Text type="warning">完善公司基本资料，审批通过后可使用更多功能。 <Link to="/merchantManagement/company/create">去完善</Link></Typography.Text>} banner />}
			{/* 页面左侧用户基础介绍 */}
			<Row gutter={24} >
				<Col lg={7} md={24} >
					<Card
						bordered={false}
						style={{ marginBottom: 24 }}
					>
						{currentUser && (
							<div>
								<div className={styles.avatarHolder} >
									<IconFont name='icon-touxiang' size="120" className={styles.avatar}></IconFont>
									<div>
										<Typography.Text className={styles.name}>{currentUser?.Name}</Typography.Text>
									</div>
									<Divider dashed />
								</div>
								{renderUserInfo(currentUser)}
							</div>
						)}
					</Card>
				</Col>
				{/* 页面右侧内容 */}
				<Col lg={17} md={24} >
					<Card
						tabList={renderTabList(!loading ? [currentUser?.CityAuthority || currentUser?.ServerpartIds ?
							(currentUser?.CityAuthority || currentUser?.ServerpartIds).split(',').length : 0, myshopList?.length] : [0, 0])}
						activeTabKey={activeTabKey}
						onTabChange={(_tabKey: string) => {
							setActiveTabKey(_tabKey as TabKeyProp);
							if (_tabKey === "permission") {
								getRoleMenu(currentUser?.ID)
								getParentRoles()
							}
						}}
					>
						{/* 我的服务区 */}
						{activeTabKey === 'myserverpart' && !serverpartloading && myServerpartList &&
							<ServerpartCardList serverpartList={myServerpartList} />
						}
						{/* 我的门店 */}
						{activeTabKey === 'myshop' && !shopLoading && !loading && myshopList &&
							<ShopCardList shopList={myshopList} shopTree={shopTree} />
						}
						{/* 我的权限 */}
						{
							activeTabKey === 'permission' && <MyPemission loading={myRoleLoading} myRoleTree={myRoleTree || []} roleTree={roleTree}></MyPemission>
						}
					</Card>
				</Col>
			</Row>
		</GridContent>
	);
};

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