import moment from 'moment';
import React from 'react';
import _ from 'lodash';
import { message, Checkbox } from 'antd';
import { BaseStore, LMConfig } from '@zenview/micro-basic-library';
import { formatTimeStamp, thousand } from '@zenview/micro-utils';
import RelationShipServer from './service';
import dictWithImg from './dictWithImg';
import IconFont from '../../themeComponents/IconFont';
import PersonCard from '../../components/Card/PersonCard';
import BaseIconCard from '../../components/Card/BaseIconCard';
import VehicleFileCard from '../../components/Card/VehicleFileCard';
import { desensitizationByState } from '../../businessComponents/DesensitizationInformationQuery';
const { placeTypeWithIcon, relationDeviceType } = dictWithImg;
const { BSConfig } = LMConfig;
const { place, device } = BaseStore;
//制造一个空的promise
function emptyPromise() {
  return new Promise((resolve) => resolve(false));
}
function getDeviceInfo(cid, list) {
  let deviceList = list || device.deviceList;
  let deviceInfo = deviceList.find((v) => v.cid === cid) || {};
  let deviceType = deviceInfo.deviceType;
  let item = relationDeviceType.find((v) => v.value.split(',').includes(deviceType)) || {};
  return item;
}
function getPlaceInfo(placeId) {
  let placeInfo = place.getPlaceInfoById(placeId);
  if (!placeInfo || !placeInfo.placeTags) {
    return {};
  }
  let placeItem = placeTypeWithIcon.find((v) => v.value === placeInfo.placeTags[0]) || {};
  return placeItem;
}
export async function getPersonNodesAndLinks(personData = {}, searchKeys = []) {
  let { accompaniesUrl, aidCidRelation, frequentedPlacesUrl, aid, personId, aidPictureInfos ,portraitPictureUrl,picUrl,roommatesUrl} = personData;
  let id = personData.personId || personData.aid || (personData.bindAids && personData.bindAids[0]);
  aid = aid ? aid : personData.bindAids ? personData.bindAids[0] : undefined;
  let resArr = await Promise.all([
    searchKeys.includes('queryPersonAccompanies') ? RelationShipServer.queryPersonAccompanies(accompaniesUrl) : emptyPromise(), // 同行
    searchKeys.includes('getAidsTogetherByAid') ? RelationShipServer.getAidsTogetherByAid({ aid, personId }) : emptyPromise(), // 查询常同出现的人
    searchKeys.includes('getPersonFrequentedPlaces7')
      ? RelationShipServer.getPersonFrequentedPlaces(
          frequentedPlacesUrl,
          {},
          {
            statisticPeroidType: 0,
          }
        )
      : emptyPromise(), // 7天常去地
    searchKeys.includes('getPersonFrequentedPlaces30')
      ? RelationShipServer.getPersonFrequentedPlaces(
          frequentedPlacesUrl,
          {},
          {
            statisticPeroidType: 1,
          }
        )
      : emptyPromise(), // 30天常去地
    searchKeys.includes('getLivePlaceByAid') ? RelationShipServer.getLivePlaceByAid({ aid, personId }) : emptyPromise(), // 查询人员疑似居住地
    searchKeys.includes('queryAidAndCidRelation') ? RelationShipServer.queryAidAndCidRelation(aidCidRelation) : emptyPromise(), // 查询人员设备关系
    // aid && (searchKeys.includes('getPersonVehicle') || searchKeys.includes('companion')) ? RelationShipServer.queryAidAndXidRelation({ aid }) : emptyPromise(), // 查询aid和车关系
    aid && searchKeys.includes('queryAidAndNonVehicleRelation') ? RelationShipServer.queryAidAndNonVehicleRelation({ aid }) : emptyPromise(), // 查询aid和非机动车车关系
    personId && searchKeys.includes('queryPersonAndVehicleOwnerRelation') ? RelationShipServer.queryPersonAndVehicleOwnerRelation({ personId }) : emptyPromise(), // 查询aid和非机动车车关系
    personId && searchKeys.includes('getPersonRoommates') ? RelationShipServer.getPersonRoommates(roommatesUrl) : emptyPromise(), // 查询实口同屋关系
  ]);
  let [accRes, commonListRes, frePlaces7Res, frePlaces30Res, livePlacesRes, cidRelationRes, 
    // personVehicleRes, 
    nonVehicleRes, personVehOwnerRes ,poommatesRes] = resArr;

  let newNodes = [];
  let newLinks = [];
  newNodes.push({
    id: id,
    name: desensitizationByState(personData.personName) || id,
    avatar: portraitPictureUrl|| (aidPictureInfos && aidPictureInfos[0] && aidPictureInfos[0].newestPictureUrl) ||(Array.isArray(picUrl)&&picUrl[0]) ,
    type: 'person',
  });
  let accList = accRes.data ? accRes.data.list || [] : [];
  // accList = accList.slice(0, 10)
  accList.forEach((v) => {
    newNodes.push({
      id: v.accoompanyAid,
      name: v.accoompanyAid,
      avatar: v.newestPictureUrl || v.lastestPictureUrl,
      personInfoUrl: v.personInfoUrl,
      type: 'person',
    });
    let item = {
      source: id,
      target: v.accoompanyAid,
      relation: '同行',
      type: 'person',
    };
    item.linkId = `${item.source}-${item.target}-${item.relation}`;
    newLinks.push(item);
  });

  let commonList = commonListRes.data || [];
  // commonList = commonList.slice(0, 10)

  commonList.forEach((v) => {
    newNodes.push({
      id: v.tag,
      name: v.tag,
      personInfoUrl: v.personInfoUrl,
      type: 'person',
      avatar: v.url,
    });
    let item = {
      source: id,
      target: v.tag,
      relation: '常同出现',
      type: 'person',
    };
    item.linkId = `${item.source}-${item.target}-${item.relation}`;
    newLinks.push(item);
  });

  let cidRelation = cidRelationRes.data || {};
  if (cidRelation.firstCid) {
    newNodes.push({
      name: cidRelation.firstDeviceName,
      type: 'device',
      avatar: getDeviceInfo(cidRelation.firstCid).img,
      // avatar: "",
      id: cidRelation.firstCid,
    });
    let item = {
      source: id,
      type: 'device',
      target: cidRelation.firstCid,
      relation: '首次出现设备',
      time: cidRelation.firstCaptureTime,
    };
    item.linkId = `${item.source}-${item.target}-${item.relation}`;
    newLinks.push(item);
  }
  if (cidRelation.lastCid) {
    newNodes.push({
      name: cidRelation.lastDeviceName,
      type: 'device',
      avatar: getDeviceInfo(cidRelation.lastCid).img,
      // avatar: "",
      id: cidRelation.lastCid,
    });
    let item = {
      source: id,
      type: 'device',
      target: cidRelation.lastCid,
      relation: '最后出现设备',
    };
    item.linkId = `${item.source}-${item.target}-${item.relation}`;
    newLinks.push(item);
  }
  let maxDevices = cidRelation.maxDevices || [];
  // maxDevices = maxDevices.slice(0, 10)

  maxDevices.forEach((v) => {
    newNodes.push({
      name: v.deviceName,
      type: 'device',
      id: v.cid,
      // avatar: "",
      avatar: getDeviceInfo(v.cid).img || '/micro-apps/micro-dep-librarys/images/device/Gun.png',
    });
    let item = {
      source: id,
      type: 'device',
      target: v.cid,
      relation: '经过次数最多设备',
    };
    item.linkId = `${item.source}-${item.target}-${item.relation}`;
    newLinks.push(item);
  });

  let livePlaces = livePlacesRes.data || [];
  livePlaces.forEach((v) => {
    newNodes.push({
      name: v.placeName,
      type: 'place',
      // avatar: "",
      avatar: getPlaceInfo(v.tag).img,
      id: v.tag,
    });
    let item = {
      source: id,
      type: 'place',
      target: v.tag,
      relation: '疑似居住地',
      count: v.count,
    };
    item.linkId = `${item.source}-${item.target}-${item.relation}`;
    newLinks.push(item);
  });

  const frePlaces7List = frePlaces7Res.data ? frePlaces7Res.data.places || [] : [];
  frePlaces7List.forEach((v) => {
    const placeInfo = getPlaceInfo(v.placeId);
    newNodes.push({
      name: v.placeName,
      type: 'place',
      avatar: placeInfo ? placeInfo.img : null,
      id: v.placeId,
    });
    let item = {
      source: id,
      type: 'place',
      target: v.placeId,
      relation: '最近一周常去地',
    };
    item.linkId = `${item.source}-${item.target}-${item.relation}`;
    newLinks.push(item);
  });

  const frePlaces30List = frePlaces30Res.data ? frePlaces30Res.data.places || [] : [];
  frePlaces30List.forEach((v) => {
    newNodes.push({
      name: v.placeName,
      type: 'place',
      avatar: getPlaceInfo(v.placeId).img,
      id: v.placeId,
    });
    let item = {
      source: id,
      type: 'place',
      target: v.placeId,
      relation: '最近一月常去地',
    };
    item.linkId = `${item.source}-${item.target}-${item.relation}`;
    newLinks.push(item);
  });
  // let personVehicleData = (Array.isArray(personVehicleRes.data) && personVehicleRes.data[0]) || {};
  // const personVehicleList = personVehicleData.driverPlates || [];
  // searchKeys.includes('getPersonVehicle') &&
  //   personVehicleList.forEach((v) => {
  //     newNodes.push({
  //       name: v.plateNo,
  //       type: 'vehicle',
  //       avatar: v.url,
  //       id: v.plateId,
  //     });
  //     let item = {
  //       source: id,
  //       type: 'vehicle',
  //       target: v.plateId,
  //       relation: '驾乘',
  //     };
  //     item.linkId = `${item.source}-${item.target}-${item.relation}`;
  //     newLinks.push(item);
  //   });

  // const companionList = personVehicleData.aidSamePassenger || [];
  // searchKeys.includes('companion') &&
  //   companionList.forEach((v) => {
  //     newNodes.push({
  //       name: v.aid,
  //       type: 'person',
  //       avatar: v.url,
  //       id: v.aid,
  //     });
  //     let item = {
  //       source: id,
  //       type: 'person',
  //       target: v.aid,
  //       relation: '同乘',
  //     };
  //     item.linkId = `${item.source}-${item.target}-${item.relation}`;
  //     newLinks.push(item);
  //   });

  if (nonVehicleRes && nonVehicleRes.data && nonVehicleRes.data.vehicleId) {
    const nonVehicleData = nonVehicleRes.data || {};
    newNodes.push({
      name: nonVehicleData.vehicleId,
      type: 'nonVehicle',
      avatar: nonVehicleData.vehicleImg,
      id: nonVehicleData.vehicleId,
    });
    let item = {
      source: id,
      type: 'nonVehicle',
      target: nonVehicleData.vehicleId,
      relation: '最后驾乘非机动车',
      ...nonVehicleData,
    };
    item.linkId = `${item.source}-${item.target}-${item.relation}`;
    newLinks.push(item);
  }

  let personVehOwnerData = personVehOwnerRes.data || [];
  personVehOwnerData.forEach((v) => {
    newNodes.push({
      name: v.vehiclePlateNum,
      type: 'vehicle',
      avatar: v.vehicleUrl,
      id: v.plateId,
    });
    let item = {
      source: id,
      type: 'vehicle',
      target: v.plateId,
      relation: '名下车辆',
      isNoLinkClick:true,
    };
    item.linkId = `${item.source}-${item.target}-${item.relation}`;
    newLinks.push(item);
  });
  
  let poommatesData = poommatesRes.data||[]
  poommatesData.forEach( v => {
    newNodes.push({
      name: desensitizationByState(v.personName),
      type: 'person',
      avatar: v.portraitPictureUrl,
      id: v.personId,
      isPersonId: true,
    });
    let item = {
      source: id,
      type: 'person',
      target: v.personId,
      relation: '同屋',
      isNoLinkClick:true,
    };
    item.linkId = `${item.source}-${item.target}-${item.relation}`;
    newLinks.push(item);
  })

  return { newNodes, newLinks };
}

