import * as service from '@/pages/screen/services'
import get from 'lodash/get';
import {RepairTaskFilter} from '../constants';
import moment from 'moment';
import {pIRight, last30dayRight, random} from '../mocks'

const getRandomList = () => {
  const randomNum1 = Math.random().toFixed(3) * 100 + 50
  const randomNum2 = Math.random().toFixed(3) * 100 + 50
  const randomNum3 = Math.random().toFixed(3) * 100 + 50
  const randomNum4 = Math.random().toFixed(3) * 100 + 50
  return [randomNum4, 200, randomNum1, 80, randomNum2, 110, 130, 150, 70, 150, 80, randomNum3];
}

// total数据mock
const DefaultTotalNum = 201315;
const DefaultTotalNumList = new Array(12).fill(0).map((item, index) => {
  return DefaultTotalNum + (index % 2 === 0 ? 5 * index : (-5 * index));
});

export default {
  namespace: 'overview',

  state: {
    month: new Date().getMonth(),
    useElectricData: {
      month: 0.01,
      year: 0.12,
      total:DefaultTotalNumList[new Date().getMonth()]
    },
    realData: {
      number_count: 0,
      station_count: 0,
      monitor_device_count: 0,
      capacity_count: 0,
      list1: [],
      list2: [],
      list3: [],
      list4: []
    },
    inspectionData: {
      reach: 1,
      reach_year_on_year: 0.03,
      reach_month_on_month: random(0, 0.03, 2),
      exception_handling: 1,
      exception_year_on_year: 0.02,
      exception_month_on_month: random(0, 0.03, 2)
    },
    currentTab: 'repair',
    repairData: [],
    warningData: [],
    defectData: [],
    // 托管电量
    sumActiveEnergy: 26097284.52,
    sumReactiveEnergy: 8584633.07,
    // 总功率
    sumPower: 0,
    // 总负载
    sumPayload: 0,
    // 微电网
    monthEnergyFees: 60314.25,
    historyTrustEnergyFees: 1831695.77,
    photovoltaic: {
      total: 853269.5,
      totalAssemblyCapacity: 722.5,
      realTimePowerGeneration: 257.1,
      totalPower: 257.1,
      realTimePowerList:  pIRight.map((item, index) => ({
        time: `${(index)}点`,
        value: item
      }))
    },
    energyStorage: {
      total: 1506.6,
      totalAssemblyCapacity: 1506.6,
      realPower: 302.4,
      sumCharging: 1378797.82,
      sumDischarge: 1130213.61,
      avgEfficiency: '75.25%',
      sumProfit: 59.112,
      theoryProfit: 78.551
    },
    chargingPile: {
      sumCharging: 25571.51,
      realTimeUseRate: 0.253,
      totalNum: 512,
      dcPile: 0,
      acPile: 512,
      todayCharging: 120.32,
      yesterdayCharging: 230.99,
      monthCharging: 2243.01,
      lastMothCharging: 6075.24,
    },
    lateLy30Charging: last30dayRight
  },

  reducers: {
    changeMonth(state, { payload }) {
      return {
        ...state,
        month: payload,
      };
    },
    updateData(state, { payload }) {
      return {
        ...state,
        ...payload
      }
    },
    autoIncreaseMonth(state, {payload}) {
      return {
        ...state,
        useElectricData: {
          ...state.useElectricData,
          total: state.useElectricData.total + (Math.random() * 10 > 5 ? 2 : 1)
        }
      }
    },
    autoIncreaseRightMock(state, {payload}) {
      const increase = Math.random() * 10 > 5 ? 15 : 5;
      return {
        ...state,
        monthEnergyFees: state.monthEnergyFees + increase,
        historyTrustEnergyFees: state.historyTrustEnergyFees + increase
      }
    }
  },

  effects: {
    *fetchRealTimeData({ payload }, { call, put }) {
      const res = yield call(service.getRealTimeData, payload);
      yield put({
        type: 'updateData',
        payload: {
          realData: {
            ...get(res, 'data.bean', {}),
            // number_count: 5121,
            // station_count: 5121,
            // monitor_device_count: 1852,
            // capacity_count: 1812730,
            list1: getRandomList(),
            list2: getRandomList(),
            list3: getRandomList(),
            list4: getRandomList()
          }
        }
      });
    },
    *onMonthChange({ payload }, { call, put }) {
      // const res = yield call(service.getStatisticsData, payload);
      yield put({type: 'updateData', payload: {
        useElectricData: {
          month: random(-0.2, 0.2, 2),
          year: 0.12,
          total: DefaultTotalNumList[payload]
        },
      }})

      yield put({type: 'updateData', payload: {
        inspectionData: {
          reach: 1,
          reach_year_on_year: 0.03,
          reach_month_on_month: random(0, 0.03, 2),
          exception_handling: random(0.95, 1, 2),
          exception_year_on_year: 1,
          exception_month_on_month: random(0, 0.03, 2)
        }
      }})
    },
    *fetchTabData({payload}, {call, put}) {
      const {currentTab} = payload;
      yield put({
        type: 'updateData',
        payload: {
          currentTab
        }
      })
      const repair = yield call(service.getRepairList, payload)
      const warning = yield call(service.getAlarmList, payload)
      const defect = yield call(service.getDefectList, payload)
      try {
        yield put({
          type: 'updateData',
          payload: {
            repairData: get(repair, 'data.list', []).filter(item => RepairTaskFilter.includes(item.status)),
            warningData: get(warning, 'data.list', []),
            defectData: get(defect, 'data.list', [])
          }
        })
      } catch (error) {

      }
    },
    *fetchScreenRealData({payload}, {call, put, select}) {
      const date = moment();
      const {company, area} = yield select(state => state.screen)
      const params = {
        startTime: `${date.format('YYYY-MM-DD')} 00:00:00`,
        endTime: `${date.format('YYYY-MM-DD')} 23:59:59`,
        enterprise_id: company,
        province: area[0],
        city: area[1],
        real: 1
      }

      const result = yield call(service.realDataMonitor, params);
      const {
        ep, // 有用功
        eq,
        power,
        load_rate,
      } = get(result, 'data.list[0]', {});
      yield put({
        type: 'updateData',
        payload: {
          sumActiveEnergy: ep || 0,
          sumReactiveEnergy: eq || 0,
          sumPower: power || 0,
          sumPayload: load_rate || 0
        }
      });
    },
    *fetchMonthEp(a, {call, put, select}) {
      const {screen, overview} = yield select(state => state);
      const {company} = screen;
      const {useElectricData} = overview;
      const result = yield call(service.getMonthTotal, {enterprise_id: company});
      const total = get(result, 'data.bean.month_ep', 0);

      yield put({type: 'updateData', payload: {
        useElectricData: {
          ...useElectricData,
          total: parseInt(total)
        }
      }})
    },
    *fetchRealPLData(a, {call, put, select}) {
      const {overview} = yield select(state => state);
      const {photovoltaic} = overview;

      yield put({
        type: 'updateData',
        payload: {
          photovoltaic: {
            ...photovoltaic,
            realTimePowerGeneration: pIRight[new Date().getHours()]
          }
        }
      })
    }
  },
};
