import { Button, View } from '@tarojs/components'
import Taro, { setNavigationBarTitle, useDidShow, usePullDownRefresh, useRouter } from '@tarojs/taro'
import type { ReactNode } from 'react'
import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import classnames from 'classnames'
import Remark from '../orderDetails/components/remark'
import styles from './index.module.scss'
import Form from './components/form'
import Popup from '@/components/popup'
import { debounce } from '@/common/util'
import { alert, goLink } from '@/common/common'
import { formatDateTime, formatPriceDiv, formatWeightDiv } from '@/common/format'
import Address from '@/components/address'
import { MpPurchaser, MpPurchaserPost, MpPurchaserPut } from '@/api/customer'
// 卡片盒子元素
interface Obs {
  title?: string
  modeName?: string
  showMode?: boolean
  children?: ReactNode
  clickNode?: () => void
}

const DefaultBox = (props: Obs) => {
  const {
    title = '标题',
    modeName = '大货',
    showMode = false,
    children,
    clickNode,
  } = props

  return (
    <View className={styles.defaltBox}>
      <View className={styles.titleBox}>
        <View className={styles.title}>{title}</View>
        {
          showMode && <View className={styles.modeName} onClick={() => clickNode?.()}>{modeName}</View>
        }
      </View>
      <View className={styles.modeLine}></View>
      {children}
    </View>
  )
}
const DefaultBoxWithMemo = memo(DefaultBox)

