import React from 'react';
import TagInput from '../TagInput';
import TabHeader from '../TabHeader';
import TagPortal from '../TagPortal';
import UploadPortal from '../UploadPortal';
import { BaseStore, Dict } from '@zenview/micro-basic-library';
import { message } from 'antd';
import Service from '../service';
// import { menu } from '@zenview/utils'
import _ from 'lodash';
import './index.less';

// const { Service /* Dict, Shared, Utils */ } = window;
//const vehicleTags = _.cloneDeep(Dict.map.behaviorAttr)
const placeholderTypes = {
  person: '请输入人员姓名、身份证号、经过的设备或场所查询',
  vehicle: '请输入车牌号、车主姓名、身份证号查询',
  device: '请输入设备名称查询',
  place: '请输入场所名称查询',
  house: '请选择房屋标签、属性查询',
};
const TagPortalComponent = Dict.withDict(['119100'])(TagPortal);

class ObjectMapTagSelect extends React.Component {
  constructor(props) {
    super(props);
    const { defaultTags, type = 'person', keywords, uploadInfo, hasSingleType } = this.props;
    const objectTypes = this.queryObjectAuth();
    this.tagBoxRef = React.createRef();
    this.tagInputRef = React.createRef();
    this.timer = null;

    this.state = {
      type: objectTypes.indexOf(type) > -1 ? type : objectTypes[0],
      visibleTag: false,
      visibleUpload: false,
      uploadInfo: uploadInfo ? _.cloneDeep(uploadInfo) : undefined,
      isSetDefault: Array.isArray(defaultTags) && defaultTags.length > 0,
      selectTags: defaultTags ? _.cloneDeep(defaultTags) : [],
      keywords: keywords || undefined,
      keywordsList: [],
      objectTypes: hasSingleType ? [] : objectTypes,
    };
  }
  static getDerivedStateFromProps(props, state) {
    const options = {};
    if (!state.isSetDefault && Array.isArray(props.defaultTags) && props.defaultTags.length > 0 && state.selectTags.length === 0) {
      options.selectTags = _.cloneDeep(props.defaultTags);
      options.isSetDefault = true;
    }
    if (props.keywords && state.keywords === undefined) {
      options.keywords = props.keywords;
    }
    if (props.uploadInfo && !state.uploadInfo) {
      options.uploadInfo = _.cloneDeep(props.uploadInfo);
    }
    if (Object.keys(options).length > 0) {
      return options;
    }
    return null;
  }
  componentWillUnmount() {
    clearTimeout(this.timer);
    this.tagBoxRef = null;
    this.tagInputRef = null;
    this.timer = null;
  }
  queryObjectAuth() {
    const userAuthListAlias = BaseStore.auth.userAuthList.map((item) => item.alias);

    let arr = []; //, 'device', 'house', 'place''device', 'house', 'place', 'vehicle'
    if (userAuthListAlias.includes('personArchivesView') || userAuthListAlias.includes('communityActualPerson')) {
      arr.push('person');
    }
    if (userAuthListAlias.includes('vehicleArchives') || userAuthListAlias.includes('communityActualVehicle')) {
      arr.push('vehicle');
    }
    if (userAuthListAlias.includes('houseArchivesView') || userAuthListAlias.includes('communityActualHouse')) {
      arr.push('house');
    }
    if (userAuthListAlias.includes('placeFile')) {
      arr.push('place');
    }
    if (userAuthListAlias.includes('deviceFile') || userAuthListAlias.includes('communityActualDevice')) {
      arr.push('device');
    }
    return arr;
  }
  /**
   * @选择tag或取消tag
   */
  onSelect = (item, localType) => {
    let tags = this.state.selectTags;
    const index = tags.findIndex((v) => v.code === item.code);
    if (index > -1) {
      tags.splice(index, 1);
    } else {
      //TODO 单选的分组
      if (item.tagGroup === '119905') {
        tags = tags.filter((v) => v.typeCode !== item.typeCode);
      }
      if (tags.length >= 10) {
        return message.warn('选择的标签数量不能超过10个');
      }
      tags.push(item);
    }
    const options = { selectTags: tags };
    if (localType === 'keyword') {
      const { type } = this.state;
      if ((type === 'person' && item.type.includes('PERSONID')) || (type === 'vehicle' && item.type.includes('PLATEID')) || (type === 'device' && +item.type===2) || (type === 'place' && +item.type===6) ) {
        return this.setState({ selectTags: [], keywords: '', keywordsList: [] }, () => {
          this.tagInputRef.current.autoFocusInput();
          this.tagInputRef.current.clearInput();
          this.props.onSearch({ tags: [item] });
        });
      }
      options.keywords = null;
      options.keywordsList = [];
      this.tagInputRef.current.clearInput();
    }
    this.setState(options);
    this.tagInputRef && this.tagInputRef.current.autoFocusInput();
  };
  imageUpload = (item) => {
    // this.setState({ uploadInfo: item });
    this.setState({ selectTags: [], keywordsList: [], keywords: '' }, () => {
      this.props.onSearch({ uploadInfo: item });
    });
    this.tagInputRef && this.tagInputRef.current.autoFocusInput();
  };
  onTypeChange = (type) => {
    this.setState({ type, selectTags: [], keywords: null, keywordsList: [], uploadInfo: undefined });
    this.props.onTypeChange && this.props.onTypeChange(type);
    this.tagInputRef.current.clearInput();
  };
  openTagSelect = () => {
    if (!this.state.visibleTag) {
      this.setState({ visibleTag: true, visibleUpload: false });
    }
  };
  openImgUpload = () => {
    if (!this.state.visibleUpload) {
      this.setState({ visibleUpload: true, visibleTag: false });
    }
  };
  onTagChange = (tags) => {
    console.log(tags)
    this.setState({ selectTags: tags });
  };

