import { useState, useEffect } from 'react';
import { Button, Cascader, Input, message, List, Typography } from 'antd';
import { getOrgListService } from '../../services/ktj/org';
import { OrgItem } from '../../services/ktjTypes';
import {bleItem, child, GwdItem, orgCascaderType, systemItem} from './types';
import { sysSet } from '../../services/user/system';
import {  useAppDispatch, useAppSelector } from "../../utils/hooks";
import { updateSystemAccountState, updateSystemOrgState } from '../../store/system/systemSlice';
import {createWebSocket, sharedWsUrl} from "../../services/socket";
import {start, stop, disconnect, connect} from "../../services/ble/ble";
export default function Setting(){
  useEffect(()=>{
    queryRailData()
    onBleStart()
    querySettingData()
    return ()=>{
      onBleStop()
    }
  },[])
  const dispatch = useAppDispatch();
  const deviceInfo = useAppSelector(store => store.context.device);
  const systemState = useAppSelector((store) => store.systemState);
  const [systemList, setSystemList] = useState<systemItem[]>([])
  const [accountInfo, setAccountInfo] = useState<systemItem>({})
  const [orgInfo, setOrgInfo] = useState<systemItem>({})
  const [orgValues, setOrgValues] = useState<string[]>([])
  const [bleList, setBleList] = useState<bleItem[]>([])

  // 创建 websocket 客户端
  const wsClient = createWebSocket(sharedWsUrl);
  function querySettingData(){
      let systemInfo = systemState.systemInfo
      setSystemList(systemInfo)
  }


  useEffect(() => {
    const subscription = wsClient.dataOb.subscribe(data => {
      // @ts-ignore
      if (data.messageType === "STATE" && data.path === "/api/ble/ble-list") {
        // @ts-ignore
        setBleList(data.data)
      }
    });
    wsClient.connect();
    return () => subscription.unsubscribe();
  });

  useEffect(()=>{
    if(systemState.orgInfo){
      const cloneOrgItem = systemState.orgInfo
      let orgItem:systemItem = {
        id: cloneOrgItem.id,
        name: cloneOrgItem.name,
        code: cloneOrgItem.code,
        value: cloneOrgItem.value
      }
      setOrgInfo(orgItem)
    }
  }, [systemState.orgInfo])


  useEffect(()=>{
    if(systemState.accountInfo){
      const cloneAccountItem = systemState.accountInfo
      let accountInfo:systemItem = {
        id: cloneAccountItem.id,
        name: cloneAccountItem.name,
        code: cloneAccountItem.code,
        value: cloneAccountItem.value
      }
      setAccountInfo(accountInfo)
    }
  }, [systemState.accountInfo])


  useEffect(()=>{
    if(orgInfo && orgInfo.value){
      let orgIds:string[] = []
      const values:child[] = JSON.parse(orgInfo.value)
      values.map(item => {
        orgIds.push(item.value)
      })
      setOrgValues(orgIds)
    }
  }, [orgInfo])

  //获取铁路局数据
  const [KTJOrgList, setKTJOrgList] = useState<orgCascaderType[]>([]);
  function queryRailData(){
    getOrgListService().then((res) => {
      if (res && res.data) {
        let resData: OrgItem[] = res.data;
        let data = convertToCascaderData(resData)
        setKTJOrgList(data)
      }
    }).catch((e) => {});
  }

  function onOrgChange(value:string[], selectedOptions: orgCascaderType[]){
    if(selectedOptions && selectedOptions.length){
      let orgList = selectedOptions.map(item => {
        return {
          value:item.value,
          label:item.label
        }
      })
      const orgParams = {
        ...orgInfo,
        value:JSON.stringify(orgList)
      }
      sysSet(orgParams, "PUT").then(res=>{
        if(res.status === 0){
          dispatch(updateSystemOrgState(orgParams))
          message.success("修改成功")
        }
      })
    }
  }

  let newAccountInfo = {
    name:'',
    value: ''
  }
  function onSaveAccount(){
    const accountParams = {
      code:"UPLOAD_USERNAME", 
      name:accountInfo.name,
      value:newAccountInfo.value,
      id:accountInfo.id
    }
    sysSet(accountParams, "PUT").then(res=>{
      if(res.status === 0){
        dispatch(updateSystemAccountState(accountParams))
        message.success("修改成功")
      }
    })
  }

  function onAccountChange(accountValue:string){
    newAccountInfo.name = accountInfo.name || '';
    newAccountInfo.value = accountValue;
  }

  function convertToCascaderData(data:OrgItem[]) {
    return data.map(item => {
      const newItem:orgCascaderType = {
        value: item.key,
        label: item.value,
      };
      if (item.gwdDicList && item.gwdDicList.length > 0) {
        newItem.children = item.gwdDicList.map(gwdItem => {
          const newGwdItem:GwdItem = {
            value: gwdItem.key,
            label: gwdItem.value,
          };
          if (gwdItem.railDicList && gwdItem.railDicList.length > 0) {
            newGwdItem.children = gwdItem.railDicList.map(railItem => ({
                value: railItem.key,
                label: railItem.value || railItem.input
            }));
          }
          return newGwdItem;
        });
      }
      return newItem;
    });
  }

  function onBleStart() {
    start().then(() => {
      message.success('蓝牙开始扫描')
    })
  }

  function onBleStop() {
    stop().then(() => {
    })
  }

  function bleConnect(address: string) {
    connect(address).then((res) => {
      if (res.status !== 0) {
        message.error(res.data.info);
        return
      }
      message.success('蓝牙连接成功')
    })
  }

  function bleDisconnect() {
    disconnect().then(() => {
      message.success('蓝牙断开连接')
    })
  }

  const connectionStatus = () => {
    if (!deviceInfo.isConnected) {
      return (
          <section className='p-[20px]'>
            <div>附近设备</div>
            {bleList.map(item => {
              return <div key={item.address}>
                <div className={'flex justify-between w-1/4 pt-2.5'}>
                  <p >
                    <p className={'text-[16px] text-gray-400'}>{item.name}</p>
                    <p className={'text-[12px] text-gray-400'}>{item.address}</p>
                  </p>
                  {
                    item.connect ? <p className={'text-[12px] text-gray-400'}>已连接</p> : <Button type={'primary'} onClick={() =>bleConnect(item.address)}>连接</Button>
                  }

                </div>
              </div>
            })}
          </section>
      );
    } else {
      if(deviceInfo.connectedType === 'UART_CHANNEL') {
        return (
            <div className='p-[20px]'>
              已通过usb连接
              <div className="mt-[1rem] ml-[1.6rem]">sn码：{deviceInfo.sn}</div>
            </div>
        )

      }else if(deviceInfo.connectedType === 'BLE_CHANNEL') {
        return (
            <div className='p-[20px]'>
              已通过蓝牙连接
              <Button className={'ml-[10px]'} onClick={bleDisconnect}>断开连接</Button>
              <div className="mt-[1rem] ml-[1.6rem]">sn码：{deviceInfo.sn}</div>
            </div>
        )
      }
    }
  };


  // @ts-ignore
  return <><div className={'pr-2.5 pl-2.5  w-full h-full'}>
    <div className={'h-full w-full bg-white p-10 rounded-2xl'}>
      <h1 className='text-[20px]'>系统配置</h1>
      <section className='p-[20px]'>
        <div>
          <span>铁路局：</span>
          <Cascader className='w-[300px]' key={orgValues.length} defaultValue={orgValues} options={KTJOrgList} onChange={onOrgChange} placeholder="请选择局段线" /></div>
        <div className='mt-[10px]'>
         <span> {accountInfo.name}：</span>
          <Input key={accountInfo.value} defaultValue={accountInfo.value} onChange={(e)=>{onAccountChange(e.target.value)}} className='w-[300px]'></Input>
          <Button className='ml-[10px]' size='small' type="primary" onClick={onSaveAccount}>保存</Button>
        </div>
      </section>
      <h1 className='text-[20px]'>设备配置</h1>
      {connectionStatus()}
    </div>

  </div>
    </>
}