import { Image, Text, View } from '@tarojs/components'
import { useDidShow } from '@tarojs/taro'
import type { FC } from 'react'
import { useEffect, useState } from 'react'
import { useDispatch } from 'react-redux'
import type { Dispatch } from 'redux'
import defaultAvatar from '../../styles/image/defaultAvatar.png'
import styles from './index.module.scss'
import { checkKey, goLink } from '@/common/common'
import type { TabBarAction } from '@/reducers/tabBar'
import { TabBarIndex } from '@/reducers/tabBar'
import { TabBarType } from '@/constants/tabbar'
import NormalButton from '@/components/normalButton'
import Tag from '@/components/tag'
import Divider from '@/components/divider'
import LayoutBlock from '@/components/layoutBlock'
import IconCard from '@/components/iconCard'
import type { IconNames } from '@/components/iconfont/iconfont'
import useUserInfo from '@/use/useUserInfo'
import { useSelector } from '@/reducers/hooks'
import { BASE_URL } from '@/common/constant'
import useGetCode from '@/use/useGetCode'

// 用户头像
const UserAvatar = ({ src }: { src?: string }) => {
  return (
    <View className={styles.userAvatar}>
      <Image className="full-100" src={src || defaultAvatar} />
      {src ? null : <Text className={styles['userAvatar-text']}>编辑</Text>}
    </View>
  )
}
interface IconCardType {
  jurisdiction?: string // 权限key值
  iconName: IconNames
  name: string
  path: string
}

const feature: IconCardType[] = [
  {
    iconName: 'icon-pandiansaoma',
    name: '盘点扫码',
    path: '',
    jurisdiction: 'counting_scanning_code_page',
  },
  {
    iconName: 'icon-fahuoliebiao',
    name: '发货列表',
    path: '/pages/delivery/index',
    jurisdiction: 'shipping_list_page',
  },
  {
    iconName: 'icon-yaoqingma',
    name: '邀请码',
    path: '/pages/inviteCode/index',
    jurisdiction: 'invitation_code_page',
  },
  {
    iconName: 'icon-tihuoliebiao',
    name: '提货列表',
    path: '/pages/takeDelivery/index',
    jurisdiction: 'picking_list_module_page',
  },
  {
    iconName: 'icon-shouhouzhongxin',
    name: '退货退款',
    path: '/pages/refundPage/index',
    jurisdiction: 'return_and_refund_page',
  },
  {
    iconName: 'icon-shoukuanliebiao',
    name: '收款列表',
    path: '/pages/newCollection/index',
    jurisdiction: 'collection_list_page',
  },
  {
    iconName: 'icon-kehuxinxi',
    name: '客户列表',
    path: '/pages/customerManagement/index',
    jurisdiction: 'customer_list_page',
  },
  {
    iconName: 'icon-lingquseka',
    name: '领取色卡',
    path: '/pages/getColorCard/index',
    jurisdiction: 'ignore',
  },
  {
    iconName: 'icon-jianyang',
    name: '领取剪样',
    path: '/pages/sampleCutting/index',
    jurisdiction: 'ignore',
  },
]

const fabric: IconCardType[] = [
  {
    iconName: 'icon-yansequyang',
    name: '颜色取样',
    path: '/pages/colorRelated/takeColor/index',
    jurisdiction: 'color_sampling_page',
  },
  {
    iconName: 'icon-qusechazhao',
    name: '取色查找',
    path: '/pages/colorRelated/findColor/index',
    jurisdiction: 'color_search_page',
  },
  {
    iconName: 'icon-yangpinduibi',
    name: '样品对比',
    path: '/pages/colorRelated/sampleComparison/index',
    jurisdiction: 'sample_comparison_page',
  },
]

const statisticAnalysis: IconCardType[] = [
  {
    iconName: 'icon-xiaoshou',
    name: '销售',
    path: '/pages/saleStatistic/index',
    jurisdiction: 'sales_page',
  },
  {
    iconName: 'icon-duizhang',
    name: '对账',
    path: '',
    jurisdiction: 'reconciliation_page',
  },
  {
    iconName: 'icon-yuncangkucun',
    name: '云仓库存',
    path: '',
    jurisdiction: 'cloud_warehouse_inventory_page',
  },
  {
    iconName: 'icon-qianzhicangkucun',
    name: '前置仓库存',
    path: '',
    jurisdiction: 'front_warehouse_page',
  },
]