export async function getDeviceNodesAndLinks(cid = '', searchKeys = [], deviceSearchTime = 7, objectDataList) {
  let newNodes = [];
  let newLinks = [];
  let endId = new Date() * 1;
  let startId = new Date() * 1 - deviceSearchTime * 24 * 60 * 60 * 1000;
  let aids = [];
  let hasPersonIdList = [];
  searchKeys.forEach((v) => {
    let item = objectDataList[v];
    let aid = item.aid || item.bindAids[0];
    aids.push(aid);
    if (item.personId) {
      hasPersonIdList.push({
        aid,
        person: item.personId,
      });
    }
  });
  const options = { cid, aids, endId, startId };
  let res = await RelationShipServer.getAidsByCidAndAids(options);
  let aidDataList = res.data.list || [];
  if (aidDataList.length === 0) {
    return message.warn('没有查到相关关系');
  }
  aidDataList.forEach((v) => {
    newNodes.push({
      name: v.aid,
      type: 'person',
      id: v.aid,
      avatar: v.url,
    });
    let item = {
      source: cid,
      target: v.aid,
      type: 'person',
      relation: '经过',
      isNoLinkClick:true,

    };
    item.linkId = `${item.source}-${item.target}-${item.relation}`;
    newLinks.push(item);

    let hasPersonId = hasPersonIdList.find((j) => j.aid === aids[0]) || {};
    let item2 = {
      source: hasPersonId.person || aids[0],
      target: v.aid,
      type: 'person',
      relation: '同出现',
    };
    item2.linkId = `${item2.source}-${item2.target}-${item2.relation}`;
    newLinks.push(item2);
  });

  return { newNodes, newLinks };
}

