import React, { useState, useRef, useContext, useMemo, useEffect } from 'react'
import { Checkbox, Row, Col, Button, message, Input } from 'antd'
import { useDrag, useDrop, DndProvider } from 'react-dnd'
import { CaretRightOutlined } from '@ant-design/icons'
import styles from './index.less'
import { GlobalStore } from '../index'
import { getCardVersion, upgradeCardVersion } from '@/services/mobileConfig/api'

const { Search } = Input

const cardTypes = ['管理', '执行', '运营']
const tabs = ['产品组件', '项目组件']

const cards = [
  [
    {
      title: '运营总览',
      count: 1,
      children: [
        { name: '运营总览', widget: 'OVERVIEW', type: '运营' }
      ]
    },
    {
      title: '水厂',
      count: 2,
      children: [
        { name: '水厂总览', widget: 'WATER_OVERVIEW', type: '运营' },
        { name: '供水量曲线', widget: 'WATER_CHART', type: '运营' },
      ]
    },
    {
      title: '管网',
      count: 4,
      children: [
        { name: '管网监控', widget: 'PIPEMONITORING', type: '运营' },
        { name: '管网采集', widget: 'PIPEGATHER', type: '运营' },
        { name: '管网巡检', widget: 'PIPEINSPECTION', type: '运营' },
        { name: '维修工单', widget: 'MAINTENANCEORDER', type: '运营' },
      ]
    },
    {
      title: '二供',
      count: 3,
      children: [
        { name: '二供总览', widget: 'OPERATIONAL_OVERVIEW', type: '运营' },
        { name: '泵房运行状态', widget: 'PUMP_STATUS', type: '运营' },
        { name: '泵房维修保养', widget: 'PUMP_MAINTAIN', type: '运营' },
      ]
    },
    {
      title: '营收',
      count: 1,
      children: [
        { name: '营收总览', widget: 'REVENUE_OVERVIEW', type: '运营' },
      ]
    },
    {
      title: 'DMA',
      count: 1,
      children: [{ name: '大表监控', widget: 'LARGE_MONITORING', type: '运营' }],
    },
  ],
  [
    {
      title: '江西水务集团GIS项目',
      count: 1,
      children: [
        { name: '运营总览', widget: 'OPERATIONSOVERVIEW', type: '运营' },
        { name: '管网资产', widget: 'PIPELINEASSETS', type: '运营' },
        { name: '管网采集', widget: 'PIPELINECOLLECTION', type: '运营' },
        { name: '巡检运维', widget: 'INSPECTIONMAINTENANCE', type: '运营' },
        { name: '事件工单', widget: 'EVENTWORKORDER', type: '运营' },
        { name: '子公司业务排行', widget: 'SUBSIDIARYBUSINESSRANKING', type: '运营' },
      ]
    },
  ]
]

const getNanoid = (len = 10) => {
  var orgStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let returnStr = "";
  for (var i = 0; i < len; i++) {
    returnStr += orgStr.charAt(Math.floor((Math.random() * orgStr.length)));
  }
  return `${returnStr}`
}

const Group = (props) => {

  const id = getNanoid()
  const ref = useRef(null)

  const [{ dragging }, drag, dragPreview] = useDrag({
    type: 'box',
    item: {
      id: id,
      name: '通栏布局',
      widget: '通栏布局',
      children: []
    },
    collect(monitor) {
      return {
        dragging: monitor.isDragging()
      }
    }
  });

  drag(ref)

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

  return (
    <div
      ref={ref}
      className={styles.group}
      style={{ border: dragging ? '2px solid #001bff' : '' }}
      onClick={() => boxClick()}
    >
    </div>
  )
}

const Card = (props) => {

  const ref = useRef(null)
  const id = getNanoid()

  const [{ dragging }, drag] = useDrag({
    type: 'card',
    item: {
      id: id,
      name: props.name,
      widget: props.widget,
      iconShow: false,
      icon: '',
      url: '',
      param: '',
    },
  })

  drag(ref)

  return (
    <div
      ref={ref}
      className={styles.card}
    >
      <div className={styles.cardType} type={props.type}>{props.type + '组件'}</div>
      <div className={styles.box}>
        <div className={styles.cardBox} widget={props.widget}></div>
      </div>
      <div className={styles.swiper}>{props.name}</div>
    </div>
  )
}

