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 { version } from 'less';

let timing
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 api = useRef();
   const pageRef = useRef(page);
   const chooseAll = useRef(true);


   useEffect(() => {
      console.log(45464);
      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))
   }, [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) {
                              vv.children.map(cc => {
                                 if (c.camera) playVideo.push(cc)
                              })
                           }
                        })
                     }
                  })
               }
            }
            if (v.children) {
               videoPlay(v.children, 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);

      let nameData = videoData?.find(v => v?.label.includes(searchs.name))
      console.log(nameData);

      filterGroup

      if (searchs?.field0) {
         let videoId = [] //视频id
         for (let i in searchs) {
            console.log(i, searchs[i]);

         }

      }

   }, [searchs])




   useEffect(() => {
      let pollingTimes = pollingTime || 1
      if (timing) clearInterval(timing)
      if (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 * 5)
      }
   }, [polling, playData,pollingTime])

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

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

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


   //宫格设置点击
   const flipScreens = (data) => {
      console.log(data);
      switch (data) {
         case "单屏":
            setPageSize(1)
            break;
         case "4分屏":
            setPageSize(4)
            break;
         case "6分屏":
            setPageSize(6)
            break;
         case "12分屏":
            setPageSize(12)
            break;
         default:
            break
      }
   }

   // console.log(playData);

   return (
      <>
         <div
            className='KJBlue'
            style={{
               width: '100%', height: '100%',
               background: 'url(/assets/images/application/background.png) 100% 100%',
               backgroundSize: '100% 100%',
               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: '#FFFFFF',
                  lineHeight: '70px',
                  letterSpacing: '5px',
                  background: 'url(/assets/images/application/titleBottom.png) 100% 100%',
                  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: '2px solid #003D9E', position: 'relative', padding: 5 }}>
                  <div>查询：
                     <TreeSelect
                        style={{ width: 230, border: '1px solid rgba(255, 255, 255, 0.488)' }}
                        dropdownStyle={{ maxHeight: 300, overflow: 'auto', color: '#FFFFFF', }}
                        treeData={queryData}
                        placeholder="请选择"
                        multiple={true}
                        value={queryValue}
                        maxTagCount={1}
                        onChange={(e) => {
                           setQueryValue(e)
                        }}
                     />
                  </div>

                  <Tree
                     multiple
                     treeData={leftTree}
                     value={leftValue}
                     blockNode={false}
                     defaultExpandAll
                     onChange={(e) => {
                        // console.log(e);
                        setLeftValue(e)
                     }}
                     onSelect={(e) => {
                        // console.log(e);
                     }}
                     style={{ color: '#FFFFFF' }}
                  />
                  <Checkbox
                     checked={selectAll}
                     onChange={checked => {
                        setSelectAll(!selectAll)
                        chooseAll.current = !chooseAll.current
                     }}
                     ria-label="Checkbox 示例"
                     style={{ position: 'absolute', right: 10, bottom: 10 }}
                  >
                     全选</Checkbox>
               </div>
               <div style={{
                  flex: 1, marginLeft: '4px', border: '2px solid #003D9E',
               }}>
                  <div style={{ display: 'flex', }}>
                     <div 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 => {
                              return <Form.Select
                                 label={<span style={{ marginRight: -14, display: 'inline-block' }} title={v.name}>我的...:</span>}
                                 labelPosition="left"
                                 field={"field" + v.num}
                                 style={{ width: 75, color: "#fff", background: "#01185f", boxShadow: " inset 0px 0px 5px 1px rgba(28, 96, 254, 0.4)" }}
                                 placeholder="全部"
                                 showClear
                              >
                                 {v.filters.map(vv => <Form.Select.Option value={vv.cameraIds} 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, }}
                           onClick={() => {
                              api.current.validate().then((v) => {
                                 let aa = JSON.stringify(v);
                                 setSearchs(JSON.parse(aa))
                                 // 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 style={{ flex: 1, height: '100%' }}>
                        <Row style={{ height: `calc( 100% - 160px )` }}>
                           {playData?.slice((page - 1) * pageSize, page * pageSize)?.map(v => {
                              return <VideoCard key={'VideoCard' + v.key} data={v} pageSize={pageSize} />
                           })}
                        </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: 'white' }}
                              onChange={(currentPage, pageSize) => {
                                 setPage(currentPage)
                                 pageRef.current= currentPage
                              }}
                           /> : ""}
                        </div>
                     </div>
                     {/* 视频设置 */}
                     <div style={{
                        width: 64, height: 476, background: ' #01185F', boxShadow: 'inset 0px 0px 5px 1px rgba(28,96,254,0.4000)', borderRadius: ' 1px', textAlign: 'center',
                     }}>
                        {[{ img: 'gongge', value: '宫格设置', screen: [{ img: 'screen1', value: '单屏' }, { img: 'screen4', value: '4分屏' }, { img: 'screen6', value: '6分屏' }, { img: 'screen12', value: '12分屏' },] },
                        { img: 'polling', value: '轮询设置' },
                        { img: 'back', value: '背投', },
                        { img: 'monitor', 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: '#01185F', boxShadow: ' inset 0px 0px 5px 1px rgba(28,96,254,0.2500)', display: 'flex', justifyContent: 'space-evenly', alignItems: 'center' }}>
                                             {v.screen.map((item) => {
                                                return <div key={item.img} onClick={() => flipScreens(item.value)}>
                                                   <img src={`/assets/images/application/${item.img}.png`} alt="" style={{ width: 40, height: 40, }} />
                                                   <div style={{ width: 40, fontWeight: 400, color: ' #D9D9D9', fontSize: 12, textAlign: 'center' }}>{item.value}</div>
                                                </div>
                                             })}
                                          </div>
                                       case '轮询设置':
                                          return <div style={{ height: 48, background: '#01185F', boxShadow: ' inset 0px 0px 5px 1px rgba(28,96,254,0.2500)', color: ' #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', }} checked={polling} />
                                             轮询间隔
                                             <Input value={pollingTime} style={{ width: 80, color: "#D9D9D9", border: ' 1px solid #D9D9D9', }}
                                                onChange={(value) => {
                                                   setPollingTime(Number(value.replace(/[^0-9]/ig, '')))
                                                }} />
                                             分钟
                                          </div>
                                       default:
                                          break;
                                    }
                                 }}
                              >
                                 <img src={`/assets/images/application/${v.img}.png`} alt="" style={{ width: 54, height: 54, margin: '20px 0 0px 10px' }} />
                              </Popover>
                              <div style={{ width: 32, marginLeft: 16 }}>{v.value}</div>
                           </div>
                        })}
                     </div>
                  </div>
               </div>
            </div>
         </div >
      </>

   )
}

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

export default connect(mapStateToProps)(VideoScreen)
