import { Button, Image, Text, View } from '@tarojs/components'
import Taro, { useDidShow, usePullDownRefresh } from '@tarojs/taro'
import classnames from 'classnames'
import { useMemo, useState } from 'react'
import styles from './index.module.scss'
import Customer from './components/customer'
import { useSelector } from '@/reducers/hooks'
import { alert, goLink } from '@/common/common'
import { formatImgUrl, formatPriceDiv } from '@/common/fotmat'
import { userassets, userorderStatistics } from '@/api/mine'
import useLogin from '@/use/useLogin'
import IconFont from '@/components/iconfont/iconfont'
import SvgIconfont from '@/components/svgIconfont'
import { BASE_URL, getCDNSource } from '@/common/constant'
import { GetCashBackInfo } from '@/api/user'

export default () => {
  const userInfo = useSelector(state => state.userInfo)
  const { fetchData: Apiassets, state: priceState } = userassets()
  const { fetchData: ApigetTotal, state: orderState } = userorderStatistics()
  const { getAdminUserInfo, getPhoneNumber } = useLogin()

  const { fetchData, state } = GetCashBackInfo()

  useDidShow(() => {
    ApigetTotal()
    fetchData()
    getAdminUserInfo()
    Apiassets()
  })

  const [customer_service_show, set_customer_service_show] = useState(false)
  const customerClose = () => {
    set_customer_service_show(false)
  }

  const priceList = useMemo(() => {
    console.log('priceState::', priceState.data)
    return [
      {
        label: '预存货款(元)',
        value: formatPriceDiv(priceState?.data?.wallet_money || 0, 100, true),
        url: '/pages/depositBeforehand/index',
      },
      {
        label: '账期货款(元)',
        value: formatPriceDiv(priceState?.data.credit_line || 0, 100, true),
        url: '/pages/creditLine/index',
      },
    ]
  }, [priceState])

  const orderList = useMemo(() => {
    return [
      { label: '待配布', icon: 'icon-daipeibu2', url: '/pages/order/orderList/index?status=0', number: orderState?.data?.wait_match > 99 ? '99+' : orderState?.data?.wait_match },
      { label: '待付款', icon: 'icon-daifukuan2', url: '/pages/order/orderList/index?status=1', number: orderState?.data?.wait_pay > 99 ? '99+' : orderState?.data?.wait_pay },
      { label: '待发货', icon: 'icon-daifahuo2', url: '/pages/order/orderList/index?status=2', number: orderState?.data?.wait_shipped > 99 ? '99+' : orderState?.data?.wait_shipped },
      { label: '待收货', icon: 'icon-daishouhuo2', url: '/pages/order/orderList/index?status=3', number: orderState?.data?.already_shipped > 99 ? '99+' : orderState?.data?.already_shipped },
      { label: '退款/售后', icon: 'icon-tuikuan-shouhou', url: '/pages/salesAfter/salesAfterList/index', number: orderState?.data?.after_return > 99 ? '99+' : orderState?.data?.after_return },
    ]
  }, [orderState])

  const menuList = [
    { label: '地址管理', icon: 'icon-dizhiguanli', callback: () => goLink('/pages/addressManager/index') },
    { label: '码单管理', icon: 'icon-mdgl', icon_status: 'local', callback: () => goLink('/pages/codeList/index') },
    { label: '色卡剪样', icon: 'icon-sekajianyanglingqu', callback: () => goLink('/pages/colorCardClipping/index') },
    // { label: '颜色对比', icon: 'icon-yanseduibi', callback: () => goLink('/pages/sampleComparison/index') },
    { label: '我的客服', icon: 'icon-wodekefu', text: '7x24小时服务', callback: () => (set_customer_service_show(true)) },
  ]

  const mGetPhoneNumber = async(ev) => {
    if (ev.detail?.code) {
      await getPhoneNumber(ev.detail.code)
      await ApigetTotal()
      await getAdminUserInfo()
      await Apiassets()
    }
    else {
      alert.none('绑定失败!')
    }
  }

  const integral = () => {
    // alert.none('【积分】暂未对外开放 敬请期待')
    goLink('/pages/sampleComparison/index')
  }

  usePullDownRefresh(async() => {
    await ApigetTotal()
    await getAdminUserInfo()
    await Apiassets()
    Taro.stopPullDownRefresh()
  })

  const handleClickInviteFriends = () => {
    if (!userInfo?.adminUserInfo?.is_bd) {
      goLink('/pages/inviteCode/index')
    }
    else {
      goLink('/pages/inviteCode/inviteFriends/index')
    }
  }

  const [current_env, _] = useState(CURRENT_ENV)
  const [current_version, __] = useState(CURRENT_VERSION)

  return (
    <View className={styles.user_main}>
      {!userInfo?.adminUserInfo?.phone && <View className={styles.getPhoneButton} onClick={() => goLink('/pages/login/index')}></View>}
      <View className={styles.user_main__header}>
        <View className={styles.user_main__header_con}>
          <View className={styles.header_img_name}>
            <View className={styles.header_img}>
              <Image className={styles.header_img_src} mode="aspectFill" src={`${userInfo?.adminUserInfo?.avatar_url}`} />
            </View>
            <View className={styles.header_name}>
              <View className={styles.header_user}>
                <Text className={styles.header_user_name}>{userInfo?.adminUserInfo?.phone ? userInfo?.adminUserInfo?.company_name : '点击登录'}</Text>
                {
                  userInfo?.adminUserInfo?.is_bd && <View className={styles.header_user_label}>
                    <Image className={styles.BD_label} mode="aspectFill" src={getCDNSource('/mall/BD_label.png')}></Image>
                  </View>
                }
              </View>
              <View className={styles['arcd-info-left-phone']}>
                <View className={styles.header_title}> {userInfo?.adminUserInfo?.phone || 'Hi,欢迎来到商城'}</View>
              </View>
              {/* {!!userInfo?.adminUserInfo?.company_name && <View className={styles.header_picture} >
                <View className={styles.icon_renzhengchenggong}><IconFont name="icon-renzhengchenggong" size={24} /></View>
                <View className={styles.header_picture_name}>{userInfo?.adminUserInfo?.company_name}</View></View>} */}
            </View>
            <View className={styles.header_setting} onClick={() => goLink('/pages/userEdit/index')}>
              <IconFont name="icon-shezhi" size={50} />
            </View>
          </View>
          <View className={styles.header_count}>
            <View className={styles.header_count__item} onClick={() => goLink('/pages/collection/index')}>
              <IconFont name="icon-shoucangshangpin" size={50} />
              <Text>商品收藏</Text>
            </View>
            <View className={styles.header_count__item} onClick={integral}>
              <IconFont name="icon-yanseduibi1" size={50} />
              <Text>颜色对比</Text>
            </View>
            <View className={styles.header_count__item} onClick={handleClickInviteFriends}>
              <IconFont name="icon-erweima" size={50} />
              <Text>邀请好友</Text>
            </View>
          </View>
          <Image className={styles.header_bg} src={formatImgUrl('/mall/user_header_bg.png', '')} mode="aspectFit"></Image>
        </View>
        {userInfo?.adminUserInfo?.order_access_status == 3 && <View className={styles.price_count}>
          <View className={styles.price_count_list}>
            {priceList?.map((item, index) => {
              return <View key={index} className={styles.list_item} onClick={() => goLink(item.url)}>
                <Text className={styles.list_item_title}>{item.label}</Text>
                <View className={styles.list_item_number}><Text>¥</Text> {item.value}</View>
              </View>
            })}
            <Image className={styles.price_bg} src={formatImgUrl('/mall/price_bg.png', '')} mode="aspectFit"></Image>
          </View>
        </View>}

      </View>
      <View className={styles.order_count}>
        <View className={styles.order_count__title}>
          <Text className={styles.title_text}>我的订单</Text>
          <View className={styles.title__more} onClick={() => goLink('/pages/order/orderList/index')}>
            <Text>全部订单</Text>
            <View className={styles.title_more_icon}><IconFont name="icon-xiala" size={35} /></View>
          </View>
        </View>
        <View className={styles.order_count__list}>
          {orderList?.map((item, index) => {
            return <View key={index} className={styles.order_count__item} onClick={() => goLink(item.url)}>
              <IconFont name={item.icon as any} size={70} />
              <Text className={styles.item_img}>{item.label}</Text>
              {!!item.number && <Text className={styles.order_number}>{item.number}</Text>}
            </View>
          })}

        </View>
      </View>
      <View className={classnames(styles.nav_list, styles.earnings_list)}>
        <View className={styles.nav_list__title}>
          <Text className={styles.title_text}>下单返现活动</Text>
        </View>
        <View className={styles.earnings_con}>
          <View className={styles.earnings_price}>
            <Text className={styles.earnings_title}>活动返现收益（元）</Text>
            <View className={styles.earnings_total}><Text>¥</Text> <Text className={styles.all_earnings}>{formatPriceDiv(state.data.total_income).toLocaleString()}</Text> <View className={styles.today_earnings}>今日收益 {formatPriceDiv(state.data.today_income).toLocaleString()}</View></View>
          </View>
          <View className={styles.more} onClick={() => goLink('/pages/activityIncome/index')}><Text>查看收益</Text><IconFont name="icon-rukou" size={30} /></View>
        </View>
      </View>
      <View className={styles.nav_list}>
        <View className={styles.nav_list__title}>
          <Text className={styles.title_text}>我的服务</Text>
        </View>
        <View className={styles.list_con}>
          {menuList.map((item, index) => {
            return <View key={index} className={styles.list_item} onClick={item?.callback}>
              {item.icon_status != 'local' ? <IconFont name={item.icon as any} size={70} /> : <SvgIconfont name={item.icon as any} style={{ fontSize: '70rpx' }} />}
              <View className={styles.list_item_con}>
                <Text>{item.label}</Text>
                <View className={styles.title_more_kf}>
                  <Text>{item.text}</Text>
                  <View className={styles.title_more_icon}><IconFont name="icon-xiala" size={40} /></View>
                </View>
              </View>
            </View>
          })}
        </View>
      </View>
      <View className={styles.bottom_version}>
        {current_env !== 'production' && <View >{current_version}</View>}
        {current_env !== 'production' && <View >{BASE_URL}</View>}
      </View>
      <Customer show={customer_service_show} onClose={customerClose} />
    </View>
  )
}
