import { Text, View } from '@tarojs/components'
import Taro, { getCurrentPages, useDidShow, useUnload } 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 { ColorItem } 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 { formatHashTag } from '@/common/fotmat'
import { submitCutSampleOrderApi } from '@/api/cutSample'
import { addressListApi } from '@/api/addressManager'
import NavBar from '@/components/navBar'
import IconFont from '@/components/iconfont/iconfont'

export interface submitData {
  address_id: number
  cut_sample_order_product_color_list: { color_num: number; product_color_id: number }[]
  remark: string
  shipment_mode: number
}

export interface ParamItem {
  code: string
  id: number
  color_card_name: string
  texture_url: string
  lab: { l: number; a: number; b: number }
  rgb: { r: number; g: number; b: number }
  is_add: boolean
  count?: number
  component: string
  craft: string
  describe: string
  hexadecimal_code: string
  is_favorite: boolean
  kind_code: string
  kind_id: number
  kind_name: string
  name: string
  product_color_count: number
  product_screw_id: number
  weight_density: string
  width: string
  colors: ColorItem[]
}
export default () => {
  const submitData = useRef<submitData>({
    address_id: 0,
    cut_sample_order_product_color_list: [],
    remark: '',
    shipment_mode: 2,
  })

  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('cutSample') ? JSON.parse(Taro.getStorageSync('cutSample')) : []
    const info = Taro.getStorageSync('cutSampleOther') ? JSON.parse(Taro.getStorageSync('cutSampleOther')) : {}
    setList(() => list)
    computeCount(list)
    if (info.address) {
      setAddressInfo(info.address)
      submitData.current.address_id = info?.address?.id || 0
    }
    else {
      getAddressDefault()
    }
    setRemarkData(info.remark)
  })

  useUnload(() => {
    Taro.removeStorageSync('cutSample')
    Taro.removeStorageSync('cutSampleOther')
  })

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

  const onDelData = useCallback((val: ParamItem) => {
    return (id: number) => {
      const res = val.colors?.filter((citem) => {
        return citem.id != id
      })
      if (res.length <= 0 && list.length === 1) {
        return alert.none('不能删除最后一个剪样')
      }
      else {
        if (res.length > 0) {
          list?.map((item, index) => {
            if (item.id === val.id) {
              list[index] = { ...item, colors: [...res] }
            }
          })
          computeCount(list)
          setList(() => [...list])
        }
        else {
          const data = list?.filter(item => item.id != val.id)
          computeCount(data)
          setList(() => [...data])
        }
      }
    }
  }, [list])

  // 计算总数
  const [numText, setNumText] = useState('')
  const computeCount = (list) => {
    let p_count = 0
    let c_count = 0
    let all_count = 0
    list?.map((item) => {
      p_count += 1
      item.colors?.map((citem) => {
        c_count += 1
        all_count += citem.count
      })
    })
    console.log('list:::', list)
    setNumText(() => `当前共 ${p_count} 种面料, ${c_count} 种色号,共 ${all_count} 份`)
  }

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

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

  const { fetchData: submitFetchData } = submitCutSampleOrderApi()
  const onSubmitData = async() => {
    Taro.showModal({
      title: '确定提交订单？',
      async success(val) {
        if (val.confirm) {
          submitData.current.cut_sample_order_product_color_list = []
          list?.map((item) => {
            item.colors?.map((citem) => {
              submitData.current.cut_sample_order_product_color_list.push({
                color_num: citem.count || 0,
                product_color_id: citem.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/cutSampleListOrderDetail/index', { id: res.data.id }, 'redirectTo')
          }
        }
      },
    })
  }

  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) => {
      if (item.is_default) {
        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 || 0
    setAddressInfo(defaultInfo!)
  }
  const onClickBack = () => {
    Taro.showModal({
      content: '返回后页面数据将不回保留，确认返回？',
      confirmColor: '#4a8dff',
      success: ({ confirm }) => {
        if (confirm) {
          Taro.navigateBack({
            delta: 1,
          })
        }
      },
    })
  }

  return <View className={styles.main}>
    <NavBar hasLeft leftSlot={
      <View onClick={onClickBack}>
        <IconFont customClassName={styles.backIcon} name="icon-rukou" size={48} color="#191919"></IconFont>
      </View>
    } title="领取剪样"
    ></NavBar>
    <View className={styles.address_info}><Address onSelect={getAddress} defaultValue={addressInfo} /></View>
    <View className={styles.add_card_btn} onClick={onAddCard}>添加剪样</View>
    {list?.map((item, index) => <View key={item.id} className={styles.card_con}>
      <View className={styles.card_header}>{formatHashTag(item.code, item.name)}</View>
      <View className={styles.card_list}>
        {item.colors?.map(citem =>
          <ProductCard key={citem.id} value={citem} onDelData={onDelData(item)} onChangeNum={onChangeNum} />,
        )}
        {(list?.length - 1 === index) && <View className={styles.express_btn}>快递到付</View>}
      </View>
    </View>)}
    <View className={styles.remark}><Remark onSave={onRemark} defaultValue={remarkData} /></View>
    <View className={styles.order_btn}>
      <View className={styles.btn_con} onClick={onSubmitData}>
        <Text>{numText}</Text>
        <View className={styles.btn}>提交订单</View>
      </View>
    </View>
  </View>
}
