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

export default ()=>{
  const [showSiteModal, setShowSiteModal] = useState(false);
  const {type,id} = useRouter().params;
  useEffect(()=>{
    if(type=="add"){
      setNavigationBarTitle({title:"新增收货地址"})
    }else{
      // initalFormData();
      setNavigationBarTitle({title:"编辑收货地址"})
    }
  },[])
  // 获取编辑地址信息
  const {fetchData: getFromData} = addressDetailApi()
  const initalFormData = async ()=>{
    const detail = await getFromData({id});
    const siteArray = []
    // setFormData({
    //   name: detail.data.name,
    //   phone: detail.data.phone,
    //   site: detail.data.,
    //   siteArray: [],
    //   district_id: detail.data.district_id,
    //   address_detail: detail.data.address_detail,
    //   is_default: false
    // })
  }
  
  const {fetchData, state} = addressAddApi()
  // 保存
  const [formData, setFormData] = useState({
    name: "",
    phone:"",
    site:"",
    siteArray: [],
    district_id:"",
    address_detail: "",
    is_default: false
  })
  const rules = {
    name: [{
      message: "请输入收货人姓名"
    }],
    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 = await fetchData({
        name: formData.name,
        phone:formData.phone,
        site:formData.site,
        district_id:formData.district_id,
        address_detail: formData.address_detail,
        is_default: formData.is_default
      });
      if(result.success){
        alert.success("保存成功")
      }else{
        alert.error(result.msg);
      }
      // Taro.navigateBack();
    }).catch((message)=>{
      alert.none(message)
    })
  }
  // 监听表单完善
  const [hozon, setHozon] = useState(false);
  useEffect(()=>{
    if(retrieval){
      retrieval(formData).then(()=>setHozon(true)).catch(()=>setHozon(false))
    }
  },[formData])
  // 设置选择地址
  const handleSetSite = (ev:any)=>{
    console.log(ev);
    
    if(ev.length>=3){
      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 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 addressOnSelect={handleSetSite}  defaultValue={[ {name: "广东省", id: 193}, {name: "佛山市", id: 202}, {name: "高明区", id: 204}]} addressOnClose={()=>setShowSiteModal(false)} show={showSiteModal}/>
    </View>
  )
}
