import { Text, View } from '@tarojs/components'
import Taro, { useRouter } from '@tarojs/taro'
import type { FC } from 'react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import styles from './index.module.scss'
import { DeliverNoticeOrder, DeliveryNoticeOrderAudit, DeliveryNoticeOrderUpload } from '@/api'
import { formatDateTime, formatMeterDiv, formatWeightDiv } from '@/common/format'
import Cell from '@/components/cell'
import Divider from '@/components/divider'
import LayoutBlock from '@/components/layoutBlock'
import NormalButton from '@/components/normalButton'
import SaleModeTag from '@/components/saleModeTag'
import UploadImage from '@/components/uploadImage'
import { alert } from '@/common/common'

const DeliveryDetail: FC = () => {
  const router = useRouter()

  const { fetchData } = DeliverNoticeOrder()

  const [detailInfo, setDetailInfo] = useState<Record<string, any>>({})

  const getData = async() => {
    const { id, order_no } = router.params
    const res = await fetchData({
      id,
      order_no,
    })
    console.log('res==>', res.data)
    setDetailInfo(res.data)
  }

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

  const { fetchData: uploadData } = DeliveryNoticeOrderUpload()

  const { fetchData: FetchAudit } = DeliveryNoticeOrderAudit()

  const DetailItem = useMemo(() => {
    const element
      = !!detailInfo?.weight_list?.length
      && detailInfo?.weight_list.map((weightItem, index) => {
        return (
          <View key={index} className={styles.detailInfo}>
            <Divider direction="horizontal" customClassName={styles.divider}></Divider>
            <View className={styles.detailInfoItem}>
              <View className={styles['detailInfoItem--title']}>
                <View className="">
                  <Text style={{ marginRight: '20rpx' }}>
                    {weightItem.product_code} {weightItem.product_name}
                  </Text>
                  <SaleModeTag saleMode={weightItem?.sale_mode} />
                </View>
                <View className="">共 {weightItem?.sale_mode === 0 ? `${weightItem.roll} 条` : `${formatMeterDiv(weightItem?.length || 0)} 米`}</View>
              </View>
              <View className={styles['detailInfoItem--detail']}>
                <View className={styles['detailInfoItem--detail--row']}>
                  <View className={styles['detailInfoItem--detail--name']}>
                    {weightItem.product_color_code} {weightItem.product_color_name}
                  </View>
                  <View className={styles['detailInfoItem--detail--count']}>
                    x{weightItem?.sale_mode === 0 ? `${weightItem.roll} 条` : `${formatMeterDiv(weightItem?.length || 0)} 米`}
                  </View>
                  <View className={styles['detailInfoItem--detail--weight']}>{formatWeightDiv(weightItem.weight)}kg</View>
                </View>
              </View>
            </View>
          </View>
        )
      })
    return <>{element}</>
  }, [detailInfo])

  const [readyToUploadList, setReadyToUploadList] = useState<string[]>([])

  const handleUploadChange = (imageList: string[]) => {
    console.log('imageList===>', imageList)
    setReadyToUploadList(prev => [...prev, ...imageList])
  }
  // 上传附件
  const handleUploadPic = useCallback(async() => {
    const res = await uploadData({
      id: Number(router.params.id),
      delivery_appendix: readyToUploadList,
    })
    if (res.success) {
      alert.success('上传成功')
    }
    else {
      alert.error('上传核失败')
    }
  }, [readyToUploadList])

  // 审核
  const handleAudit = useCallback(() => {
    if (readyToUploadList.length === 0) {
      alert.error('请先上传附件')
      return
    }
    Taro.showModal({
      confirmColor: '#337FFF',
      title: '确定审核？',
      async success(res) {
        if (res.confirm) {
          const res = await FetchAudit({ id: Number(router.params.id) })
          if (res.success) {
            alert.success('审核成功')
            getData()
          }
          else {
            alert.error('审核失败')
          }
        }
        else if (res.cancel) {
          console.log('用户点击取消')
        }
      },
    })
  }, [readyToUploadList])

  const BottomBar = useMemo(() => {
    return (
      <View className={styles.bottomBar}>
        <NormalButton plain type="primary" customStyles={{ width: '45%' }} round onClick={handleUploadPic}>
          上传附件
        </NormalButton>
        <NormalButton type="primary" round customStyles={{ width: '45%' }} onClick={handleAudit}>
          确认审核
        </NormalButton>
      </View>
    )
  }, [handleUploadPic, handleAudit])
  return (
    <View className={styles.deliveryDetail}>
      <View className={styles.content}>
        <LayoutBlock circle customStyle={{ padding: '24rpx' }}>
          <View className={styles.detailTop}>
            <View className={styles.orderNo}>发货单号：{detailInfo?.order_no}</View>
            {detailInfo?.status === 0 ? <View className={styles['status--toBeAudit']}>待审核</View> : <View className={styles['status--audited']}>已完成</View>}
          </View>
          {DetailItem}
          <View className={styles.total}>
            <Text>汇总：</Text>
            <Text className={styles.totalContent}>
              共{detailInfo?.delivery_product_nums || 0}种面料，{detailInfo?.delivery_product_color_nums || 0}种颜色，共
              {detailInfo?.sale_mode === 0 ? `${detailInfo?.total_roll}条` : `${formatMeterDiv(detailInfo?.total_length).toLocaleString()}米`}
              ，重量{formatWeightDiv(detailInfo?.total_weight).toLocaleString()}kg
            </Text>
          </View>
        </LayoutBlock>
        <LayoutBlock circle customStyle={{ padding: '24rpx' }}>
          <View className={styles.orderInfoTop}>订单信息</View>
          <Divider direction="horizontal" customClassName={styles.divider}></Divider>
          <View className="orderInfoDetail">
            <Cell title="订单备注：" desc={detailInfo?.sale_order_remark || '暂无备注信息'}></Cell>
            <Cell title="创建时间：" desc={formatDateTime(detailInfo?.create_time) || '暂无创建时间'}></Cell>
            <Cell title="发货方式：" desc={detailInfo?.shipment_mode_name || '暂无发货方式'}></Cell>
            <Cell title="发货地址：" desc={`${detailInfo.province_name}${detailInfo.city_name}${detailInfo.district_name}${detailInfo.address_detail}` || '暂无发货地址'}></Cell>
          </View>
        </LayoutBlock>
        <LayoutBlock circle customStyle={{ padding: '24rpx' }}>
          <View className={styles.orderInfoTop}>附件</View>
          <Divider direction="horizontal" customClassName={styles.divider}></Divider>
          <UploadImage onlyRead={detailInfo?.status !== 0} onChange={handleUploadChange} defaultList={detailInfo?.delivery_appendix_url}></UploadImage>
        </LayoutBlock>
      </View>
      {detailInfo?.status === 0 && BottomBar}
    </View>
  )
}
export default DeliveryDetail