// 用户信息
const UserInfo: FC = () => {
  const { removeToken, removeUserInfo, userInfo } = useUserInfo()

  const dispatch = useDispatch<Dispatch<TabBarAction>>()

  console.log('userInfo==>', userInfo)
  // const [userInfo, setUserInfo] = useState({
  //   avatarUrl: '',
  //   username: '',
  //   userno: '',
  // })

  // 退出登录
  const handleLogout = () => {
    removeToken()
    removeUserInfo()
    dispatch({ type: TabBarType.SET_SELECTED, data: { selectedId: TabBarIndex.INDEX } })
    goLink('/pages/login/index', {}, 'reLaunch')
  }

  const handleClickIconCard = (item: IconCardType) => {
    console.log('item==>', item)
    goLink(item.path, {}, 'navigateTo')
  }

  const [Features, setFeatures] = useState<any[]>([])
  const [Coloring, setColoring] = useState<any[]>([])
  const [Statistics, setStatistics] = useState<any[]>([])
  useDidShow(() => {
    let arr: any[] = []
    let arrOne: any[] = []
    let arrTwo: any[] = []
    arr = feature.filter(item => checkKey(item.jurisdiction))
    arrOne = fabric.filter(item => checkKey(item.jurisdiction))
    arrTwo = statisticAnalysis.filter(item => checkKey(item.jurisdiction))
    setFeatures([...arr])
    setColoring([...arrOne])
    setStatistics([...arrTwo])
  })

  // 微信授权获取code
  const { UseGetCode } = useGetCode()
  const handReceive = async() => {
    try {
      await UseGetCode()
    }
    catch (err) {
      console.log(err, 'err')
    }
  }

  return (
    <>
      <LayoutBlock circle customStyle={{ paddingTop: '10px', paddingBottom: '10px' }}>
        <View className={styles.topBar}>
          <View className={styles.left}>
            <UserAvatar src={userInfo.userInfo?.avatar_url} />
          </View>
          <View className={styles.middle}>
            <Text className={styles.username}>{userInfo.userInfo?.user_name}</Text>
            <Text className={styles.userno}>{userInfo.userInfo.user_code}</Text>
          </View>
          <View className={styles.right}>
            <NormalButton plain type="primary" round size="normal" onClick={handleLogout}>
              退出登录
            </NormalButton>
          </View>
        </View>
        <View className={styles.bottomBar}>
          {/* 部门 */}
          <Tag type="primary" size="small" circle customStyle={{ padding: '8px 5px' }}>
            {userInfo.userInfo.department_name}
          </Tag>
          <Divider direction="vertical"></Divider>
          {/* 职责 */}
          <View className={styles.flexBox}>
            <Text className={styles.userTitle}>{userInfo.userInfo.duty_name}</Text>
            <View className={styles.receiveBox} onClick={() => handReceive()}>接收消息</View>
          </View>
        </View>
      </LayoutBlock>
      {
        !!Features.length && <LayoutBlock circle>
          <View className={styles.layoutTitle}>功能特色</View>
          <View className={styles['grid-container']}>
            {Features.map((item, key) => {
              return item.path ? <IconCard key={key} iconName={item.iconName} title={item.name} onClick={() => handleClickIconCard(item)}></IconCard> : null
            })}
          </View>
        </LayoutBlock>
      }
      {
        !!Coloring.length && <LayoutBlock circle>
          <View className={styles.layoutTitle}>布料取色</View>
          <View className={styles['grid-container']}>
            {Coloring.map((item, key) => {
              return item.path ? <IconCard key={key} iconName={item.iconName} title={item.name} onClick={() => handleClickIconCard(item)}></IconCard> : null
            })}
          </View>
        </LayoutBlock>
      }
      {
        !!Statistics.length && <LayoutBlock circle>
          <View className={styles.layoutTitle}>统计分析</View>
          <View className={styles['grid-container']}>
            {Statistics.map((item, key) => {
              return item.path ? <IconCard key={key} iconName={item.iconName} title={item.name} onClick={() => handleClickIconCard(item)}></IconCard> : null
            })}
          </View>
        </LayoutBlock>
      }

    </>
  )
}

// 我的
const User = () => {
  const [current_env, _] = useState(CURRENT_ENV)
  const [current_version, __] = useState(CURRENT_VERSION)
  return (
    <View className={styles.main}>
      <UserInfo />

      {/* 测试暂时添加 */}
      <View style={{ fontSize: '26rpx', color: '#707070', textAlign: 'center' }}>{current_version}</View>
      {current_env !== 'production' && <View style={{ fontSize: '26rpx', color: '#707070', textAlign: 'center' }}>{BASE_URL}</View>}
    </View>
  )
}

export default User
