import React, { useState } from 'react'
import useRequest from '@ahooksjs/use-request/es'

import { message, Upload } from 'antd'
import type { UploadChangeParam } from 'antd/es/upload'
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface'

import { default as EditSvg } from 'assets/edit.svg'
import { default as CameraSvg } from 'assets/camera.svg'
import VipDay from 'assets/vipday.png'
import VipMonth from 'assets/vipmonth.png'

import ValidateLogin2p from 'components/ValidateLogin2p'
import { useLogin2p } from 'Login2p/Login2pContext'
import ActivityComponent from './components/Activity.component'
import OrderComponent from './components/Order.component'
import CollectionComponent from './components/Collection.component'
import FootPrintComponent from './components/FootPrint.component'
import CommentComponent from './components/Comment.component'
import QuestionComponent from './components/Question.component'
import ProductInteriorComponent from './components/ProductInterior.component'
import ApplyAdivise from './components/ApplyAdivise'
import ApplyPhoneNumber from './components/ApplyPhoneNumber'
import { PersonalService } from './Personal.service'
import { MaterialService } from 'Material/Material.service'
import { INewPermissionType } from 'Material/components/NoPermission'
import ApplyPermission from 'Material/components/ApplyPermission'
import styles from './css/PersonalIndex.module.scss'
enum IMyMenuType {
  Schedule = 1,
  Collection = 2,
  Footprint = 3,
  Comment = 4,
  Question = 5,
  ProductInterior = 6,
  Advise = 7,
  Order = 8
}

const beforeUpload = (file: RcFile) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!')
  }
  // const isLt2M = file.size / 1024 / 1024 < 2
  // if (!isLt2M) {
  //   message.error('Image must smaller than 2MB!')
  // }
  return isJpgOrPng
}