//卡片分组
const CardGroup = (props) => {

  const [shrink, setShrink] = useState(false)

  return (
    <div className={styles.cardGroup}>
      <div className={styles['g-top']} onClick={() => setShrink(!shrink)}>
        <CaretRightOutlined style={{ transition: '0.5s all', transform: !shrink ? 'rotate(90deg)' : '' }} />
        <span>{props.title}</span>
        <span>{`(${props.count})`}</span>
      </div>
      <div className={styles['g-cards']} style={{ height: shrink ? '0px' : 'unset' }}>
        {props.children}
      </div>
    </div>
  )

}

const Left = () => {

  const { shema, setShema } = useContext(GlobalStore)
  const [cardType, setCardType] = useState(cardTypes)
  const [version, setVersion] = useState({ Version: '', lastVersion: '' })
  const [activeIndex, setActiveIndex] = useState(0)
  const [inputValue, setInputValue] = useState('')

  const cardsFilter = useMemo(() => {
    let array = []
    cards[activeIndex].forEach(v => {
      let children = v.children.filter(s => cardType.includes(s.type) && (!inputValue || s.name.includes(inputValue)))
      if (children.length) {
        array.push({ ...v, children })
      }
    })
    return array
  }, [cards, cardType, activeIndex, inputValue])

  const cardTypeChange = (value) => {
    setCardType(value)
  }

  const update = async () => {
    const { code, data, msg } = await upgradeCardVersion()
    if (code === 0) {
      getData()
    } else {
      message.error(msg)
    }
  }

  const getData = async () => {
    const { code, data } = await getCardVersion()
    if (code === 0) {
      setVersion(data)
    }
  }

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

  return (
    <div className={styles.left}>
      <div className={styles.header}>
        <div className={styles['r-left']}>
          <span style={{ paddingRight: '3px' }}>组件库</span>
          <span style={{ fontSize: '10px' }}>V{version.lastVersion}</span>
        </div>
        <div className={styles['r-right']}>
          <Button
            size='small'
            onClick={() => update()}
            style={{ display: version.Version !== version.lastVersion ? 'block' : 'none' }}
          >
            立即更新
          </Button>
        </div>
      </div>
      <div className={styles['l-content']}>
        <div className={styles.item}>
          <div className={styles['g-title']}>布局</div>
          <div className={styles['g-content']}>
            <Group></Group>
          </div>
        </div>
        <div className={styles.tabs}>
          {tabs.map((v, i) => {
            return (
              <div
                className={styles.tab}
                active={`${activeIndex === i}`}
                onClick={() => setActiveIndex(i)}
              >
                {v}
              </div>
            )
          })}
        </div>
        <div className={styles.item}>
          <div className={styles.search}>
            <Search
              placeholder="请输入关键字搜索"
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              style={{ width: 250 }}
            />
          </div>
          <div className={styles['g-checks']}>
            <Checkbox.Group
              style={{ width: '100%' }}
              value={cardType}
              onChange={cardTypeChange}
            >
              <Row>
                {
                  cardTypes.map(v => {
                    return (
                      <Col key={v} style={{ display: 'flex', justifyContent: 'center', marginLeft: '10px' }}>
                        <Checkbox value={v}>{v}</Checkbox>
                      </Col>
                    )
                  })
                }
              </Row>
            </Checkbox.Group>
          </div>
          <div className={styles['g-content']}>
            {
              cardsFilter.map(v => {
                return (
                  <CardGroup key={v.title} {...v}>
                    {
                      v.children.map(s => <Card key={s.name} {...s}></Card>)
                    }
                  </CardGroup>
                )
              })
            }
          </div>
        </div>
      </div>
    </div>
  )

}

export default Left