import {PageContainer, View, Image} 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 LoginView from "@/components/loginView";
import {Profile} from "@/store";
import Img from "@/components/image/image";
import GreenNike from "@/static/img/greenNike.png"
import {userApi} from "@/api";

const My: FC = () => {
  const globalData = Taro.getApp().globalData
  const {token, company, setCompany} = Profile.useContainer()
  const [companyShow, setCompanyShow] = useState(false)
  const [companyList, setCompanyList] = useState<Company[]>([])
  Taro.useDidShow(() => {
    try {
      userApi.companyList().then(res => {
        setCompanyList(res as Company[])
      })
    } catch (e) {
    }
  })

  return (
    <View className={styles.content} style={`paddingTop:${globalData.statusBarHeight}px`}>
      { !token ?
        <LoginView></LoginView>
        :
        <>
          <Header showCompany={()=>{setCompanyShow(true)}}/>
          <Time/>
          <Service/>
        </>

      }

      <PageContainer overlayStyle={'background:rgba(0,0,0,0.3)'} position={'bottom'} round={true} 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 =>
              <View className={styles.box} onClick={async () => {
                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) {
                    if (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>
  )
}

export default My
