import React, { useEffect, useRef, useState } from 'react';
import { connect } from 'react-redux';
import { TreeSelect, Tree, Form, Button, Popover, Tag, Switch, Input, Row, Pagination, Checkbox, InputNumber } from '@douyinfe/semi-ui';
import './videoScreen.less'
import VideoCard from './videoCard'
import { ReminderBox } from "../../../components/index";
import PerfectScrollbar from "perfect-scrollbar";

let timing
let projectScrollbar;
const VideoScreen = ({ treeData, filterGroup, videoPlay, template, headerName, showHeader }) => {
   // console.log({ 视频: treeData });
   // console.log(filterGroup);
   // console.log(headerName);
   // console.log(videoPlay);
   // console.log(template);
   // console.log(showHeader);

   // const treeData = [
   //    {
   //       label: '公司',
   //       value: '公司',
   //       key: '524252542',
   //       children: [
   //          {
   //             label: '大门',
   //             value: '大门',
   //             key: '2451245',
   //             videoData: {
   //                channelNo: 1,
   //                content: ['5442542542', '452345', '234524525'],
   //                serialNo: "F61504020",
   //                type: "yingshi",
   //                yingshiToken: "at.6vznnc23bv51vzjt7lnkj7e19bb2z61f-3gnj7m5lxp-10666cy-bgwcjkekk"
   //             }
   //          }, {
   //             label: '机房',
   //             value: '机房',
   //             key: '54252542',
   //             videoData: {
   //                channelNo: 3,
   //                content: ['5442542542', '452345', '234524525'],
   //                serialNo: "F61504020",
   //                type: "yingshi",
   //                yingshiToken: "at.6vznnc23bv51vzjt7lnkj7e19bb2z61f-3gnj7m5lxp-10666cy-bgwcjkekk"
   //             }
   //          }, {
   //             label: '后门',
   //             value: '后门',
   //             key: '52425425642',
   //             videoData: {
   //                channelNo: 2,
   //                content: ['5442542542', '452345', '234524525'],
   //                serialNo: "F61504020",
   //                type: "yingshi",
   //                yingshiToken: "at.6vznnc23bv51vzjt7lnkj7e19bb2z61f-3gnj7m5lxp-10666cy-bgwcjkekk"
   //             }
   //          },
   //       ]
   //    },
   //    {
   //       label: '外部',
   //       value: '外部',
   //       key: '25425425',
   //       children: [
   //          {
   //             label: '水库',
   //             value: '水库',
   //             key: '2542542542542',
   //             children: [
   //                {
   //                   label: '房子',
   //                   value: '房子',
   //                   key: '2542542542542',
   //                   videoData: {
   //                      channelNo: null,
   //                      content: ['5442542542', '452345', '234524525'],
   //                      serialNo: "G56384764",
   //                      type: "yingshi",
   //                      yingshiToken: "at.c7dnknnvd4irh8zddul3dgkpb4f3oz83-4n6u7zv8st-1gxz7ny-lgffyh25z",
   //                   }
   //                },
   //             ]
   //          },
   //       ]
   //    }, {
   //       label: '外',
   //       value: '外',
   //       key: '0-3',
   //       children: [
   //          {
   //             label: '库',
   //             value: '库',
   //             key: '0-3-1',
   //             children: [
   //                {
   //                   label: '子',
   //                   value: '子',
   //                   key: '0-3-1-1',
   //                },
   //             ]
   //          },
   //       ]
   //    }]

   const [pageSize, setPageSize] = useState(4) //每页视频数量
   const [page, setPage] = useState(1) //页码
   const [queryData, setQueryData] = useState([{ label: '全部', value: '全部', key: '0' }]) //查询树状数据
   const [leftTree, setLefTtree] = useState(treeData) //左侧树状数据
   const [playData, setPlayData] = useState([]) //视频数据
   const [queryValue, setQueryValue] = useState(['全部']) //查询条件
   const [leftValue, setLeftValue] = useState(treeData.map(v => v.value)) //树状被选中的视频
   const [selectAll, setSelectAll] = useState(true) //全选
   const [searchs, setSearchs] = useState({}) //搜索
   const [polling, setPolling] = useState(false) //轮询
   const [pollingTime, setPollingTime] = useState(1) //轮询时间
   const [reminder, setReminder] = useState(false); //提醒弹框
   const [formWidth, setFormWidth] = useState(840);
   const [multiScreen, setMultiScreen] = useState('');


   const api = useRef();
   const pageRef = useRef(page);
   const GONGGESCREEN = 'gonggeScreen'


   useEffect(() => {
      projectScrollbar = new PerfectScrollbar("#tree", {
         suppressScrollX: true,
      });

      const resize_ = () => {
         setFormWidth(document.getElementById('formSearch').scrollWidth)
      }
      resize_()
      window.addEventListener('resize', resize_);
      return () => {
         window.removeEventListener('resize', resize_);
      }

   }, [])
   useEffect(() => {
      const domProject = document.getElementById("tree");
      if (domProject && projectScrollbar) {
         projectScrollbar.update();
      }
   })


   useEffect(() => {
      let query = []
      treeData?.map(v => [
         query.push({ label: v.label, value: v.value, key: v.key })
      ])
      setQueryData([{ label: '全部', value: '全部', key: '00', children: query }])
      let values = treeData.map(v => v.value)
      videoData(treeData, values)
      setLefTtree(treeData)
      setLeftValue(treeData.map(v => v.value))
      api.current?.reset()
   }, [treeData, filterGroup])


   useEffect(() => {
      console.log(queryValue);
      if (treeData && queryValue.includes('全部')) {
         console.log(54254);
         setLefTtree(treeData)
         let values = treeData.map(v => v.value)
         videoData(treeData, values)
      } else {
         console.log(3);
         let leftData = []
         queryValue.map(item => {
            leftData.push(treeData?.find(({ value }) => item == value))
         })  //获取左侧树状数据
         setLefTtree(leftData)
         videoData(treeData, queryValue)
      }
   }, [queryValue]) //查询参数改变时


   useEffect(() => {
      let playVideo = []
      const videoPlay = (data, values) => {
         data?.map(v => {
            if (values?.find(vv => vv == v.value)) {
               if (v.camera) playVideo.push(v)
               if (v.children) {
                  v.children.map(vv => {
                     if (vv.camera) playVideo.push(vv)
                     if (vv.children) {
                        vv.children.map(c => {
                           if (c.camera) playVideo.push(c)
                           if (c.children) {
                              c.children.map(cc => {
                                 if (cc.camera) playVideo.push(cc)
                              })
                           }
                        })
                     }
                  })
               }
            }
            if (v.children) {
               videoPlay(v.children, leftValue)
            }
         })
      }
      console.log(leftTree, leftValue);
      videoPlay(leftTree, leftValue)
      console.log(playVideo);
      setPlayData(playVideo);

      for (let v of treeData) {  //判断是否全选
         if (!leftValue.includes(v.value)) {
            setSelectAll(false)
            return
         } else {
            setSelectAll(true)
         }
      }
   
   }, [leftValue])  //树状勾选结果

   useEffect(() => {
      console.log(searchs);
      let videoData = []
      let wholeVideo = treeData?.map(v => {
         if (v.children) {
            v.children.map(vv => {
               if (vv.camera) videoData.push(vv)
               if (vv.children) {
                  vv.children.map(c => {
                     if (c.camera) videoData.push(c)
                     if (c.children) {
                        c.children.map(cc => {
                           if (cc.camera) videoData.push(cc)
                        })
                     }
                  })
               }
            })
         }
      })
      // console.log(videoData);

      if (searchs?.name) {
         videoData = videoData?.filter(v => v.label.includes(searchs.name))
      }
      if (searchs.hasOwnProperty('field0')) {
         videoData = videoData?.filter(({ cameraId }) => filterGroup[0].filters.find(v => v.num == searchs?.field0).cameraIds.some(v => v == cameraId))
      }
      if (searchs.hasOwnProperty('field1')) {
         videoData = videoData?.filter(({ cameraId }) => filterGroup[1].filters.find(v => v.num == searchs?.field1).cameraIds.some(v => v == cameraId))
      }
      if (searchs.hasOwnProperty('field2')) {
         videoData = videoData?.filter(({ cameraId }) => filterGroup[2].filters.find(v => v.num == searchs?.field2).cameraIds.some(v => v == cameraId))
      }
      if (searchs.hasOwnProperty('field3')) {
         videoData = videoData?.filter(({ cameraId }) => filterGroup[3].filters.find(v => v.num == searchs?.field3).cameraIds.some(v => v == cameraId))
      }
      if (searchs.hasOwnProperty('field4')) {
         videoData = videoData?.filter(({ cameraId }) => filterGroup[4].filters.find(v => v.num == searchs?.field4).cameraIds.some(v => v == cameraId))
      }
      // console.log(videoData);
      setPlayData(videoData)

   }, [searchs])




   useEffect(() => {
      let pollingTimes = pollingTime || 1
      if (timing) clearInterval(timing)
      if (pollingTime && polling) {
         timing = setInterval(() => {
            let pages = pageRef.current + 1
            if (pages > Math.ceil(playData?.length / pageSize)) {
               setPage(1)
               pageRef.current = 1
            } else {
               setPage(pages)
               pageRef.current = pages
            }
         }, pollingTimes * 1000 * 60)
      }
   }, [polling, playData, pollingTime])


   useEffect(() => {
      setPage(1)
      pageRef.current = 1
   }, [pageSize])

   //确定查询条件下视频总数
   const videoData = (d, v) => {
      console.log(d, v);
      let playVideo = []
      let videos = d.filter(item => v.some(vv => vv == item.value))
      const playVideoData = (data) => {
         data.map(c => {
            if (c.camera) playVideo.push(c)
            if (c.children) playVideoData(c.children)
         })

      }
      playVideoData(videos)
      setPlayData(playVideo)
      playVideoData.current = playVideo
      return playVideo
   }


   //宫格设置点击
   const flipScreens = (data) => {
      const remind = localStorage.getItem(GONGGESCREEN) || 'false'
      console.log(remind);
      console.log(true);
      switch (data) {
         case "单屏":
            setPageSize(1)
            break;
         case "4分屏":
            setPageSize(4)
            break;
         case "6分屏":
            if (remind == 'false') {
               setReminder(true)
            } else {
               setPageSize(6)
            }
            break;
         case "12分屏":
            if (remind == 'false') {
               setReminder(true)
            } else {
               setPageSize(12)
            }
            break;
         default:
            break
      }
   }

   // console.log(playData);

   const mould = (blue, white, black) => {
      switch (template) {
         case 'blue':
            return blue
         case 'white':
            return white
         case 'black':
            return black
         default:
            break;
      }
   }

   return (
      <>
         <div
            className={template}
            style={{
               width: '100%', height: '100%',
               background: `url(/assets/images/application/${mould('buleBackground', "whiteBackground", "blackBackground")}.png)`,
               color: '#FFFFFF',
               //  minWidth: 1000,
            }}>
            {/* 头部标题 */}
            {showHeader ? <div style={{
               width: '100%', height: 80,
               textAlign: 'center',
            }}>
               <div style={{
                  height: 80,
                  padding: '0 10px',
                  display: 'inline-block',
                  fontSize: '36px',
                  fontFamily: 'SourceHanSansCN - Heavy, SourceHanSansCN',
                  fontWeight: 800,
                  color: mould('#FFFFFF', 'rgba(0,0,0,0.65)', '#FFFFFF'),
                  lineHeight: '70px',
                  letterSpacing: '5px',
                  background: `url(/assets/images/application/${mould('buletitleBottom', "whitetitleBottom", "blacktitleBottom")}.png)`,
                  backgroundSize: '100% 100%',
               }} >{headerName}</div>
            </div> : ""}


            <div style={{
               height: `calc(100% - ${showHeader ? 80 : 0}px)`, padding: '8px', display: 'flex',
            }}>
               <div style={{ width: 300, height: "100%", border: `1px solid ${mould('#003D9E', 'rgba(197,201,207,0.4', '')}`, position: 'relative', padding: 5 }}>
                  <div>查询：
                     <TreeSelect
                        className={template + 1}
                        style={{ width: 230, border: `1px solid  ${mould('rgba(255, 255, 255, 0.488)', 'rgba(151,151,151,0.5)', '')}`, backgroundColor: `${mould('#01185F', '#FFFFFF', '#ECECEC')}` }}
                        dropdownStyle={{ maxHeight: `calc(100% - 62px)`, overflow: 'auto', color: '#FFFFFF', }}
                        treeData={queryData}
                        placeholder="请选择"
                        multiple={true}
                        value={queryValue}
                        maxTagCount={1}
                        onChange={(e) => {
                           setQueryValue(e)
                        }}
                     />
                  </div>
                  <div id='tree' style={{ height: `calc(100% - 62px)`, position: "relative", }}>
                     <Tree
                        multiple
                        treeData={leftTree}
                        value={leftValue}
                        blockNode={false}
                        defaultExpandAll={true}
                        expandAll={true}
                        // labelEllipsis={true}
                        onChange={(e) => {
                           // console.log(e);
                           setLeftValue(e)
                           setPage(1)
                           pageRef.current = 1
                        }}
                        onSelect={(e) => {
                           // console.log(e);
                        }}
                        style={{ color: '#FFFFFF' }}
                     />
                  </div>

                  <Checkbox
                     checked={selectAll}
                     onChange={checked => {
                        setSelectAll(checked?.target.checked)
                        if (checked?.target.checked) {
                           setLeftValue(treeData.map(v => v.value))
                        } else {
                           setLeftValue([])
                        }
                     }}
                     ria-label="Checkbox 示例"
                     style={{ position: 'absolute', right: 10, bottom: 10 }}
                  >
                     全选</Checkbox>
               </div>
               <div style={{
                  flex: 1, marginLeft: '4px', border: `1px solid ${mould('#003D9E', 'rgba(197,201,207,0.4', '')}`,
               }}>
                  <div style={{ display: 'flex', }}>
                     <div id='formSearch' style={{ flex: 1, marginTop: '10px', }}>
                        <Form
                           onSubmit={(values) => console.log(values)}
                           // onValueChange={values=>console.log(values)}
                           getFormApi={(formApi) => (api.current = formApi)}
                           layout="horizontal"
                           style={{ position: "relative", width: "100%", flex: 1 }}
                        >
                           <Form.Input label={<span style={{ marginRight: -14, display: 'inline-block' }}>设备搜索:</span>} field="name" maxLength="36" placeholder="请输入设备名称" labelPosition="left" style={{ width: 125, color: "#fff", }} />
                           {filterGroup?.map(v => {
                              let nameLength = 2
                              let OptionWidth = 75
                              if (formWidth > 910) {
                                 switch (filterGroup.filter(v => v.forbidden).length) {
                                    case 1:
                                       nameLength = 9
                                       OptionWidth = 130
                                       break;
                                    case 2:
                                       nameLength = 9
                                       OptionWidth = 130
                                       break;
                                    case 3:
                                       nameLength = 9
                                       OptionWidth = 130
                                       break;
                                    case 4:
                                       if (formWidth > 1145) {
                                          nameLength = 9
                                          OptionWidth = 130

                                       } else {
                                          if (formWidth > 930) {
                                             nameLength = 4
                                             OptionWidth = 100
                                          }
                                       }
                                       break;
                                    case 5:
                                       if (formWidth > 1380) {
                                          nameLength = 9
                                          OptionWidth = 130
                                       } else {
                                          if (formWidth > 1100) {
                                             nameLength = 4
                                             OptionWidth = 100
                                          }
                                       }
                                       break;
                                    default:
                                       break;
                                 }
                              }
                              return v.forbidden ? <Form.Select
                                 label={<span style={{ marginRight: -14, display: 'inline-block' }} title={v.name}>{v.name.length > nameLength ? `${v.name.substr(0, nameLength)}...:` : v.name + ':'}</span>}
                                 labelPosition="left"
                                 field={"field" + v.num}
                                 style={{ width: OptionWidth, background: mould('#01185f', ' #FFFFFF', '#ECECEC'), boxShadow: `inset 0px 0px 5px 1px  ${mould('rgba(28, 96, 254, 0.4)', ' rgba(151,151,151,0.5)', 'rgba(39,39,39,0.2)')} ` }}
                                 placeholder="全部"
                                 showClear
                              >
                                 {v.filters.map(vv => <Form.Select.Option value={vv.num} key={vv.num}>{vv.name}</Form.Select.Option>)}
                              </Form.Select> : ""
                           })}
                        </Form>
                     </div>
                     <div
                        style={{
                           marginTop: '10px',
                        }}
                     >
                        <Button
                           theme="solid"
                           type="primary"
                           style={{ width: 48, height: 30, borderRadius: 3, marginRight: 8, backgroundColor: mould('#1859C1', '#525353', '#6C6C6C'), color: '#FFFFFF' }}
                           onClick={() => {
                              api.current.validate().then((v) => {
                                 let aa = JSON.stringify(v);
                                 setSearchs(JSON.parse(aa))
                                 setPage(1)
                                 pageRef.current = 1
                                 // setQuery({ limit: 10, page: 0 })
                              });
                           }}
                        >
                           搜索
                        </Button>
                        {/* <Button
                           theme="light"
                           type="primary"
                           style={{
                              width: 65,
                              height: 30,
                              backGround: "#FFFFFF",
                              borderRadius: 3,
                              border: "1px solid #D9D9D9",
                              marginBottom: 20,
                           }}
                           onClick={() => {
                              api.current.reset();
                              // setSearch({});
                              // setQuery({ limit: 10, page: 0 })
                           }}
                        >
                           重置
                        </Button> */}
                     </div>
                  </div>
                  <div style={{ display: 'flex', height: '100%' }}>
                     {/* 视频 */}
                     <div id='rearProjection' style={{ flex: 1, height: '100%' }}>
                        <Row style={{ height: `calc( 100% - 90px)` }}>
                           {playData?.slice((page - 1) * pageSize, page * pageSize)?.map(v => {
                              return <VideoCard key={'VideoCard' + v.key} data={v} pageSize={pageSize} showHeader={showHeader} videoPlay={videoPlay} mould={mould} />
                           })}
                        </Row>
                        <div
                           style={{
                              display: "flex",
                              justifyContent: 'space-between',
                              padding: "10px",
                           }}
                        >
                           <span style={{ lineHeight: "30px" }}>
                              共{playData.length}个设备
                           </span>
                           {playData.length > 0 ? <Pagination
                              total={playData.length}
                              currentPage={page}
                              pageSize={pageSize}
                              style={{ color: '#D9D9D9' }}
                              onChange={(currentPage, pageSize) => {
                                 setPage(currentPage)
                                 pageRef.current = currentPage
                              }}
                           /> : ""}
                        </div>
                     </div>
                     {/* 视频设置 */}
                     <div style={{
                        width: 64, height: 476, background: mould('#01185F', ' linear-gradient(197deg, rgba(255,255,255,0.65) 0%, #E4E4E4 100%)', 'linear-gradient(197deg, rgba(38,38,38,0.65) 0%, #101010 100%)'), boxShadow: `inset 0px 0px 5px 1px ${mould('rgba(28,96,254,0.4000)', 'rgba(97,94,94,0.5)', 'rgba(132,132,132,0.5)')}`, borderRadius: ' 1px', textAlign: 'center',
                     }}>
                        {[{ img: mould('blueGongge', 'whiteGongge', 'blackGongge'), value: '宫格设置', screen: [{ img: mould('blueScreen1', 'whiteScreen1', 'blackScreen1'), value: '单屏' }, { img: mould('blueScreen4', 'whiteScreen4', 'blackScreen4'), value: '4分屏' }, { img: mould('blueScreen6', 'whiteScreen6', 'blackScreen6'), value: '6分屏' }, { img: mould('blueScreen12', 'whiteScreen12', 'blackScreen12'), value: '12分屏' },] },
                        { img: mould('bluePolling', 'whitePolling', 'blackPolling'), value: '轮询设置', },
                        { img: mould('blueBackr', 'whiteBack', 'blackBack'), value: '背投', },
                        { img: mould('blueMonitor', 'whiteMonitor', 'blackMonitor'), value: '监控地图' },].map((v, index) => {
                           return <div key={v.value + index}>
                              <Popover
                                 position='left'
                                 trigger="click"  //气泡点击出效果，方便调试
                                 content={() => {
                                    switch (v.value) {
                                       case '宫格设置':
                                          return <div style={{ height: 69, background: mould('#01185F', 'linear-gradient(245deg, #FFFFFF 0%, #EAEBEC 100%)', 'linear-gradient(197deg, rgba(38,38,38,0.65) 0%, #101010 100%)'), boxShadow: `inset 0px 0px 5px 1px ${mould('rgba(28,96,254,0.2500)', 'rgba(97,94,94,0.39)', 'rgba(132,132,132,0.5)')}`, display: 'flex', justifyContent: 'space-evenly', alignItems: 'center' }}>
                                             {v.screen.map((item) => {
                                                return <div key={item.img} onClick={() => { flipScreens(item.value); setMultiScreen(item.value) }}>
                                                   <img src={`/assets/images/application/${item.img}.png`} alt="" style={{ width: 40, height: 40, }} />
                                                   <div style={{ width: 40, fontWeight: 400, color: mould('#D9D9D9', '#615E5E', '#D9D9D9'), fontSize: 12, textAlign: 'center' }}>{item.value}</div>
                                                </div>
                                             })}
                                          </div>
                                       case '轮询设置':
                                          return <div style={{ height: 48, background: mould('#01185F', 'linear-gradient(245deg, #FFFFFF 0%, #EAEBEC 100%)', 'linear-gradient(197deg, rgba(38,38,38,0.65) 0%, #101010 100%)'), boxShadow: `inset 0px 0px 5px 1px ${mould('rgba(28,96,254,0.2500)', 'rgba(97,94,94,0.39)', 'rgba(132,132,132,0.5)')}`, color: mould("#D9D9D9", '', "#D9D9D9"), display: 'flex', justifyContent: 'space-evenly', alignItems: 'center' }}>
                                             <Switch onChange={(v, e) => {
                                                console.log(v);
                                                setPolling(v)
                                             }} aria-label="a switch for demo" style={{ border: ' 1px solid #D9D9D9', backgroundColor: polling ? mould('#2F53EA', '#4B4B4B', '#555F6D') : mould('#E8F0FF', '#C2C2C2', '#D7D7D7') }} checked={polling} />
                                             轮询间隔
                                             <Input value={pollingTime} disabled={polling ? false : true} style={{ width: 80, color: mould("#D9D9D9", '', "#D9D9D9"), border: ' 1px solid #D9D9D9', backgroundColor: polling ? "" : 'rgb(217, 217, 217)' }}
                                                onChange={(value) => {
                                                   if (value) {
                                                      setPollingTime(Number(value.replace(/[^0-9]/ig, '')))
                                                   } else {
                                                      setPollingTime(null)
                                                   }
                                                }} />
                                             分钟
                                          </div>
                                       default:
                                          break;
                                    }
                                 }}
                              >
                                 <img src={`/assets/images/application/${v.img}.png`} alt="" style={{ width: 54, height: 54, margin: '20px 0 0px 10px' }}
                                    onClick={() => {
                                       if (v.value == '背投') document.getElementById('rearProjection').requestFullscreen()
                                    }} />
                              </Popover>
                              <div style={{ width: 32, marginLeft: 16, color: mould('#D9D9D9', '#615E5E', '#D9D9D9'), }}>{v.value}</div>
                           </div>
                        })}
                     </div>
                  </div>
               </div>
            </div>
         </div >

         <ReminderBox
            title="分屏过多会导致浏览器内存不足，请根据您的电脑性能选择合适的分屏数量。"
            wait="取消"
            toadd="确定"
            visible={reminder}
            USER={GONGGESCREEN}
            onOk={() => {
               setReminder(false)
               if (multiScreen == "6分屏") setPageSize(6)
               if (multiScreen == "12分屏") setPageSize(12)
            }}
            close={() => {
               setReminder(false)
               setPageSize(pageSize)
            }}
         />
      </>

   )
}

function mapStateToProps (state) {
   const { auth } = state;
   return {
      user: auth.user,
   };
}

export default connect(mapStateToProps)(VideoScreen)
