import { Button, Input, Text, Textarea, View } from '@tarojs/components'
import Taro, { setNavigationBarTitle, useRouter } from '@tarojs/taro'
import { useEffect, useState } from 'react'
import { alert, retrieval } from '@/common/common'
import Address from '@/components/address'
import FromList from '@/components/FromList'
import './index.scss'
import { addressAddApi, addressDetailApi, addressEditApi } from '@/api/addressManager'
import useLogin from '@/use/useLogin'

const AddressAdd = () => {
  useLogin()
  const [showSiteModal, setShowSiteModal] = useState(false)
  const { type, id } = useRouter().params
  // 保存
  const [formData, setFormData] = useState({
    name: '',
    phone: '',
    site: '',
    siteArray: [],
    district_id: '',
    address_detail: '',
    is_default: false,
    id: 0,
  })
  // 获取编辑地址信息
  const { fetchData: getFromData } = addressDetailApi()
  const initalFormData = async() => {
    const detail = await getFromData({ id })
    const { province_id, province_name, city_id, city_name, district_id, district_name } = detail.data
    const siteArray = [{ id: province_id, name: province_name }]
    city_id && siteArray.push({ id: city_id, name: city_name })
    district_id && siteArray.push({ id: district_id, name: district_name })
    setFormData({
      name: detail.data.name,
      phone: detail.data.phone,
      site: siteArray.map(item => item.name).join(' '),
      siteArray: siteArray as any,
      district_id: detail.data.district_id,
      address_detail: detail.data.address_detail,
      is_default: detail.data.is_default,
      id: detail.data.id,
    })
  }

  const { fetchData } = addressAddApi()
  const { fetchData: editFetch } = addressEditApi()

  const rules = {
    name: [
      {
        message: '请输入正确收货人姓名',
        // validator: (value:any, rule:any)=>{ // 自定义验证，返回true表示匹配到了(错误)
        //   return value.length>5;
        // }
      },
    ],
    phone: [
      {
        message: '请输入正确的电话号码',
        regex: /^1[3|5|6|9|2|8|7]\d{9}$/,
      },
    ],
    district_id: [
      {
        message: '请选择地址',
      },
    ],
    address_detail: [
      {
        message: '请输入详细地址',
      },
    ],
  }
  const handleSave = () => {
    retrieval(formData, rules)
      .then(async() => {
        const result
          = type == 'add'
            ? await fetchData({
              name: formData.name,
              phone: formData.phone,
              district_id: formData.district_id,
              address_detail: formData.address_detail,
              is_default: formData.is_default,
            })
            : await editFetch({
              name: formData.name,
              phone: formData.phone,
              district_id: formData.district_id,
              address_detail: formData.address_detail,
              is_default: formData.is_default,
              id: formData.id,
            })
        if (result.success) {
          Taro.eventCenter.trigger('addressList:refresh')
          Taro.navigateBack()
          alert.success('保存成功')
        }
        else {
          alert.error(result.msg)
        }
      })
      .catch((message) => {
        alert.none(message)
      })
  }
  useEffect(() => {
    if (type == 'add') {
      setNavigationBarTitle({ title: '新增收货地址' })
    }
    else {
      initalFormData()
      setNavigationBarTitle({ title: '编辑收货地址' })
    }
  }, [])
  // 监听表单完善
  const [hozon, setHozon] = useState(false)
  useEffect(() => {
    if (retrieval) {
      retrieval(formData)
        .then(() => setHozon(true))
        .catch(() => setHozon(false))
    }
  }, [formData])
  // 设置选择地址
  const handleSetSite = (ev: any) => {
    if (ev.length > 0) {
      setFormData({
        ...formData,
        siteArray: ev,
        site: ev.map(item => `${item.name} `),
        district_id: ev[ev.length - 1]?.id,
      })
    }
    else {
      alert.error('请选择地址')
    }
  }

  return (
    <View className="add-address">
      <FromList
        onInput={(ev: any) => setFormData({ ...formData, name: ev.detail.value })}
        value={formData.name}
        label="联系人"
        placeholder="请输入收货人姓名"
      />
      <FromList
        primordialType="number"
        onInput={(ev: any) => setFormData({ ...formData, phone: ev.detail.value })}
        value={formData.phone}
        label="联系方式"
        placeholder="请输入联系方式"
      />
      <FromList value={formData.site} onClick={() => setShowSiteModal(true)} label="收货地址" type="select" placeholder="请选择/省/市/区" />
      <FromList
        onInput={(ev: any) => setFormData({ ...formData, address_detail: ev.detail.value })}
        value={formData.address_detail}
        label="详细地址"
        type="textarea"
        placeholder="请输入详细地址（街道、门牌号等）"
      />
      <View className="add-address-default">
        <Text>设为默认地址</Text>
        <View onClick={() => setFormData({ ...formData, is_default: !formData.is_default })}>
          {formData.is_default
            ? (
              <View className="add-address-default-active">
                <Text className="iconfont icon-tick" />
              </View>
            )
            : (
              <View className="add-address-default-noactive"></View>
            )}
        </View>
      </View>

      <Button style={{ background: hozon ? '#007aff' : '' }} hoverClass="none" className="add-address-save" onClick={handleSave}>
        保存
      </Button>
      <Address addressOnChange={handleSetSite} defaultValue={formData.siteArray} addressOnClose={() => setShowSiteModal(false)} show={showSiteModal} />
    </View>
  )
}

export default AddressAdd
