import React, { useState, createContext, useRef, useEffect } from 'react'
import { useDrag, useDrop, DndProvider } from 'react-dnd'
import QRcode from 'qrcode.react'
import { Button, Popover, message } from 'antd'
import { EyeOutlined, LeftOutlined } from '@ant-design/icons'
import { HTML5Backend } from 'react-dnd-html5-backend'
import styles from './index.less'
import Left from './Left'
import Container from './Container'
import Right from './Right'
import html2canvas from 'html2canvas'
import { request } from '@wisdom-utils/utils/es';
import { getSiteTree } from '@/services/siteManage/api'

const HtmlToCanvas = (DOM, option) => {
  // function saveFile(data, filename) {
  //   let save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a')
  //   save_link.href = data
  //   save_link.download = filename
  //   let event = document.createEvent('MouseEvents')
  //   event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
  //   save_link.dispatchEvent(event)
  // }

  // async function exportToPic() {

  //   let fileName = option.text
  //   let canvas = await html2canvas(DOM, option)
  //   let pageData = canvas.toDataURL('image/jpeg', 1.0)
  //   saveFile(pageData.replace("image/jpeg", "image/octet-stream"), `${fileName}.jpeg`)
  // }

  // exportToPic()

}

export const GlobalStore = createContext(null)

const initShema = {
  work: [],
  active: true,
  type: '运营组件',
  theme: '供水主题背景',
  themeStyle: '个人版',
}

const Designer = (props) => {

  const { currentCard, } = props
  const [shema, setShema] = useState(currentCard['卡片结构'] ? { ...JSON.parse(currentCard['卡片结构']) } : initShema)
  const [currentSite, setCurrentSite] = useState('永吉水务有限公司')
  const containerRef = useRef(null)

  const goBack = () => {
    props?.goBack?.()
  }

  const UploadSingleFile = (data) => {
    return request({
      url: `${origin}/PandaCore/GateWay/PandaOMS/OMS/FileCenter/UploadSingleFile`,
      method: 'post',
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      data,
    });
  }

  const saveDesgin = async () => {
    const moblieDOM = containerRef?.current?.moblieRef?.current
    const canvas = await html2canvas(moblieDOM)
    canvas.toBlob(async blob => {
      const file = new File([blob], `${currentCard['名称']}.png`, { type: 'image/png' })
      const formData = new FormData();
      formData.append('singleFile', file);
      const { code, data, msg } = await UploadSingleFile(formData)
      if (code === 0) {
        console.log('shema', shema)
        props?.saveDesgin?.({ ...currentCard, '卡片结构': JSON.stringify(shema), '路径': data })
      } else {
        message.error({ content: msg })
      }
    })
  }

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

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

  const preview = () => {
    props?.saveDesgin?.({ ...currentCard, '卡片结构': JSON.stringify(shema) })
  }

  return (
    <DndProvider backend={HTML5Backend}>
      <GlobalStore.Provider
        value={{ shema, setShema }}
      >
        <div className={styles.designer}>
          <div className={styles.top}>
            <div className={styles['top-left']}>
              <div className={styles['l-icon']}></div>
              <div className={styles['l-text']}>工作台搭建</div>
            </div>
            <div className={styles['top-right']}>
              <Button style={{ marginRight: '10px' }} icon={<span className={styles.goBack}></span>} onClick={goBack}>返回</Button>
              <Popover
                trigger="click"
                content={
                  <div>
                    <QRcode value={`${window.origin}/civ_mobile/product/water/monitor/workbench?env=dev&schemeName=${currentCard['名称']}&station=${currentSite}`} />
                  </div>
                }
              >
                <Button icon={<EyeOutlined />} style={{ marginRight: '10px', background: '#00AF88', color: 'white' }} onClick={preview}>预览</Button>
              </Popover>
              <Button type="primary" icon={<span className={styles.saveDesgin}></span>} onClick={saveDesgin}>发布</Button>
            </div>
          </div>
          <div className={styles.bottom}>
            <div className={styles['b-content']}>
              <Left></Left>
              <Container ref={containerRef}></Container>
              <Right></Right>
            </div>
          </div>
        </div>
      </GlobalStore.Provider>
    </DndProvider>
  )

}

export default Designer