export async function getPlaceNodesAndLinks(pid = '', searchKeys = []) {
  let resArr = await Promise.all([
    searchKeys.includes('getAidsByFrequentPid7') ? RelationShipServer.getAidsByFrequentPid({ pid, days: 7 }) : emptyPromise(),
    searchKeys.includes('getAidsByFrequentPid30') ? RelationShipServer.getAidsByFrequentPid({ pid, days: 30 }) : emptyPromise(),
  ]);
  let [frePerson7Res, frePerson30Res] = resArr;
  let frePerson7List = frePerson7Res.data || [];
  let frePerson30List = frePerson30Res.data || [];
  let newNodes = [];
  let newLinks = [];
  frePerson7List.forEach((v) => {
    newNodes.push({
      name: v.aid,
      type: 'person',
      id: v.aid,
      avatar: v.url,
    });
    let item = {
      source: pid,
      target: v.aid,
      type: 'place',
      isReverse: true, //代表是否是通过场所或者设备查询出的关系
      relation: '最近一周常去地',
    };
    item.linkId = `${item.source}-${item.target}-${item.relation}`;
    newLinks.push(item);
  });
  frePerson30List.forEach((v) => {
    newNodes.push({
      name: v.aid,
      type: 'person',
      id: v.aid,
      avatar: v.url,
    });
    let item = {
      source: pid,
      target: v.aid,
      type: 'place',
      isReverse: true,
      relation: '最近一月常去地',
    };
    item.linkId = `${item.source}-${item.target}-${item.relation}`;
    newLinks.push(item);
  });

  return { newNodes, newLinks };
}

