import React from 'react';
import { message, Row, Col } from 'antd';
import { uuid, thousand, cache } from '@zenview/micro-utils'
import { Service as ServiceLog } from '@zenview/micro-basic-library'
import communityObjectQuery from '../../../businessComponents/CommunityComponents'
import { queryLogTypes } from '../../../businessComponents/CommunityComponents/Dict/type'
import Service from '../../../businessComponents/CommunityComponents/service'
import './index.less';
import db from './db'

const { ObjectTagSelect, Header } = communityObjectQuery

// const searchInstanceLM = new LM_DB(LM_DB_NAMES.searchParams)

class CommunityObjectQuery extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
      chartsData: [],
      countLoading: false,
      type: 'person',
      horsty: [],
    };
  }

  onTypeChange = (type) => {
    if (type === 'vehicle') {
      this.getVehicleCount();
    }
    if (type === 'person') {
      this.getPersonCount();
    }
    if (type === 'house') {
      this.getHouseCount();
    }
    if (type === 'place') {
      this.getPlaceCount();
    }
    if (type === 'device') {
      this.getDeviceCount();
    }
    this.setState({ type });
  };

  componentDidMount() {
    this.getPersonCount();
  }

  getHouseCount = async () => {
    try{
      let res = await Service.queryHouseRecordCount();
      this.setState({
        count: res && res.count || 0,
      });
    }catch(err){
      this.setState({
        count: 0,
      });
    }
  }

  getVehicleCount = async () => {
    try{
      let res = await Service.getVehicleCount();
      this.setState({
        count: res.data.count,
      });
    }catch(err){
      this.setState({
        count: 0,
      });
    }
  };

  getPersonCount = async () => {
    try{
      let res = await Service.getPersonCount();
      this.setState({
        count: res.data,
      });
    }catch(err){
      this.setState({
        count: 0,
      });
    }
  };

  getPlaceCount = async () => {
    try{
      const userInfo = cache.getCache('userInfo', 'session')
      let res = await Service.queryPlacesByOrganizationId({
        organizationId: userInfo.organizationId,
        includeSubOrgIds: true
      });
      this.setState({
        count: res.data.length,
      });
    }catch(err){
      this.setState({
        count: 0,
      });
    }
  };

  getDeviceCount = async () => {
    try{
      let res = await Service.countDeviceType();
      let sum = 0;
      res.data.map((v) => {
        return (sum = sum + v.count);
      });
      this.setState({
        count: sum,
      });
    }catch(err){
      this.setState({
        count: 0,
      });
    }
  };

  onSearch = async ({ tags = [], keywords, uploadInfo }) => {
    if (!uploadInfo && !keywords && tags.length === 0) {
      message.info('请输入关键字进行搜索');
      return;
    }
    let { history, location } = this.props;
    // let base = ''
    // if (themeMode === 'single') {
    //   base = `/objectMap/${BaseStore.tab.createTabKey()}`;
    // }

    const id = uuid();
    const data = { id, tags, keywords, uploadInfo };

    let name = 'personArchives' 
    let pageTitle =''
    switch(this.state.type){
      case 'person':{
        db.personArchives.put(data)
        name = 'personArchives' 
        pageTitle='人员'
        break
      }
      case 'vehicle':{
        db.vehicleArchives.put(data)
        name = 'vehicleArchives' 
        pageTitle='车辆'
        break
      }
      case 'house':{
        db.houseArchives.put(data)
        name = 'houseArchives' 
        pageTitle='房屋'
        break
      }
      case 'place':{
        db.objectQueryList.put(data)
        name = 'objectMap' 
        pageTitle='场所'
        break
      }
      case 'device':{
        db.objectQueryList.put(data)
        name = 'objectMap' 
        pageTitle='设备'
        break
      }
    }
    
    location.pathname = `/${name}/objectQueryList`;
    location.search = `?id=${id}&type=${this.state.type}`;
    location.state = { pageTitle:`${pageTitle}档案列表` };

    const findType = queryLogTypes.find((t)=> t.type === this.state.type)

    // console.log(tags)
    let logInfo = {
      "description": `搜索【${tags&&tags.length?tags.map((t)=> t.tagName||t.name).join(','):''}${keywords&&(tags&&tags.length ? ',' +keywords : keywords)}】【${findType.name}】`,
      "module": 150500,
      "function": 150599
    }
    if(uploadInfo && uploadInfo.pictureUrl){
      logInfo.description = `搜索【${uploadInfo.pictureUrl}】【${findType.name}】`
    }

    ServiceLog.logger.save(logInfo);

    history.push(location);
  };

  render() {
    let { count, countLoading, type } = this.state;
    let nums = thousand(count).split('');
    return (
      <Row className="community-object-query" style={{ height: '100%' }}>
        <Col span={24}>
          <Header countLoading={countLoading} nums={nums} type={type} />
        </Col>
        <Col span={24} className="personnel-file-view-search-view">
          <div className="personnel-file-view-search">
            <ObjectTagSelect onSearch={this.onSearch} onTypeChange={this.onTypeChange} />
          </div>
        </Col>
      </Row>
    );
  }
}

export default CommunityObjectQuery;
