import {FC, useCallback, useEffect, useState} from "react";
import {Form, Image, Input, Picker, View} from "@tarojs/components";
import Taro, {getSetting, authorize} from "@tarojs/taro";
import {curriculum, Meeting, meetingAPi} from "@/api";
import {formatDate} from "@/utils/time";
import PopPut from "@/components/popPut/popPut";
import MyButton from "@/components/button/MyButton";
import styles from './spotMeeting.module.scss'
import code from '@/static/img/code.png'
import Icon from "@/components/icon";
import failure from "@/static/img/failure.png"
import {Profile} from "@/store";
import DateTimePicker from "@/components/dateTimePicker/dateTimePicker";

const SpotMeeting: FC = () => {
  const path = encodeURIComponent("/pages/meeting/meeting")
  const params = Taro.getCurrentInstance().router?.params as { id: string | undefined }
  const [manages, setManages] = useState<Manage[]>([])
  const [start, setStart] = useState<string>(formatDate(new Date(new Date().getTime() + 24 * 60 * 60 * 1000), "YY-MM-dd 08:00"))
  const [end, setEnd] = useState<string>(formatDate(new Date(new Date().getTime() + 24 * 60 * 60 * 1000), "YY-MM-dd 18:00"))
  const [depid, setDepid] = useState<number | null>(null)
  const [imgUrl, setImgUrl] = useState('')
  const [name, setName] = useState('')
  const [description, setDescription] = useState('')
  const [loading, setLoading] = useState(false)
  const [status, setStatus] = useState(0)  // 状态
  const [id, setId] = useState<number | undefined>(params.id ? Number(params.id) : undefined)
  const pathUrl = process.env.TARO_ENV === 'h5' ? '/official/qrcode' : '/wechat/link'
  const {company} = Profile.useContainer()

  function setData(res: Meeting | null) {
    /**
     * params.id 查看详情请求
     * 当onShow的时候 id === res.id 数据相同不进行以下流程
     */
    if (params.id || id !== res?.id) {
      setImgUrl('')
      setDepid(res?.dep_id || null)
      setName(res?.name || '')
      setDescription(res?.description || '')
      setStatus(res?.status || 0)
      setId(res?.id || 0)

      if (res) {
        downUrl(res.id, false)
        setEnd(formatDate(new Date(res.estimate_end_time), "YY-MM-dd 18:00"))
        setStart(formatDate(new Date(res.estimate_start_time), "YY-MM-dd 08:00"))
      }
    } else {
      setLoading(false)
    }
  }

  useEffect(() => {
    curriculum.department().then(res => {
      setManages(res.data)
    })
  }, [])

  Taro.useDidShow(() => {
    setLoading(true)
    if (params.id != undefined) {
      meetingAPi.setMeeting(params.id).then(setData)
    } else {
      meetingAPi.exists().then(setData)
    }
  })

  const depChange = useCallback((e) => {
    setDepid(manages[Number(e.detail.value)]?.id)
  }, [manages])

  const change_start = useCallback((time: string) => {
    const mil = new Date(time).getTime()
    const endMil = new Date(end).getTime()
    if (mil > endMil) {
      Taro.showToast({title: '大于结束时间', icon: 'error'})
    } else {
      setStart(time)
    }
  }, [end])

  const change_end = useCallback((time: string) => {
    const mil = new Date(time).getTime()
    const startMil = new Date(start).getTime()
    if (mil < startMil) {
      Taro.showToast({title: '小于开始时间', icon: 'error'})
    } else {
      setEnd(time)
    }
  }, [start])

  /** 下载二维码 */
  const handleWriteFile = useCallback(() => {
    if (imgUrl == null) {
      Taro.showToast({title: '下载失败', icon: 'error'})
      return
    }
    Taro.saveImageToPhotosAlbum({
      filePath: imgUrl,
      success() {
        Taro.showModal({title: '下载成功'})
      },
      fail() {
        Taro.showToast({title: '下载失败', icon: 'error'})
      }
    })
  }, [imgUrl])

  /** 查看保存权限 */
  const handleSaveCode = useCallback(() => {
    if (process.env.TARO_ENV !== 'h5') {
      getSetting({
        success: function ({authSetting}) {
          //没有权限则申请
          if (!authSetting["scope.writePhotosAlbum"]) {
            authorize({
              scope: "scope.writePhotosAlbum",
              success: () => {
                //存储二维码
                handleWriteFile()
              },
              fail() {
                Taro.showToast({title: '保存授权失败', icon: "error"})
              }
            });
          } else {
            handleWriteFile()
          }
        },
      });
    } else {
      Taro.showToast({title: '请截图保存', icon: 'none'})
    }
  }, [imgUrl]);

  /** 获取二维码地址 */
  const downUrl = (id: number, down = true) => {
    Taro.showLoading({title: '加载二维码'})
    const url = process.env.TARO_APP_API + pathUrl + '?meeting_id=' + id + '&path=' + path

    if (process.env.TARO_ENV !== 'h5') {
      Taro.downloadFile({
        url,
        success(res) {
          setImgUrl(res.tempFilePath)
          if (down) {
            handleSaveCode()
          }
        },
        fail() {
          Taro.hideLoading()
          Taro.showModal({title: '二维码生成失败'})
          setLoading(false)
        }
      })
    } else {
      setTimeout(() => {
        setImgUrl(url)
      })
      if (down) {
        handleSaveCode()
      }
    }
  }

  const submit = useCallback(async (e) => {
    if (loading && status === 2) return;

    if (imgUrl) { // 已有
      handleSaveCode()
      return
    }

    const values: Meeting = e.detail.value
    if (!values.name) {
      Taro.showToast({title: '请填写会议名称', icon: 'error'})
      return
    }

    setLoading(true)
    try {
      const res = await meetingAPi.setMeetings({
        ...values,
        estimate_end_time: new Date(end).getTime(),
        estimate_start_time: new Date(start).getTime(),
        dep_id: depid,
        company_id: company?.id!
      })
      downUrl(res.id)
      setStatus(0)
      setId(res.id)
    } catch (e) {
      setLoading(false)
    }
  }, [imgUrl, depid, end, start])

  function imagLoad() {
    Taro.hideLoading()
    setLoading(false)
  }

  /** 开始 */
  async function onStart() {
    try {
      await meetingAPi.start(id!)
      setStatus(1)
      Taro.showModal({
        title: '现场会开始',
        content: '扫描二维码可加入'
      })
    } catch (e) {
    }
  }

  async function onEnd() {
    try {
      await meetingAPi.end(id!)
      setImgUrl('')
      setStatus(2)
    } catch (e) {
    }
  }

  async function putMeeting() {
    Taro.showLoading()
    await meetingAPi.putMeeting(id!, {
      name,
      dep_id: depid,
      company_id: company?.id!,
      description,
      estimate_end_time: new Date(end).getTime(),
      estimate_start_time: new Date(start).getTime(),
    })
    Taro.hideLoading()
    Taro.showToast({title: '修改成功'})
  }


  return (
    <View className={styles.page}>

      <View className={styles.box}>
        <View>现场会</View>
        {process.env.TARO_ENV === 'h5' && <View className='text-center text-muted'>微信公众号，浏览器中请截图保存</View>}

        <View className={styles.code}>
          {
            imgUrl
              ? <Image
                src={imgUrl}
                mode='aspectFit'
                style={{width: '200px'}}
                onLoad={imagLoad}
                onError={imagLoad}
                fadeIn/>
              : <>
                <View className={styles.empty}>填完写完整信息</View>
                <Image src={code} mode='aspectFit' style={{width: '150px'}}/>
              </>
          }
          {status === 2 && <Image src={failure} className={styles.failure}/>}
        </View>

        <View className={styles.choice}>
          <Form onSubmit={submit}>
            <PopPut
              title='会议名称'
              chevron
              content={<Input
                className='input'
                name='name'
                value={name}
                disabled={status > 0}
                placeholder='请输入会议标题'
                onInput={(e) => setName(e.detail.value)}
              />}
            />

            <DateTimePicker
              name='estimate_start_time'
              defaultValue={start}
              disabled={status === 1}
              onChange={(time) => change_start(time)}
            >
              <PopPut title='开始时间' content={start}/>
            </DateTimePicker>


            <DateTimePicker
              name='estimate_end_time'
              defaultValue={end}
              disabled={status === 1}
              onChange={(time) => change_end(time)}
            >
              <PopPut title='结束时间' content={end}/>
            </DateTimePicker>

            <Picker
              mode='selector'
              range={manages}
              onChange={depChange}
              disabled={status === 1}
              rangeKey='name'
              name='dep_id'>
              <PopPut title='选择部门' content={manages?.find(x => x.id == depid)?.name}/>
            </Picker>

            <View className='flex justify-between'>
              {
                id !== undefined && <>
                  {
                    status === 0 && <MyButton
                      fillet
                      type='warn'
                      width={150}
                      className={styles.buttonDel}
                      onClick={onStart}>
                      开始
                    </MyButton>
                  }
                  {
                    status === 1 &&
                    <MyButton fillet type='warn' width={150} className={styles.buttonDel} onClick={onEnd}>结束</MyButton>
                  }
                </>
              }

              {
                imgUrl && <MyButton
                  fillet
                  disabled={!imgUrl || status === 1}
                  width={150}
                  onClick={putMeeting}
                  className={styles.button}>
                  修改
                </MyButton>
              }

            </View>

            <MyButton
              formType='submit'
              fillet
              width={200}
              className={styles.button}
              loading={loading}>
              {imgUrl ? "保存二维码" : "新建现场会"}
            </MyButton>
          </Form>
        </View>

        {
          !params.id
          && <View
            className='text-center text-muted my-3'
            onClick={() => Taro.navigateTo({url: '/pages/manage/meetings/meetings'})}>
            历史列表 <Icon name='chevron-right'/>
          </View>
        }
      </View>
    </View>
  )
}

export default SpotMeeting
