import { ScrollView, Text, View } from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import React, { useCallback, useEffect, useMemo, useRef, useState, useTransition } from 'react'
import ProductBlock from '../productBlock'
import BottomBtn from '../bottomBtn'
import Operation from '../operation'
import type { listType } from '../search'
import Search from '../search'
import NoShop from '../noShop'
import RecommendOpen from '../RecommendOpen'
import styles from './index.module.scss'
import { DelShoppingCartApi, GetProductColorApi, GetShoppingCartV2Api } from '@/api/shopCart'
import type { ProductType } from '@/context/ContextShop'
import { useCurrenShop } from '@/context/ContextShop'
import type { saleModeType } from '@/common/enum'
import LoadingCard from '@/components/loadingCard'
import { alert, goLink } from '@/common/common'
import InfiniteScroll from '@/components/infiniteScroll'
import { dataLoadingStatus, throttle } from '@/common/util'
import { ApplyOrderAccessApi, GetAdminUserInfoApi } from '@/api/user'
import { setParam } from '@/common/system'
import type { SalesManDialogRef } from '@/components/bindSalesManDialog'
import BindSalesManDialog from '@/components/bindSalesManDialog'
import { useSelector } from '@/reducers/hooks'
import OrganizationNameModal from '@/components/organizationNameModal'
import useLogin from '@/use/useLogin'
import { companyDetailApi, companyUpdateApi } from '@/api/company'