/**个人中心 */
const PersonalIndex: React.FC = () => {
  const login2p = useLogin2p()
  const [actMenu, setActMenu] = useState<number>(IMyMenuType.Schedule)
  const [visibleApply, setVisibleApply] = useState(false)

  const [menuOption, setMenuOption] = useState<{ key: IMyMenuType; name: string }[]>([
    { key: IMyMenuType.Schedule, name: '活动日程' },
    { key: IMyMenuType.Order, name: '支付订单' },
    { key: IMyMenuType.Collection, name: '我的收藏' },
    { key: IMyMenuType.Footprint, name: '我的足迹' },
    { key: IMyMenuType.Question, name: '活动提问' },
    { key: IMyMenuType.Comment, name: '我的留言' },
    { key: IMyMenuType.Advise, name: '优化建议' }
  ])

  const [imageUrl, setImageUrl] = useState<string>()
  const [adviseVisible, setAdviseVisible] = useState(false)
  const [phoneVisible, setPhoneVisible] = useState(false)

  // 获取配置权限显示
  // eslint-disable-next-line no-empty-pattern
  const {} = useRequest(PersonalService.getConfigIsShow, {
    formatResult: response => response.data.Data,
    onSuccess: res => {
      // if (res.IsBelongRai) {
      //   setMenuOption([...menuOption, { key: IMyMenuType.ProductInterior, name: '产品内测' }])
      // }
    }
  })
  // 头像修改
  const { run: applyHeadImgUpdate } = useRequest(PersonalService.postHeadImgUpdate, {
    manual: true,
    onSuccess: res => {
      login2p.getUserDetail()
      setImageUrl(undefined)
    }
  })
  const { run: uploadImg } = useRequest(MaterialService.postUploadImage, {
    manual: true,
    onSuccess: res => {
      message.info(res.data.Msg)
      if (res?.data?.Data?.ResourceUrl) {
        setImageUrl(res.data?.Data?.ResourceUrl)
        applyHeadImgUpdate(res.data.Data.ResourceUrl)
      }
    }
  })
  const { run: applyTry } = useRequest(MaterialService.postApplyTry, {
    manual: true,
    onSuccess: res => {
      res.data.Success
        ? message.success('已提交给您的对口销售，请耐心等待。')
        : message.info(res.data.Msg || res.data.ErrMsg)
    }
  })

  const uploadButton = (
    <div className="hover-head">
      <img src={CameraSvg} alt="头像" className="camera-img" />
      <div className="hover-text">修改头像</div>
    </div>
  )
  const uploadProps: UploadProps = {
    name: 'file',
    multiple: false,
    className: `avatar-uploader ${styles['people-upload']}`,
    listType: 'picture-card',
    showUploadList: false,
    withCredentials: true,
    beforeUpload: beforeUpload,
    customRequest: option => {
      uploadImg(option.file)
    },
    onChange: (info: UploadChangeParam<UploadFile>) => {
      if (info.file.status === 'uploading') {
        return
      }
    }
  }
  const handleChangeMenu = (key: string | number) => {
    if (key === IMyMenuType.Advise) {
      setAdviseVisible(true)
      return
    }
    window.scrollTo(0, 0)
    setActMenu(key as number)
  }
  const handleToOther = (type: 'about') => {
    if (type === 'about') window.open(`${window.location.origin}/about`)
  }
  const handleToApplyPower = () => {
    if (!login2p.jwt) return
    // HasPermission=2,4,6，已提交过申请的，提示：您已提交过申请，请等待销售与您联系。
    if (
      login2p.userInfo?.HasPermission === INewPermissionType.HasApplyQY ||
      login2p.userInfo?.HasPermission === INewPermissionType.HasApplyFICC ||
      login2p.userInfo?.HasPermission === INewPermissionType.HasApplyPotential
    ) {
      message.info('您已提交过申请，请等待销售与您联系。')
      return
    }
    // HasPermission=3，5，不弹表单，直接提交申请
    if (
      login2p.userInfo?.HasPermission === INewPermissionType.NoApplyQY ||
      login2p.userInfo?.HasPermission === INewPermissionType.NoApplyFICC
    ) {
      applyTry({ ApplyMethod: 1 })
      return
    }
    // HasPermission=7，弹表单填写，提交申请
    setVisibleApply(true)
  }
  const handleOKApply = () => {
    setVisibleApply(false)
  }

  return (
    <div className={`${styles['personal-page']}`}>
      <ValidateLogin2p>
        <div className="personal-left-wrapper">
          <div className="personal-head">
            <Upload {...uploadProps}>
              <img src={imageUrl || login2p?.userInfo?.Headimgurl} alt="头像" className="person-img" />
              {uploadButton}
            </Upload>
          </div>
          <div className="person-content">
            <div className="person-name"> {login2p.userInfo?.UserName || '--'}</div>
            <div className="person-phone">{login2p.userInfo?.Mobile}</div>
            <div className="person-company">{login2p.userInfo?.CompanyName || '--'}</div>
            {/* <div className="person-power">
              {login2p.userInfo?.PermissionName?.map((item, index) => (
                <div className={item ? 'person-power-one' : ''} key={index}>
                  {item}
                </div>
              ))}
            </div> */}
          </div>
          <div className="person-power-wraper">
            {login2p.userInfo?.HasPermission === INewPermissionType.OK ? (
              <div className="person-haspower">
                <div className="person-haspower-label">{login2p.userInfo?.PermissionStatus}</div>
                <div className="person-haspower-text">
                  <div>
                    {login2p.userInfo?.StartDate.replaceAll('-', '.')}~{login2p.userInfo?.EndDate.replaceAll('-', '.')}
                  </div>
                  {login2p.userInfo?.PermissionStatus.includes('试用') ? null : (
                    <div>
                      剩余研选点数：
                      <span className="hightlight-text">{login2p.userInfo?.CompanyPointsNum || 0}</span>
                    </div>
                  )}
                </div>
              </div>
            ) : (
              <div className="person-nopower">
                <span>暂无权限，可点击</span>
                <div className="person-nopower-btn" onClick={handleToApplyPower}>
                  申请
                </div>
              </div>
            )}
          </div>
          <div className="personal-phone-line">
            <span className="phone-label g-va-middle">外呼号码</span>
            <span className="phone-number g-va-middle">
              {login2p.userInfo?.OutboundCountryCode ? login2p.userInfo?.OutboundCountryCode + '-' : ''}
              {login2p.userInfo?.OutboundMobile}
            </span>
            <span className="phone-edit-icon" onClick={() => setPhoneVisible(true)}>
              <img src={EditSvg} alt="图标" className="edit-icon" />
            </span>
          </div>
          {login2p.userInfo?.UserCardType !== 0 ? (
            <div className="vip-card-wrapper">
              {login2p.userInfo?.UserCardType === 1 ? (
                <img src={VipDay} alt="vip" className="vip-card-img" />
              ) : (
                <img src={VipMonth} alt="vip" className="vip-card-img" />
              )}
              <span className="vip-timetext">有效期至{login2p.userInfo?.UserCardEndDate}</span>
            </div>
          ) : null}
          <div className="personal-menu-wrapper">
            {menuOption.map(item => (
              <div
                key={item.key}
                className={`personal-menu-item ${actMenu === item.key ? 'personal-act-menu' : ''}`}
                onClick={() => handleChangeMenu(item.key)}
              >
                {item.name}
              </div>
            ))}
          </div>
        </div>
        <div className="personal-right-wrapper" id="scrollableDiv">
          <div className="personal-component-wrapper">
            {actMenu === IMyMenuType.Schedule && <ActivityComponent />}
            {actMenu === IMyMenuType.Order && <OrderComponent />}
            {actMenu === IMyMenuType.Collection && <CollectionComponent />}
            {actMenu === IMyMenuType.Footprint && <FootPrintComponent />}
            {actMenu === IMyMenuType.Comment && <CommentComponent />}
            {actMenu === IMyMenuType.Question && <QuestionComponent />}
            {actMenu === IMyMenuType.ProductInterior && <ProductInteriorComponent />}
          </div>
        </div>

        <ApplyAdivise visible={adviseVisible} onCloseModel={() => setAdviseVisible(false)} />
        <ApplyPhoneNumber
          visible={phoneVisible}
          phone={`${login2p.userInfo?.OutboundCountryCode ? login2p.userInfo?.OutboundCountryCode + '-' : ''}${
            login2p.userInfo?.OutboundMobile
          }`}
          onCloseModel={() => setPhoneVisible(false)}
        />
      </ValidateLogin2p>
      <ApplyPermission visible={visibleApply} onCloseModel={handleOKApply} />
    </div>
  )
}

export default PersonalIndex
