import { Text, View } from '@tarojs/components'
import Taro, { useDidShow, useUnload } from '@tarojs/taro'
import { useCallback, useEffect, useState } from 'react'
import styles from './index.module.scss'
import LayoutBlock from '@/components/layoutBlock'
import NormalButton from '@/components/normalButton'
import Divider from '@/components/divider'
import IconFont from '@/components/iconfont/iconfont'
import LabAndImg from '@/components/LabAndImg'
import Counter from '@/components/counter'
import Tag from '@/components/tag'
import { alert, goLink } from '@/common/common'
import { ClientListApi } from '@/api/order'
import AddressDetailBox from '@/pages/orderDetails/components/addressDetailBox'
import Popup from '@/components/popup'
import Remark from '@/pages/orderDetails/components/remark'
import { formatRemoveHashTag } from '@/common/format'
import { SubmitColorCardOrder } from '@/api/colorCard'
import MoveBtn from '@/components/moveBtn'

const AddColorCard = () => {
  // 获取选择的客户
  const pages = Taro.getCurrentPages()
  const currPage = pages[pages.length - 1] // 获取当前页面
  const [addressInfo, setAddressInfo] = useState<any>({})

  // 获取客户
  const [clientList, setClientList] = useState<any[]>([])
  const { fetchData: fetchClientData } = ClientListApi()

  const [order, setOrder] = useState<any[]>([])

  useDidShow(() => {
    const colorCardCache = Taro.getStorageSync('colorCardCache')
    if (colorCardCache) {
      console.log('colorCardCache', JSON.parse(colorCardCache))
      setOrder(JSON.parse(colorCardCache))
    }
  })

  const [clientInfo, setClientInfo] = useState({
    clientId: -1,
    clientName: '',
    clientPhone: '',
  })

  const getClient = async() => {
    const res = await fetchClientData({
      page: 1, size: 10,
    })
    if (!res.success) {
      return alert.error(res.msg)
    }
    currPage.data.clientId = res.data.list.length > 0 ? res.data.list[0]?.id : -1
    currPage.data.clientName = res.data.list.length > 0 ? res.data.list[0]?.name : ''
    currPage.data.clientPhone = res.data.list.length > 0 ? res.data.list[0]?.phone : ''
    const {
      clientId,
      clientName,
      clientPhone,
    } = currPage.data
    setClientInfo({
      clientId,
      clientName,
      clientPhone,
    })
    setClientList([...res.data.list])
  }

  useEffect(() => {
    getClient()
  }, [])

  useUnload(() => {
    Taro.removeStorageSync('colorCardCache')
  })

  // 选择客户
  const handleSelectCustomer = () => {
    goLink(`/pages/customerPage/index?clientId=${clientInfo?.clientId}`)
  }
  // 添加色卡
  const handleAddColorCard = () => {
    Taro.setStorageSync('colorCardCache', JSON.stringify(order))

    goLink('/pages/getColorCard/colorCardList/index', { isGoBack: true })
  }

  const { fetchData } = SubmitColorCardOrder()
  // 提交订单
  const handleSubmitOrder = async() => {
    if (!addressInfo.address_id) {
      Taro.showToast({
        title: '请选择地址',
        icon: 'none',
        duration: 2000,
      })
      return
    }
    if (!clientInfo.clientId) {
      Taro.showToast({
        title: '请选择客户',
        icon: 'none',
        duration: 2000,
      })
      return
    }
    // 请求数据
    const res = await fetchData({
      address_id: addressInfo.address_id,
      color_card_infos: order.map(item => ({ id: item.id, count: item.count || 1 })),
      purchaser_id: clientInfo.clientId,
      remark,
    })
    if (res.success) {
      Taro.showToast({
        title: '提交成功',
        icon: 'success',
        duration: 2000,
      })
      Taro.removeStorageSync('colorCardCache')
      setTimeout(() => {
        goLink('/pages/getColorCard/colorCardDetail/index', { id: res.data.id }, 'redirectTo')
      }, 2000)
    }
  }

  const labAndImgObj = useCallback((item) => {
    return { lab: item?.lab, rgb: item?.rgb, texture_url: item?.texture_url }
  }, [])

  const getInputValue = () => {

  }

  const deleteColorCard = (id) => {
    setOrder((prev) => {
      return prev.filter(item => item.id !== id)
    })
    Taro.setStorageSync('colorCardCache', JSON.stringify(order.filter(item => item.id !== id)))
  }

  const handleCountChange = (value: number, id: number) => {
    console.log('value', value)
    if (order.length === 1 && value === 0) {
      Taro.showToast({
        title: '最后一个色卡不能删除',
        icon: 'none',
        duration: 2000,
      })
      return
    }
    if (value === 0) {
      Taro.showModal({
        content: '确认删除所选色卡？',
        confirmText: '删除',
        confirmColor: '#337fff',
        success(res) {
          if (res.confirm) {
            deleteColorCard(id)
          }
        },
      })
      return
    }
    setOrder((prev) => {
      const newOlder = prev.map((item) => {
        if (item.id === id) {
          item.count = value
        }
        return item
      })
      Taro.setStorageSync('colorCardCache', JSON.stringify(newOlder))
      return newOlder
    })
  }

  const handSelect = () => {
    goLink(`/pages/addressManager/index?purchaser_id=${clientInfo.clientId}`)
  }
  // 接受选择客户页面传递过来的数据
  useDidShow(() => {
    // 判断是否有跳转选择客户
    if (currPage.data?.clientId && currPage.data?.clientId !== '') {
      setClientInfo({
        clientId: currPage.data?.clientId,
        clientName: currPage.data?.clientName,
        clientPhone: currPage.data?.clientPhone,
      })
    }
    // 默认客户
    if (currPage.data?.clientId == null) {
      setClientInfo(() => {
        return {
          clientId: clientList.length > 0 ? clientList[0]?.id : -1,
          clientName: clientList.length > 0 ? clientList[0]?.name : '',
          clientPhone: clientList.length > 0 ? clientList[0]?.phone : '',
        }
      })
    }
  })

  const initAddressInfo = () => {
    setAddressInfo(val => ({
      ...val,
      province_name: '',
      address_id: '',
      city_name: '',
      address_detail: '',
      district_name: '',
      target_user_name: '',
      purchaser_phone: '',
    }))
  }

  useDidShow(() => {
    // 获取选择的地址
    console.log('addressObj', currPage.data?.addressObj, clientInfo.clientId, currPage.data?.clientId)
    if (!currPage.data?.addressObj) { return initAddressInfo() }
    const {
      purchaser_id,
      province_name,
      id,
      city_name,
      address_detail,
      district_name,
      name,
      phone,
    } = currPage.data?.addressObj
    if (purchaser_id === currPage.data?.clientId) {
      setAddressInfo(val => ({
        ...val,
        province_name: province_name || '',
        address_id: id || '',
        city_name: city_name || '',
        address_detail: address_detail || '',
        district_name: district_name || '',
        target_user_name: name || '',
        purchaser_phone: phone || '',
      }))
    }
    else {
      initAddressInfo()
    }
    const selectId = id
    const obj = currPage?.data?.ids?.filter((item) => { return item == selectId })
    console.log('ids', currPage?.data?.ids)
    if (currPage?.data?.ids && obj.length === 0) {
      initAddressInfo()
    }
  })

  // 备注操作
  const [showDesc, setShowDesc] = useState(false)
  const [remark, setRemark] = useState('')
  const handleShowDesc = () => {
    setShowDesc(true)
  }

  const getRemark = useCallback((value: string) => {
    setShowDesc(false)
    console.log('remark', value)
    setRemark(value)
  }, [])

  return <MoveBtn showList={['businessManager']}>
    <View className={styles.main}>
      <View className={styles.context}>
        {/* 客户信息 */}
        <LayoutBlock circle onClick={handleSelectCustomer} customStyle={{ marginTop: '12px' }} customClassName={styles.layoutBlock}>
          <View className={styles.customerTop}>
            <View>客户信息</View>
          </View>
          <Divider direction="horizontal" customStyles={{ margin: '12px 0' }}></Divider>
          <View className={styles.customerBottom}>
            {
              clientInfo.clientId !== -1
                ? (<>
                  <Text>
                    {clientInfo.clientName}
                  </Text>
                  <Text>
                    {clientInfo.clientPhone}
                  </Text>
                </>
                )
                : <View>选择领取客户</View>
            }
            <IconFont name="icon-chakanquanbukehu" color="#444444" size={32}></IconFont>
          </View>
        </LayoutBlock>
        {
          clientInfo.clientId !== -1 && <AddressDetailBox
            showBtn={false}
            showWhatFont="物流"
            navSelect={handSelect}
            obj={addressInfo}
            receivingStatus={2}
            icon={<IconFont name="icon-dizhi1" size={60}></IconFont>}
          ></AddressDetailBox>
        }

        <NormalButton customClassName={styles.addButton} circle onClick={handleAddColorCard} plain size="normal" type="primary">添加色卡</NormalButton>
        {/* 色卡信息 */}
        <LayoutBlock customStyle={{ marginTop: '12px' }} circle customClassName={styles.layoutBlock}>
          <View className={styles.colorCardTop}>色卡信息</View>
          <Divider direction="horizontal" customStyles={{ margin: '12px 0' }}></Divider>
          {
            order.map((item) => {
              return (
                <View className={styles.colorCardBottom} key={item.id}>
                  <View style={{ minWidth: '24%' }}>
                    <View className={styles.leftCont}>
                      <LabAndImg value={labAndImgObj(item)} />
                    </View>
                  </View>
                  <View className={styles.rightCont}>
                    <View className={styles.rightCont__top}>
                      {item.color_card_name}
                    </View>
                    <View className={styles.rightCont__bottom}>
                      <View className={styles.rightCont__left}>
                        {
                          item.affiliation_product.map((product_color, index) => {
                            return <Tag customStyle={{ marginRight: '5px', marginBottom: '2px', padding: '5px', background: '#e3ecff', color: '#558cff', borderColor: '#e3ecff' }} key={index} size="small" circle>{formatRemoveHashTag(product_color.code)}</Tag>
                          })
                        }
                      </View>
                      <View className={styles.rightCont__right}>
                        <Counter
                          onBlue={getInputValue}
                          defaultNum={item?.count || 1}
                          onChange={e => handleCountChange(e, item.id)}
                          onClickBtn={getInputValue}
                          unit="本"
                          minNum={0}
                          maxNum={999}
                        />
                      </View>
                    </View>
                    <Divider direction="horizontal" customStyles={{ margin: '12px 0 0 ' }}></Divider>
                  </View>
                </View>
              )
            })
          }
          <View className={styles.paymentMethod}>快递到付</View>
        </LayoutBlock>
        {/* 备注信息 */}
        <LayoutBlock circle customClassName={styles.layoutBlock} onClick={handleShowDesc}>
          <View className={styles.remarkTop}>
            <View className={styles.remarkTitle}>备注信息</View>
            <View className={styles.remarkTag}>
              <Text>填写/修改备注</Text>
              <IconFont name="icon-chakanquanbukehu" color="#444444" size={32}></IconFont>
            </View>
          </View>
          <Divider direction="horizontal" customStyles={{ margin: '12px 0' }}></Divider>
          <View className={styles.remarkBottom}>
            <View className={styles.remarkContent}>{ remark || '尚未备注信息' }</View>
          </View>
        </LayoutBlock>

      </View>
      <View className={styles.bottomBar}>
        <View className={styles.bottomTotal}>
        当前共 {order.length} 种色卡,共 {order.reduce((total, curr) => total + (curr.count || 1), 0)} 本
        </View>
        <NormalButton
          customClassName={styles.bottomBar__button}
          type="primary"
          round
          onClick={handleSubmitOrder}
        >
        提交订单
        </NormalButton>

      </View>
      <Popup show={showDesc} showTitle={false} onClose={() => setShowDesc(false)}>
        <Remark onSave={getRemark} defaultValue={remark} showInput={!!showDesc} />
      </Popup>
    </View>
  </MoveBtn>
}
export default AddColorCard
