import {PageContainer, View, Image, Text} from "@tarojs/components";
import Taro from "@tarojs/taro";
import styles from './my.module.scss'
import Header from "./components/header/header";
import {FC, useState} from "react";
import Time from "@/pages/my/components/header/time";
import Service from "@/pages/my/components/header/service";
import {Profile} from "@/store";
import Img from "@/components/image/image";
import GreenNike from "@/static/img/greenNike.png"
import {curriculum, userApi} from "@/api";
import LearningRecord from "@/components/learningRecord/learningRecord";
import NavigationBar from "@/components/navigationBar/navigationBar";
import over from "@/static/img/over.png";
import incomplete from "@/static/img/incomplete.png";
import avatar from "@/static/img/avatar.png";

interface List {
  title: string
  time: string | number
  src: string,
  type?: number
}
function jump(token: string | null, type?: number) {
  if (!token) {
    Taro.navigateTo({url: '/pages/login/login'})
    return;
  }
  if (!type) return;
  Taro.navigateTo({url: "/pages/business/courType/courType?type=" + type})
}

const My: FC = () => {
  const globalData = Taro.getApp().globalData
  const {token, company, setCompany, user} = Profile.useContainer()
  const [companyShow, setCompanyShow] = useState(false)
  const [companyList, setCompanyList] = useState<Company[]>([])
  const [navbarOpacity, setNavbarOpacity] = useState('0')
  const navbarHeight = globalData.statusBarHeight + globalData.textBarHeight;
  const [auditMode, setAuditMode] = useState(true)

  Taro.useDidShow(() => {
    token && userApi.companyList().then(res => {
      setCompanyList(res as Company[])
    })
  })

  Taro.usePageScroll((e) => {
    const v = (Math.min(e.scrollTop / navbarHeight, 1)).toFixed(6)
    if (v != navbarOpacity) {
      setNavbarOpacity(v)
    }
  })

  const [list, setList] = useState<List[]>([
    {title: '已完成', time: '0', src: over, type: 3},
    {title: '未完成', time: '0', src: incomplete, type: 4},
  ])

  Taro.useDidShow(async () => {
    try {
      const res = await curriculum.course()
      setAuditMode(res.audit_mode)
      const oldList: List[] = JSON.parse(JSON.stringify(list))
      oldList[1].time = res.finished_count || 0
      oldList[2].time = res.not_finished_count || 0
      setList(oldList)
    } catch (e) {
    }
  })

  return (
    <View>
      <NavigationBar
        style={{opacity: navbarOpacity}}
        className={styles.navbar}
        backgroundColor={`rgba(255,255,255,${Number(navbarOpacity) * .9})`}
        cancelBack
        leftNode={
          <View className={styles.navigation}
                style={{transform: `translate(0,${Number(navbarOpacity) > .5 ? "0%" : '-350%'})`}}>
            <Img className="rounded-50" src={user?.avatar || avatar} mode='heightFix' width={50} height={50}
                 errorType='avatar'/>
            <Text className='pl-2'>{token ? user?.name : '请登录'}</Text>
          </View>
        }/>

      <View className={styles.bg}/>

      <View className={styles.content}>
        <View className='mb-4' style={{opacity: 1 - Number(navbarOpacity)}}>
          <Header companyList={companyList} showCompany={() => companyList.length >= 2 && setCompanyShow(true)}/>
        </View>

        {
          !auditMode && <>
            <Time/>
            <View className="bg-white rounded-20 mb-2 clip">
              <View className="flex p-2">
                {list.map((d) => (
                  <View className={styles.timeBox} style={{marginBottom: '0 !important'}} key={d.title}
                        onClick={() => jump(token, d.type)}>
                    <View className={styles.timeBoxFlex}
                          style={{backgroundColor: 'rgba(0,0,0,0.02)', borderRadius: '16rpx'}}>
                      <View>
                        <View className='mb-2 font-28 font-weight'>{d.title}</View>
                        <View className='text-muted font-26 mt-1'>{d.time}</View>
                      </View>
                      <Image src={d.src} mode='aspectFit' className={styles.timeImag}/>
                    </View>
                  </View>
                ))}
              </View>
              {
                <View className="p-2">
                  <LearningRecord style={{paddingTop: '0 !important'}} userId={user?.id}/>
                </View>
              }
            </View>
          </>
        }


        <Service/>

        <PageContainer
          overlayStyle={'background:rgba(0,0,0,0.3)'}
          position='bottom'
          round
          show={companyShow}
          onClickOverlay={() => setCompanyShow(false)}>
          <View className="px-3 py-5">
            <View className="font-32 pb-3" style={{
              display: 'flex',
              justifyContent: 'center',
              borderBottom: '2rpx solid #f5f8f7'
            }}>
              选择公司</View>
            {
              companyList.length >= 1 &&
              companyList.map((d, idx) =>
                <View className={`${styles.box} ${companyList.length - 1 === idx && styles.noBorder} `}
                      onClick={async () => {
                        if (company?.id === d.id) return;
                        Taro.showLoading({
                          title: '切换公司中',
                          mask: true,
                        })
                        const data = await userApi.companyReplace(d.id)
                        Taro.hideLoading()
                        !data && setCompany(d)
                        !data && Taro.showModal({
                          title: '友情提示',
                          content: '切换公司成功，需要重新进入',
                          showCancel: false,
                          success: function (res) {
                            res.confirm && Taro.reLaunch({url: '/pages/my/my'})
                          }
                        })
                        setCompanyShow(false)
                      }}>
                  <View className={styles.image}>
                    <Img width={68} height={68} src={d.logo}/>
                  </View>
                  <View className={styles.innerBox}>
                    <View className={styles.title}>{d.name}</View>
                    <Image src={company?.id === d.id ? GreenNike : ''} className={styles.icon}></Image>
                  </View>
                </View>
              )
            }
          </View>
        </PageContainer>
      </View>
    </View>

  )
}

export default My
