var angular = require('angular');
require('jsUtil');
require('../modules');

var module = angular.module('flowmodulebase.services');

module.factory('FlowLogService', function($http) {

  function filterWorkflowlog(workflowlog) {
    var flowLogs = [];
    workflowlog.logs.forEach(function(log) {
      var receivename = log.receivename;
      if (!receivename) { return; }
      receivename.split(',').forEach(function(name) {
        flowLogs.push(new FlowLog(log.sendtime, log.sendname, name, log.wflevename,
            log.receivewfname, log.staytime, log.accreditinfo));
      });
    });
    return flowLogs;
  }

  function FlowLog(receivetime, sendname, receivename, wflevename, receivewfname, staytime, accreditinfo) {
    var receiveTime = getReceiveTimes(receivetime);
    this.receiveDay = receiveTime[0]; // 天
    this.receiveHM = receiveTime[1]; // 小时和分钟
    this.sendname = sendname;
    this.receivename = receivename;
    this.wflevename = wflevename;
    this.receivewfname = receivewfname;
    this.staytime = getStayTime(staytime);
    this.accreditinfo = accreditinfo;
  }

  function getStayTime(staytime) {
    if(!staytime) {
      return '小于1分';
    } else {
      if (staytime.indexOf('小时') !== -1) {
        return staytime.substring(0, staytime.indexOf('小时') + 2);
      }
    }
    return staytime;
  }

  function getReceiveTimes(receivetime) {
    var receiveTimes = [];
    var hm = '';
    var date = jsUtil.parseDate(receivetime, 'Y-m-d H:i:s');
    var smartDate = jsUtil.smartListDateParser(date);
    var hours = receivetime.substring(receivetime.indexOf(' ') + 1, receivetime.indexOf(':'));  // 获取小时
    var minutes = receivetime.substring(receivetime.indexOf(':') + 1, receivetime.lastIndexOf(':')); // 获取分钟
    if (smartDate.indexOf('-') !== -1) {
      hm = hours + ':' + minutes;
    } else if (smartDate.indexOf(':') === -1) {
      hm = hours + '点' + minutes;
    }
    receiveTimes.push(smartDate);
    receiveTimes.push(hm);
    return receiveTimes;
  }

  var FlowLogService = {
    getFlowLog: function(flowType, recordId) {
      return $http.get('/workflow/floglog', {
        timeout: 15000,
        params: {
          flowType: flowType,
          recordId: recordId
        }
      }).then(function(res) {
        return JSON.parse(res.data.flowLog);
      });
    },

    getViewFlowLog: function(flowType, recordId) {
      return this.getFlowLog(flowType, recordId).then(function(data) {
        return filterWorkflowlog(data);
      });
    }
  };

  return FlowLogService;
});
