import * as service from '@/pages/screen/services';
import { DispatchDataMap, PeopleStatusEnum, DispatchDataList } from '@/pages/screen/constants';
import { isEqual, differenceWith, get } from 'lodash';
import { photovoItaicList, last30day, pIRight } from '@/pages/screen/mocks';

export default {
  namespace: 'screen',

  state: {
    search: '',
    video: '',
    eleDiagram: '',
    runStatus: '',
    checkInfo: '',
    videoDiviceId: '',
    stationData: null,
    energyChart: null,
    selectedPoint: null,
    selectedCustomerStation: null,
    data: [],
    vehicleList: [],
    customerList: [],
    peopleList: [],
    diffDataList: [],
    assets: [],
    liveVideo: [],
    liveVideoShow: false,
    hasKey: false,
    filterTypes: DispatchDataList.map(item => item.value), // 根据类型（人、车、户号）过滤
    company: '', // 公司
    companyList: [], // 所有公司
    area: [], // 地区
    features: [], // 选择的功能
    // 微电网
    photovoltaic: {
      total: 743029,
      totalAssemblyCapacity: 660.0,
      realTimePowerGeneration: 78.4,
      totalPower: 78.4,
      realTimePowerList:  photovoItaicList.map((item, index) => ({
        time: `${(index)}点`,
        value: item / 1000
      }))
    },
    energyStorage: {
      total: 552.0,
      totalAssemblyCapacity: 552.0,
      realPower: 78.3,
      sumCharging: 115749.7,
      sumDischarge: 103257.8,
      avgEfficiency: 0.909,
      sumProfit: 48248.6,
      theoryProfit: 53078.8
    },
    chargingPile: {
      sumCharging: 327.3,
      realTimeUseRate: 0.076,
      totalNum: 15,
      dcPile: 15,
      acPile: 0,
      todayCharging: 183.4,
      yesterdayCharging: 196.78,
      monthCharging: 1542.3,
      lastMothCharging: 3668.4,
    },
    lateLy30Charging: last30day,
    peopleVideo: {
      url: ''
    }
  },

  reducers: {
    handleSearchValue(state, { payload }) {
      return {
        ...state,
        search: payload,
      };
    },
    handleFilterTypes(state, { payload }) {
      return {
        ...state,
        filterTypes: payload,
      };
    },
    handleVideo(state, { payload }) {
      return {
        ...state,
        video: payload,
      };
    },
    handleRunStatus(state, { payload }) {
      return {
        ...state,
        runStatus: payload,
      };
    },
    handleCheckInfo(state, { payload }) {
      return {
        ...state,
        checkInfo: payload,
      };
    },
    handleCheckStatistics(state, { payload }) {
      return {
        ...state,
        stationData: payload,
      };
    },
    handleEleDiagram(state, { payload }) {
      return {
        ...state,
        eleDiagram: payload,
      };
    },
    handleEnergyChart(state, { payload }) {
      return {
        ...state,
        energyChart: payload,
      };
    },
    handleCustomerStation(state, { payload }) {
      return {
        ...state,
        selectedCustomerStation: payload,
      };
    },
    handleVideoDiviceId(state, { payload }) {
      return {
        ...state,
        videoDiviceId: payload,
      };
    },
    handleData(state, { payload }) {
      return {
        ...state,
        data: payload,
      };
    },
    handleVehicleList(state, { payload }) {
      return {
        ...state,
        vehicleList: payload,
      };
    },
    handleCustomerList(state, { payload }) {
      return {
        ...state,
        customerList: payload,
      };
    },
    handlePeopleList(state, { payload }) {
      return {
        ...state,
        peopleList: payload,
      };
    },
    handelDiffData(state, { payload }) {
      return {
        ...state,
        diffDataList: payload,
      };
    },
    handleSelectedPoint(state, { payload }) {
      return {
        ...state,
        selectedPoint: payload, // { type: '', id: '' }
      };
    },
    handleAssets(state, { payload }) {
      return {
        ...state,
        assets: payload,
      };
    },
    handleLiveVideo(state, { payload }) {
      return {
        ...state,
        liveVideo: payload,
      };
    },
    showLiveVideo(state, { payload }) {
      return {
        ...state,
        liveVideoShow: payload.liveVideoShow,
        videoSource: payload.videoSource
      };
    },
    filterCompany(state, { payload }) {
      return {
        ...state,
        company: payload
      };
    },
    filterArea(state, { payload }) {
      return {
        ...state,
        area: payload
      };
    },
    handleCompanyList(state, { payload }) {
      return {
        ...state,
        companyList: payload
      };
    },
    filterFeatures(state, { payload }) {
      const features = [...state.features];
      const index = features.indexOf(payload)
      if (index > -1) {
        features.splice(index, 1)
      } else {
        features.push(payload)
      }
      return {
        ...state,
        features
      };
    },
    updateRealTimePower(state, {payload}) {
     return  {
       ...state,
       photovoltaic: {
         ...state.photovoltaic,
         realTimePowerGeneration: payload
       }
     }
    },
    updatePeopleVideo(state, {payload}) {
      return {
        ...state,
        peopleVideo: payload
      }
    }
  },

  effects: {
    *fetchVehiclePeople(_, { call, put, all, select, take }) {
      yield put({
        type: 'handelDiffData',
        payload: [],
      })
      const [vehicle, peopleReal] = yield all([
        call(service.getVehicle, { get_all: 1 }),
        call(service.getPeopleReal),
      ]);

      const vehicleList = get(vehicle, 'data.list', [])
        .filter(item => item.longitude && item.latitude)
        .map((item, index) => ({
          ...item,
          position: [+item.longitude, +item.latitude],
          type: DispatchDataMap.vehicle,
          id: `${item.number_plate}_${DispatchDataMap.vehicle}_${item.imei}`,
          label: item.number_plate,
          _id: item.imei, // 服务端 id
        }));

      const peopleList = get(peopleReal, 'data.bean.history_location', [])
        .filter(item => item.longitude && item.latitude)
        .map((item, index) => ({
          ...item,
          position: [+item.longitude, +item.latitude],
          type: DispatchDataMap.people,
          id: `${item.user_id}_${DispatchDataMap.people}_${item.user_id}`,
          label: item.name,
          status: get(peopleReal, 'data.bean.recent_location', []).some(
            i => (`${i.user_id}` === `${item.user_id}`) && i.longitude && i.latitude,
          )
            ? PeopleStatusEnum.online
            : PeopleStatusEnum.offline,
          _id: item.user_id, // 服务端 id
        }));

      const { vehicleList: originVehicle, peopleList: originPeople } = yield select(state => state.screen)

      const newDate = [].concat(vehicleList, peopleList)
      const oldDate = [].concat(originVehicle, originPeople)
      const diff = differenceWith(newDate, oldDate, isEqual)
      yield all([
        put({
          type: 'handelDiffData',
          payload: diff,
        }),
        put({
          type: 'handleVehicleList',
          payload: vehicleList,
        }),
        put({
          type: 'handlePeopleList',
          payload: peopleList,
        }),
      ]);
      console.log('oldDate', oldDate.length)
      console.log('newDate', newDate.length)
      console.log('model diff', diff)
      return diff
    },

    *fetchCustomer(_, { put, call, all }) {
      const customer = yield call(service.getCustomer, { get_all: 1 });
      const customerList = [];
      const topCustomerName = [
        '普洛斯(上海)虹桥西物流园',
        '上海市临港实验中学',
        '上海景瑞物业管理有限公司(康桥)',
        '上海康桥先进制造技术创业园有限公司',
        '三亚京海国际假日酒店有限公司',
        '中海海惠物业服务有限公司三亚分公司',
        '上海华仪风能电气有限公司',
        '上海勃林格殷格翰药业有限公司',
        '上海南汇老港锻造厂',
        '上海古贺精工有限公司',
        '上海荣建化工厂有限公司',
        '上海舜斯化工有限公司',
        '上海星跃物业管理有限公司(总部湾)',
      ];
      const topCustomers = [];
      const companyList = get(customer, 'data.bean.enterprises', [])
      console.log('companyList', companyList)
      const hasPermissionCompanyIds = companyList.map(item => item.id)

      /**
       * 顺序：
        0 id,
        1 name,
        2 number,
        3 longitude,
        4 latitude,
        5 address,
        6 adcode,
        7 type,
        8 service_enterprise_id
        9 province
        10 city
      */
      get(customer, 'data.list', [])
        .filter(item => item[3] && item[4] && hasPermissionCompanyIds.includes(item[8]))
        .map((item, index) => {
          const data = {
            name: item[1],
            number: item[2],
            longitude: item[3],
            latitude: item[4],
            position: [+item[3], +item[4]],
            address: item[5],
            adcode: item[6],
            type: DispatchDataMap.customer,
            // 开通的功能：返回结构 "0,1,2,6"
            features: item[7] ? `${item[7]}` : '',
            // service_enterprise_id
            enterprise: [item[8]],
            id: `${item[6]}_${DispatchDataMap.customer}_${item[0]}`,
            label: item[1],
            province: item[9],
            city: item[10],
            reportDate: item[11], // 报告日期
            _id: item[0], // 服务端 id
          };
          if (topCustomerName.includes(item[1])) {
            topCustomers.push(data);
          } else {
            customerList.push(data);
          }
        });

      console.log('topCustomers', topCustomers)

      yield all([
        put({
          type: 'handleCustomerList',
          payload: topCustomers.concat(customerList),
        }),
        put({
          type: 'handleCompanyList',
          payload: companyList,
        })
      ])
    },

    *fetchLiveVideos({ payload }, { put, call, all }) {
      const res = yield call(service.getLiveVideo, payload);
      const data = get(res, 'data.list', []);
      yield all([
        put({
          type: 'handleLiveVideo',
          payload: data,
        }),
        put({
          type: 'handleVideoDiviceId',
          payload: data[0] && data[0].deviceId,
        }),
      ]);
    },

    *fetchRealPLData(a, {call, put, select}) {
      const {overview} = yield select(state => state);
      const {photovoltaic} = overview;

      yield put({
        type: 'updateRealTimePower',
        payload: photovoltaic[new Date().getHours()]
      })
    },

    *getPeopleVideoUrl({payload}, {put, call, all}) {
      const res = yield call(service.getLiveVideoUrl, payload.userId);
      const data = get(res, 'data.list[0]', {});
      console.log('data', data)
      yield put({
        type: 'updatePeopleVideo',
        payload: data
      })
    }
  },
};