export async function getVehicleNodesAndLinks(vehicleData, searchKeys = []) {
  console.log(vehicleData);
  let plateId = vehicleData.id;
  let resArr = await Promise.all([
    searchKeys.includes('queryVehicleAndXidRelation') ? RelationShipServer.queryVehicleAndXidRelation({ plateId }) : emptyPromise(),
    searchKeys.includes('queryVehicleOwnerInfoUrl') ? RelationShipServer.queryVehicleOwnerInfoUrl(vehicleData.queryVehicleOwnerInfoUrl) : emptyPromise(),
    searchKeys.includes('queryVehicleAndNonVehicleRelationUrl')
      ? RelationShipServer.queryVehicleAndNonVehicleRelationUrl(vehicleData.queryVehicleAndNonVehicleRelationUrl)
      : emptyPromise(),
  ]);
  let [vehicleAndXidRelationRes,vehicleOwnerInfoRes,vehicleAndNonVehicleRes] = resArr;
  let data = vehicleAndXidRelationRes.data;
  let newNodes = [];
  let newLinks = [];

  newNodes.push({
    id: plateId,
    name: vehicleData.plateNo,
    avatar: vehicleData.representeImgUrl && vehicleData.representeImgUrl[0],
    type: 'vehicle',
  });
  if (data.lastAppearCid) {
    let id = data.lastAppearCid;
    newNodes.push({
      name: data.idNameMap ? data.idNameMap[id] : id,
      type: 'device',
      id: id,
      // avatar: "",
      avatar: getDeviceInfo(id).img || '/micro-apps/micro-dep-librarys/images/device/Gun.png',
    });
    let item = {
      source: plateId,
      target: id,
      type: 'device',
      relation: '最后一次出现设备',
    };
    item.linkId = `${item.source}-${item.target}-${item.relation}`;
    newLinks.push(item);
  }
  if (data.firstAppearCid) {
    let id = data.firstAppearCid;
    newNodes.push({
      name: data.idNameMap ? data.idNameMap[id] : id,
      type: 'device',
      id: id,
      avatar: getDeviceInfo(id).img || '/micro-apps/micro-dep-librarys/images/device/Gun.png',
    });
    let item = {
      source: plateId,
      target: id,
      type: 'device',
      relation: '首次出现',
      time: data.lastAppearTime,
    };
    item.linkId = `${item.source}-${item.target}-${item.relation}`;
    newLinks.push(item);
  }
  if (data.mostAppearCid) {
    let mostAppearCid = data.mostAppearCid || [];
    // mostAppearCid =mostAppearCid.slice(0, 3)
    mostAppearCid.forEach((v) => {
      let id = v;
      newNodes.push({
        name: data.idNameMap ? data.idNameMap[id] : id,
        type: 'device',
        id: id,
        // avatar: "",
        avatar: getDeviceInfo(id).img || '/micro-apps/micro-dep-librarys/images/device/Gun.png',
      });
      let item = {
        source: plateId,
        target: id,
        type: 'device',
        relation: '出现次数最多',
      };
      item.linkId = `${item.source}-${item.target}-${item.relation}`;
      newLinks.push(item);
    });
  }
  if (data.livePlaceId) {
    data.livePlaceId.forEach((v) => {
      let id = v;
      newNodes.push({
        name: data.idNameMap ? data.idNameMap[id] : id,
        type: 'place',
        id: id,
        // avatar: "",
        avatar: getPlaceInfo(id).img,
      });
      let item = {
        source: plateId,
        sourceType: 'vehicle',
        target: id,
        type: 'place',
        relation: '疑似居住地',
      };
      item.linkId = `${item.source}-${item.target}-${item.relation}`;
      newLinks.push(item);
    });
  }

  if (data.weekOftenPlaceId) {
    data.weekOftenPlaceId.forEach((v) => {
      let id = v;
      newNodes.push({
        name: data.idNameMap ? data.idNameMap[id] : id,
        type: 'place',
        id: id,
        // avatar: "",
        avatar: getPlaceInfo(id).img,
      });
      let item = {
        source: plateId,
        target: id,
        type: 'place',
        relation: '车辆近一周常去地',
      };
      item.linkId = `${item.source}-${item.target}-${item.relation}`;
      newLinks.push(item);
    });
  }

  if (data.oftenPlaceId30Days) {
    data.oftenPlaceId30Days.forEach((v) => {
      let id = v;
      newNodes.push({
        name: data.idNameMap ? data.idNameMap[id] : id,
        type: 'place',
        id: id,
        // avatar: "",
        avatar: getPlaceInfo(id).img,
      });
      let item = {
        source: plateId,
        target: id,
        type: 'place',
        relation: '车辆近一月常去地',
      };
      item.linkId = `${item.source}-${item.target}-${item.relation}`;
      newLinks.push(item);
    });
  }
  let driverAidObjs = data.driverAidObjs || [];

  driverAidObjs.forEach((v) => {
    newNodes.push({
      name: v.aid,
      type: 'person',
      id: v.aid,
      avatar: v.url,
    });
    let item = {
      source: v.aid,
      target: plateId,
      type: 'vehicle',
      isReverse: true,
      relation: '驾乘',
    };
    item.linkId = `${item.source}-${item.target}-${item.relation}`;
    newLinks.push(item);
  });

  console.log(vehicleOwnerInfoRes);
  let vehicleOwnerInfoData = vehicleOwnerInfoRes.data||[]
  vehicleOwnerInfoData.forEach((v) => {
    newNodes.push({
      name: v.ownerName,
      type: 'person',
      avatar: v.portraitPicUrl,
      id: v.personId,
      personId:v.personId
    });
    let item = {
      source: plateId,
      type: 'person',
      target: v.personId,
      relation: '车主',
      isNoLinkClick:true,
    };
    item.linkId = `${item.source}-${item.target}-${item.relation}`;
    newLinks.push(item);
  });

  console.log(vehicleAndNonVehicleRes);
  if (vehicleAndNonVehicleRes && vehicleAndNonVehicleRes.data && vehicleAndNonVehicleRes.data.vehicleId) {
    const nonVehicleData = vehicleAndNonVehicleRes.data || {};
    newNodes.push({
      name: nonVehicleData.vehicleId,
      type: 'nonVehicle',
      avatar: nonVehicleData.vehicleImg,
      id: nonVehicleData.vehicleId,
    });
    let item = {
      source: plateId,
      type: 'nonVehicle',
      target: nonVehicleData.vehicleId,
      relation: '相同驾乘人员',
      ...nonVehicleData,
    };
    item.linkId = `${item.source}-${item.target}-${item.relation}`;
    newLinks.push(item);
  }
  return { newNodes, newLinks };
}

