import { Text, View } from '@tarojs/components'
import Taro, { getCurrentPages, useDidShow } from '@tarojs/taro'
import { useCallback, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import type { AddressItem } from './components/address'
import Address from './components/address'
import type { ParamItem } from './components/productCard'
import ProductCard from './components/productCard'
import Remark from './components/remark'
import { alert, goLink } from '@/common/common'
import { SubmitColorCardApi } from '@/api/colorCard'
import { getFilterData } from '@/common/util'
import { UseSubscriptionMessage } from '@/use/useCommon'
import { SUBSCRIPTION_MESSAGE_SCENE } from '@/common/enum'
import { addressListApi } from '@/api/addressManager'

export interface submitData {
  address_id: number
  color_card_infos: { count: number; id: number }[]
  remark: string
}
export default () => {
  const submitData = useRef<submitData>({
    address_id: 0,
    color_card_infos: [],
    remark: '',
  })

  const [addressInfo, setAddressInfo] = useState<AddressItem>()
  const getAddress = (e) => {
    submitData.current.address_id = e.id
    setAddressInfo(() => e)
  }
  const [list, setList] = useState<ParamItem[]>([])
  useDidShow(() => {
    const list = Taro.getStorageSync('colorCard') ? JSON.parse(Taro.getStorageSync('colorCard')) : []
    const info = Taro.getStorageSync('colorCardOther') ? JSON.parse(Taro.getStorageSync('colorCardOther')) : {}
    setList(() => list)
    computeCount(list)
    if (info.address) {
      setAddressInfo(info.address)
      submitData.current.address_id = info?.address?.id || 0
    }
    else {
      getAddressDefault()
    }
    setRemarkData(info.remark)

    Taro.removeStorageSync('colorCard')
    Taro.removeStorageSync('colorCardOther')
  })

  const onAddCard = () => {
    Taro.setStorageSync('colorCard', JSON.stringify(list))
    Taro.setStorageSync('colorCardOther', JSON.stringify({ address: addressInfo || {}, remark: submitData.current.remark }))
    Taro.navigateTo({
      url: '/pages/colorCardList/index',
    })
  }

  const onDelData = useCallback((id) => {
    if (list.length === 1) { return alert.none('不能删除最后一个色卡') }
    const res = list?.filter((item) => {
      return item.id != id
    })
    computeCount(res)
    setList(() => res)
  }, [list])

  // 计算总数
  const [numText, setNumText] = useState('')
  const computeCount = (list) => {
    let res = 0
    list.map(item => res += item.count)
    setNumText(() => `当前共 ${list.length} 种色卡, 共 ${res} 本`)
  }

  const onChangeNum = useCallback((val: { id: number; count: number }) => {
    list?.map((item) => {
      if (item.id == val.id) {
        item.count = val.count
      }
    })
    setList(() => list)
    computeCount(list)
  }, [list])

  // 订阅消息
  const { ColorCard } = SUBSCRIPTION_MESSAGE_SCENE
  const { openSubscriptionMessage } = UseSubscriptionMessage()

  const { fetchData: submitFetchData } = SubmitColorCardApi()
  const onSubmitData = async() => {
    submitData.current.color_card_infos = []
    list?.map((item) => {
      submitData.current.color_card_infos.push({
        count: item.count || 0,
        id: item.id,
      })
    })
    if (!submitData.current.address_id) { return alert.none('请选择收货地址') }
    await openSubscriptionMessage({ scenes: ColorCard.value })
    const res = await submitFetchData(getFilterData(submitData.current))
    if (res.success) {
      alert.success('提交成功')
      goLink('/pages/colorCardOrderDetail/index', { id: res.data.id })
    }
  }

  const [remarkData, setRemarkData] = useState('')
  const onRemark = (e) => {
    submitData.current.remark = e
    setRemarkData(e)
  }

  // 获取默认地址
  const { fetchData: addressListFetchData, state } = addressListApi()
  const getAddressDefault = async() => {
    const res = await addressListFetchData()
    let defaultInfo: AddressItem|null = null
    res?.data.list?.map((item) => {
      defaultInfo = {
        id: item.id,
        address_title: item.province_name + item.city_name + item.district_name + item.address_detail,
        address_name: item.name,
        address_phone: item.phone,
      }
    })
    submitData.current.address_id = defaultInfo!.id
    setAddressInfo(defaultInfo!)
  }

  return <View className={styles.main}>
    <Address onSelect={getAddress} defaultValue={addressInfo} />
    <View className={styles.add_card_btn} onClick={onAddCard}>添加色卡</View>
    <View className={styles.card_con}>
      <View className={styles.card_header}>色卡信息</View>
      <View className={styles.card_list}>
        {list?.map(item => <ProductCard key={item.id} value={item} onDelData={onDelData} onChangeNum={onChangeNum} />)}
        <View className={styles.express_btn}>快递到付</View>
      </View>
    </View>
    <Remark onSave={onRemark} defaultValue={remarkData} />
    <View className={styles.order_btn}>
      <View className={styles.btn_con} onClick={onSubmitData}>
        <Text>{numText}</Text>
        <View className={styles.btn}>提交订单</View>
      </View>
    </View>
  </View>
}
