import {
  getHDIncidentList,
  IncidentItem,
  IncidentItemDetail,
} from '@/api/incident';
import {
  getAllResources,
  getAllsingleDevice,
  ResourceItemDetail,
  SingleDeviceItem,
  getAllvideoDevice,
  searchWarehouseByGoods,
  DHUserResponse,
  getDHUserToken,
} from '@/api/resource';
import {
  PENDING_DISPOSAL_INCIDENT,
  PENDING_INCIDENT,
  // EMERGENCY_VEHICLES,
  VIDEO_SURVEILLANCE,
  WARNING_INCIDENT,
  SINGLE_PAWN,
  // EMERGENCY_TEAM,
} from '@/components/MarkerMap/constants';
import { ElMessage } from 'element-plus';
import { type } from 'os';
import { defineStore } from 'pinia';

type AllResources = NonNullable<IncidentItemDetail['baseInfo']> &
  NonNullable<SingleDeviceItem> & ResourceItemDetail;

type Simply<T> = { [K in keyof T]: T[K] };

export interface MarkerType extends Simply<AllResources> {
  locations?: string;
  marker?: any;
  popup?: any;
  [key: string]: any;
}

export interface MarkerStateType {
  warningIncident: MarkerType[];
  pendingIncident: MarkerType[];
  pendingDisposalIncident: MarkerType[];
  videoSurveillance: MarkerType[];
  emergencyVehicles: MarkerType[];
  emergencyTeam: MarkerType[];
  emergencyWarehouse: MarkerType[];
  singleDevice: SingleDeviceItem[];
  /** 详情页面 点击监控点位 打开视频 */
  livevideovisible: boolean;
  livevideos: MarkerType[];
  incident: MarkerType[];
  loading: boolean;
  currentIncident: MarkerType;
}

export interface MainActionsType {
  toggleLoading(): void;
  getHDIncidentList(): void;
  getAllResources(): void;
  getAllsingleDevice(): void;
  searchWarehouseByGoods(name?: string): void;
  initDHUser(): void;
}

export default defineStore<'marker', MarkerStateType, {}, MainActionsType>(
  'marker',
  {
    state: () => ({
      currentIncident: {},
      incident: [],
      warningIncident: [],
      pendingIncident: [],
      pendingDisposalIncident: [],
      videoSurveillance: [],
      emergencyVehicles: [],
      emergencyTeam: [],
      singleDevice: [],
      emergencyWarehouse: [],
      livevideos: [],
      livevideovisible: false,
      loading: false,
    }),
    actions: {
      toggleLoading() {
        this.loading = !this.loading;
      },
      async getHDIncidentList() {
        try {
          this.toggleLoading();
          const { data } = await getHDIncidentList();
          this.incident = (data as MarkerType[]) ?? [];
        } finally {
          this.toggleLoading();
        }
      },
      async initDHUser() {
        const { data } = await getDHUserToken();
        if (data.token) {
          localStorage.setItem('token', data.token.toString());
          localStorage.setItem('userId', data.userId.toString());
          localStorage.setItem('userName', data.userName.toString());
          ElMessage.success(
            '成功获取后台登陆的视频账号：' + data.userName.toString(),
          );

          // localStorage.setItem('token','S4NbecfYB19QUJHT4T8M7G_6566288360343616')
          // localStorage.setItem('userId', 'S4NbecfYB19QUJHT4T8M7G');
          // localStorage.setItem('userName', 'system');
        }
      },
      async getAllsingleDevice() {
        try {
          this.toggleLoading();
          const { data } = await getAllsingleDevice();

          this.singleDevice = [];

          this.singleDevice = Object.values(data).map((item) => ({
            ...item,
            locations: `${item.gpsX},${item.gpsY}`,
          }));
          // console.log(this.singleDevice);
        } finally {
          this.toggleLoading();
        }
      },

      async getAllvideoDevice() {
        try {
          this.toggleLoading();
          const { data } = await getAllvideoDevice();
          let videoData = [];
          for (var index in data) {
            var cp = data[index];

            // if (!cp.gpsX) {
            //   cp['channelId'] = '6565283731802368';

            //   cp["gpsX"] = 118.28 + (parseInt(index) * 3) / 10;
            //   cp["gpsY"] = 33.97 + (parseInt(index) * 3) / 10;
            // }
            // cp['isOnline'] = true;
            // cp['status'] = 1;
            //  console.log(cp);
            if (cp.gpsX) {
              videoData.push(cp);
            }
          }
          this.videoSurveillance = [];

          this.videoSurveillance = Object.values(videoData).map((item) => ({
            ...item,
            locations: `${item.gpsX},${item.gpsY}`,
          }));
          // console.log(this.videoSurveillance);
        } finally {
          this.toggleLoading();
        }
      },

      async getAllResources() {
        try {
          this.toggleLoading();
          const { data } = await getAllResources();
          // @ts-ignore
          this.emergencyVehicles =
            data.应急车队
              .filter(
                (i) =>
                  i.latitude !== null &&
                  i.latitude !== undefined &&
                  i.latitude !== '' &&
                  i.latitude !== '0',
              )
              .map((i) => ({
                ...i,
                locations: `${i.longitude},${i.latitude}`,
              })) ?? [];
          // @ts-ignore
          this.emergencyTeam =
            data.应急队伍
              .filter(
                (i) =>
                  i.latitude !== null &&
                  i.latitude !== undefined &&
                  i.latitude !== '' &&
                  i.latitude !== '0',
              )
              .map((i) => ({
                ...i,
                locations: `${i.longitude},${i.latitude}`,
              })) ?? [];
          // @ts-ignore
          this.emergencyWarehouse =
            data.应急仓库
              .filter(
                (i) =>
                  i.latitude !== null &&
                  i.latitude !== undefined &&
                  i.latitude !== '' &&
                  i.latitude !== '0',
              )
              .map((i) => ({
                ...i,
                locations: `${i.longitude},${i.latitude}`,
              })) ?? [];
        } finally {
          this.toggleLoading();
        }
      },
      async searchWarehouseByGoods(name) {
        try {
          this.toggleLoading();
          const { data } = await searchWarehouseByGoods(name);
          this.emergencyWarehouse =
            data.map((i) => ({
              ...i,
              locations: `${i.longitude},${i.latitude}`,
            })) ?? [];
        } finally {
          this.toggleLoading();
        }
      },
    },
  },
);