export async function getDetailList(link, nodeData) {
  let sourceData = nodeData[link.source.id];
  let personAid = link.target.id;
  let targetData = nodeData[personAid];
  if (targetData) {
    personAid = targetData.aid || (targetData.bindAids && targetData.bindAids[0]) || link.target.id;
  }
  let result = {};
  let data = {};
  if (link.relation === '同行') {
    let option = {
      aid2: personAid,
    };
    result = await RelationShipServer.queryDetailAccompany(sourceData.detailAccompanyUrl, option, sourceData.aid);
    let list = result.data;
    let arr = [];

    list.forEach((v) => {
      let dataList = [];
      v.accompanyCaptureInfos.forEach((j) => {
        dataList.push([
          {
            aid: link.source.id,
            captureTime: j.aid1CaptureTime,
            deviceName: j.deviceName,
            imgUrl: j.aid1FaceUrl,
            captureId: j.aid1CaptureId,
          },
          {
            aid: j.aid2,
            captureTime: j.aid2CaptureTime,
            deviceName: j.deviceName,
            imgUrl: j.aid2FaceUrl,
            captureId: j.aid2CaptureId,
          },
        ]);
      });
      arr.push({
        list: dataList,
      });
    });
    arr = _.sortBy(arr, function (o) {
      return -o.list[0][0].captureTime * 1;
    });
    arr.map((v, k) => (v.desc = `第${arr.length - k}次同行`));
    data.dataDesc = (
      <p className="relation-detail-desc">
        <IconFont type={'icon-S_View_SelectChoosed'} />
        同行次数：
        <span className="relation-detail-desc-con">{arr.length}次</span>
      </p>
    );
    data.dataList = arr;
    data.hasTimeLine = true;
    data.singleCard = false;
  }
  if (link.relation === '常同出现' || link.relation === '同出现') {
    let option = {
      aid2: personAid,
    };

    result = await RelationShipServer.getDetailTogether(sourceData.togetherUrl, option, sourceData.aid);
    let list = _.flattenDeep(result.data.map((v) => v.accompanyCaptureInfos));

    let arr = [];
    list.forEach((v) => {
      let time = null;
      time = moment(+v.aid1CaptureTime).format('YYYY.MM.DD');
      let item = arr.find((j) => j.desc === time);
      if (item) {
        item.list.push([
          {
            aid: link.source.id,
            captureTime: v.aid1CaptureTime,
            deviceName: v.deviceName,
            imgUrl: v.aid1FaceUrl,
            captureId: v.aid1CaptureId,
          },
          {
            aid: v.aid2,
            captureTime: v.aid2CaptureTime,
            deviceName: v.deviceName,
            imgUrl: v.aid2FaceUrl,
            captureId: v.aid2CaptureId,
          },
        ]);
      } else {
        arr.push({
          desc: time,
          list: [
            [
              {
                aid: sourceData.aid,
                captureTime: v.aid1CaptureTime,
                deviceName: v.deviceName,
                imgUrl: v.aid1FaceUrl,
                captureId: v.aid1CaptureId,
              },
              {
                aid: v.aid2,
                captureTime: v.aid2CaptureTime,
                deviceName: v.deviceName,
                imgUrl: v.aid2FaceUrl,
                captureId: v.aid2CaptureId,
              },
            ],
          ],
        });
      }
    });
    data.dataDesc = (
      <p className="relation-detail-desc">
        <IconFont type={'icon-S_View_SelectChoosed'} />
        同出现次数：
        <span className="relation-detail-desc-con">{link.relation === '常同出现' ? arr.length : list.length}次</span>
      </p>
    );
    data.dataList = _.sortBy(arr, function (o) {
      return new Date(o.desc) * -1;
    });
    data.hasTimeLine = true;
    data.singleCard = false;
  }

  if (link.relation === '最近一月常去地' || link.relation === '最近一周常去地' || (link.sourceType === "person" &&link.relation === "疑似居住地")) {
    let days = 30;
    if (link.relation === '最近一周常去地') {
      days = 7;
    }
    if (link.relation === '疑似居住地') {
      if (link.count > 7) {
        days = 30;
      } else {
        days = 7;
      }
    }
    let id = '';
    let placeId = '';
    if (link.isReverse) {
      placeId = link.source.id;
      id = link.target.id;
    } else {
      id = link.source.id;
      placeId = link.target.id;
    }
    let aid = nodeData[id].aid || nodeData[id].bindAids[0];
    let aids = [aid];
    let placeIds = [placeId];
    let startTime = moment()
      .subtract(days - 1, 'd')
      .set({ hour: 0, minute: 0, second: 0 })
      .valueOf();
    let endTime = moment().set({ hour: 0, minute: 0, second: 0 }).valueOf();

    result = await RelationShipServer.queryAidDetail({
      aids,
      startTime,
      endTime,
      offset: 0,
      limit: 10000,
      placeIds,
    });
    let list = result.data.list;

    let arr = [];
    list.forEach((v) => {
      let time = null;
      time = moment(+v.captureTime).format('YYYY.MM.DD');
      let item = arr.find((j) => j.time === time);
      if (item) {
        item.list.push({
          aid: aid,
          captureTime: v.captureTime,
          deviceName: v.deviceName,
          imgUrl: v.faceUrl,
          ...v,
        });
      } else {
        arr.push({
          time: time,
          list: [
            {
              aid: aid,
              captureTime: v.captureTime,
              deviceName: v.deviceName,
              imgUrl: v.faceUrl,
              ...v,
            },
          ],
        });
      }
    });
    arr.map((v) => (v.desc = `${v.time}(共经过${v.list.length}次)`));
    data.dataList = _.sortBy(arr, function (o) {
      return -moment(o.time) * 1;
    });
    data.dataDesc = (
      <p className="relation-detail-desc">
        <IconFont type={'icon-S_View_SelectChoosed'} />
        出现频次：
        <span className="relation-detail-desc-con">
          {link.relation !== '疑似居住地' ? `${days}天内` : ''}
          出现{arr.length}天,共抓拍{list.length}次
        </span>
      </p>
    );
    data.hasTimeLine = true;
    data.singleCard = true;
  }
  if (link.relation === '经过次数最多设备' || link.relation === '最后出现设备' || link.relation === '首次出现设备') {
    let options = {
      aids: [sourceData.aid || (sourceData.bindAids && sourceData.bindAids[0])],
      cids: [link.target.id],
      startTime: new Date(moment().subtract(BSConfig.relationDataCycle || 30, 'd')).getTime(),
      endTime: new Date() * 1,
      limit: 10000,
    };

    if (link.relation === '首次出现设备') {
      options.limit = 1;
      options.sortType = 0;
    }
    if (link.relation === '最后出现设备') {
      options.limit = 1;
      options.sortType = 1;
    }
    result = await RelationShipServer.queryAidDetail(options);
    //  await Service.face.queryFaces(options);
    let list = result.data.list;

    let arr = [];
    list.forEach((v) => {
      let time = null;
      time = moment(+v.captureTime).format('YYYY.MM.DD');
      let item = arr.find((j) => j.time === time);
      if (item) {
        item.list.push({
          aid: sourceData.aid,
          captureTime: v.captureTime,
          deviceName: v.deviceName,
          imgUrl: v.faceUrl,
          ...v,
        });
      } else {
        arr.push({
          time: time,
          list: [
            {
              aid: sourceData.aid,
              captureTime: v.captureTime,
              deviceName: v.deviceName,
              imgUrl: v.faceUrl,
              ...v,
            },
          ],
        });
      }
    });
    arr.map((v) => (v.desc = `${v.time} ${link.relation === '经过次数最多设备' ? ` (共经过${v.list.length}次)` : ''}`));
    data.dataList = _.sortBy(arr, function (o) {
      return -moment(o.time) * 1;
    });
    if (link.relation === '经过次数最多设备') {
      data.dataDesc = (
        <p className="relation-detail-desc">
          <IconFont type={'icon-S_View_SelectChoosed'} />
          经过次数：
          <span className="relation-detail-desc-con">{list.length}次</span>
        </p>
      );
    }
    data.hasTimeLine = true;
    data.singleCard = true;
  }
  if (link.relation === '首次出现' || link.relation === '最后一次出现设备' || link.relation === '出现次数最多') {
    let days = BSConfig.relationDataCycle || 30;
    let startTime = moment(moment().subtract(days, 'd').format('YYYY-MM-DD 00:00:00')).valueOf();
    let endTime = new Date() * 1;
    let plateId = link.source.id;
    let cid = link.target.id;
    let options = {
      plateId,
      startTime,
      endTime,
      offset: 0,
      limit: 10000,
      cid,
    };
    if (link.relation === '最后一次出现设备') {
      options.limit = 1;
    }
    if (link.relation === '首次出现') {
      options.limit = 1;
      if (sourceData.firstData && sourceData.firstData.firstAppearTime) {
        options.startTime = +sourceData.firstData.firstAppearTime - 1000;
        options.endTime = +sourceData.firstData.firstAppearTime + 1000 || new Date(moment().subtract(BSConfig.relationDataCycle || 30, 'd')).getTime();
      }
    }
    result = await RelationShipServer.queryVehicleAndXidDetail(options);
    let list = result.data.list;
    let arr = [];
    list.forEach((v) => {
      let time = null;
      v.type = 'vehicle';
      time = moment(+v.captureTime).format('YYYY.MM.DD');
      let item = arr.find((j) => j.time === time);
      if (item) {
        item.list.push({
          plateId: sourceData,
          captureTime: v.captureTime,
          deviceName: v.deviceName,
          imgUrl: v.vehicleUrl,
          ...v,
        });
      } else {
        arr.push({
          time: time,
          list: [
            {
              plateId: sourceData,
              captureTime: v.captureTime,
              deviceName: v.deviceName,
              imgUrl: v.vehicleUrl,
              ...v,
            },
          ],
        });
      }
    });
    arr.map((v) => (v.desc = `${v.time}${link.relation === '出现次数最多' ? ` (共经过${v.list.length}次)` : ''} `));
    data.dataList = _.sortBy(arr, function (o) {
      return -moment(o.time) * 1;
    });
    if (link.relation === '出现次数最多') {
      data.dataDesc = (
        <p className="relation-detail-desc">
          <IconFont type={'icon-S_View_SelectChoosed'} />
          经过次数：
          <span className="relation-detail-desc-con">{list.length}次</span>
        </p>
      );
    }
    data.hasTimeLine = true;
    data.singleCard = true;
  }
  if (link.relation === '车辆近一周常去地' || (link.sourceType === 'vehicle' && link.relation === '疑似居住地') || link.relation === '车辆近一月常去地') {
    let days = link.relation === '车辆近一周常去地' ? 7 : 30;
    let plateId = link.source.id;
    let placeId = link.target.id;
    let startTime = moment(moment().subtract(days, 'd').format('YYYY-MM-DD 00:00:00')).valueOf();
    let endTime = moment(moment().subtract(0, 'd').format('YYYY-MM-DD 00:00:00')).valueOf();
    result = await RelationShipServer.queryVehicleAndXidDetail({
      plateId,
      startTime,
      endTime,
      offset: 0,
      limit: 10000,
      placeId,
    });
    let list = result.data.list;
    let arr = [];
    list.forEach((v) => {
      let time = null;
      v.type = 'vehicle';
      time = moment(+v.captureTime).format('YYYY.MM.DD');
      let item = arr.find((j) => j.time === time);
      if (item) {
        item.list.push({
          plateId: sourceData,
          captureTime: v.captureTime,
          deviceName: v.deviceName,
          imgUrl: v.vehicleUrl,
          ...v,
        });
      } else {
        arr.push({
          time: time,
          list: [
            {
              plateId: sourceData,
              captureTime: v.captureTime,
              deviceName: v.deviceName,
              imgUrl: v.vehicleUrl,
              ...v,
            },
          ],
        });
      }
    });
    arr.map((v) => (v.desc = `${v.time}(共经过${v.list.length}次)`));
    data.dataList = _.sortBy(arr, function (o) {
      return -moment(o.time) * 1;
    });
    data.dataDesc = (
      <p className="relation-detail-desc">
        <IconFont type={'icon-S_View_SelectChoosed'} />
        出现频次：
        <span className="relation-detail-desc-con">
          {link.relation !== '疑似居住地' ? `${days}天内` : ''}
          出现{arr.length}天,共抓拍{list.length}次
        </span>
      </p>
    );
    data.hasTimeLine = true;
    data.singleCard = true;
  }
  if (link.relation === '同乘') {
    let option = {
      aid1: link.source.id,
      aid2: personAid,
    };
    result = await RelationShipServer.queryAidSamePassengerDetail(option);

    let list = result.data;
    let arr = [];
    list.forEach((v) => {
      let list = [];
      v.aidSamePassengers.forEach((j) => {
        list.push([
          {
            captureTime: j.captureTimeAid1,
            deviceName: j.deviceNameAid1,
            imgUrl: j.faceUrlAid1,
            captureId: j.captureIdAid1,
          },
          {
            captureTime: j.captureTimeAid2,
            deviceName: j.deviceNameAid2,
            imgUrl: j.faceUrlAid2,
            captureId: j.captureIdAid2,
          },
          {
            captureTime: j.captureTimeVehicle,
            deviceName: j.deviceNameVehicle,
            imgUrl: j.vehicleUrl,
            captureId: j.captureIdVehicle,
            type: 'vehicle',
            id: j.imgId,
          },
        ]);
      });
      arr.push({
        time: v.date,
        list,
      });
    });

    arr.map((v) => (v.desc = `${v.time}(共同乘${v.list.length}次)`));
    data.dataList = _.sortBy(arr, function (o) {
      return -moment(o.time) * 1;
    });
    data.hasTimeLine = true;
    data.singleCard = false;
  }
  if (link.relation === '驾乘') {
    let option = {
      aid: link.source.id,
      plateId: link.target.id,
    };
    result = await RelationShipServer.queryAidDriverDetail(option);
    let list = result.data;
    let arr = [];
    list.forEach((v) => {
      let list = [];
      v.personVehicles.forEach((j) => {
        list.push([
          {
            captureTime: j.captureTimeAid,
            deviceName: j.deviceNameAid,
            imgUrl: j.faceUrl,
            captureId: j.captureIdAid,
          },
          {
            captureTime: j.captureTimeVehicle,
            deviceName: j.deviceNameVehicle,
            imgUrl: j.vehicleUrl,
            captureId: j.captureIdVehicle,
            type: 'vehicle',
            id: j.imgId,
          },
        ]);
      });
      arr.push({
        time: v.date,
        list,
      });
    });
    arr.map((v) => (v.desc = `${v.time}(共驾乘${v.list.length}次)`));
    data.dataList = _.sortBy(arr, function (o) {
      return -moment(o.time) * 1;
    });
    data.hasTimeLine = true;
    data.singleCard = false;
  }
  data.relationName = link.relation;
  return data;
}

