import React, { useState, useEffect } from 'react';
import { Tree, Input, Checkbox, Spin,Modal,Form,Col,Row,message,Space } from 'antd';
import { EditOutlined,PlusCircleOutlined, DeleteOutlined,ExclamationCircleOutlined} from '@ant-design/icons';
import './index.less';
import { formItemLayout, btnItemLayout } from '../../../../components/crud/FormLayoutProps';
import { getGcaqTreeData } from '../../../../service/warn';
import apiurl from '../../../../service/apiurl';
import { httppost3,httpget6, httpget } from '../../../../utils/request';

const { Search } = Input;

type IProps = {
  onSelectFun?: any;
  setAdcd?: any;
  showCheckbox: any;
  tableName?: any;
  onChangeOpen?: any;
  hasAlertBox?: boolean;//顶部是否有预警条
  isFetch?: boolean;
}
const { confirm } = Modal;
const AdcdTreeSelector: React.FC<IProps> = ({ onSelectFun, setAdcd, showCheckbox, tableName, hasAlertBox }) => {
  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 [jdOpen, setJdOpen] = useState(false)
  const [form] = Form.useForm();
  const [mode, setMode] = useState('')
  const [itemDetail, setItemDetail] = useState<any>({})
  const [orderMax, setOrderMax] = useState<any>(0)
  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 () => {
    const adcdTreedata: any = await getGcaqTreeData();
    const item:any = adcdTreedata
    if (item) {
      setSelectedKeys([item[0]?.id])
      setAdcd(item[0]?.name)
    }
    if (adcdTreedata.length > 0) {
      handelTreeData(adcdTreedata);
      setTreeData(adcdTreedata);
      setLoading(false);
      setOrderMax(Math.max(...adcdTreedata.map((item:any) => item?.orderIndex)))
    }
  };
  // @ts-ignore
  const handelTreeData = (data) => {
    if (data.length > 0) {
      // @ts-ignore
      data.forEach(item => {
        item.title = item.name;
        item.key = item.id;
        if (item.children && item.children.length > 0) {
          handelTreeData(item.children);
        }
      });
    }
  }

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


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

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

      let adcdVal = "";
      adcdVal = selectData.title;

      let params = { id: adcdVal };
      if(onSelectFun){
        onSelectFun(params);
      }
      if(setAdcd){
        setAdcd(adcdVal)
      }
    } else {
      let params = { id: "" };
      if(onSelectFun){
        onSelectFun(params);
      }
      if(setAdcd){
        setAdcd("")
      }
    }
  };





  // 删除
  const deleteJd = (v: any) => {
    confirm({
      title: '删除',
      icon: <ExclamationCircleOutlined />,
      content: '确认删除此数据',
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      onOk: async() => {
        try {
          const res = await httpget6(apiurl.zsk.gcaq.deleteTree + `/${v.id}`)
          if (res.code === 200) { 
            message.success('删除成功');
            getCustomerTreeData();
          } 
          if (res.code === 400) { 
            message.error(res.description);
          }
        } catch (error) {
          console.log(error);
        }
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
 
  // 新增节点
  const saveJd = (v: any) => {
    if (v) {
      //  form.setFieldValue('name', v.title);
       setItemDetail(v);
    }
    setJdOpen(true);
    setMode("save");
  }

  // 编辑节点
  const editJd = (v: any) => { 
    setJdOpen(true);
    form.setFieldsValue(v);
    setMode("edit");
    setItemDetail(v);
  }

  const onOk = async () => { 
    const name = form.getFieldValue('name').replace(/\s/g,"");
    if(!name) return
    const url = mode == "save" ? apiurl.zsk.gcaq.saveTree : apiurl.zsk.gcaq.editTree;
    let saveParams = {
      name,
      // parentId: itemDetail?.id || undefined,
      // orderIndex:itemDetail?.orderIndex || orderMax
    }
    let editParams = {
      ...itemDetail,
      name
   } 
    try {
      const res = mode != 'save' ? await httppost3(url,editParams):await httpget(url, saveParams)
      if (res.code == 200) {
        message.success(mode == "save" ? '新增成功' : '编辑成功');
        setJdOpen(false);
        getCustomerTreeData();
        form.resetFields();
      } else if (res.code == 400) {
        message.error(res.description);
      }
    } catch (error) {
      console.log(error);
      
    }
  }
  return (
    <div  className='AdcdTreeSelectorStyle'>
      <div
        style={{
        padding: '10px',
        color: "#409eff",
        borderBottom: "1px solid #dfdfdf",
        marginBottom: 20,
        cursor: "pointer"
        }}
        onClick={saveJd}
      >新增知识库类型</div>
      {
        loading?
          <div style={{position:"absolute",top:"200px",left:"35%",background:"#fff",padding:"20px 30px",borderRadius:"10px"}}>
            <Spin tip="正在加载..." size="large" spinning={loading} />
          </div>:null 
      }

      <div className="treeBox1" style={{...treeBoxHeight,marginTop:"10px"}}>
        <div style={{ width: "300px"}}>
          {
            treeData.length > 0 &&
            <Tree
              defaultExpandAll={true}
              blockNode={false}
              onExpand={onExpand}
              checkedKeys={checkedKeys}
              onSelect={onSelect}
              selectedKeys={selectedKeys}
              treeData={isFiter ? newTreeData : treeData}
              showLine={true}
              titleRender={(v: any) => {
                return (
                    <div
                      style={{width:200}}
                      className='treeTitle'
                        >
                        <span>{v.title}</span>
                       <Space 
                        size={4}
                        className='treeBtn'
                        >
                          {/* <PlusCircleOutlined
                               style={{ fontSize: 15 }}
                               title='新增'
                               onClick={(e) => {
                                 e.stopPropagation();
                                 saveJd(v);
                               }}
                               className='hover-ele'
                             /> */}
                          <EditOutlined
                            title='编辑'
                            style={{ fontSize: 15 }}
                            onClick={(e) => {
                              e.stopPropagation();
                              editJd(v);
                            }}
                            className='hover-ele'
                          />
                          <DeleteOutlined
                            title='删除'
                            style={{ fontSize: 15 }}
                            onClick={(e) => {
                              e.stopPropagation();
                              deleteJd(v);
                            }}
                            className='hover-ele'
                          />
                       
                      </Space>
                      </div>
                )
              }}
            />
          }
        </div>
      
      </div>
      <Modal
        open={jdOpen}
        title={mode == "save" ? "新增" : '编辑'}
        destroyOnClose
        onCancel={() => { setJdOpen(false); form.resetFields()}}
        onOk={onOk}
      >
        <Form form={form} {...formItemLayout}>
          <Row>
            <Col span={24}>
              <Form.Item
                label="知识库类型"
                name="name"
                rules={[{required: true}]}
              >
            <Input  allowClear/>
           </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>
  );
};

export default AdcdTreeSelector;
