import { Text, View } from '@tarojs/components'
import Taro, { useDidShow, useRouter } from '@tarojs/taro'
import { useMemo, useState } from 'react'
import styles from './index.module.scss'
import Address from './components/address'
import type { orderParam } from './components/productCard'
import ProductCard from './components/productCard'
import Remark from './components/remark'
import OrderInfo from './components/orderInfo'
import type { orderStateItem } from './components/orderState'
import OrderState from './components/orderState'
import { alert, goLink } from '@/common/common'
import SearchInput from '@/components/searchInput'
import { ColorCardOrderCancelApi, GetColorCardOrderDetailApi } from '@/api/colorCard'

interface Param {
  address: string
  color_card_info: orderParam[]
  create_time: string
  create_user_name: string
  creator_id: number
  id: number
  order_no: string
  order_progress: orderStateItem[]
  order_status: number
  order_status_name: string
  purchaser_id: number
  purchaser_name: string
  purchaser_phone: string
  remark: string
  sale_user_id: number
  sale_user_name: string
  shipment_mode: number
  shipment_mode_name: string
  target_user_name: string
  target_user_phone: string
  update_time: string
  update_user_name: string
  updater_id: number
}

export default () => {
  const router = useRouter()

  const [orderData, setOrderData] = useState<Param>()
  const { fetchData: fetchDataDtail } = GetColorCardOrderDetailApi()
  const getColorCardOrderDetail = async() => {
    const res = await fetchDataDtail({ id: router.params.id })
    setOrderData(() => res.data)
  }

  useDidShow(() => {
    getColorCardOrderDetail()
  })

  const addressData = useMemo(() => {
    return {
      address_title: orderData?.address || '',
      address_name: orderData?.purchaser_name || '',
      address_phone: orderData?.purchaser_phone || '',
      address_mode: orderData?.shipment_mode_name || '',
    }
  }, [orderData])

  // 取消订单
  const { fetchData: fetchDataCancel } = ColorCardOrderCancelApi()
  const onCancel = async() => {
    Taro.showModal({
      title: '确定取消订单？',
      async success(res) {
        if (res.confirm) {
          const res = await fetchDataCancel({ id: orderData?.id })
          if (res.success) {
            alert.success('取消成功')
            getColorCardOrderDetail()
          }
        }
        else if (res.cancel) {
          console.log('用户点击取消')
        }
      },
    })
  }
  return <View className={styles.main}>
    <OrderState list={orderData?.order_progress} />
    <Address defaultValue={addressData} />
    <ProductCard value={orderData?.color_card_info || []} />
    <OrderInfo {...orderData} />
    <Remark value={orderData?.remark || ''} placeholder="尚未备注信息" />
    {orderData?.order_status === 1 && <View className={styles.order_btn}>
      <View className={styles.btn_con}>
        <View className={styles.btn} onClick={onCancel}>取消订单</View>
      </View>
    </View>}
  </View>
}