export async function getDetailListVehicle(link) {
  let sourceData = link.source.id;
  let result = {};
  let data = {};
  if (link.relation === '最近一周常去地' || link.relation === '最近一月常去地') {
    let days = link.relation === '最近一周常去地' ? 7 : 30;
    let plateId = link.source.id;
    let placeId = link.target.id;
    let startTime = moment(moment().subtract(days, 'd').format('YYYY-MM-DD 00:00:00')).valueOf();
    let endTime = moment(moment().subtract(0, 'd').format('YYYY-MM-DD 00:00:00')).valueOf();
    result = await RelationShipServer.queryVehicleAndXidDetail({
      plateId,
      startTime,
      endTime,
      offset: 100,
      limit: 1,
      placeId,
    });
    let list = result.data.list;
    let arr = [];
    list.forEach((v) => {
      let time = null;
      time = moment(+v.captureTime).format('YYYY.MM.DD');
      let item = arr.find((j) => j.time === time);
      if (item) {
        item.list.push({
          plateId: sourceData,
          captureTime: v.captureTime,
          deviceName: v.deviceName,
          imgUrl: v.vehicleUrl,
          ...v,
        });
      } else {
        arr.push({
          time: time,
          list: [
            {
              plateId: sourceData,
              captureTime: v.captureTime,
              deviceName: v.deviceName,
              imgUrl: v.vehicleUrl,
              ...v,
            },
          ],
        });
      }
    });
    arr.map((v) => (v.desc = `${v.time}(共经过${v.list.length}次)`));
    data.dataList = _.sortBy(arr, function (o) {
      return -moment(o.time) * 1;
    });
    data.dataDesc = (
      <p className="relation-detail-desc">
        <IconFont type={'icon-S_View_SelectChoosed'} />
        出现频次：
        <span className="relation-detail-desc-con">
          {link.relation !== '疑似居住地' ? `${days}天内` : ''}
          出现{arr.length}天,共抓拍{list.length}次
        </span>
      </p>
    );
    data.hasTimeLine = true;
    data.singleCard = true;
  }
  data.relationName = link.relation;
  return data;
}

