import { Button, Image, Picker, Text, Textarea, View } from '@tarojs/components'
import Taro, { chooseMedia } from '@tarojs/taro'
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { alert, goLink, isEmptyObject, retrieval } from '@/common/common'
import Popup from '@/components/popup'
import { companyTypeApi, portraitUpdateApi, realNameUpdateApi } from '@/api/user'
import { companyDetailApi, companyUpdateApi } from '@/api/company'
import './index.scss'
import ModifyModal from './components/ModifyModal'
import useLogin from '@/use/useLogin'
import { useSelector } from '@/reducers/hooks'
import useUploadCDNImg from '@/use/useUploadImage'
import { IMG_CND_Prefix } from '@/common/constant'
import useUserInfo from '@/use/useUserInfo'

export default () => {
  const { getPhoneNumber, getAdminUserInfo } = useLogin()
  const { adminUserInfo } = useSelector(state => state.userInfo)
  // 用户信息
  useEffect(() => {
    setFormData({
      ...formData,
      ...(adminUserInfo as any),
    })
  }, [adminUserInfo])
  useEffect(() => {
    setFormData({
      ...(adminUserInfo as any),
      company_type_index: 0,
    })
    getCompanyTypeData()
  }, [])
  // 表单数据
  const [formData, setFormData] = useState<typeof adminUserInfo>(adminUserInfo)
  // 昵称修改保存
  const { fetchData: realNameUpdateFetch } = realNameUpdateApi()
  const rules = {
    text: [
      {
        message: '请输入',
      },
    ],
  }
  const { fetchData: saveFetch } = companyUpdateApi()
  const { fetchData: getCompanyFetch } = companyDetailApi()
  const handleTextareaSave = async(text, type) => {
    retrieval({ text }, rules)
      .then(async() => {
        let result
        if (type == 'Ickname') {
          result = await realNameUpdateFetch({ real_name: text })
        }
        else {
          const params = await getCompanyFetch()
          result = await saveFetch({
            ...params.data,
            company_name: text,
          })
        }
        if (result.success) {
          getAdminUserInfo()
          ;(ModifyIcknameEl.current as any).setModalShow(false)
          ;(ModifyCompanyNameEl.current as any).setModalShow(false)
          alert.success('保存成功')
        }
        else {
          alert.none(result.msg)
        }
      })
      .catch((message) => {
        alert.none(message)
      })
  }
  // Taro.eventCenter.on('message:detail', (message) => console.log(message))
  // 面面跳转
  const onNavigate = (url: string) => {
    goLink(url)
  }
  // 肖像编辑
  const { fetchData: portraitUpdateFetch } = portraitUpdateApi()
  const { getWxPhoto } = useUploadCDNImg()
  const handleSelectRortrait = () => {
    Taro.showModal({
      title: '提示',
      content: '是否确定更改头像？',
      showCancel: true,
      async success(ev) {
        if (ev.confirm) {
          const result = await getWxPhoto('mall')
          const portraitUpdateResult = await portraitUpdateFetch({
            avatar_url: IMG_CND_Prefix + (result as any).url,
          })
          if (portraitUpdateResult.success) {
            getAdminUserInfo()
            alert.success('保存成功')
          }
          else {
            alert.none(portraitUpdateResult.msg)
          }
        }
      },
    })
  }
  const mGetPhoneNumber = (ev) => {
    if (ev.detail?.code) {
      getPhoneNumber(ev.detail.code)
    }
    else {
      alert.none('绑定失败!')
    }
  }
  const ModifyIcknameEl = useRef(null)
  const ModifyCompanyNameEl = useRef(null)
  // 获取企业类型
  const { fetchData: companyTypeFetch, state: companyTypeData } = companyTypeApi()
  const getCompanyTypeData = async() => {
    const reuslt = await companyTypeFetch()
    if (reuslt.success) {
      reuslt.data?.list?.every((item, index) => {
        if (item.id == (adminUserInfo as any).purchaser_type) {
          setFormData({
            ...(adminUserInfo as any),
            company_type_index: index,
          })
          return false
        }
        return true
      })
    }
  }
  // 修改企业类型
  const handleCompanyType = async(ev) => {
    const { value } = ev.detail
    const item = companyTypeData.data.list && companyTypeData.data.list[value]
    if (item) {
      if (item.id == 0) { return alert.error('请选择类型') }
      const params = await getCompanyFetch()
      const result = await saveFetch({
        ...params.data,
        purchaser_type: item.id,
      })
      if (result.success) {
        getAdminUserInfo()
        alert.success('保存成功')
      }
      else {
        alert.none(result.msg)
      }
    }
  }

  const { removeToken, removeSessionKey, removeUserInfo } = useUserInfo()
  const outLogin = () => {
    removeToken()
    removeSessionKey()
    removeUserInfo()
    goLink('/pages/index/index', {}, 'switchTab')
  }

  const comanyTypeDataFormat = useMemo(() => {
    if (companyTypeData.data.list) {
      return companyTypeData.data.list?.map((item) => {
        if (item.id == 0) { item.name = '--请选择类型--' }
        return item
      })
    }
    else {
      return []
    }
  }, [companyTypeData])

  return (
    <View className="user-edit">
      <View onClick={handleSelectRortrait} className="user-edit-portrait">
        <Image src={(formData as any)?.avatar_url} />
        <View>点击编辑头像</View>
      </View>
      <View className="user-edit-content">
        <UserEditList
          onClick={() => (ModifyIcknameEl.current as any).setModalShow(true)}
          data={(formData as any)?.user_name}
          label="昵称"
          placeholder="请输入"
          icon=""
        />
        <UserEditList label="手机号" placeholder="去绑定" icon="">
          {(formData as any)?.phone
            ? (
              <View className="user-edit-content-phone">
                <View>{(formData as any)?.phone}</View>
              </View>
            )
            : (
              <Button className="user-edit-content-bindphone" openType="getPhoneNumber" onGetPhoneNumber={mGetPhoneNumber}>
              去绑定
              </Button>
            )}
        </UserEditList>
      </View>
      <View className="user-edit-content">
        <UserEditList
          onClick={() => (ModifyCompanyNameEl.current as any).setModalShow(true)}
          data={(formData as any)?.company_name}
          label="组织名称"
          placeholder="待绑定"
          icon=""
        />
        {/* <UserEditList label="组织类型" placeholder="完善公司/组织信息" icon="">
          <Picker mode="selector" range={comanyTypeDataFormat as any} rangeKey="name" value={(formData as any)?.purchaser_type} onChange={handleCompanyType}>
            {formData?.purchaser_type_name}
          </Picker>
        </UserEditList> */}
        <UserEditList label="我的认证" placeholder="待绑定" icon="" useIcon="true">
          <View className={`user-edit-content-company ${(formData as any)?.authentication_status == 4 && 'user-edit-content-company-adopt'}`}>
            <Text className="iconfont " /> {(formData as any)?.authentication_status == 4 ? '已认证' : '未认证'}
          </View>
        </UserEditList>
        <UserEditList label="创建人" data={(formData as any)?.founder_user_name} placeholder="完善公司/组织信息" icon="" useIcon="true" />
      </View>
      <Button hoverClass="none" className="user-edit-logout" onClick={outLogin}>
        退出当前账号
      </Button>

      <ModifyModal title="修改昵称" ref={ModifyIcknameEl} value={(formData as any)?.user_name} save={value => handleTextareaSave(value, 'Ickname')} />
      <ModifyModal
        title="修改名称"
        ref={ModifyCompanyNameEl}
        value={(formData as any)?.company_name}
        save={value => handleTextareaSave(value, 'companyName')}
      />
    </View>
  )
}

// 列表
const UserEditList = memo((props: any) => {
  return (
    <View onClick={props.onClick} className="user-edit-list">
      <View className="user-edit-list-left">{props.label}</View>
      <View className="user-edit-list-right">
        <View>{props.children ? props.children : props.data ? props.data : <View className="user-edit-list-right-placeholder">{props.placeholder}</View>}</View>
        {!props.useIcon && <Text className="iconfont icon-a-moreback"></Text>}
      </View>
    </View>
  )
})
