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 Remark from '../takeDelivery/components/remark'
import styles from './index.module.scss'
import { TakeGoodsOrder, TakeGoodsOrderAudit, TakeGoodsOrderRefuse } 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'
import Popup from '@/components/popup'

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

  const { fetchData } = TakeGoodsOrder()

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

  const getData = async() => {
    const { id } = router.params
    const res = await fetchData({
      id,
    })
    console.log('res==>', res.data)
    setDetailInfo(res.data)
    // 动态设置标题
    Taro.setNavigationBarTitle({
      title: res.data.take_goods_order_type_name,
    })
  }

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

  const { fetchData: FetchAudit } = TakeGoodsOrderAudit()

  const DetailItem = useMemo(() => {
    const element
      = !!detailInfo?.dyelot_number_list?.length
      && detailInfo?.dyelot_number_list.map((weightItem, key) => {
        return (
          <View className={styles.detailInfo} key={key}>
            <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.sale_roll} 条` : `${formatMeterDiv(weightItem?.sale_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.sale_roll} 条` : `${formatMeterDiv(weightItem?.sale_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 { fetchData: refuseOrder } = TakeGoodsOrderRefuse()

  const [showRemarkModal, setShowRemarkModal] = useState(false)

  const handleRefuseOrder = async(remark: string) => {
    const res = await refuseOrder({
      id: Number(router.params.id),
      remark,
    })
    if (res.success) {
      alert.success('拒收成功')
      getData()
    }
    else {
      alert.error('该操作失败')
    }
  }

  const onRemarkSave = async(remark: string) => {
    handleRefuseOrder(remark)
  }

  // 拒收
  const handleRefuse = useCallback(() => {
    setShowRemarkModal(true)
  }, [])

  // 审核
  const handleAudit = useCallback(() => {
    Taro.showModal({
      confirmColor: '#337FFF',
      title: '确定要提货？',
      async success(res) {
        if (res.confirm) {
          const res = await FetchAudit({ take_goods_order_id: [Number(router.params.id)] })
          if (res.success) {
            alert.success('提货成功')
            getData()
          }
          else {
            alert.error('请求失败')
          }
        }
      },
    })
  }, [readyToUploadList])

  // 底部按钮栏
  const BottomBar = useMemo(() => {
    if (detailInfo?.take_goods_order_type !== 0) {
      // 采购提货
      return (
        <View className={styles.bottomBar}>
          <NormalButton type="primary" round onClick={handleAudit} customStyles={{ width: '100%' }}>
            确认提货
          </NormalButton>
        </View>
      )
    }
    else {
      // 退货提货
      return (
        <View className={styles.bottomBar} style={{ justifyContent: 'space-between' }}>
          <NormalButton type="primary" plain round onClick={handleRefuse} customStyles={{ width: '25%' }}>
            拒收
          </NormalButton>
          <NormalButton type="primary" round onClick={handleAudit} customStyles={{ width: '25%' }}>
            确认提货
          </NormalButton>
        </View>
      )
    }
  }, [handleRefuse, handleAudit])
  return (
    <View className={styles.deliveryDetail}>
      <View className={styles.content}>
        <LayoutBlock circle customStyle={{ padding: '24rpx' }}>
          <View className={styles.detailTop}>
            <View className={styles.orderNo}>提货单号：{detailInfo?.take_order_no}</View>
            {detailInfo?.take_goods_status === 0
              ? (
                <View className={styles['status--takingGoods']}>{detailInfo?.take_goods_status_name}</View>
              )
              : (
                <View className={styles['status--finished']}>{detailInfo?.take_goods_status_name}</View>
              )}
          </View>
          {detailInfo?.take_goods_order_type === 0 && <Text className={styles.topBar__orderType}>供应信息：{detailInfo?.supplier_name}</Text>}
          {DetailItem}
          <View className={styles.total}>
            <Text>汇总：</Text>
            <Text className={styles.totalContent}>
              共{detailInfo?.product_count || 0}种面料，{detailInfo?.product_color_count || 0}种颜色，共
              {detailInfo?.sale_mode === 0 ? `${detailInfo?.take_roll}条` : `${formatMeterDiv(detailInfo?.take_meters).toLocaleString()}米`}
              ，重量{formatWeightDiv(detailInfo?.total_take_weight).toLocaleString()}kg
            </Text>
          </View>
        </LayoutBlock>
        {detailInfo?.take_goods_order_type !== 0 && (
          <>
            <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?.fabric_piece_accessory_url}></UploadImage>
            </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?.accessory_url}></UploadImage>
            </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?.auditor_name || '暂无提货人'}></Cell>
            <Cell title="创建时间：" desc={formatDateTime(detailInfo?.create_time) || '暂无创建时间'}></Cell>
            <Cell title="提货时间：" desc={formatDateTime(detailInfo?.audit_time) || '暂无提货时间'}></Cell>
          </View>
        </LayoutBlock>
        {detailInfo?.take_goods_order_type !== 0 && (
          <LayoutBlock circle customStyle={{ padding: '24rpx' }}>
            <View className={styles.orderInfoTop}>备注信息</View>
            <Divider direction="horizontal" customClassName={styles.divider}></Divider>
            <View className="orderInfoDetail">{detailInfo?.remark}</View>
          </LayoutBlock>
        )}
      </View>
      {detailInfo?.take_goods_status === 0 && BottomBar}
      <Popup show={showRemarkModal} showTitle={false} onClose={() => setShowRemarkModal(false)}>
        <Remark onSave={onRemarkSave} defaultValue={detailInfo?.remark} />
      </Popup>
    </View>
  )
}
export default TakeDeliveryDetail
