import React from 'react'
import { Image, Text, View, Input, Label } from '@tarojs/components'
import './index.scss'

import { useEffect } from 'react';
import { useState } from 'react';
import backNav from '@/images/backNav.png'
import next from '@/images/next.png'
import uncheck from '@/images/uncheck.png'
import checked from '@/images/checked.png'
import Taro from '@tarojs/taro';
import { useRouter } from '@tarojs/taro';
import { Button, Textarea, Address } from '@nutui/nutui-react-taro';
import { cities, createAddress, getAddress, updateAddress } from '../../utils/api';
import { useCallback } from 'react';
import { backOrGo, closeLoading, errorNotice, loading, redirectTo } from '../../utils/utils';



function Index() {

  const param = useRouter().params
  const [id] = useState(param.id)
  const [home] = useState(param.home)
  const [addrId, setAddrId] = useState([])
  const [isDefault, setIsDefault] = useState(false)
  const [user, setUser] = useState('')
  const [phone, setPhone] = useState('')
  const [addrInfo, setAddrInfo] = useState('')


  const [text, setText] = useState('请选择地址')
  const [normal, setNormal] = useState(false)
  const [cityList, setCityList] = useState([])
  const [province, setProvince] = useState([])

  const [city, setCity] = useState([])

  const [country, setCountry] = useState([])
  const [town, setTown] = useState([])

  const [address, setAddress] = useState({
    province,
    city,
    country,
    town,
    addressIdStr: '0_0_0_0',
  })

  useEffect(() => {
    cities().then(res => {
      if (!res) return
      setCityList(res.items)
      setProvince(res.items?.filter(item => item.deep == 0))
    })
  }, [])

  useEffect(() => {
    if (!id) return
    getAddress().then(re => {
      if (!re) return
      const data = re.items.filter(item => item.id == id)
      if (data.length < 1) return
      const addr = data[0]
      console.log(addr)
      setAddrId([addr.province_id, addr.city_id, addr.county_id])
      setText(`${addr.province.name}${addr.city.name}${addr.county.name}`)
      setAddrInfo(addr.address)
      setUser(addr.recipient_name)
      setPhone(addr.recipient_phone)
      setAddress({ province: addr.province, city: addr.city, country: addr.county, town: [], addressIdStr: `${addr.province_id}_${addr.city_id}_${addr.county_id}_0` })
      if (addr.province_id && addr.city_id) {
        cities(addr.province_id).then(r => {
          setCity(r.items)
        })
      }
      if (addr.city_id && addr.county_id) {
        cities(addr.city_id).then(r => {
          console.log(r.items, addr, addrId)
          setCountry(r.items)
        })
      }
    })
  }, [id])

  const onChange = async (cal) => {
    const re = await cities(cal.value.id)
    const d = re.items
    if (!d.length) {
      setNormal(false)
      return
    }
    setTimeout(() => {
      switch (cal.next) {
        case 'city':

          setCity(d)
          break;
        case 'country':
          setCountry(d)
          break;
        default:
          setNormal(false)
      }
    }, 200)
  }
  const close = (val) => {
    setNormal(false)
    if (val.data && !!val.data.addressStr) {
      setText((val.data).addressStr)
      setAddress({ province: val.data.province, city: val.data.city, country: val.data.country, town: val.data.town, addressIdStr: val.data.addressIdStr })
    }
  }

  // 返回页面
  const backFn = () => {
    Taro.getCurrentPages().length > 0 && Taro.navigateBack({ delta: 1 })
  }

  const submit = async () => {
    const addressId = address.addressIdStr.split('_')
    if (!phone || !user || !addrInfo || address.addressIdStr == '0_0_0_0') {
      errorNotice('请填写地址完整信息')
      return
    }

    if (user.length < 2) {
      errorNotice('收货人姓名不能小于2个字符')
      return
    }

    if (addrInfo.length < 6) {
      errorNotice('详细地址信息不能小于6个字符')
      return
    }

    const data = {
      zipcode: '000000',
      recipient_phone: phone,
      recipient_name: user,
      address: addrInfo,
      province_id: Number(addressId[0]),
      city_id: Number(addressId[1]),
      county_id: Number(addressId[2]),
      is_default: isDefault
    }

    if (id) {
      loading('地址编辑中...')
      const re = await updateAddress(id, data)
      closeLoading()
      if (re) {
        backOrGo('/pages/address/index')
      }
      return
    }

    loading('地址新增中...')
    const re = await createAddress(data)
    closeLoading()
    if (re) {
      backOrGo('/pages/address/index')
    }
  }

  return (
    <View className='addr-c-container'>
      <View className='addr-detail-title'>
        <Image src={backNav} className="square-35 absolute left-10 nav-icon" onClick={backFn} />
        {
          home ? '我的地址' : "新增地址"
        }

      </View>

      <View className='addr-c-body' >
        <View className='addr-c-item'>
          <View className='addr-c-form'>
            <View className='addr-c-form-name'>收货人</View>
            <Input className='addr-c-form-input' placeholder='请输入收货人' value={user} onInput={(e) => {
              setUser(e.detail.value)
            }} />
          </View>
          <View className='addr-c-form'>
            <View className='addr-c-form-name'>电话</View>
            <Input className='addr-c-form-input' placeholder='请输入收货电话' value={phone} onInput={(e) => {
              setPhone(e.detail.value)
            }} />
          </View>
          <View className='addr-c-form'>
            <View className='addr-c-form-name'>所在地区</View>
            <View className='flex justify-between items-center addr-c-form-input' onClick={() => { setNormal(true) }}>
              <Label>{text}</Label>
              <Image src={next} className='next-icon' />
            </View>
          </View>
          <View className='addr-c-form bt-none'>
            <View className='addr-c-form-name '>详细地址</View>
          </View>
          <Textarea placeholder='请输入详细地址' autosize rows="4" maxlength={100} defaultValue={addrInfo} onChange={(e) => {
            setAddrInfo(e)
          }} />
        </View>
        <View className=' mt-22 addr-c-item'>
          <View className='addr-c-form  bt-none' onClick={() => {
            setIsDefault(x => !x)
          }}>
            <View className='text-black'>设为默认地址</View>
            <Image src={isDefault ? checked : uncheck} className='w-6 h-6' />
          </View>
        </View>
      </View>
      <Button className='addr-c-btn' onClick={submit} >保存地址</Button>

      <Address
        modelValue={normal}
        modelSelect={addrId}
        province={province}
        city={city}
        country={country}
        customAddressTitle="请选择所在地区"
        onChange={onChange}
        onClose={close}
      />
    </View>
  )
}

export default Index