export const placeInfoCard = (id, click) => {
  let placeInfo = place.getPlaceInfoById(id) || {};
  let placeItem = getPlaceInfo(id) || {};
  let labelList = _.compact(
    placeInfo.placeTags.map((v) => {
      let item = placeTypeWithIcon.find((j) => j.value === v) || {};
      return item.name;
    })
  );
  let countInfo = place.getPlaceDeviceCount(id);
  return (
    <BaseIconCard
      click={click}
      className="relational-atlas-card"
      icon={`${placeItem.multicolorIcon || 'icon-M_Photo_Place'}`}
      title={{
        icon: 'icon-S_Place_Place',
        label: placeInfo.areaName,
      }}
      data={[
        {
          icon: 'icon-S_Point_Camera',
          label: '设备',
          info: thousand(countInfo.count || 0),
        },
        // {
        //   icon: "icon-S_Bar_PeopleAll",
        //   label: "总出现人员",
        //   info: thousand(placeInfo.personCount)
        // },
        // {
        //   icon: "icon-S_Place_Other",
        //   label: "重要场所",
        //   info: thousand(placeInfo.childrenPlaceCount)
        // },
        {
          icon: 'icon-S_Photo_Label',
          label: '场所标签',
          info: labelList.join(','),
        },
      ]}
    />
  );
};

