import React, { useState, useRef,useEffect,forwardRef, useImperativeHandle } from 'react';
import {Tree, Input, Checkbox, Spin, Modal,Tabs} from 'antd';
import { FileTextOutlined } from '@ant-design/icons';
import Jbxx from '../../../../Home/MapCtrl/components/Skjcxx/jbxx'
import Krqx from '../../../../Home/MapCtrl/components/Skjcxx/Krqx'
import Zrtx from '../../../../Home/MapCtrl/components/Skjcxx/zrtx'
import Jzw from '../../../../Home/MapCtrl/components/Skjcxx/jzw'
import Jsxx from '../../../../Home/MapCtrl/components/Skjcxx/jsxx'
import Gctp from '../../../../Home/MapCtrl/components/Skjcxx/gctp'
import Fxya from '../../../../Home/MapCtrl/components/Skjcxx/fxya'
import Sjbg from '../../../../Home/MapCtrl/components/Skjcxx/sjbg'
import SdzJbxx from '../../../../Home/MapCtrl/components/sdz/jbxx'
import SdzZrr from '../../../../Home/MapCtrl/components/sdz/zrr'
import SdzGctp from '../../../../Home/MapCtrl/components/sdz/gctp'
import SdzFxya from '../../../../Home/MapCtrl/components/sdz/fxya'
import SdzSjzl from '../../../../Home/MapCtrl/components/sdz/sjzl'
import './index.less';


const { Search } = Input;

type IProps = {
  onSelectFun?: any;
  setCode?: any;
  showCheckbox: any;
  tableName?: any;
  hasAlertBox?: boolean;//顶部是否有预警条
  setTag?: any,
  data?: any,
  clickHandler?: any,
  url?:any
}

