import React, { useRef, useContext, useState, useEffect, forwardRef, useImperativeHandle } from 'react'
import styles from './index.less'
import {
  DownOutlined,
  VerticalAlignTopOutlined,
  UpOutlined,
  VerticalAlignBottomOutlined,
  CheckOutlined,
  CaretDownOutlined,
} from '@ant-design/icons'
import { useDrag, useDrop, DndProvider } from 'react-dnd'
import { GlobalStore } from '../index'
import Group from './Group'
import TipBox from './TipBox'
import moment from 'moment'
import { getSiteTree } from '@/services/siteManage/api'
import { Carousel } from 'antd'

const btns = [
  { title: '置顶', icon: <VerticalAlignTopOutlined /> },
  { title: '上一项', icon: <UpOutlined /> },
  { title: '下一项', icon: <DownOutlined /> },
  { title: '置底', icon: <VerticalAlignBottomOutlined /> },
]

const Container = (props, ref) => {

  useImperativeHandle(ref, () => ({
    moblieRef
  }))

  const currentDate = moment().format('YYYY-MM-DD')
  const moblieRef = useRef(null)
  const [currentSite, setCurrentSite] = useState('永吉水务有限公司')
  const { shema, setShema } = useContext(GlobalStore)
  const { work, carousel } = shema

  const [, drop] = useDrop(() => {
    return {
      accept: 'box',
      drop(box) {
        setShema(boxs => ({ ...boxs, work: [...boxs.work, box] }))
      }
    }
  })

  drop(moblieRef)

  const pageClick = () => {
    let array = []
    shema?.work.forEach(v => {
      array.push({ ...v, active: false, children: v.children.map(s => ({ ...s, active: false })) })
    })
    setShema({ ...shema, work: array, active: true, carousel: { ...shema.carousel, active: false } })
  }

  const getSite = async () => {
    const { code, data } = await getSiteTree({ node: -1 })
    if (code === 0) {
      setCurrentSite(data?.list?.[0].text)
    }
  }

  const getData = () => {
    getSite()
  }

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

  const btnsClick = (item) => {
    let index = 0
    if (item.title === '置顶') {
      moblieRef.current.scrollTop = 0
      index = 0
    } else if (item.title === '置底') {
      moblieRef.current.scrollTop = (moblieRef.current.scrollHeight - moblieRef.current.clientHeight)
      index = shema?.work.length - 1
    } else if (item.title === '上一项') {
      let ativeIndex = shema?.work?.findIndex(v => v.active) - 1
      index = ativeIndex >= 0 ? ativeIndex : 0
      moblieRef.current.scrollTop = moblieRef.current.scrollTop - 70
    } else if (item.title === '下一项') {
      let ativeIndex = shema?.work?.findIndex(v => v.active) + 1
      index = ativeIndex < (shema?.work.length - 1) ? ativeIndex : shema?.work.length - 1
      moblieRef.current.scrollTop = moblieRef.current.scrollTop + 70
    }
    let array = []
    shema?.work.forEach((v, i) => {
      array.push({ ...v, active: index === i, children: v.children.map(s => ({ ...s, active: false })) })
    })
    setShema({ ...shema, work: array, active: false, carousel: { ...shema.carousel, active: false } })
  }

  const carouselClick = (e) => {
    e.stopPropagation()
    let array = []
    shema?.work.forEach(v => {
      array.push({ ...v, active: false, children: v.children.map(v => ({ ...v, active: false })) })
    })
    setShema({ ...shema, work: array, active: false, carousel: { ...shema.carousel, active: true } })
  }

  const getMoblieCenter = () => {
    if (shema.themeStyle === '个人版') {
      return (
        <div
          className={styles['moblieCenter-a']}
          name={shema.theme}
        >
          <div className={styles['m-info']}>
            <div className={styles['i-company']}>
              <span className={styles['c-address']}></span>
              <span>{currentSite}</span>
              <DownOutlined style={{ fontSize: '12px', marginLeft: '5px' }} />
            </div>
            <div className={styles['i-date']}>
              <span></span>
              <span>{currentDate}</span>
              <DownOutlined style={{ fontSize: '12px', marginLeft: '5px' }} />
            </div>
          </div>
          <div style={{ padding: '10px' }}>
            {
              work?.length > 0 ? (
                work?.map((v, i) => <Group key={v.id} index={i} {...v} />)
              ) : <TipBox style={{ marginTop: '10px' }} text='左侧拖拽布局到这里' />
            }
          </div>
        </div>
      )
    }
    return (
      <div
        className={styles['moblieCenter-b']}
        name={shema.theme}
      >
        <div
          className={styles.slideShow}
          onClick={(e) => carouselClick(e)}
          active={`${carousel?.active}`}
          style={!carousel?.active && !carousel?.imgUrls?.length > 0 ? { borderBottom: '1px dashed #DDDDDD' } : {}}
        >
          <div className={styles.top}>
            <div className={styles['top-left']}>
              <span className={styles['l-icon']}></span>
              <span className={styles['l-text']}>{currentSite}</span>
              <CaretDownOutlined style={{ color: '#999999' }} />
            </div>
            <div className={styles['top-right']}>
              <span className={styles['r-icon']}></span>
              <span className={styles['r-text']}>{currentDate}</span>
            </div>
          </div>
          {
            carousel?.imgUrls?.length > 0 ? (
              <Carousel autoplay>
                {
                  carousel?.imgUrls?.map(v => {
                    return (
                      <div className={styles['carousel-item']}>
                        <img style={{ width: '100%', height: '100%' }} src={`${window.origin}/PandaOMS/OMS/FileCenter/DownLoadFiles?module=图库&filePath=${v}`} />
                      </div>
                    )
                  })
                }
              </Carousel>
            ) : <TipBox text='点击此处设置轮播图' />
          }
        </div>
        <div className={styles.groups}>
          {
            work?.length > 0 ? (
              work?.map((v, i) => <Group key={v.id} index={i} {...v} />)
            ) : <TipBox text='左侧拖拽布局到这里' />
          }
        </div>
      </div>
    )
  }

  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <div className={styles.moblieBox}>
          <div className={styles.moblieBoxTop}></div>
          <div
            ref={moblieRef}
            className={styles.moblie}
            onClick={() => pageClick()}
            active={`${shema.active}`}
            style={{ background: shema?.background }}
          >
            {getMoblieCenter()}
          </div>
        </div>
        <div className={styles['c-btns']}>
          {
            btns.map(v => {
              return (
                <div key={v.title} className={styles['c-btn']} onClick={() => btnsClick(v)}>{v.icon}</div>
              )
            })
          }
        </div>
      </div>
    </div>
  )

}

export default forwardRef(Container)