import {PageContainer, View, Image, ScrollView, 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
}

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 pageHeight = globalData.windowHeight - globalData.textBarHeight - globalData.statusBarHeight


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

  function onScroll(e) {
    const v = (Math.min(e.detail.scrollTop / navbarHeight, 1) * 0.9).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()
      const oldList: List[] = JSON.parse(JSON.stringify(list))
      oldList[1].time = res.finished_count
      oldList[2].time = res.not_finished_count
      setList(oldList)
    } catch (e) {
    }
  })


  return (
    <View className={styles.page}>
      <NavigationBar
        backgroundColor={`rgba(255,255,255,${navbarOpacity})`}
        cancelBack>
        {
          Number(navbarOpacity) > .5 && <View className='flex align-center'>
            <Img src={user?.avatar || avatar} mode='heightFix' width={60} height={60}/>
            <Text className='pl-1'>{user?.name}</Text>
          </View>
        }
      </NavigationBar>

      <ScrollView scrollY enhanced showScrollbar={false} style={{height: pageHeight}} onScroll={onScroll}>
        <View className={styles.content}>
          <View style={{opacity: 1 - Number(navbarOpacity)}}>
            <Header companyList={companyList} showCompany={() => companyList.length >= 2 && setCompanyShow(true)}/>
          </View>
          <Time/>

          {
            token && user && <View>
              <LearningRecord userId={user.id}/>
              <Service/>
            </View>
          }
          <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>
      </ScrollView>

    </View>
  )
}

export default My