const AdcdTreeSelector: React.FC<IProps> = forwardRef(({
  onSelectFun,
  clickHandler,
  setCode,
  setTag,
  showCheckbox,
  tableName,
  hasAlertBox,
  data,
  url
}, ref) => {
  const [loading, setLoading] = useState(true);
  const [treeData, setTreeData] = useState([]);
  const [newTreeData, setNewTreeData] = useState([]);
  const [isFiter, setIsFiter] = useState(false);
  const [expandedKeys, setExpandedKeys] = useState([]);
  const [checkedKeys, setCheckedKeys] = useState([]);
  const [selectedKeys, setSelectedKeys] = useState<any>([]);
  const [selectedItem, setSelectedItem] = useState({});
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  const [treeBoxHeight, setTreeBoxHeight] = useState({})
  const [itemDetail, setItemDetail] = useState<any>({}) // 树中的每一项的详细信息

  const [open, setOpen] = useState(false)
  const [keys, setKeys] = useState(1)
  const selectKeysRef = useRef()
  console.log("data22",data);
  
  useImperativeHandle(ref, () => ({
    getTreeData: () => {
      getCustomerTreeData();
    }
  }))
  const TabList1 = [
    {
      key: '1',
      label: '基本信息',
    },
    {
      key: '2',
      label: '库容曲线',
    },
    {
      key: '3',
      label: '责任体系',
    },
    {
      key: '4',
      label: '建筑物',
    },
    {
      key: '5',
      label: '建设信息',
    },
    {
      key: '6',
      label: '工程图片',
    },
    {
      key: '7',
      label: '防汛预案',
    },
    {
      key: '8',
      label: '设计报告',
    },
  ]
  const TabList2 = [
    {
      key: '1',
      label: '基本信息',
    },

    {
      key: '3',
      label: '责任体系',
    },
    {
      key: '6',
      label: '工程图片',
    },
    {
      key: '7',
      label: '防汛预案',
    },
    {
      key: '8',
      label: '设计资料',
    },
  ]
  useEffect(() => {
    getCustomerTreeData();
  }, []);

  useEffect(() => {
    if(tableName){
      setSelectedKeys([]);
    }
  }, [tableName]);

  useEffect(()=>{
    //根据预警条计/多选框计算高度
    if(hasAlertBox){
      if(showCheckbox){
        setTreeBoxHeight({height:"calc( 100vh - 240px )"})
      }else{
        setTreeBoxHeight({height:"calc( 100vh - 210px )"})
      }
    }else{
      if(showCheckbox){
        setTreeBoxHeight({height:"calc( 100vh - 224px )"})
      }else{
        setTreeBoxHeight({height:"calc( 100vh - 194px )"})
      }
    }
  },[hasAlertBox])

  const getCustomerTreeData = async () => {
    let params = {
      "level": 4
    };
    // const adcdTreedata:any = await getGczxGcTreeData(params);
    const adcdTreedata: any = await url(params);
    const item:any = adcdTreedata?.[0]?.children?.[0]
    if (item) {
      if (selectKeysRef.current) {
        setSelectedKeys(selectKeysRef.current)
        setCode(selectKeysRef.current[0])
      } else {
        setCode(item.code)
        setSelectedKeys([item.code])
        setTag(item.type)
      }
      // setCode(item.code)
      // setSelectedKeys([item.code])
    }

    if (adcdTreedata.length > 0) {
      handelTreeData(adcdTreedata);
      setTreeData(adcdTreedata);
      setLoading(false);
    }
  };
  // @ts-ignore
  const handelTreeData = (data) => {
    if (data.length > 0) {
      // @ts-ignore
      data.forEach(item => {
        item.title = item.sname;
        // (
        //   <span  style={{position:'relative'}}>
        //     {item.sname}
        //     <div  style={{color:'red',position:'absolute',left:'50px'}}>按钮</div>
        //   </span>
        // )
        item.key = item.code;
        if (item.children && item.children.length > 0) {
          handelTreeData(item.children);
        }
      });
    }
  }

  const onExpand = (expandedKeysValue: any) => {
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };

  const [adcdLevel,setAdcdLevel] = useState(false);

  const onSelect = (selectedKeysValue: any, info: any) => {
    setSelectedKeys(selectedKeysValue);
    selectKeysRef.current = selectedKeysValue;
    setSelectedItem(info);

    if (info.selectedNodes.length > 0) {
      let selectData = info.selectedNodes[0];

      let adcdVal = "";
      adcdVal = selectData.code;
      // if(!adcdLevel){
      //   const code = selectData.code.substring(0,15);
      //   if(code.endsWith('000000000')){//县
      //     adcdVal = selectData.code.substring(0,6);
      //   }else if(code.endsWith('000000')){//镇
      //     adcdVal = selectData.code.substring(0,9);
      //   }else if(code.endsWith('000')){//村
      //     adcdVal = selectData.code.substring(0,12);
      //   }else{
      //     adcdVal = selectData.code;
      //   }
      // }else{
      //   adcdVal = selectData.code;
      // }

      let params = { code: adcdVal };
      if(onSelectFun){
        onSelectFun(params);
      }
      if(setCode){
        setCode(adcdVal)
        setTag(selectData.type)
      }
    } else {
      let params = { code: "" };
      if(onSelectFun){
        onSelectFun(params);
      }
      if(setCode){
        setCode("")
        setTag("")
      }
    }
  };

  useEffect(() => {
    if(selectedKeys.length>0 && Object.keys(selectedItem).length>0){
      onSelect(selectedKeys,selectedItem);
    }
  }, [adcdLevel]);

  // @ts-ignore
  const rebuildData = (value, arr) => {
    if (!arr) {
      return [];
    }
    // @ts-ignore
    let newarr = [];
    if (Object.prototype.toString.call(arr) === "[object Array]") {
      // @ts-ignore
      arr.forEach((element) => {
        if (element.sname.indexOf(value) > -1) {
          const ab = rebuildData(value, element.children);
          const obj = {
            ...element,
            children: ab,
          };
          newarr.push(obj);
        } else {
          if (element.children && element.children.length > 0) {
            const ab = rebuildData(value, element.children);
            const obj = {
              ...element,
              children: ab,
            };
            if (ab && ab.length > 0) {
              newarr.push(obj);
            }
          }
        }
      });
    }

    // @ts-ignore
    setNewTreeData(newarr.length > 0 ? newarr : []);
    // @ts-ignore
    return newarr;
  };
  // @ts-ignore
  const fiterData = (event) => {
    setIsFiter(true);
    if (treeData.length > 0) {
      rebuildData(event.target.value, treeData)
    }
  };
  const onChange = (key:any) => {
    setKeys(key)
  }
  return (
    <div style={{position:"relative"}} className='GcTreeSelectorStyle '>
      {!loading && <Search allowClear style={{ width: "229px" }} placeholder="请输入" onChange={e => fiterData(e)} />}
      {/* <Search
      placeholder="input search text"
      enterButton="Search"
      size="large"
    /> */}
      {
        treeData.length > 0 && showCheckbox && !loading &&
        <>
          <div className="checkboxBox">
            <Checkbox
              style={{marginLeft:"8px"}}
              onChange={(e)=>{
                setAdcdLevel(e.target.checked);
              }}
            >仅查询当前级</Checkbox>
          </div>
        </>
      }

      {
        loading?
          <div style={{position:"absolute",top:"200px",left:"50px",background:"#fff",padding:"20px 30px",borderRadius:"10px"}}>
            <Spin tip="正在加载..." size="large" spinning={loading} />
          </div>:null
      }

      <div className="treeBox" style={{...treeBoxHeight,marginTop:showCheckbox?"30px":"0"}}>
        <div style={{ width: "230px", overflow: "hidden" }} className='tree-container'>
          {
            treeData.length > 0 &&
            <Tree
              defaultExpandAll={true}
              blockNode={false}
              onExpand={onExpand}
              checkedKeys={checkedKeys}
              titleRender={(v:any)=>{
                return (<>
                    {
                    v.children?.length > 0 ? null :
                      <>
                      <div  style={{color:'#a8a8a8',position:'absolute',right:'25px'}} onClick={(e)=>{
                        e.stopPropagation()
                        setOpen(true)
                          setItemDetail(v)
                          console.log(v);
                          
                        clickHandler(v)
                      }}><FileTextOutlined /></div>
                      </>
                  }
                    <div className={v.status ? "" : "no-matter"}>{v.title}</div>
                </>)
              }}
              onSelect={onSelect}
              selectedKeys={selectedKeys}
              treeData={isFiter ? newTreeData : treeData}
            />
          }
        </div>
        <Modal
          title=""
          width={1000}
          style={{ height: '646px' }}
          open={open}
          footer={null}
          onCancel={() => {
            setOpen(false)
            setKeys(1)
          }}
          className='detail-modal'
          destroyOnClose
        >
          <div className="dp-popup-content">
          <div className="content-body tyb skpop" id='tyb'>
            <div className="title flexac flex">
              <div className="name flex flexac">
                <div className='nameBorder'></div>
                {itemDetail.type === 1 ?data?.resName : data?.hystName}
              </div>
            </div>
              <div style={{ padding: '5px', display: 'flex' }}>
                <>
                  <Tabs
                    defaultActiveKey="1"
                    type="card"
                    onChange={onChange}
                    items={itemDetail.type === 1 ? TabList1 : TabList2}
                    tabPosition='left'
                    tabBarStyle={{margin:0}}
                  />
                  {itemDetail.type == 1 ? 
                    <div style={{backgroundColor:'#fff',overflowY:'auto',padding:'0 5px 5px 5px'}}>
                      {keys == 1 && <Jbxx data={data} />}
                      {keys == 2 && <Krqx record={data} />}
                      {keys == 3 && <Zrtx record={data} />}
                      {keys == 4 && <Jzw record={data} />}
                      {keys == 5 && <Jsxx record={data} />}
                      {keys == 6 && <Gctp record={data} />}
                      {keys == 7 && <Fxya record={data} />}
                      {keys == 8 && <Sjbg record={data} />}
                    </div> :
                     <div style={{backgroundColor:'#fff',overflowY:'auto',padding:'0 5px 5px 5px'}}>
                       {keys == 1 && <SdzJbxx data={data} />}
                       {keys == 3 && <SdzZrr data={data} />}
                       {keys == 6 && <SdzGctp data={data} />}
                       {keys == 7 && <SdzFxya data={data} />}
                       {keys == 8 && <SdzSjzl data={data} />}
                   </div>
                 }
                
                </>
              </div>
          </div>
        </div>
        </Modal>
      </div>

    </div>
  );
});

export default AdcdTreeSelector;
