import { Image, ScrollView, Text, View } from "@tarojs/components";
import { FC, memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import classnames from "classnames";
import styles  from './index.module.scss'
import ReasonPopup from "./components/reasonPopup";
import OtherReason from "./components/otherReason";
import { useDidShow, useRouter } from "@tarojs/taro";
import { GetSaleOrderDetailApi } from "@/api/order";
import KindList from "./components/kindList"
import { ReturnApplyOrderApi, ReturnGoodsStatusApi } from "@/api/salesAfterOrder";
import { alert, goLink } from "@/common/common";
import UploadImage from "@/components/uploadImage"
import TextareaEnhance from "@/components/textareaEnhance";

type ReasonParam = 1|2|3 //1 退货原因 2 货物状况 3 退货说明
export default () => {

    useDidShow(() => {
        getSaleOrderPreView()
    })

    const router = useRouter()
    const orderId = useRef<number>(Number(router.params.id))

    //需要提交的数据
    const [submitData, setSubmitData] = useState<any>({
        fabric_piece_accessory_url: [],
        goods_status: 0,
        reason_describe: '',
        return_explain: 0,
        return_reason: 1,
        roll: 0,
        roll_list: [],
        sale_order_id: orderId.current
    })

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

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

    //格式化数据格式
    const [formatDetailOrder, setFormatDetailOrder] = useState<any>() //格式化后的数据
    const formatData = () => {  
        setFormatDetailOrder({
            sale_mode: orderDetail.sale_mode,
            sale_mode_name: orderDetail.sale_mode_name, 
            total_colors: orderDetail.total_colors, //总颜色数量
            total_number: orderDetail.total_number, //总数量
            total_fabrics: orderDetail.total_fabrics, //面料数量
            unit: orderDetail.sale_mode == 0?'条':'m', //单位
            list: orderDetail.product_list,
            status: orderDetail.status, //订单状态
            
        })
    }

    //数据总量
    const dataCount = useMemo(() => {
        if(formatDetailOrder) {
            return `${formatDetailOrder.total_fabrics}种面料，${formatDetailOrder.total_colors}种颜色，共${formatDetailOrder.total_number}条`
        }
    }, [formatDetailOrder])
   
    
    //退货选择弹窗
    const [showReason, setShowReason] = useState<{show:true|false, title: string}>({show:false, title: ''})
    const closeReason = useCallback(() => setShowReason({...showReason, show:false}), [])
    const onShowReason = (status) => {
        setShowReason({...showReason, show:true})
    }

    //面料数据
    let roll_list = useRef({})

    //大货时获取计步器数据
    const getNumChange = useCallback((val) => {
        if(parseInt(val.number) > 0) {
            roll_list.current[val.color_id] = {product_color_id: val.color_id, product_roll: val.number}
        } else {
            delete roll_list.current[val.color_id]
        }

        let count = 0 
        Object.values(roll_list.current).map((item: any) => {
            count += item.product_roll
        })
        setSubmitData((e) => ({...e, roll_list:Object.values(roll_list.current), roll: count}))
    }, [])

    //散剪和剪板
    const getSelectChange = useCallback((val) => {
        console.log('val::', val)
        if(val.status) {
            roll_list.current[val.color_id] = {product_color_id: val.color_id, product_roll: val.length}
        } else {
            delete roll_list.current[val.color_id]
        }
        let count = 0 
        Object.values(roll_list.current).map((item: any) => {
            count += item.product_roll
        })
        setSubmitData((e) => ({...e, roll_list:Object.values(roll_list.current), roll: count}))
    }, [])  

    //获取图片列表
    const getImageList = useCallback((list) => {
        setSubmitData((e) => ({...e, fabric_piece_accessory_url:list}))
    }, [])

    //其他说明
    const getOtherReason = useCallback((val) => {
        setSubmitData((e) => ({...e, reason_describe: val}))
    }, [])

    //提交数据
    const {fetchData: fetchDataReturnApply} = ReturnApplyOrderApi()
    const onSubmitData = async () => {
        if(submitData.roll_list.length <= 0) return alert.error('请选择退货颜色')
        let res = await fetchDataReturnApply(submitData)
        if(res.success) {
            alert.success('申请成功')
            goLink('/pages/salesAfterList/index',{}, 'reLaunch')
        } else {
            alert.error('申请失败')
        }
        console.log('提交：：',submitData)
    }

    //底部按钮
    const onSubmit = (val) => {
        if(val == 2) {
            onSubmitData()
        }
    }

    const [returnGoodsInfo, setReturnGoodsInfo] = useState<{title:string, list: any[]}>({title:'', list:[]})
    //售后货物状况
    const {fetchData: fetchDataGoodsStatus} = ReturnGoodsStatusApi()
    const getReturnGoodsStatus = async () => {
        let res = await fetchDataGoodsStatus()
        setReturnGoodsInfo((e) => ({...e, title: '售后货物状况', list:res.data?.list||[]}))
    }
    useEffect(() => {
        getReturnGoodsStatus()
    }, [])

    return (
        <View className={styles.apply_after_sales_main}>
            <View className={styles.apply_after_sales_con}>
                <View className={styles.kind_number}><Text>{dataCount}</Text></View>
                <ScrollView scrollY className={styles.scroll}>
                    <View className={styles.scroll_con}>
                        <KindList order={formatDetailOrder} onNumChange={getNumChange} onSelectChange={getSelectChange}/>
                        <View className={styles.returnSaleInput}>
                            <View className={styles.returnSaleInput_item}>
                                <View className={styles.title}>退货原因</View>
                                <View className={styles.select} onClick={() => onShowReason(1)}>
                                    <Text>请选择</Text>
                                    <Text className={classnames(styles.miconfont, 'iconfont icon-a-moreback')}></Text>
                                </View>
                            </View>
                            <View className={styles.returnSaleInput_item}>
                                <View className={styles.title}>货物状况</View>
                                <View className={styles.select} onClick={() => onShowReason(2)}>
                                    <Text>请选择</Text>
                                    <Text className={classnames(styles.miconfont, 'iconfont icon-a-moreback')}></Text>
                                </View>
                            </View>
                            <View className={styles.returnSaleInput_item}>
                                <View className={styles.title}>退货说明</View>
                                <View className={styles.select} onClick={() => onShowReason(3)}>
                                    <Text>请选择</Text>
                                    <Text className={classnames(styles.miconfont, 'iconfont icon-a-moreback')}></Text>
                                </View>
                            </View>
                            <View className={styles.returnSaleInput_item}>
                                <View className={styles.title}>拍照上传</View>
                                <View className={styles.upload_image}>
                                    <UploadImage onChange={getImageList}/>
                                </View>
                            </View>
                            <TextareaEnhance onChange={getOtherReason} title='其他说明'/>
                        </View>
                       
                    </View>
                </ScrollView>
                <View className="common_safe_area_y"></View>
            </View>
            <View  className={styles.btns_con}>
                <View  className={styles.btns_two}>
                    <View  className={styles.rest_btn} onClick={() => onSubmit(1)}>取消</View>
                    <View  className={styles.verify_btn } onClick={() => onSubmit(2)}>确认</View>
                </View >
            </View >
            <ReasonPopup show={showReason.show} onClose={closeReason} title={returnGoodsInfo.title} list={returnGoodsInfo.list}/>   
        </View>
    )
}