import { Image, ScrollView, Text, View } from '@tarojs/components'
import Taro, { useDidShow, useRouter } from '@tarojs/taro'
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 KindList from './components/kindList'
import CutKindList from './components/cutkindList'
import { GetSaleOrderDetailApi } from '@/api/order'
import { ReturnApplyOrderApi, ReturnExplainApi, ReturnGoodsStatusApi, ReturnReasonApi } from '@/api/salesAfterOrder'
import { alert, goLink } from '@/common/common'
import UploadImage from '@/components/uploadImage'
import TextareaEnhance from '@/components/textareaEnhance'
import useLogin from '@/use/useLogin'
import { throttle } from '@/common/util'

enum returnStatus {
  return_reason = 1, // 原因
  goods_status = 2, // 状况
  return_explain = 3, // 说明
}
const ApplyAfterSales = () => {
  useLogin()

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

  // 需要提交的数据
  const [submitData, setSubmitData] = useState<any>({
    fabric_piece_accessory_url: [],
    goods_status: '', // 货物状况
    reason_describe: '', // 其他说明
    return_explain: '', // 退货说明
    return_reason: '', // 退货原因
    roll: 0,
    roll_list: [],
    sale_order_id: orderId.current,
  })

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

  useDidShow(() => {
    getSaleOrderPreView()
  })
  // 格式化数据格式
  const [formatDetailOrder, setFormatDetailOrder] = useState<any>() // 格式化后的数据
  const formatData = () => {
    setFormatDetailOrder({
      ...orderDetail,
      unit: orderDetail.sale_mode == 0 ? '条' : 'm', // 单位
      list: orderDetail.product_list,
    })
  }

  // 数据总量
  const dataCount = useMemo(() => {
    if (formatDetailOrder) {
      const total_number = formatDetailOrder.sale_mode == 0 ? `${formatDetailOrder.av_total_number}条` : `${formatDetailOrder.av_total_number / 100}米`
      return `${formatDetailOrder.av_total_fabrics}种面料，${formatDetailOrder.av_total_colors}种颜色，共${total_number}`
    }
  }, [formatDetailOrder])

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

  // 大货时获取计步器数据
  const getNumChange = useCallback((val) => {
    if (parseInt(val.number) > 0) {
      roll_list.current[val.color_id] = { product_roll: val.number, sale_order_detail_id: val.sale_order_detail_id }
    }
    else {
      delete roll_list.current[val.color_id]
    }
    setSubmitData(e => ({ ...e, roll_list: Object.values(roll_list.current) }))
  }, [])
  // 监听获取到的数据
  useEffect(() => {
    if (orderDetail) {
      formatData()
    }
  }, [orderDetail])
  // 散剪和剪板
  const getSelectChange = useCallback((val) => {
    if (val.status) {
      roll_list.current[val.sale_order_detail_id] = { product_roll: val.length, sale_order_detail_id: val.sale_order_detail_id }
    }
    else {
      delete roll_list.current[val.sale_order_detail_id]
    }
    setSubmitData(e => ({ ...e, roll_list: Object.values(roll_list.current) }))
  }, [])

  // 获取图片列表
  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.none('请选择或输入退货颜色') }
    console.log('submitData::', submitData)
    const res = await fetchDataReturnApply(submitData)
    if (res.success) {
      alert.success('申请成功')
      goLink('/pages/salesAfter/salesAfterList/index', {}, 'reLaunch')
    }
    else {
      alert.error(res.msg)
    }
  }

  // 底部按钮
  const onSubmit = throttle((val) => {
    if (val == 2) {
      if (submitData.goods_status === '') { return alert.error('请选择货物状况') }
      if (submitData.return_explain === '') { return alert.error('请选择退货原因') }
      if (!submitData.return_explain && !submitData.reason_describe) { return alert.error('请填写其他说明') }
      onSubmitData()
    }
    else {
      Taro.navigateBack()
    }
  }, 600)

  // 退货原因选择弹窗
  const [showReason, setShowReason] = useState(false)
  const closeReason = useCallback(() => setShowReason(false), [])
  const onShowReason = () => {
    setShowReason(true)
  }

  // 请求获取到的数据
  const [returnGoodsInfo, setReturnGoodsInfo] = useState([])

  // 退货原因
  const { fetchData: fetchDataReturnReason } = ReturnReasonApi()
  const getReturnReason = async() => {
    const res = await fetchDataReturnReason()
    setReturnGoodsInfo(e => res.data?.list)
  }
  useEffect(() => {
    getReturnReason()
  }, [])
  // 售后退货说明
  const { fetchData: fetchDataReturnExplain } = ReturnExplainApi()
  const getReturnExplain = async(id) => {
    const res = await fetchDataReturnExplain({ return_reason: id })
    setReturnGoodsInfo(e => res.data?.list)
  }
  // 退货原因选择列表返回的数据
  const [returnObj, setReturnObj] = useState<any>([])
  const onReturnSelect = useCallback((val) => {
    const res = val.data[val.data.length - 1]
    if (val.index == 1) {
      getReturnExplain(res.id)
      setReturnGoodsInfo(() => [])
    }
    if (val.index == 2) { setReturnObj(val.data) }
  }, [])
  const onHeaderSelect = useCallback((val) => {
    setReturnGoodsInfo(e => [])
    if (val.index == 1) { getReturnReason() }
  }, [])

  // 选择货物状况
  const [showStatus, setShowStatus] = useState(false)
  const [statusInfo, setStatusInfo] = useState<any>()
  const [statusGoodsInfo, setStatusGoodsInfo] = useState([])
  const { fetchData: fetchDataGoodsStatus } = ReturnGoodsStatusApi()
  const getReturnGoodsStatus = async() => {
    const res = await fetchDataGoodsStatus()
    setStatusGoodsInfo(e => res.data?.list)
  }
  const onShowStatus = () => {
    setShowStatus(() => true)
    getReturnGoodsStatus()
  }
  const closeStatus = useCallback(() => {
    setShowStatus(() => false)
  }, [])
  const onStatusSelect = useCallback((val) => {
    const res = val.data[val.data.length - 1]
    setStatusInfo(res)
  }, [])

  useEffect(() => {
    if (returnObj.length > 0) {
      submitData.return_reason = returnObj[0].id
      submitData.return_explain = returnObj[1].id
    }
    if (statusInfo) {
      submitData.goods_status = statusInfo.id
    }
    setSubmitData(() => ({ ...submitData }))
  }, [returnObj, statusInfo])

  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}>
            {(orderDetail?.sale_mode == 0 && <KindList order={formatDetailOrder} onNumChange={getNumChange} />) || (
              <CutKindList order={formatDetailOrder} onSelectChange={getSelectChange} />
            )}
            <View className={styles.returnSaleInput}>
              <View className={styles.returnSaleInput_item}>
                <View className={styles.title}>退货原因</View>
                <View className={styles.select} onClick={onShowReason}>
                  <Text className={returnObj?.length > 0 && styles.selected}>
                    {returnObj?.length > 0 ? `${returnObj[0]?.name}/${returnObj[1]?.name}` : '请选择'}
                  </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={onShowStatus}>
                  <Text className={statusInfo?.name && styles.selected}>{statusInfo?.name || '请选择'}</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}
        onClose={closeReason}
        title="退货原因"
        list={returnGoodsInfo}
        onHeaderSelect={onHeaderSelect}
        onSelect={onReturnSelect}
        dataLength={2}
      />
      <ReasonPopup show={showStatus} onClose={closeStatus} title="货物状况" list={statusGoodsInfo} onSelect={onStatusSelect} dataLength={1} />
    </View>
  )
}

export default ApplyAfterSales
