import React, { useEffect, useState } from 'react';
import {
  Badge,
  Button,
  Card,
  Descriptions,
  Icon,
  message,
  Popconfirm,
  Row,
  Spin,
  Tabs,
  Tooltip,
} from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { connect } from 'dva';
import { router } from 'umi';
import { MetaDataCommon } from '../data';
import Definition from './definition';
import { ConnectState, Dispatch } from '@/models/connect';
import apis from '@/services';
import Save from '.';

interface Props {
  dispatch: Dispatch;
  location: Location;
  close: Function;
  save: Function;
}

interface State {
  basicInfo: Partial<MetaDataCommon>;
  saveVisible: boolean;
  deviceCount: number;
  spinning: boolean;
  units: any;
}

const Detail: React.FC<Props> = props => {
  const initState: State = {
    basicInfo: {},
    saveVisible: false,
    deviceCount: 0,
    spinning: true,
    units: {},
  };
  const {
    dispatch,
    location: { pathname },
  } = props;
  const [events, setEvents] = useState<any[]>([]);
  const [functions, setFunctions] = useState<any[]>([]);
  const [properties, setProperties] = useState<any[]>([]);
  const [tags, setTags] = useState<any[]>([]);
  const [basicInfo, setBasicInfo] = useState(initState.basicInfo);
  const [saveVisible, setSaveVisible] = useState(initState.saveVisible);
  const [spinning, setSpinning] = useState(initState.spinning);
  const [units, setUnits] = useState(initState.units);
  const [productId, setProductId] = useState('');

  const handleSearch = (id?: string) => {
    const list = pathname.split('/');
    const temp = id || list[list.length - 1];
    dispatch({
      type: 'metadataCommon/queryById',
      payload: temp,
      callback: (r: any) => {
        if (r.status === 200) {
          const data = r.result;
          setBasicInfo(data)
          if (data.metadata) {
            const metadata = JSON.parse(data.metadata);
            setEvents(metadata.events);
            setFunctions(metadata.functions);
            setProperties(metadata.properties);
            setTags(metadata.tags);
          }
          setSpinning(false);
        }
      },
    });
  };

  useEffect(() => {
    apis.metadataCommon
      .units()
      .then((response: any) => {
        if (response.status === 200) {
          setUnits(response.result);
        }
      })
      .catch(() => {});


    if (pathname.indexOf('save') > 0) {
      const list = pathname.split('/');
      handleSearch(list[list.length - 1]);
      setProductId(list[list.length - 1]);
    }
  }, []);

  const saveData = (item?: any) => {
    let data: Partial<MetaDataCommon>;
    const metadata = JSON.stringify({ events, properties, functions, tags });

    // TODO 这个地方有疑惑，set数据之后此处数据还是未更新。原因待查
    if (item) {
      data = { ...item, metadata };
    } else {
      data = { ...basicInfo, metadata };
    }
    apis.metadataCommon
      .saveOrUpdate(data)
      .then(r => {
        if (r.status === 200) {
          setSaveVisible(false);
          message.success('保存成功');
          const list = pathname.split('/');
          handleSearch(list[list.length - 1]);
        }
      })
      .catch(() => {});
  };

  const updateData = (type: string, item: any, onlySave: boolean) => {
    let metadata = JSON.stringify({ events, properties, functions, tags });
    if (type === 'event') {
      metadata = JSON.stringify({ events: item, properties, functions, tags });
    } else if (type === 'properties') {
      metadata = JSON.stringify({ events, properties: item, functions, tags });
    } else if (type === 'function') {
      metadata = JSON.stringify({ events, properties, functions: item, tags });
    } else if (type === 'tags') {
      metadata = JSON.stringify({ events, properties, functions, tags: item });
    }

    const data = { ...basicInfo, metadata };

    apis.metadataCommon
      .saveOrUpdate(data)
      .then((re: any) => {
        if (re.status === 200) {
          message.success('保存成功');
          // if (!onlySave) {
          //   deploy(data);
          // }
        }
      })
      .catch(() => {})
      .finally(() => setBasicInfo({ ...data, state: onlySave ? basicInfo.state : 1 }));
  };

  const titleInfo = (
    <Row>
      <div>
        <span>物模型：{basicInfo.name}</span>
      </div>
    </Row>
  );

  return (
    <Spin tip="加载中..." spinning={spinning}>
      <PageHeaderWrapper title={titleInfo}>
        {!spinning && (
           <Definition
           basicInfo={basicInfo}
           eventsData={events}
           functionsData={functions}
           propertyData={properties}
           tagsData={tags}
           unitsData={units}
           saveEvents={(data: any, onlySave: boolean) => {
             setEvents(data);
             updateData('event', data, onlySave);
           }}
           saveFunctions={(data: any, onlySave: boolean) => {
             setFunctions(data);
             updateData('function', data, onlySave);
           }}
           saveProperty={(data: any[], onlySave: boolean) => {
             setProperties(data);
             updateData('properties', data, onlySave);
           }}
           saveTags={(data: any[], onlySave: boolean) => {
             setTags(data);
             updateData('tags', data, onlySave);
           }}
           update={() => handleSearch(productId)}
         />
        )}

        {saveVisible && (
          <Save
            data={basicInfo}
            close={() => setSaveVisible(false)}
            save={(item: any) => {
              setBasicInfo(item);
              saveData(item);
            }}
          />
        )}
      </PageHeaderWrapper>
    </Spin>
  );
};
export default connect(({ metadataCommon, loading }: ConnectState) => ({
  metadataCommon,
  loading,
}))(Detail);