interface AddressParms {
  id: number
  name: string
}
const CustomerEditor = () => {
  const router = useRouter()

  const [infoObj, setinfoObj] = useState<any>()

  const [formData, setformData] = useState<any>()

  const [addressArr, setaddressArr] = useState<AddressParms[]>([])

  // 默认业务员
  useDidShow(() => {
    if (router.params.type === 'add') {
      setNavigationBarTitle({ title: '新增客户' })
    }
    else {
      setNavigationBarTitle({ title: '客户编辑' })
    }
    const userInfo = JSON.parse(Taro.getStorageSync('userInfo'))
    // 获取选择的客户
    const pages = Taro.getCurrentPages()
    const currPage = pages[pages.length - 1] // 获取当前页面
    // 判断是否有跳转选择业务员
    if (currPage.data?.saleuserId && currPage.data?.saleuserId !== '') {
      setformData(val => ({
        ...val,
        sale_user_id: currPage.data?.saleuserId,
        sale_user_name: currPage.data?.saleuserName,
      }))
    }
    // 默认业务员
    if (currPage.data?.saleuserId == null) {
      setformData(e => ({
        ...e,
        sale_user_id: userInfo?.user_id,
        sale_user_name: userInfo?.user_name,
      }))
    }
  })

  const { fetchData: getDesc } = MpPurchaser()

  const handTitle = useCallback((e) => {
    setformData(val => ({ ...val, name: e }))
  }, [])

  const handName = useCallback((e) => {
    setformData(val => ({ ...val, short_name: e }))
  }, [])

  const handUsername = useCallback((e) => {
    setformData(val => ({ ...val, director: e }))
  }, [])

  const handUserPhone = useCallback((e) => {
    setformData(val => ({ ...val, phone: e }))
  }, [])

  const handAddress = useCallback((e) => {
    setformData(val => ({ ...val, address_detail: e }))
  }, [])

  // 客户类型数组
  const [list, setlist] = useState<any[]>([
    {
      id: 1,
      name: '布行',
      check: false,
    },
    {
      id: 2,
      name: '二批',
      check: false,
    },
    {
      id: 3,
      name: '制衣厂',
      check: false,
    },
  ])

  // 选择客户类型
  const handItem = (item) => {
    list.map((it) => {
      if (it.id === item.id) {
        it.check = true
      }
      else {
        it.check = false
      }
      return it
    })
    setlist([...list])
    setformData(val => ({ ...val, purchaser_type: item.id }))
  }
  // 备注操作
  const [remarkDesc, setremarkDesc] = useState('')
  const getInfo = async() => {
    Taro.showLoading({
      title: '请稍等...',
      mask: true,
    })
    const res = await getDesc({ id: router.params.id })
    setinfoObj(res.data)
    list.map((item) => {
      if (item.id == res.data.purchaser_type) {
        item.check = true
      }
      else {
        item.check = false
      }
      return item
    })
    setlist([...list])
    setformData({
      sale_user_id: res.data?.sale_user_id,
      sale_user_name: res.data?.sale_user_name,
      name: res.data?.name,
      short_name: res.data?.short_name,
      director: res.data?.director,
      phone: res.data?.phone,
      addressName: res.data?.province_name + res.data?.city_name + res.data?.district_name,
      address_detail: res.data?.address_detail,
      purchaser_type: res.data?.purchaser_type,
      district_id: res.data?.district_id,
    })
    setremarkDesc(res.data?.remark)
    let arr: any[] = []
    arr = [
      { id: res.data.province_id, name: res.data.province_name },
      { id: res.data.city_id, name: res.data.city_name },
      { id: res.data.district_id, name: res.data.district_name },
    ]
    setaddressArr([...arr])
    Taro.hideLoading()
  }

  const [showDesc, setShowDesc] = useState(false)
  const getRemark = useCallback(async(e) => {
    setShowDesc(false)
    setremarkDesc(e)
    // setformData((val) => ({ ...val, remark: e }))
  }, [])

  // 地址选择
  const [showSiteModal, setShowSiteModal] = useState(false)

  const handleSetSite = (ev) => {
    const addressName: any = []
    ev.forEach((v) => {
      addressName.push(v?.name)
    })
    if (ev.length === 3) {
      setShowSiteModal(false)
      setformData(val => ({ ...val, addressName: ev[0]?.name + ev[1]?.name + ev[2]?.name || '', district_id: ev[2]?.id }))
    }
  }

  const onClose = () => {
    setShowSiteModal(false)
  }
  useEffect(() => {
    if (router.params.type === 'edit') {
      getInfo()
    }
  }, [])
  const isDisabled = useMemo(() => {
    let empty: any = null
    if (typeof (formData) == 'undefined') { return }
    for (const key in formData) {
      if (key in formData) {
        if (formData[key] !== '' && typeof (formData[key]) !== 'undefined') {
          empty = false
        }
        else {
          empty = true
          break
        }
      }
    }
    return empty
  }, [formData])

  // 重置
  const handReset = () => {
    setformData({
      sale_user_id: '',
      sale_user_name: '',
      name: '',
      short_name: '',
      director: '',
      phone: '',
      addressName: '',
      address_detail: '',
      purchaser_type: '',
      remark: '',
      district_id: '',
    })
  }

  const { fetchData: postFetch } = MpPurchaserPost()
  const { fetchData: putFetch } = MpPurchaserPut()
  // 提交
  const handSure = async() => {
    // if (!isDisabled) return false
    const query = {
      ...formData,
      remark: remarkDesc,
      id: infoObj?.id,
    }
    if (router.params.type == 'add') {
      delete query.id
    }
    Taro.showModal({
      content: '确定要提交吗？',
      confirmText: '确认',
      cancelText: '取消',
      async success(res) {
        if (res.confirm) {
          const res = await (router.params.type == 'add' ? postFetch(query) : putFetch(query))
          Taro.showLoading({
            title: '请稍等...',
            mask: true,
          })
          if (res.msg === 'success') {
            Taro.showToast({
              title: '成功',
            })
            Taro.hideLoading()
            Taro.navigateBack({
              delta: 1,
            })
          }
          else {
            Taro.showToast({
              title: res.msg,
              icon: 'error',
            })
          }
        }
      },
    })
  }

  return (
    <>

      <View className={styles.mainBox}>
        <Form
          title="客户全称"
          handBlur={handTitle}
          placeholderFont="请输入全称"
          inputValue={formData?.name}
        ></Form>
        <Form
          title="客户简称"
          handBlur={handName}
          placeholderFont="请输入简称"
          inputValue={formData?.short_name}
        ></Form>
        <Form
          title="客户类型"
          showInput={false}
        >
          <View className={styles.flexBox}>
            {
              list.map((item, key) => {
                return (
                  <View key={key} className={classnames(item.check ? styles.activeBox : styles.itemBox)} onClick={() => handItem(item)}>{item.name}</View>
                )
              })
            }
          </View>
        </Form>
        <Form
          title="联系人"
          handBlur={handUsername}
          placeholderFont="请输入联系人"
          inputValue={formData?.director}
        ></Form>
        <Form
          title="联系电话"
          handBlur={handUserPhone}
          inputType="number"
          placeholderFont="请输入号码"
          maxlength={11}
          inputValue={formData?.phone}
        ></Form>
        <Form
          title="省市区"
          isDisabled
          showMore
          inputValue={formData?.addressName}
          placeholderFont="请选择省市区"
          handNav={() => setShowSiteModal(true)}
        ></Form>
        <Form
          title="详细地址"
          handBlur={handAddress}
          placeholderFont="请输入地址"
          inputValue={formData?.address_detail}
        ></Form>
        <Form
          title="业务员"
          isDisabled
          showMore
          placeholderFont="请选择业务员"
          handNav={() => goLink('/pages/saleuserPage/index')}
          showBorder={false}
          inputValue={formData?.sale_user_name}
        ></Form>
      </View>
      <DefaultBoxWithMemo title="备注信息" showMode modeName={`${'填写/修改备注'} >`} clickNode={() => setShowDesc(true)}>
        <View className={classnames(remarkDesc === '' ? styles.remarkFontactive : styles.remarkFont)}>{remarkDesc === '' ? '尚未备注信息' : remarkDesc}</View>
      </DefaultBoxWithMemo>
      <Popup show={showDesc} showTitle={false} onClose={() => setShowDesc(false)}>
        <Remark onSave={e => getRemark(e)} defaultValue={infoObj?.remark} showInput={!!showDesc} />
      </Popup>
      <Address addressOnChange={val => handleSetSite(val)} defaultValue={addressArr} addressOnClose={() => onClose()} show={showSiteModal} />
      <View className={styles.safeBox}></View>
      <View className={styles.bottomBox}>
        <Button className={styles.resetBox} onClick={() => { handReset() }}> 重置</Button >
        <Button className={classnames(isDisabled ? styles.button2 : styles.activeButton)} disabled={isDisabled} onClick={() => handSure()}> 确认</Button >
      </View>
    </>
  )
}
export default CustomerEditor