  closePortal = () => {
    const { visibleTag, visibleUpload } = this.state;
    if (visibleTag || visibleUpload) {
      this.setState({ visibleTag: false, visibleUpload: false });
    }
  };

  /**
   * @查询关键字转换成字典格式
   * 屏蔽缓存
   */
  onInputChange = (value, shouldQueryRecommend = true) => {
    const { type } = this.state;
    clearTimeout(this.timer);
    if (!value) {
      return this.setState({ keywordsList: [], keywords: value });
    }
    this.setState({ keywords: value });
    if (!shouldQueryRecommend ) {
      return;
    }
    if (type === 'vehicle') {
      this.timer = setTimeout(() => this.queryRecommendVehicle(value), 500);
    } else if (type === 'device') {
      this.timer = setTimeout(() => this.queryRecommendDevice(value), 500);
    } else if (type === 'place') {
      this.timer = setTimeout(() => this.queryRecommendPlace(value), 500);
    } else {
      this.timer = setTimeout(() => this.queryRecommend(value), 500);
    }
  };

  /**
   * @查询推荐列表plateRecommend
   */
  queryRecommendVehicle = async (value) => {
    const result = await Service.plateRecommend({ keywords: value });
    let list = result.data || [];
    list = list.filter((v) => v.type[0] === 'TID' || v.type[0] === 'PLATEID');
    list.forEach((item) => {
      let name = item.plateNo || item.dicName || value;
      item.description = name;
      item.label = name;
      item.localType = 'keyword';
      item.code = item.xid;
    });

    this.setState({ keywordsList: list });
  };

  queryRecommend = async (value) => {
    const result = await Service.personRecommend({ keywords: value });
    let list = result.data || [];
    list = list.filter((v) => v.type[0] === 'TID' || v.type[0] === 'PERSONID' || v.type[0] === 'CID' || v.type[0] === 'PID');
    list.forEach((item) => {
      let name = item.placeName || item.dicName || item.device_name || item.personName;
      item.description = name;
      item.label = name;
      item.code = item.xid;
      item.localType = 'keyword';
    });
    this.setState({ keywordsList: list });
  };
  queryRecommendDevice = async (value) => {
    const result = await Service.personRecommendPage({ keywords: value });
    let list = result.data.list || [];
    list = list.filter((v) => v.type === '2' || v.type === '7');
    list.forEach((item) => {
      item.label = item.description;
      item.localType = 'keyword';
      item.code = item.id;
    });

    this.setState({ keywordsList: list });
  };
  queryRecommendPlace = async (value) => {
    const result = await Service.personRecommendPage({ keywords: value });
    let list = result.data.list || [];
    list = list.filter((v) => v.type === '6');
    list.forEach((item) => {
      item.label = item.description;
      item.localType = 'keyword';
      item.code = item.id;
    });

    this.setState({ keywordsList: list });
  };

  onSearch = () => {
    const { selectTags, uploadInfo, keywords } = this.state;

    // console.log(selectTags)
    this.props.onSearch({ tags: selectTags, keywords, uploadInfo });
  };

  render() {
    const { hasSingleType = true, disabled } = this.props;
    const { type, visibleTag, selectTags, keywords, keywordsList, visibleUpload, uploadInfo = {}, objectTypes } = this.state;
    if (!hasSingleType && objectTypes.length === 0) {
      return null;
    }
    return (
      <div className="tag-group-select-layout">
        {hasSingleType && <TabHeader objectTypes={objectTypes} onTypeChange={this.onTypeChange}></TabHeader>}
        <TagInput
          disabled={disabled}
          type={type}
          ref={this.tagInputRef}
          keywords={keywords}
          selectList={selectTags}
          onInputChange={this.onInputChange}
          openTagSelect={this.openTagSelect}
          openImgUpload={this.openImgUpload}
          closePortal={this.closePortal}
          deleteTag={this.onSelect}
          deleteImg={() => this.imageUpload({})}
          onSearch={this.onSearch}
          pictureUrl={uploadInfo.pictureUrl}
          placeholder={placeholderTypes[type]}
        />
        <div className="tag-box-popup" ref={this.tagBoxRef}></div>
        <TagPortalComponent
          key="tag-select"
          keywordsList={keywordsList}
          visible={visibleTag}
          selectTags={selectTags}
          getContainer={() => this.tagBoxRef.current}
          onSelect={this.onSelect}
          keywords={keywords}
          type={type}
        />
        <UploadPortal key="imageSelect" type={type} getContainer={() => this.tagBoxRef.current} visible={visibleUpload} onChange={this.imageUpload} />
      </div>
    );
  }
}

export default ObjectMapTagSelect;
