import { GetSaleOrderDetailApi } from "@/api/order";
import { goLink } from "@/common/common";
import { formatDateTime, formatPriceDiv } from "@/common/fotmat";
import Popup from "@/components/popup";
import SearchInput from "@/components/searchInput";
import { Text, Textarea, View } from "@tarojs/components"
import Taro, { useRouter } from "@tarojs/taro";
import classnames from "classnames";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import AddressInfo from "./components/addressInfo";
import KindList from "./components/kindList";
import OrderState from "./components/orderState";
import Remark from "./components/remark";
import WeightMemo from "./components/weightMemo";
import styles  from './index.module.scss'
 
 export default () => {
    const [showDesc, setShowDesc] = useState(false)
    
    const router = useRouter()
    useEffect(() => {
        getSaleOrderPreView()
    }, [])

    //获取订单详情
    const [orderDetail, setOrderDetail] = useState<any>() //获取到的原始数据
    const {fetchData: getOrderFetchData} = GetSaleOrderDetailApi()
    const getSaleOrderPreView = async () => {
        if(router.params.id) {
            let res = await getOrderFetchData({id: router.params.id})
            setOrderDetail(res.data)
        }       
    }

    //监听获取到的数据
    useEffect(() => {
        if(orderDetail)
            formatData()
    }, [orderDetail])

    //格式化数据格式
    const [formatDetailOrder, setFormatDetailOrder] = useState<any>() //格式化后的数据
    const formatData = () => {  
        if(orderDetail?.color_list&&orderDetail?.color_list.length > 0) {
            let dataList = {}
            let num_count = 0 //总数量
            orderDetail?.color_list.map(item => {
                dataList[item.product_code] =  dataList[item.product_code]||{}
                dataList[item.product_code].product_code = item.product_code
                dataList[item.product_code].product_name = item.product_name
                dataList[item.product_code].sale_mode_name = orderDetail.sale_mode_name
                dataList[item.product_code].color_list =  dataList[item.product_code]?.color_list||[]
                dataList[item.product_code].color_list.push(item)
                //大货
                if (orderDetail.sale_mode == 0) num_count += item.roll
                //剪板或散件
                if (orderDetail.sale_mode == 1 || orderDetail.sale_mode == 2) num_count += item.length
            })
            if (orderDetail.sale_mode == 1 || orderDetail.sale_mode == 2) num_count = Number(num_count / 100);
            setFormatDetailOrder({
                estimate_amount: orderDetail.estimate_amount, //预估金额
                estimate_weight: orderDetail.estimate_weight, 
                sale_mode: orderDetail.sale_mode,
                sale_mode_name: orderDetail.sale_mode_name, 
                colo_count: orderDetail.color_list.length, //颜色数量
                num_count: num_count, //总数量
                unit: orderDetail.sale_mode == 0?'条':'m', //单位
                list: Object.values(dataList)
            })
        }
    }

    const formatPreViewOrderMemo = useMemo(() => {
        return formatDetailOrder
    }, [formatDetailOrder])

    //复制功能
    const clipboardData = () => {
        Taro.setClipboardData({
            data: orderDetail?.order_no||'',
            success: function (res) {
                Taro.showToast({
                    icon: 'none',
                    title: '复制成功'
                })
            }
        })
    }

    //格式化初始地址
    const defaultAddress = useMemo(() => {
        const address = orderDetail?.default_address
        if(address) {
            return  {
                province_name: address.province_name,
                city_name: address.city_name,
                district_name: address.district_name,
                address_detail: address.address_detail,
                id: address.id,
                name: address.name,
                phone: address.phone
            }
        }
        return null
    }, [orderDetail])

    //订单备注
    const [orderRemark, setOrderRemark] = useState('')
    const getRemark = useCallback((e) => {
        setOrderRemark(() => e)
        setShowDesc(() => false)
    }, [])

    //修改地址
    const changeAddress = useCallback(() => {
        goLink('/pages/editOrder/index', {id: router.params.id})
    }, [router.params])
    return (
        <View className={styles.order_main}>
            <View className={styles.weight_memo_con}>
                <WeightMemo/>
            </View>
            <OrderState />
            <View onClick={() => changeAddress()}>
                <AddressInfo defaultValue={defaultAddress} disabled={true} />
            </View>
            <KindList value={formatPreViewOrderMemo}/>
            <View className={styles.order_info} >
                <View className={styles.order_info_title}>订单信息</View>
                <SearchInput showBorder={false} title='单号'>
                    <View className={styles.order_num}>
                        <Text>{orderDetail?.order_no}</Text>
                        <View className={styles.order_num_btn} onClick={() => clipboardData()}>复制</View>
                    </View>
                </SearchInput>
                <SearchInput showBorder={false} title='下单时间'>
                    <Text>{formatDateTime(orderDetail?.create_time)}</Text>
                </SearchInput>
                <SearchInput showBorder={false} title='付款时间'>
                    <Text>{formatDateTime(orderDetail?.create_time)}</Text>
                </SearchInput>
            </View>
            <View className={styles.order_desc} onClick={() => setShowDesc(true)}>
                <View className={styles.order_desc_con}>订单备注</View>
                {
                    orderRemark&&<View className={styles.order_desc_text}>{orderRemark}</View>||
                    <View className={styles.order_desc_text_hint}>填写备注</View>
                }
                <View className={classnames(styles.miconfont, 'iconfont icon-a-moreback')}></View>
            </View>
            <View className={styles.submit_order}>
                <View className={styles.order_btn}>取消订单</View>    
            </View>        
            <Popup show={showDesc} showTitle={false} onClose={() => setShowDesc(false)} >
                <Remark onSave={(e) => getRemark(e)}/>
            </Popup>
            <View className="common_safe_area_y"></View>
        </View>
    )
 }
