'use strict';

const request = require('superagent');

const moment = require("moment");


function getFireAlarmList (opts) {
   return async function (ctx, next) {
      const models = ctx.fs.dc.models;
      let errMsg = { message: '获取消防告警失败' }
      try {
         const res = await models.FireAlarm.findAll();
         ctx.status = 200;
         ctx.body = res;
      } catch (error) {
         ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
         ctx.status = 400;
         ctx.body = errMsg
      }
   }
}

// 新增消防告警
function addAlarm (opts) {
   return async function (ctx, next) {
      const models = ctx.fs.dc.models;
      try {
         const body = ctx.request.body
         await models.FireAlarm.create(body)

         ctx.status = 204;
         ctx.body = { message: '新建消防告警成功' }
      } catch (error) {
         ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
         ctx.status = 400;
         ctx.body = { message: '新建消防告警失败' }
      }
   }
}

// 修改消防告警
function updateAlarm (opts) {
   return async function (ctx, next) {
      try {
         const models = ctx.fs.dc.models;
         const { id } = ctx.params;
         const body = ctx.request.body;
         await models.FireAlarm.update(
            body,
            { where: { id: id, } }
         )
         ctx.status = 204;
         ctx.body = { message: '修改消防告警成功' }

      } catch (error) {
         ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
         ctx.status = 400;
         ctx.body = { message: '修改消防告警失败' }
      }
   }
}


function videoList (opts) {
   return async function (ctx) {
      try {
         const { models, } = ctx.fs.dc;
         const { app, yingshiTokenRes } = ctx

         let yingshiToken = ''
         if (yingshiTokenRes && yingshiTokenRes.token && yingshiTokenRes.expire && moment().isBefore(moment(yingshiTokenRes.expire))) {
            yingshiToken = yingshiTokenRes.token
         } else {
            const tokenRes = await app.fs.yingshiRequest.post(`lapp/token/get`, {
               query: {
                  appKey: opts.yingshiKey,
                  appSecret: opts.yingshiSecret
               }
            })
            if (tokenRes.code == 200 && tokenRes.data) {
               const { accessToken, expireTime } = tokenRes.data

               ctx.yingshiTokenRes = {
                  token: accessToken,
                  expire: expireTime
               }
               yingshiToken = accessToken
            } else {
               throw '未能获取进行萤石鉴权'
            }
         }

         // const deviceRes = await app.fs.yingshiRequest.post(`lapp/device/list`, {
         //     query: {
         //         accessToken: yingshiToken,
         //     }
         // })

         ctx.status = 200;

         let deviceRes_ = [{
            deviceName: '楼前大桥',
            deviceSerial: 'L48947105',
         }, {
            deviceName: '滁北大桥',
            deviceSerial: 'L48947108',
         }, {
            deviceName: '新联桥',
            deviceSerial: 'L48947110',
         }, {
            deviceName: '湾庄线',
            deviceSerial: 'L48947112',
         }, {
            deviceName: '新土线',
            deviceSerial: 'AA9943808',
         }, {
            deviceName: '东文大桥',
            deviceSerial: 'L48947087',
         }, {
            deviceName: '莲姚线',
            deviceSerial: 'L48947082',
         }, {
            deviceName: '荷漳公路',
            deviceSerial: 'L48947109',
         }, {
            deviceName: '新武大桥',
            deviceSerial: 'L48947086',
         },]

         const deviceState = await Promise.all(deviceRes_.map(d => {
            return app.fs.yingshiRequest.post(`lapp/device/info`, {
               query: {
                  accessToken: yingshiToken,
                  deviceSerial: d.deviceSerial
               }
            })
         }))

         for (let d of deviceRes_) {
            let corState = deviceState.find(item => item.code == 200 && item.data && item.data.deviceSerial == d.deviceSerial)
            if (corState) {
               d.status = corState.data.status
            } else {
               d.status = 0
            }
            d.token = yingshiToken
         }

         ctx.body = deviceRes_
         // ||
         //  (deviceRes.data || []).map(item => {
         //     return {
         //         ...item,
         //         token: yingshiToken,
         //     }
         // })
      } catch (error) {
         ctx.fs.logger.error(`path: ${ctx.path}, error: error`);
         ctx.status = 400;
         ctx.body = {
            message: typeof error == 'string' ? error : undefined
         }
      }
   }
}


function getDetails (opts) {
   return async function (ctx) {
      try {
         const { app, yingshiTokenRes } = ctx
         const res = await app.fs.baiDuJiaotong.get('trafficindex/city/details/?cityCode=163')

         ctx.status = 200
         ctx.body = res || {}

      } catch (error) {
         ctx.fs.logger.error(`path: ${ctx.path}, error: error`);
         ctx.status = 400;
         ctx.body = {
            message: '获取南昌市道路数据失败'
         }
      }
   }
}


// 获取消防设备
function getFireDevice (opts) {
   return async function (ctx, next) {
      let rslt = {};
      try {
         let url = `${opts.tfApi}/device/alarm/statistic?_timeStamp=${new Date().getTime()}`;
         const res = (await request.get(url).set("X-API-TOKEN", "9911510d-9dae-438d-9b6e-0545ef003c58")).body.data;
         rslt = res.items;
         ctx.status = 200;
         ctx.body = rslt;
      } catch (error) {
         ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
         ctx.status = 400;
         ctx.body = { message: '获取消防设备失败' }
      }
   }
}

// 获取火情趋势
function getFireTrend (opts) {
   return async function (ctx, next) {
      let rslt = [];
      try {
         let url = `${opts.tfApi}/alarms/trend?key=1`;
         const res = (await request.get(url).set("X-API-TOKEN", "9911510d-9dae-438d-9b6e-0545ef003c58")).body.data;
         let start = moment().add(-6, 'day').startOf('day').valueOf();
         let end = moment().endOf('day').valueOf();
         res.map(item => {
            const time = moment(item.time).valueOf();
            if (time >= start && time <= end) {
               rslt.push({ time: item.time, count: item.val })
            }
         })
         ctx.status = 200;
         ctx.body = rslt;
      } catch (error) {
         ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
         ctx.status = 400;
         ctx.body = { message: '获取火情趋势失败' }
      }
   }
}


function getSurroundingConditions (opts) {
   return async function (ctx) {
      try {

         const { app, yingshiTokenRes } = ctx
         const { center } = ctx.query;
         const res = await app.fs.baiDu.get(`traffic/v1/around?ak=${opts.baiduAK}&center=${center}&radius=1000`)

         ctx.status = 200
         ctx.body = res && JSON.parse(res) || {}

      } catch (error) {
         ctx.fs.logger.error(`path: ${ctx.path}, error: error`);
         ctx.status = 400;
         ctx.body = {
            message: '获取周边路况数据失败'
         }
      }
   }
}

module.exports = {
   addAlarm,
   updateAlarm,
   getFireAlarmList,
   getFireDevice,
   getFireTrend,
   videoList,
   getDetails,
   getSurroundingConditions
}