import { Button, Input, Text, Textarea, View } from '@tarojs/components'
import Taro, { setNavigationBarTitle, showModal, useRouter } from '@tarojs/taro'
import { useEffect, useState } from 'react'
import { weightAddApi, weightDeleteApi, weightDetailApi, weightEditApi } from '@/api/weightList'
import FromList from '@/components/FromList'
import { alert, retrieval } from '@/common/common'
import './index.scss'
import useLogin from '@/use/useLogin'

export default () => {
  useLogin()
  const { type, id } = useRouter().params
  useEffect(() => {
    if (type == 'add') {
      setNavigationBarTitle({ title: '添加码单信息' })
    }
    else {
      initalFormData()
      setNavigationBarTitle({ title: '修改码单信息' })
    }
  }, [])
  // 获取编辑码单信息
  const { fetchData: getFromData } = weightDetailApi()
  const initalFormData = async() => {
    const detail = await getFromData({ id })
    setFormData({
      title: detail.data.title,
      purchaser_name: detail.data.purchaser_name,
      phone: detail.data.phone,
      is_default: detail.data.is_default,
      id: detail.data.id,
    })
  }
  // 保存
  const [formData, setFormData] = useState({
    title: '',
    purchaser_name: '',
    phone: '',
    is_default: false,
    id: 0,
  })
  const rules = {
    title: [
      {
        message: '请输入抬头',
      },
    ],
    purchaser_name: [
      {
        message: '请输入客户名称',
      },
    ],
    phone: [
      {
        message: '请输入正确的电话号码',
        regex: /^1[3|5|6|9|2|8|7]\d{9}$/,
      },
    ],
  }
  const { fetchData } = weightAddApi()
  const { fetchData: editFetch } = weightEditApi()
  const handleSave = () => {
    retrieval(formData, rules)
      .then(async() => {
        const result
          = type == 'add'
            ? await fetchData({
              title: formData.title,
              purchaser_name: formData.purchaser_name,
              phone: formData.phone,
              is_default: formData.is_default,
            })
            : await editFetch({
              title: formData.title,
              purchaser_name: formData.purchaser_name,
              phone: formData.phone,
              is_default: formData.is_default,
              id: formData.id,
            })
        if (result.success) {
          Taro.eventCenter.trigger('weightList:refresh')
          Taro.navigateBack()
          alert.success('保存成功')
        }
        else {
          alert.error(result.msg)
        }
      })
      .catch((message) => {
        alert.none(message)
      })
  }
  // 监听表单完善
  const [hozon, setHozon] = useState(false)
  useEffect(() => {
    if (retrieval) {
      retrieval(formData)
        .then(() => setHozon(true))
        .catch(() => setHozon(false))
    }
  }, [formData])

  const { fetchData: deleteFetch } = weightDeleteApi()
  const handleDelete = () => {
    showModal(({
      title: '提示',
      content: '是否删除码单？',
      async success(ev) {
        if (ev.confirm) {
          const result = await deleteFetch({ id: formData.id })
          if (result.success) {
            alert.success('删除成功')
            Taro.eventCenter.trigger('weightList:refresh')
            Taro.navigateBack()
          }
        }
      },
    }))
  }
  const handleUpdate = () => {
    if (type === 'add') {
      setFormData(() => ({ title: '', purchaser_name: '', phone: '', is_default: false, id: 0 }))
    }
    else {
      handleDelete()
    }
  }

  return (
    <View className="add-code-header-main">
      <View className="add-address">
        <FromList
          onInput={(ev: any) => setFormData({ ...formData, title: ev.detail.value })}
          value={formData.title}
          label="公司抬头"
          placeholder="请输入码单显示抬头信息"
        />
        <FromList
          onInput={(ev: any) => setFormData({ ...formData, purchaser_name: ev.detail.value })}
          value={formData.purchaser_name}
          label="客户名称"
          placeholder="请输入码单显示客户名称"
        />
        <FromList
          onInput={(ev: any) => setFormData({ ...formData, phone: ev.detail.value })}
          value={formData.phone}
          label="电话号码"
          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>
        <View className="weight_bottom_btn_con">
          <View className="weight_bottom_btn">
            <Button hoverClass="none" className="add-address-save" onClick={handleUpdate}>
              {type === 'add' ? '取消' : '删除'}
            </Button>
            <Button hoverClass="none" className="add-address-save" onClick={handleSave}>
              {type === 'add' ? '提交' : '修改'}
            </Button>
          </View>
          <View className="common_safe_area_y"></View>
        </View>

      </View>
    </View>

  )
}