export class DeviceInfoCard extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      deviceInfo: {},
    };
  }
  async componentDidMount() {
    let { id } = this.props;

    let deviceInfo = BaseStore.device.getDeviceByCId(id);
    if (!deviceInfo) {
      try {
        deviceInfo = await BaseStore.device.getDeviceForPlaceAuth(id);
      } catch (error) {
        deviceInfo = {};
      }
    }

    this.setState({
      deviceInfo,
    });
  }
  render() {
    let { deviceInfo } = this.state;
    let { name, click } = this.props;
    let deviceType = deviceInfo.deviceType;
    let item = relationDeviceType.find((v) => v.value === deviceType) || {};

    let placeInfo = place.getPlaceInfoById(deviceInfo.placeId) || {};
    let placeTags = placeInfo.placeTags || [];
    let labelList = placeTags.map((v) => placeTypeWithIcon.find((j) => j.value === v) && placeTypeWithIcon.find((j) => j.value === v).name);
    return (
      <BaseIconCard
        click={click}
        className="relational-atlas-card"
        icon={item.multicolorIcon || 'icon-L_index_CameraGun'}
        title={{
          icon: 'icon-S_Point_Camera',
          label: deviceInfo.deviceName || name,
        }}
        data={[
          {
            icon: 'icon-S_Place_Place',
            label: '所在场所名称',
            info: placeInfo.areaName || '暂无',
          },
          {
            icon: 'icon-S_Place_Community',
            label: '所在场所类型',
            info: labelList.length ? labelList.join(',') : '暂无',
          },
        ]}
      />
    );
  }
}

export const deviceInfoCard = (id, deviceList) => {
  let deviceInfo = deviceList.find((v) => v.cid === id) || {};
  let deviceType = deviceInfo.deviceType;
  let item = relationDeviceType.find((v) => v.value === deviceType) || {};

  let placeInfo = place.placeList.find((v) => v.placeId === deviceInfo.placeId) || {};
  let placeTags = placeInfo.placeTags || [];
  let labelList = placeTags.map((v) => placeTypeWithIcon.find((j) => j.value === v) && placeTypeWithIcon.find((j) => j.value === v).name);

  return (
    <BaseIconCard
      className="relational-atlas-card"
      icon={item.multicolorIcon || 'icon-M_Photo_Device'}
      title={{ icon: 'icon-S_Point_Camera', label: deviceInfo.deviceName }}
      data={[
        {
          icon: 'icon-S_Place_Place',
          label: '所在场所名称',
          info: placeInfo.areaName,
        },
        {
          icon: 'icon-S_Place_Community',
          label: '所在场所类型',
          info: labelList.length ? labelList.join(',') : '暂无',
        },
      ]}
    />
  );
};

export const personInfoCard = (personData, click) => {
  if (!personData) {
    return <></>;
  }

  let id = personData.personId || personData.aid || (personData.bindAids && personData.bindAids[0]);
  let { recentData = {}, personName } = personData;
  return (
    <PersonCard
      // sourceData={item}
      // click={jumpDetail}
      // footer={getFooter(item.tagCodes, labelList)}
      click={click}
      imgUrl={recentData.recentUrl}
      data={[
        {
          infos: [
            {
              info: desensitizationByState(personName) || id,
              name: '姓名',
              style: { color: 'var(--primary)', fontWeight: '700' },
              icon: 'icon-S_View_Clustering',
            },
          ],
        },
        {
          label: '最近出现:',
          infos: [
            {
              info: recentData.recentAppearanceAddress || '暂无',
              icon: 'icon-S_Bar_Add',
            },
            {
              info: recentData.recentAppearanceTime ? formatTimeStamp(+recentData.recentAppearanceTime) : '暂无',
              icon: 'icon-S_Edit_ClockEnd',
            },
          ],
        },
      ]}
    />
  );
};

export const vehicleInfoCard = (vehicleData, click) => {
  if (!vehicleData) {
    return <></>;
  }
  const plateMapping = {
    117751: 'Black',
    117752: 'White',
    117753: 'Yellow',
    117754: 'Blue',
    117755: 'Green',
    117756: 'YellowGreen',
    117757: 'WhiteGreen',
  };

  return (
    <VehicleFileCard
      sourceData={vehicleData}
      click={click}
      // footer={<TagFooter {...footer} />}
      imgUrl={vehicleData.representeImgUrl === undefined ? undefined : vehicleData.representeImgUrl[0]}
      imageNum={vehicleData.pictureCount}
      data={[
        {
          infos: [
            {
              info: vehicleData.plateNo,
              group: 'plate',
              type: plateMapping[vehicleData.plateColor],
            },
          ],
        },
        {
          infos: [
            {
              info: vehicleData.recentData.lastAppearCidName || '暂无',
              icon: 'icon-S_Bar_Add',
            },
            {
              info: vehicleData.recentData.lastAppearTime ? formatTimeStamp(+vehicleData.recentData.lastAppearTime) : '暂无',
              icon: 'icon-S_Edit_ClockEnd',
            },
          ],
          label: '最近出现:',
        },
      ]}
    />
  );
};

export const CheckBoxItem = (selectKeys = [], value, label) => {
  return (
    <div>
      <Checkbox disabled={selectKeys.includes(value)} value={value}>
        {label}
      </Checkbox>
    </div>
  );
};
