
import { Button, CustomWrapper, Image, RichText, Text, View } from '@tarojs/components'
import Taro, { useDidShow, usePullDownRefresh, useRouter, useShareAppMessage } from '@tarojs/taro';
import classnames from "classnames";
import DesSwiper from './components/swiper';
import OrderCount from './components/orderCount';
import ShopCart from '@/components/shopCart';
import Preview,{colorItem} from './components/preview';
import styles  from './index.module.scss'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {formatHashTag, formatImgUrl} from '@/common/fotmat'
import {GetProductDetailApi} from '@/api/material'
import useLogin from '@/use/useLogin';
import { AnalysisShortCodeApi, BindShortCodeApi, GetShortCodeApi } from '@/api/share';
import { SHARE_SCENE } from '@/common/enum';
import useUserInfo from '@/use/useUserInfo';
import LabAndImg from '@/components/LabAndImg';
import { alert } from '@/common/common';
import AddCollection from '@/components/addCollection';
import { AddFavoriteApi } from '@/api/favorite';

type item = {title:string, img:string, url:string, id:number}

type Params = {
  list?: item[]
  swiperOnClick?: (val: item) => void,
  style?: Object
}
export default (props:Params) => {
  const {checkLogin, getPhoneNumber, userInfo} = useLogin()

  //获取参数(有两种参数：1.商品id, 2.页面分享)
  const router = useRouter()
  const [params, setParams] = useState({id: '', share: null})

  //判断是否是分享过来的参数
  const  judgeParam = async () => {
    if(router.params.id) {
      setParams({...params, id:router.params.id})
    }else if(router.params.share) {
      analysisShortCode()
    }
  }

  //解析短码参数
  const {fetchData: fetchDataAnalysisShortCode} = AnalysisShortCodeApi()
  const analysisShortCode = async () => {
    let res = await fetchDataAnalysisShortCode({md5_key: router.params.share})
    setParams({id: res.data.product_id, share: res.data})
  }

  useDidShow(() => {
    checkLogin()
    judgeParam()
    setShowCart(false)
  })

  useEffect(() => {
    if(params.id) {
      getProductDetail()
    }
  }, [params])
 
  //获取数据
  const [productInfo, setProductInfo] = useState<any>({})
  const {fetchData} = GetProductDetailApi()
  const getProductDetail = async () => {
    let {data} = await fetchData({id: params.id})
    setProductInfo(data)
    Taro.stopPullDownRefresh()
  }

  useEffect(() => {
    if(productInfo.code)  getShortCode()
  }, [productInfo])


  //面料名称
  const productName = useMemo(() => {
    return formatHashTag(productInfo.code, productInfo.name)
  },[productInfo])

  const [showCart, setShowCart] = useState(false)
  const [showOrderCount, setShowOrderCount] = useState(false)
  // const html = `
  //   <img style="width:100%" src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic24.nipic.com%2F20121021%2F10910884_100200815001_2.jpg&refer=http%3A%2F%2Fpic24.nipic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1652257920&t=9353dda34f18ae2fe6803f3da35954bb">
  // `
  const html = ``

  //弹窗提示
  const [colorInfo, setColorInfo] = useState<colorItem>()
  const [showPreview, setShowPreview] = useState(false)
  const getColorItem = (item) => {
    setColorInfo({
      title: item.code,
      img: item.texture_url,
    })
    setShowPreview(true)
  }

  //收藏功能
  const [collectStatus, setCollectStatus] = useState(false)
  const changeCollect = () => {
    setCollectStatus(!collectStatus)
    setCollectionShow(true)
  }

  const {setSortCode, userInfo : userObj } = useUserInfo()
  //详情页获取分享短码
  const {ShareDetail} = SHARE_SCENE
  const {fetchData: fetchDataShortCode} = GetShortCodeApi()
  const getShortCode = async () => {
    const {data: resDetail} = await fetchDataShortCode({"share_user_id": userObj.adminUserInfo.user_id, type:ShareDetail.value, product_id: parseInt(params.id)})
    setSortCode({... userObj.sort_code, shareShortDetail: {title: productName as string, code: resDetail.md5_key, img:''}})
  }

  //授权手机号和下单
  const placeOrder = async (status = 'to_phone',e:any = {}) => {
    if(!productInfo.id) return false
    if(status == 'to_phone') {
      if(!e.detail.code) return alert.error('请授权手机号')
      try {
        await getPhoneNumber(e.detail.code)
      } catch(msg) {
        Taro.showToast({
          icon:"none",
          title: msg
        })
        return false
      }
    } 
    setShowOrderCount(true)
  }

  //加入收藏夹
  const [collectionShow, setCollectionShow] = useState(false)
  const {fetchData: addFavoritefetchData} = AddFavoriteApi()
  const onAdd =  useCallback(async (val) => {
    let res = await addFavoritefetchData({favorite_id: val.id, product_id: Number(params.id)})
    if(res.success) {
      alert.success('添加成功')
    } else {
      alert.none(res.msg)
    }
    setCollectionShow(false)
  }, [params])

  
  //页面下拉刷新
  usePullDownRefresh(() => {
    getProductDetail()
  })
  

  return (
    <View className={styles.main}>
      <DesSwiper list={productInfo.texture_url||[]}/>
      <View className={styles.product_header}>
        <View className={styles.title}>
          <View className={styles.name}>{productName}</View>
          <View className={styles.des}>{productInfo.describe}</View>
        </View>
        <View className={styles.share}>
          <View className={classnames('iconfont icon-fenxiang', styles.miconfont)}></View>
          <View className={styles.text}>分享</View>
          <Button open-type="share" className={styles.shareBtn}></Button>
        </View>
        <View className={styles.collect}>
          <View className={classnames('iconfont icon-shoucang', styles.miconfont, collectStatus&&styles.collected)} onClick={() => changeCollect()}></View>
          <View className={styles.text}>收藏</View>
        </View>
      </View>
      <View className={styles.des_data}>
        <View className={styles.title}>详情参数</View>
        <View className={styles.con}>
          <View className={styles.des_text}>编号：<Text>{productInfo.code}</Text></View>
          <View className={styles.des_text}>幅宽：<Text>{productInfo.width}</Text></View>
          <View className={styles.des_text}>克重：<Text>{productInfo.weight_density}</Text></View>
          <View className={styles.des_text}>成分：<Text>{productInfo.component}</Text></View>
        </View>
      </View>
      <View className={styles.product_color}>
        <View className={styles.title}>色号 ({productInfo?.product_color_list?.length})</View>
          <View className={styles.list}>
              {productInfo?.product_color_list?.map(item => {
                return <View className={styles.item} onClick={() => getColorItem(item)}>
                  <View className={styles.item_color}>
                    <LabAndImg value={{lab:item.lab,rgb:item.rgb,texture_url:item.texture_url}}/>
                  </View>
                  <View className={styles.item_name}>{item.code}</View>
                </View>
              })}
          </View>
      </View>
      <View className={styles.product_detail}>
          <RichText nodes={html}></RichText>
      </View>
      <View className={styles.product_buy}>
        <View className={styles.buy_cart}  onClick={() => setShowCart(true)}>
          <View className={classnames('iconfont icon-gouwuche', styles.miconfont)}></View>
          <View className={styles.text}>购物车</View>
        </View>
        {
            (!userInfo.adminUserInfo?.is_authorize_phone)&&<View className={styles.buy_btn} >
              <Button className={styles.phoneBtn} open-type="getPhoneNumber" onGetPhoneNumber={(e) => placeOrder('to_phone',e)}></Button>
              选购商品
            </View>
            || <View className={styles.buy_btn} onClick={() => placeOrder('to_order')}>选购商品</View>
        }
      </View>
      <CustomWrapper>
        <OrderCount show={showOrderCount} onClose={() => setShowOrderCount(false)} title={productName} productId={productInfo.id}/>
      </CustomWrapper>
      <ShopCart show={showCart}  onClose={() => setShowCart(false)}/>
      <Preview value={colorInfo} show={showPreview} onClose={() => setShowPreview(false)}/>
      <AddCollection show={collectionShow} onAdd={onAdd}/>
      <View className='common_safe_area_y'></View>
    </View>
  )
}
