
import { Button, Input, Text, Textarea, View } from '@tarojs/components'
import Taro, { getCurrentPages, useRouter } from '@tarojs/taro'
import { useEffect, useState } from 'react'
import FromList from '@/components/FromList'
import Address from '@/components/address'
import { alert, retrieval } from '@/common/common'
import { companyDetailApi, companyUpdateApi } from '@/api/company'
import './index.scss'
import useLogin from '@/use/useLogin'

const Company = () => {
  useLogin()
  const [showSiteModal, setShowSiteModal] = useState(false)
  const handleSelectSite = () => {
    setShowSiteModal(true)
  }
  // 保存
  const [formData, setFormData] = useState({
    address_detail: '',
    city_id: 0,
    company_id: 0,
    company_long_name: '',
    company_name: '',
    company_type: [
      0,
    ],
    director: '',
    district_id: 0,
    phone: '',
    province_id: 0,
    site: '',
    siteArray: [],
  })
  // 获取公司信息
  const { fetchData: getFromData } = companyDetailApi()
  const getData = async() => {
    const result = await getFromData()
    console.log(result.data, '===')

    setFormData({
      ...result.data,

    })
  }
  useEffect(() => {
    getData()
  }, [])

  const rules = {
    company_name: [{
      message: '请输入公司名称',
    }],
    company_long_name: [{
      message: '请输入公司全称',
    }],
    director: [{
      message: '请输入联系人',
    }],
    phone: [{
      message: '请输入正确的电话号码', regex: /^1[3|5|6|9|2|8|7]\d{9}$/,
    }],
    district_id: [{
      message: '请选择地址',
    }],
    address_detail: [{
      message: '请输入详细地址',
    }],
  }
  const { fetchData: saveFetch } = companyUpdateApi()
  const handleSave = () => {
    retrieval(formData, rules).then(async() => {
      const result = await saveFetch({
        address_detail: formData.address_detail,
        city_id: formData.city_id,
        company_id: formData.company_id,
        company_long_name: formData.company_long_name,
        company_name: formData.company_name,
        company_type: formData.company_type,
        director: formData.director,
        district_id: formData.district_id,
        phone: formData.phone,
        province_id: formData.province_id,
      })
      if (result.success) {
        Taro.eventCenter.trigger('company:detail')
        Taro.navigateBack()
        alert.success('保存成功')
      }
      else {
        alert.error(result.msg)
      }
    }).catch((message) => {
      alert.none(message)
    })

    Taro.navigateBack()
  }
  // 单选
  const radioData = ['布行', '二批', '制衣厂']
  const [radioActive, setRadioActive] = useState(0)
  const handleActiveRadio = (index: number) => {
    setRadioActive(index)
  }
  // 设置选择地址
  const handleSetSite = (ev: any) => {
    if (ev.length >= 3) {
      setFormData({
        ...formData,
        siteArray: ev,
        site: ev.map(item => `${item.name} `),
        province_id: ev[0]?.id,
        city_id: ev[1]?.id,
        district_id: ev[ev.length - 1]?.id,
      })
    }
    else {
      alert.error('请选择完整地址')
    }
  }
  // 监听表单完善
  const [hozon, setHozon] = useState(false)
  useEffect(() => {
    if (retrieval) {
      retrieval(formData).then(() => setHozon(true)).catch(() => setHozon(false))
    }
  }, [formData])

  return (
    <View className="company">
      <FromList onInput={(ev: any) => setFormData({ ...formData, company_name: ev.detail.value })} value={formData.company_name} label="公司名称" placeholder="请输入公司名称" />
      <FromList onInput={(ev: any) => setFormData({ ...formData, company_long_name: ev.detail.value })} value={formData.company_long_name} label="公司全称" placeholder="请输入公司全称" />
      <FromList value={formData.company_type} label="公司类型">
        <View className="form-radio">
          {
            radioData.map((item, index) => {
              return <View onClick={() => handleActiveRadio(index)} className={radioActive == index ? 'form-radio-active' : ''} key={index}>{item}</View>
            })
          }
        </View>
      </FromList>
      <FromList onInput={(ev: any) => setFormData({ ...formData, director: ev.detail.value })} value={formData.director} label="联系人" placeholder="请输入联系人" />
      <FromList onInput={(ev: any) => setFormData({ ...formData, phone: ev.detail.value })} value={formData.phone} label="联系方式" placeholder="请输入联系方式" />
      <FromList value={formData.site} onClick={handleSelectSite} label="收货地址" type="select" placeholder="请选择/省/市/区" />
      <FromList onInput={(ev: any) => setFormData({ ...formData, address_detail: ev.detail.value })} value={formData.address_detail} label="详细地址" type="textarea" placeholder="请输入详细地址（街道、门牌号等）" />

      <Button style={{ background: hozon ? '#007aff' : '' }} hoverClass="none" className="save-button" onClick={handleSave}>保存</Button>
      {/* <Address addressOnClose={()=>setShowSiteModal(false)} show={showSiteModal}/> */}
      <Address addressOnSelect={handleSetSite} defaultValue={[{ name: '广东省', id: 193, level: 2 }, { name: '佛山市', id: 202, level: 3 }, { name: '高明区', id: 204, level: 4 }]} addressOnClose={() => setShowSiteModal(false)} show={showSiteModal} />
    </View>
  )
}

export default Company
