import { Text, View } from '@tarojs/components'
import Taro, { useDidShow, useRouter } from '@tarojs/taro'
import { useCallback, useEffect, useMemo, useRef, useState, useTransition } from 'react'
import PayeeHead from '../payeeHead'
import type { CompanyItem } from '../payeeHead'
import WholeOrderSetting from '../wholeOrderSetting'
import type { BottomItem } from '../bottomBtn'
import BottomBtn from '../bottomBtn'
import ProductSetting from '../productSetting'
import ColorSetting from '../colorSetting'
import styles from './index.module.scss'
import SelectList from '@/components/selectList'
import { CreateCustomCodeApi, CustomPrintCalculationApi, DeleteCustomCodeApi, GetCustomCodeDetailApi, GetCustomCodeInitApi, UpdateCustomCodeApi } from '@/api/codeManage'
import { formatPriceDiv, formatWeightDiv } from '@/common/fotmat'
import { useCurrenCode } from '@/context/ContextCodeSetting'
import { alert } from '@/common/common'
import LoadingCard from '@/components/loadingCard'
import ViewCodeList from '@/components/viewCodeList'

interface previewParam {
  dyelot_number_list: any[]
  total_number: number
  title: string
  sale_mode_name: string
  purchaser_name: string
  purchaser_phone: string
  create_time: string
  bill_total_sale_price: number
  total_weight: number
  total_settle_weight: number
  total_weight_error: number
  show_pay_type: boolean
  show_order_no: boolean
  show_shipment_mode: boolean
  show_barcode: boolean
  show_qrcode: boolean
}
export default () => {
  const { productData, dispatch } = useCurrenCode()
  const { custom_print_id, sale_order_id } = useRouter().params
  const submit_ids = useRef({
    custom_print_id,
    sale_order_id,
  })
  const selectList = [
    { value: 1, label: '按整单' },
    { value: 2, label: '按面料' },
    { value: 3, label: '按颜色' },
  ]
  const modelIndex = useRef(1)
  const getTypeSelect = useCallback((index) => {
    modelIndex.current = index
    getDataInit()
  }, [])

  const [loading, setLoading] = useState(false)

  const [codeData, setCodeData] = useState<any>(null)

  const [isPending, startTransition] = useTransition()

  // 获取新增码单详情
  const { fetchData: getCustomCodeInit } = GetCustomCodeInitApi()
  const onCustomCodeInit = async() => {
    const res = await getCustomCodeInit({ id: submit_ids.current.sale_order_id })
    setCodeData(() => res?.data)
    setLoading(false)
  }

  // 获取码单编辑详情
  const { fetchData: getCustomCodeDetail } = GetCustomCodeDetailApi()
  const onGetCustomCodeDetail = async() => {
    const res = await getCustomCodeDetail({ id: submit_ids.current.custom_print_id })
    setCodeData(() => res?.data)
    setLoading(false)
  }

  const getDataInit = () => {
    setLoading(true)
    startTransition(() => {
      if (submit_ids.current.custom_print_id) {
        onGetCustomCodeDetail()
      }
      else {
        onCustomCodeInit()
      }
    })
  }

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

  const logadingStatus = useMemo(() => {
    return loading || isPending
  }, [loading, isPending])

  useEffect(() => {
    if (codeData) {
      codeData && dispatch({
        type: 'setInitData',
        data: codeData,
        sale_order_id: submit_ids.current.sale_order_id || 0,
        custom_print_id: submit_ids.current.custom_print_id || 0,
        adjust_type: modelIndex.current,
      })
      setCustomTotal(() => ({
        total_weight_error: codeData.total_weight_error,
        total_sale_weight: codeData.total_sale_weight,
        total_amount: codeData.total_amount,
      }))
      setPreviewData({
        dyelot_number_list: codeData.dyelot_number_list,
        total_number: codeData.roll,
        title: codeData.purchaser_name,
        sale_mode_name: codeData.sale_mode_name,
        purchaser_name: codeData.purchaser_name,
        purchaser_phone: codeData.purchaser_phone,
        create_time: codeData.create_time,
        bill_total_sale_price: codeData.total_amount,
        total_weight: codeData.total_sale_weight,
        total_settle_weight: codeData.total_settlement_weight,
        total_weight_error: codeData.total_weight_error,
        show_pay_type: false,
        show_order_no: false,
        show_shipment_mode: false,
        show_barcode: false,
        show_qrcode: false,
      })
    }
  }, [codeData])

  // 默认抬头
  const company = useMemo(() => {
    return {
      title: productData?.purchaser_form_title?.title,
      purchaser_name: productData?.purchaser_form_title?.purchaser_name,
      phone: productData?.purchaser_form_title?.phone,
    }
  }, [productData])

  // 修改码单
  const { fetchData: createCustomCodeApi } = CreateCustomCodeApi()
  const { fetchData: updateCustomCodeApi } = UpdateCustomCodeApi()

  // 获取码单抬头
  const getCompany = useCallback((val: CompanyItem) => {
    dispatch({ type: 'setPurchaserFormTitle', data: val })
  }, [])

  // 按钮事件
  const onBottomClick = (type: BottomItem) => {
    (async() => {
      if (type === 'save') {
        const res = custom_print_id
          ? await updateCustomCodeApi({ ...productData?.admin_data })
          : await createCustomCodeApi({ ...productData?.admin_data })
        if (res.success) {
          submit_ids.current.custom_print_id = res.data.id
          getDataInit()
          dispatch({ type: 'changeSaveStatus', data: true })
          alert.success('保存成功!')
        }
      }
      else if (type === 'del') {
        deleteCode()
      }
      else if (type === 'preview') {
        setshowPopup(true)
      }
    })()
  }

  // 自定义码单合计数据
  const [customTotal, setCustomTotal] = useState({
    total_weight_error: 0,
    total_sale_weight: 0,
    total_amount: 0,
  })

  useEffect(() => {
    console.log('productData合计数据:::', productData)
    if (productData?.admin_data && productData?.update_status === 1) {
      updateCustomOrderTotal(productData.admin_data)
    }
  }, [productData?.admin_data])

  // 更新合计数据
  const { fetchData: customPrintCalculationApi } = CustomPrintCalculationApi()
  const updateCustomOrderTotal = async(updateData) => {
    const res = await customPrintCalculationApi(updateData)
    if (res.success) {
      setCustomTotal(() => ({
        total_weight_error: res?.data?.total_weight_error,
        total_sale_weight: res?.data?.total_sale_weight,
        total_amount: res?.data?.total_amount,
      }))
      setPreviewData(e => ({
        ...e,
        bill_total_sale_price: res?.data?.total_amount,
        total_weight: res?.data?.total_sale_weight,
        total_settle_weight: res?.data?.total_settlement_weight,
        total_weight_error: res?.data?.total_weight_error,
        dyelot_number_list: res?.data?.dyelot_number_list,
      }))
    }
  }

  // 删除码单
  const { fetchData: delFetchData } = DeleteCustomCodeApi()
  const deleteCode = async() => {
    Taro.showModal({
      title: '确定删除该码单？',
      async success(res) {
        if (res.confirm) {
          const res = await delFetchData({ id: submit_ids.current.custom_print_id })
          if (res.success) {
            alert.success('删除成功')
            Taro.navigateBack()
          }
        }
        else if (res.cancel) {
          console.log('用户点击取消')
        }
      },
    })
  }

  // 获取预览码单数据
  const [previewData, setPreviewData] = useState<previewParam|{}>({})

  const [showPopup, setshowPopup] = useState(false)

  return <View className={styles.code_list__main}>
    <View className={styles.code_list__head}>
      <PayeeHead defaultValue={company} onSelect={getCompany} />
    </View>
    <SelectList onSelect={getTypeSelect} list={selectList} defaultIndex={1} />
    {logadingStatus
      ? <View className={styles.loading_card}><LoadingCard /></View>
      : <View className={styles.code_list_con}>
        <View>
          {productData?.adjust_type == 1 && <WholeOrderSetting orderData={productData?.data} />}
        </View>
        <View>
          {productData?.adjust_type == 2 && <ProductSetting orderData={productData?.data} />}
        </View>
        <View>
          {productData?.adjust_type == 3 && <ColorSetting orderData={productData?.data} />}
        </View>
        <View className={styles.code_des}>
          <View className={styles.code_des_title}>自定义单据信息</View>
          {codeData?.sale_mode === 0 && <View className={styles.code_des_item}>
            <Text>合计空差</Text>
            <Text>{formatWeightDiv(customTotal.total_weight_error)}kg</Text>
          </View>}
          <View className={styles.code_des_item}>
            <Text>合计重量</Text>
            <Text className={styles.code_des_weight}>{formatWeightDiv(customTotal.total_sale_weight)}kg</Text>
          </View>
          <View className={styles.code_des_item}>
            <Text>合计金额</Text>
            <Text className={styles.code_des_price}>¥{formatPriceDiv(customTotal.total_amount)}</Text>
          </View>
        </View>
        <View className={styles.code_des}>
          <View className={styles.code_des_title}>原始单据信息</View>
          {codeData?.sale_mode === 0 && <View className={styles.code_des_item}>
            <Text>合计空差</Text>
            <Text>{formatWeightDiv(productData?.data?.original_total_weight_error)}kg</Text>
          </View>}
          <View className={styles.code_des_item}>
            <Text>合计重量</Text>
            <Text className={styles.code_des_weight}>{formatWeightDiv(productData?.data?.original_total_sale_weight)}kg</Text>
          </View>
          <View className={styles.code_des_item}>
            <Text>合计金额</Text>
            <Text className={styles.code_des_price}>¥{formatPriceDiv(productData?.data?.original_total_amount)}</Text>
          </View>
        </View>
      </View>}
    <BottomBtn delStatus={!!productData.custom_print_id} onClick={onBottomClick} />
    <ViewCodeList orderObj={previewData} showPopup={showPopup} handClose={() => setshowPopup(false)}></ViewCodeList>
    <View className="common_safe_area_y"></View>
  </View>
}