interface FilterType {
  abstract_sort_key: -1|1|2|-2
  sale_mode: saleModeType
}
export default () => {
  const { state, dispatch } = useCurrenShop()
  const [filter, setFilter] = useState<FilterType>({
    abstract_sort_key: -1,
    sale_mode: 0,
  })

  const userInfo = useSelector(state => state.userInfo)

  const [isPending, startTransition] = useTransition()

  const { fetchData: getShoppingCartFetchData, state: shopState } = GetShoppingCartV2Api()
  const getShoppingCart = async() => {
    const res = await getShoppingCartFetchData(filter)
    if (res.success) {
      startTransition(() => {
        dispatch({ type: 'setInitData', data: { list: JSON.parse(JSON.stringify(res?.data?.product_list)), sale_mode: filter.sale_mode } })
      })
    }
  }

  const [modeNumber, setModeNumber] = useState({
    bulk_number: 0,
    length_length: 0,
    weight_number: 0,
  })
  const { fetchData: productSkuFetchData } = GetProductColorApi()
  const getProductColorNum = async() => {
    const res = await productSkuFetchData()
    if (res.success) {
      setModeNumber(res.data)
    }
  }

  const initStatus = useRef(false)
  useDidShow(() => {
    getProductColorNum()
    initStatus.current && getShoppingCart()
    initStatus.current = true
  })

  const onSelect = useCallback((status) => {
    state.list?.map((item) => {
      item.checked = status
      item.color_list?.map((citem) => {
        citem.checked = status
      })
    })
    dispatch({ type: 'updateProduct', data: { list: state.list } })
  }, [state.list])

  useEffect(() => {
    getShoppingCart()
  }, [filter])

  const onSortChange = useCallback((val) => {
    setFilter(e => ({ ...e, abstract_sort_key: val.value }))
  }, [])

  const getSelect = useCallback((val: listType) => {
    setFilter(e => ({ ...e, sale_mode: val.value }))
  }, [])

  const logadingStatus = useMemo(() => {
    return shopState.loading || isPending
  }, [shopState.loading, isPending])

  const [settingStatus, setSettingStatus] = useState(false)
  const onChangeSetting = useCallback((val) => {
    setSettingStatus(() => val)
  }, [])

  const { fetchData: delShopFetchData } = DelShoppingCartApi()
  const onBtnClick = (model) => {
    if (model) {
      delShop()
    }
    else {
      orderDetail()
    }
  }

  const bindSalesManDialogRef = useRef<SalesManDialogRef | null>(null)
  const [showModal, setShowModal] = useState(false)

  // 去结算
  const { fetchData: FetchData } = GetAdminUserInfoApi()
  const { fetchData: applyOrderAccessFetchData } = ApplyOrderAccessApi()
  const orderDetail = throttle(async() => {
    const res = await FetchData()
    if (res.data.order_access_status !== 3) {
      if (res.data.order_access_status == 1) { applyOrderAccessFetchData() }
      bindSalesManDialogRef.current?.handleChange(true)
      return
    }
    // 检测是否修改过组织昵称
    if (userInfo.adminUserInfo.first_change_name) {
      setShowModal(true)
      return
    }
    const SelectIds = getSelectIds()
    if (SelectIds.length == 0) {
      alert.error('请选择面料')
    }
    else {
      const ids = SelectIds.join('-')
      setParam({ ids, sale_mode: state.sale_mode }) // 临时存储
      goLink('/pages/order/comfirm')
    }
  }, 500)

  // 删除商品
  const delShop = () => {
    Taro.showModal({
      content: '删除所选商品？',
      async success(res) {
        if (res.confirm) {
          const ids = getSelectIds()
          console.log('ids:::', ids)
          const res = await delShopFetchData({ id: ids })
          if (res.success) {
            getShoppingCart()
            getProductColorNum()
          }
        }
        else if (res.cancel) {
          console.log('用户点击取消')
        }
      },
    })
  }

  // 弹出修改组织昵称弹窗
  const handleBindSalesManSuccess = () => {
    // 检测是否修改过组织昵称
    if (userInfo.adminUserInfo.first_change_name) {
      setShowModal(true)
    }
  }

  // 获取面料选中的id
  const getSelectIds = () => {
    const ids: number[] = []
    state.list.map((item) => {
      item.color_list.map((citem) => {
        citem.checked && ids.push(citem.id)
      })
    })
    return ids
  }

  const handleClose = useCallback(() => {
    setShowModal(false)
  }, [])
  const handleShowChange = useCallback((val: boolean) => {
    setShowModal(val)
  }, [])

  const { getAdminUserInfo } = useLogin()
  const { fetchData: saveFetch } = companyUpdateApi()
  const { fetchData: getCompanyFetch } = companyDetailApi()
  const handleOrganizationNameModalConfirm = useCallback(async(text: string) => {
    const params = await getCompanyFetch()
    const result = await saveFetch({
      ...params.data,
      company_name: text,
    })
    if (result.success) {
      getAdminUserInfo()
      handleClose()
      alert.success('保存成功')
    }
    else {
      alert.none(result.msg)
    }
  }, [])

  const onRecommendClose = useCallback(() => {
    dispatch({ type: 'setRecommendId', data: { list: state.list, recommendId: 0 } })
  }, [])

  const onSubmitSuccess = useCallback(() => {
    getProductColorNum()
    getShoppingCart()
  }, [])

  // 当减到0时删除商品
  useEffect(() => {
    if (state.delCommendId) {
      getShoppingCart()
      getProductColorNum()
    }
  }, [state.delCommendId])

  return <View className={styles.shop_main}>
    <View className={styles.shop_header}>
      <Operation onSelect={onSortChange} onChange={onChangeSetting} />
      <View className={styles.search_title}>
        <Search numberObj={modeNumber} defaultIndex={filter.sale_mode} onSelect={getSelect} />
      </View>
    </View>
    <View className={styles.shop_con}>
      {logadingStatus && <View className={styles.loading_card}><LoadingCard /></View>}
      {(!logadingStatus && state.list && state.list.length > 0) && <ScrollView scrollY className={styles.scroll_view}>
        {state.list?.map(item => (<ProductBlock productItem={item} key={item.product_id} />))}
        <View style={{ height: '100rpx' }}></View>
      </ScrollView>}
      {(!logadingStatus && !state.list) && <NoShop />}
    </View>

    <BottomBtn onSelect={onSelect} model={settingStatus} onBtnClick={onBtnClick} />
    <View>
      <BindSalesManDialog ref={bindSalesManDialogRef} onSuccess={handleBindSalesManSuccess} />
    </View>
    <View>
      <OrganizationNameModal showModal={showModal} onClose={handleClose} onShowModalChange={handleShowChange} onConfirm={handleOrganizationNameModalConfirm} />
    </View>
    <View>
      <RecommendOpen shopId={state.recommendId || 0} onShow={!!state.recommendId} onClose={onRecommendClose} submitSuccess={onSubmitSuccess} />
    </View>
    <View className="common_safe_area_y"></View>
  </View>
}
