import { Button, Input, Switch, Text, Textarea, View } from '@tarojs/components'
import Taro, { setNavigationBarTitle, useDidShow, useRouter } from '@tarojs/taro'
import { useEffect, useMemo, useState } from 'react'
import classnames from 'classnames'
import styles from './index.module.scss'
import FromList from '@/components/FromList'
import Address from '@/components/address'
import { alert } from '@/common/common'
import { MpPurchaserAddress, MpPurchaserAddressDelete, MpPurchaserAddressGet, MpPurchaserAddressPut } from '@/api/addressList'
import IconFont from '@/components/iconfont/iconfont'

const AddAddress = () => {
  const [itemList, setItemList] = useState<any[]>(
    [
      {
        title: '联系人',
        require: true,
        placeholderFont: '请输入收货人姓名',
        type: 'text',
        value: '',
      },
      {
        title: '加工厂',
        require: false,
        placeholderFont: '请输入加工厂（选填）',
        type: 'text',
        value: '',
      },
      {
        title: '联系方式',
        require: true,
        placeholderFont: '请输入联系方式',
        type: 'number',
        value: '',
        maxLength: 11,
      },
      {
        title: '收货地址',
        require: true,
        placeholderFont: '请选择/省/市/区',
        type: 'select',
        disabled: true,
        value: '',
      },
      {
        title: '详细地址',
        require: true,
        placeholderFont: '请输入详细地址（街道、门牌号等）',
        type: 'text',
        value: '',
      },
    ],
  )

  const [ischecked, setIsChecked] = useState(false)
  const [formData, setFormData] = useState({
    name: '',
    phone: '',
    site: '',
    siteArray: [],
    district_id: '',
    address_detail: '',
    is_default: false,
    id: '',
    factory: '',
  })
  const onChange = (eq) => {
    setIsChecked(eq.detail.value)
    setFormData(e => ({ ...e, is_default: eq.detail.value, address_detail: itemList[4].value }))
  }

  const router = useRouter()

  // 获取相应id的信息
  const { fetchData: infoFetch } = MpPurchaserAddressGet()
  const [infoObj, setinfoObj] = useState<any>()
  const getInfo = async() => {
    const res = await infoFetch({
      id: router.params.id,
    })
    if (res.data) {
      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 },
      ]
      setFormData({
        name: res.data.name,
        phone: res.data.phone,
        site: res.data.province_name + res.data.city_name + res.data.district_name,
        siteArray: arr as any,
        address_detail: res.data.address_detail,
        district_id: res.data.district_id,
        is_default: res.data.is_default,
        id: res.data.id,
        factory: res.data.factory,
        // purchaser_id: res.data.purchaser_id
      })
      setinfoObj(res.data)
      itemList.map((item) => {
        if (item.title === '联系人') {
          item.value = res.data.name
        }
        if (item.title === '联系方式') {
          item.value = res.data.phone
        }
        if (item.title === '收货地址') {
          item.value = `${res.data.province_name}${res.data.city_name}${res.data.district_name}`
        }
        if (item.title === '详细地址') {
          item.value = res.data.address_detail
        }
        if (item.title === '加工厂') {
          item.value = res.data.factory
        }
        return item
      })
      setItemList([...itemList])
      setIsChecked(res.data.is_default)
    }
  }
  // `${res.data.province_name} + ${res.data.city_name} + ${res.data.district_name}`
  useDidShow(() => {
    if (router.params.type === 'add') {
      setNavigationBarTitle({ title: '新增收货地址' })
    }
    else {
      setFormData(e => ({ ...e, id: router.params.id as any }))
      getInfo()
      setNavigationBarTitle({ title: '编辑收货地址' })
    }
  })
  const btnDisabled = useMemo(() => {
    let canShow = false
    const obj = itemList.filter((item) => {
      return item.require && (item.value !== '')
    })
    if (obj.length < 4) {
      canShow = true
    }
    else {
      canShow = false
    }
    return canShow
  }, [itemList])

  const [showSiteModal, setShowSiteModal] = useState(false)

  const handleSetSite = (ev: any) => {
    const addressName: any = []
    ev.forEach((v) => {
      addressName.push(v.name)
    })
    if (ev.length === 3) {
      itemList.map((it) => {
        if (it.type === 'select') {
          it.value = addressName
        }
        return it
      })
      setItemList([...itemList])
      setShowSiteModal(false)
    }
    setFormData({
      name: itemList[0]?.value,
      phone: itemList[2]?.value,
      site: addressName.join(' '),
      district_id: ev[ev.length - 1]?.id,
      is_default: ischecked,
      address_detail: itemList[4]?.value,
      id: infoObj?.id ? infoObj?.id : '',
      siteArray: ev,
      factory: itemList[1]?.value,
    })
  }

  useEffect(() => {
    setFormData(formData)
  }, [formData])

  useEffect(() => {
    setItemList(itemList)
  }, [itemList])
  const onClose = () => {
    setShowSiteModal(false)
  }

  const changeInput = (e, item) => {
    itemList.map((it) => {
      if (it.title === item.title) {
        it.value = e.detail.value
      }
      return it
    })
    setItemList([...itemList])
    setFormData(val => ({
      ...val, name: itemList[0].value, phone: itemList[2].value, address_detail: itemList[4].value, factory: itemList[1].value,
    }))
  }

  const showModal = (item) => {
    if (item.type === 'select') {
      setShowSiteModal(true)
    }
  }

  const navBack = () => {
    Taro.navigateBack({
      delta: 1,
    })
  }
  // 新增地址
  const { fetchData: addAddressFetch } = MpPurchaserAddress()
  const handAdd = async() => {
    // if (!btnDisabled) return false
    const res = await addAddressFetch({ ...formData, purchaser_id: Number(router.params.purchaser_id) })
    if (res.data) {
      Taro.showToast({
        title: '成功',
        icon: 'none',
      })
      navBack()
    }
    else {
      Taro.showToast({
        title: res.msg,
      })
    }
  }

  // 编辑地址
  const { fetchData: putFetch } = MpPurchaserAddressPut()
  const handEdit = async() => {
    // if (!btnDisabled) return false
    const res = await putFetch({ ...formData, purchaser_id: Number(router.params.purchaser_id), id: Number(infoObj?.id) })
    if (res.msg === 'success') {
      Taro.showToast({
        title: '成功',
        icon: 'none',
      })
      navBack()
    }
    else {
      Taro.showToast({
        title: res.msg,
      })
    }
  }
  // 删除地址
  const { fetchData: deleteFetch } = MpPurchaserAddressDelete()
  const handleDelete = async() => {
    Taro.showModal(({
      title: '提示',
      content: '是否删除地址？',
      async success(ev) {
        if (ev.confirm) {
          Taro.showLoading({
            title: '请稍等...',
          })
          const result = await deleteFetch({ id: Number(formData.id) })
          if (result.success) {
            alert.success('删除成功')
            Taro.hideLoading()
            Taro.navigateBack({
              delta: 1,
            })
          }
          else {
            alert.error(result.msg)
          }
        }
      },
    }))
  }
  return (
    <>
      <View className={styles.main}>
        {itemList.map((item, index) => {
          return (
            <View className={styles.itemBox} key={index}>
              <View className={styles.leftBox}>
                {item.title}
                {
                  item.require && <Text style={{ color: 'red' }}>*</Text>
                }
              </View>
              <Input
                placeholderStyle={styles.placeholderStyle}
                maxlength={item.maxLength ? 11 : 100}
                onBlur={e => changeInput(e, item)}
                type={item.type}
                onClick={() => showModal(item)}
                style={{ width: '212px' }}
                disabled={item.disabled}
                placeholder={item.placeholderFont}
                value={item.value}
                className={styles.inputClass}
              ></Input>
              {
                item.type === 'select' && <IconFont name="icon-chakanquanbukehu" color="#000000" size={40}></IconFont>
              }
            </View>
          )
        })}

      </View>
      <View className={styles.checkBox}>
        <View className={styles.leftCheck}>
          <View className={styles.topFont}>设置默认地址</View>
          <View className={styles.bottomFont}>提醒：下单会优先使用该地址</View>
        </View>
        <Switch checked={ischecked} color="#337fff" onChange={(e) => { onChange(e) }} style={{ marginRight: '20rpx' }} />
      </View>

      {
        router.params.type === 'add'
                && <View className={styles.bottomBox}>
                  <Button disabled={btnDisabled} onClick={() => handAdd()} className={classnames(btnDisabled ? styles.btn : styles.adtiveBtns)}>保存</Button>
                </View>
      }
      {
        router.params.type === 'edit'
                && <View className={styles.bottomBox}>
                  <Button className={styles.delectBox} onClick={() => handleDelete()}>删除</Button>
                  <Button onClick={() => handEdit()} disabled={btnDisabled} className={classnames(btnDisabled ? styles.nobtn : styles.sureBox)} >确认</Button>
                </View>
      }
      <Address addressOnChange={handleSetSite} defaultValue={formData.siteArray} addressOnClose={() => onClose()} show={showSiteModal} />

    </>
  )
}

export default AddAddress
