"use strict";
appCore.controller("MyDiaryUnfilledReportCloneCtrl3", ["$state", "$scope", "$http", "$timeout", "vServices", "$uibModal", "$document",
  function ($state, $scope, $http, $timeout, vServices, $uibModal, $document) {
    $scope.$root.page.title = "My Diary Unfilled Report";
    $scope.isAdmin = $scope.$root.gUser.id;
    $scope.project = [];
    $scope.selectAll = { selected: false };
    $scope.CheckedId = "";
    $scope.tblheader = [];
    $scope.tblheader2 = [];
    $scope.revenueCenters = [];
    $scope.showLockDiv = false;
    $scope.myDiary = { default: [], project: [], heroes: [], datatable: [], datatable2: [] };
    $scope.prebilled = [];
    $scope.consolidatedData = [];
    $scope.reportViewModel = '2';
    $scope.billingType = '';
    $scope.invoiceData = {};
    $scope.dTable = null;
    $scope.showBtn = true;
    $scope.numOfWeeks = 0;
    $scope.numOfWeeksArr = [];
    $scope.weekDays = [];
    $scope.lastDay = 0;
    $scope.isLocked = false;

    $scope.filter = {
      fromDate: moment().subtract(2, "days").format("DD-MM-YYYY"),
      toDate: moment().format("DD-MM-YYYY"),
      rc_name: 0,
      minHours: 0,
      project: 0,
      proj_id: 0,
      monthyear: '',
      pageName: "My Diary Report",
      timezn: 'Asia/Kolkata'
    };
    let numOr0 = n => isNaN(n) ? 0 : n;
    $scope.sum = (item, list) => list.map(o => o[item]).reduce((a, b) => parseFloat(numOr0(a)) + parseFloat(numOr0(b)));
    $scope.tempArry = [];

    const convertDataForProject = res => {
      if (res) {
        $scope.project = [];
        $scope.project.push({ id: 0, name: " Select Project", proj_status: "active" });
        res = $scope.$root.sort(res, "proj_name");
        res = res.filter(proj => proj.proj_status === "active");
        res.map((o) => $scope.project.push({ id: o.projectid, name: o.proj_name, proj_status: o.proj_status, proj_mydiaryLockDate: o.proj_mydiaryLockDate }));
        $scope.filter.project = $scope.project[0];
      }
    };
    $scope.clickSelectAll = function () {
      angular.forEach($scope.myDiary.default, function (value) {
        value.selected = $scope.selectAll.selected;
        if ($scope.selectAll.selected) {
          if ($scope.CheckedId.length == 0) {
            $scope.CheckedId = value.mydiaryid;
          }
          else {
            $scope.CheckedId += ", " + value.mydiaryid;
          }
        }
      });
      if (!$scope.selectAll.selected) $scope.CheckedId = "";
    };
    $scope.updateLockedDate = function () {
      if (!$scope.myDiaryLock.LockTillDate) toastr.error("Please provide valid Date to Lock.");
      else vServices.callApi("mydiary/lock", "PUT", { proj_id: $scope.filter.project.id, lock_date: $scope.myDiaryLock.LockTillDate }).then((res) => {
        if (res) {
          //toastr.success(res, "Message");
        }
        $state.go($state.current, {}, { reload: true });
      });
    };
    $scope.Checked = function () {
      $scope.CheckedId = "";
      $scope.selectAll.selected = true;
      angular.forEach($scope.myDiary.default, function (value) {
        if (value.selected) {
          if ($scope.CheckedId.length == 0) {
            $scope.CheckedId = value.mydiaryid;
          }
          else {
            $scope.CheckedId += ", " + value.mydiaryid;
          }
        }
        else $scope.selectAll.selected = false;
      });
    };

    const convertDataForMyDiary = res => {
      if ($scope.dTable) $scope.dTable.destroy();
      $scope.tblheader = [];
      $scope.myDiary.datatable = [];
      $scope.consolidatedData = [];
      $scope.showLoader = false;
      document.getElementById('blackout').style.display = 'block';
      const yr = moment($scope.filter.monthyear).format('YYYY');
      const mnt = moment($scope.filter.monthyear).format('MM');
      const firstDayOfMonth = new Date(yr, mnt - 1, 1).getDay();
      const secondDayOfMonth = new Date(yr, mnt - 1, 2).getDay();
      const lastDayM = moment($scope.filter.monthyear).clone().endOf('month').format('DD-MM-YYYY');
      const lastDay = moment(lastDayM, 'DD-MM-YYYY').day();
      $scope.lastDay = lastDay;
      console.log(res);
      res.forEach(i => {
        let countPrebilled = 0;
        let countHours = 0;
        let temArrHours = [];
        let temArrPrebilledHours = [];
        let totalBillingDays = 0;
        let weeklySumHero = 0;
        let weeklySumMngr = 0;
        let daysCounter = 0;
        let weekCountInMonth = 0;
        i.logged_hours.forEach((j, index) => {
          totalBillingDays += 1;
          const leaves = j.logtype.split(',');
          j.dayType = leaves;
          const dayOfWeek = moment(j.inserton).day();
          const empOnLeave = leaves.includes('16') || leaves.includes('17') || leaves.includes('22') || leaves.includes('23') ? false : true;
          if (!j.prebilled && (dayOfWeek !== 0 || dayOfWeek !== 6) && empOnLeave) {
            let hour = j.hours ? parseFloat(j.hours) : 0;
            countHours = parseFloat(hour);
            countPrebilled = 0;
          }
          if (j.prebilled && (dayOfWeek !== 0 || dayOfWeek !== 6) && empOnLeave) {
            let prebilled = j.prebilled ? parseFloat(j.prebilled) : 0;
            let hour = j.hours ? parseFloat(j.hours) : 0;
            countPrebilled = parseFloat(prebilled);
            countHours = parseFloat(hour);
          }

          if (dayOfWeek !== 0 && dayOfWeek !== 6 && empOnLeave) { // exclude Saturday and Sunday
            weeklySumHero += countHours;
            weeklySumMngr += countPrebilled;
            daysCounter++;
          }
          if ((dayOfWeek == 6 && ((firstDayOfMonth == 0 && moment(j.inserton).format('DD') > 1) || (secondDayOfMonth == 0 && moment(j.inserton).format('DD') > 2) || (firstDayOfMonth != 0 && secondDayOfMonth != 0))) || index === i.logged_hours.length - 1) { // Sunday or end of month
            temArrHours.push({ 'hours': weeklySumHero, 'preHours': weeklySumMngr });
            temArrPrebilledHours.push({ 'preHours': weeklySumMngr });
            j.lastWeekData = { 'hours': weeklySumHero, 'preHours': weeklySumMngr };
            weeklySumHero = 0;
            weeklySumMngr = 0;
            daysCounter = 0;
            weekCountInMonth += 1;
          }
          j.currentDay = moment(j.inserton).day();
          j.lastDayOfMonth = index === i.logged_hours.length - 1 ? true : false;
        });
        i.totalBillingDays = totalBillingDays;
        i.countHours = countHours;
        i.weeklyHours = temArrHours;
        i.weeklyPrebilled = temArrPrebilledHours;
        i.weekCountInMonth = weekCountInMonth;
        $scope.numOfWeeks = weekCountInMonth;
      });
      $scope.prebilled = res;
      console.log(res);
      if (res) {
        let newResult = null, newResult1 = null, resHero = null;
        $scope.myDiary.datatable.map((o) => {
          o.destroy();
        });
        // remove date from header
        document.querySelectorAll("#myDiaryDataTableView thead tr th.datehead").forEach(o => o.remove());

        $scope.myDiary = { default: [], project: [], heroes: [], datatable: [] };
        let res1 = $scope.$root.sort(res, "emp_first_name");
        $scope.myDiary.default = $scope.$root.sort(res1, "proj_name");

        newResult = res.map(o => o.proj_name + "~" + o.projectid).filter((v, i, s) => s.indexOf(v) === i).sort();

        newResult.forEach(o => {
          const proj = o.split("~");
          $scope.myDiary.project.push({ name: proj[0], id: proj[1], data: res.filter(j => j.projectid === parseInt(proj[1])) });
        });

        newResult1 = res.map(o => o.emp_first_name + " " + o.emp_last_name + "-" + o.employeeid).filter((v, i, s) => s.indexOf(v) === i).sort();
        resHero = $scope.$root.sort(res, "projectid");
        newResult1.forEach(o => {
          const hero = o.split("-");
          $scope.myDiary.heroes.push({ name: hero[0], id: hero[1], data: resHero.filter(j => j.employeeid === parseInt(hero[1])) });
        });
        $scope.tblheader = [];

        var headerLength = 1;
        var flags = [], output = [], inserton = [], l = res[0].logged_hours.length, i;
        for (i = 0; i < l; i++) {
          if (flags[res[0].logged_hours[i].dates]) continue;
          flags[res[0].logged_hours[i].dates] = true;
          output.push(res[0].logged_hours[i].dates);
          inserton.push(res[0].logged_hours[i].inserton);
        }
        for (var k in output) {
          var currentDay = moment(inserton[k]).day();
          var lastDayOfMon = new Date(moment(inserton[k]).format('YYYY'), moment(inserton[k]).format('MM') + 1, 0);
          var lastDayOfMonth = moment(lastDayOfMon).format('DD') == moment(inserton[k]).format('DD') ? true : false;
          if (currentDay != 0) {
            headerLength++;
            var node = document.createElement("th");
            var node2 = document.createElement("th");
            var textnode;
            var textnode2;
            var dayHeader = currentDay == 6 ? 'Week' : moment(inserton[k]).format('DD-MM-YYYY');
            if ($scope.reportViewModel == '1') {
              textnode = document.createTextNode(dayHeader);
              textnode2 = document.createTextNode(dayHeader);
            }
            if ($scope.reportViewModel == '2') {
              let conv = moment(inserton[k]).format('YYYY-MM-DD');
              let compact = currentDay == 6 ? 'Week' : moment(conv).format('DD-MM');
              textnode = document.createTextNode(compact);
              textnode2 = document.createTextNode(compact);
            }
            if (currentDay == 6) {
              node.setAttribute("class", "datehead weekend daily");
              node2.setAttribute("class", "datehead weekend managerFilled daily");
            } else {
              node.setAttribute("class", "datehead daily");
              node2.setAttribute("class", "datehead managerFilled daily");
            }
            node.appendChild(textnode);
            node2.appendChild(textnode2);
            document.querySelector("#myDiaryDataTableView thead tr").appendChild(node);
            document.querySelector("#myDiaryDataTableView thead tr").appendChild(node2);
          }
        }
        if (lastDay != 6 && lastDay != 0) {
          var node = document.createElement("th");
          var node2 = document.createElement("th");
          var dayHeader = 'Week';
          var textnode = document.createTextNode(dayHeader);
          var textnode2 = document.createTextNode(dayHeader);
          node.setAttribute("class", "datehead weekend daily");
          node2.setAttribute("class", "datehead weekend daily");
          node.appendChild(textnode); node2.appendChild(textnode2);
          document.querySelector("#myDiaryDataTableView thead tr").appendChild(node);
          document.querySelector("#myDiaryDataTableView thead tr").appendChild(node2);
        }

        $scope.$root.callDataTable("#myDiaryDataTableView", headerLength * 100, (t) => {
          $scope.dTable = t;
        }, { orientation: 'landscape' }, { fixedColumns: { left: 3 } });
        $scope.callConsolidated();
        vServices.callApi("invoice/singleInvoice?projId=" + $scope.filter.proj_id, "GET", {}).then(res => {
          if (res) {
            $scope.invoiceData = res[0];
          }
        });
      }
      $scope.showBtn = true;
      document.getElementById('blackout').style.display = 'none';
    };

    const convertDataForMyDiaryWeekly = res => {
      if ($scope.dTable2) $scope.dTable2.destroy();
      $scope.tblheader2 = [];
      $scope.myDiary.datatable2 = [];
      $scope.showLoader = false;
      $scope.weekDays = [];
      document.getElementById('blackout').style.display = 'none';
      const yr = moment($scope.filter.monthyear).format('YYYY');
      const mnt = moment($scope.filter.monthyear).format('MM');
      const firstDayOfMonth = new Date(yr, mnt - 1, 1).getDay();
      const secondDayOfMonth = new Date(yr, mnt - 1, 2).getDay();
      const lastDay = new Date(yr, mnt + 1, 0).getDay();
      $scope.lastDay = lastDay;
      res.forEach(i => {
        let countPrebilled = 0;
        let countHours = 0;
        let temArrHours = [];
        let temArrPrebilledHours = [];
        let totalBillingDays = 0;
        let weeklySumHero = 0;
        let weeklySumMngr = 0;
        let daysCounter = 0;
        let weekCountInMonth = 0;
        let weekDays = '';
        i.logged_hours.forEach((j, index) => {
          totalBillingDays += 1;
          const leaves = j.logtype.split(',');
          j.dayType = leaves;
          const dayOfWeek = moment(j.inserton).day();
          const empOnLeave = leaves.includes('16') || leaves.includes('17') || leaves.includes('22') || leaves.includes('23') ? false : true;
          if (!j.prebilled && (dayOfWeek !== 0 || dayOfWeek !== 6) && empOnLeave) {
            let hour = j.hours ? parseFloat(j.hours) : 0;
            countHours = parseFloat(hour);
            countPrebilled = 0;
          }
          if (j.prebilled && (dayOfWeek !== 0 || dayOfWeek !== 6) && empOnLeave) {
            let prebilled = j.prebilled ? parseFloat(j.prebilled) : 0;
            let hour = j.hours ? parseFloat(j.hours) : 0;
            countPrebilled = parseFloat(prebilled);
            countHours = parseFloat(hour);
          }
          if (dayOfWeek !== 0 && dayOfWeek !== 6 && empOnLeave) { // exclude Saturday and Sunday
            weeklySumHero += countHours;
            weeklySumMngr += countPrebilled;
            weekDays += ',' + moment(j.inserton).format('DD');
            daysCounter++;
          }
          if ((dayOfWeek == 0 && ((firstDayOfMonth == 0 && moment(j.inserton).format('DD') > 1) || (secondDayOfMonth == 0 && moment(j.inserton).format('DD') > 2) || (firstDayOfMonth != 0 && secondDayOfMonth != 0))) || index === i.logged_hours.length - 1) { // Sunday or end of month
            temArrHours.push({ 'hours': weeklySumHero, 'preHours': weeklySumMngr });
            temArrPrebilledHours.push({ 'preHours': weeklySumMngr });
            var len = weekDays.slice(1).split(',').length - 1;
            var dys = weekDays.slice(1).split(',')[0] + '-' + weekDays.slice(1).split(',')[len];
            j.lastWeekData = { 'hours': weeklySumHero, 'preHours': weeklySumMngr, 'days': dys.toString() };
            $scope.weekDays.push(dys.toString());
            weeklySumHero = 0;
            weeklySumMngr = 0;
            daysCounter = 0;
            weekCountInMonth += 1;
            weekDays = '';
          }
          j.currentDay = moment(j.inserton).day();
          j.lastDayOfMonth = index === i.logged_hours.length - 1;
        });
        i.totalBillingDays = totalBillingDays;
        i.countHours = countHours;
        i.weeklyHours = temArrHours;
        i.weeklyPrebilled = temArrPrebilledHours;
        i.weekCountInMonth = weekCountInMonth;
        $scope.numOfWeeks = weekCountInMonth;
      });
      const numOfWeeks = $scope.numOfWeeks;
      $scope.numOfWeeksArr = [];
      for (let i = 0; i < numOfWeeks; i++) {
        let k = i + 1;
        $scope.numOfWeeksArr.push({ 'week': 'Week ' + k, 'days': $scope.weekDays[i] });
      }
      $scope.prebilled = res;
      console.log(res);
      if (res) {
        let newResult = null, newResult1 = null, resHero = null;
        $scope.myDiary.datatable.map((o) => {
          o.destroy();
        });
        // remove date from header
        document.querySelectorAll("#myDiaryDataTableView2 thead tr th.weeks").forEach(o => o.remove());
        $scope.myDiary = { default: [], project: [], heroes: [], datatable: [], datatable2: [] };
        let res1 = $scope.$root.sort(res, "emp_first_name");
        $scope.myDiary.default = $scope.$root.sort(res1, "proj_name");
        newResult = res.map(o => o.proj_name + "~" + o.projectid).filter((v, i, s) => s.indexOf(v) === i).sort();
        newResult.forEach(o => {
          const proj = o.split("~");
          $scope.myDiary.project.push({ name: proj[0], id: proj[1], data: res.filter(j => j.projectid === parseInt(proj[1])) });
        });
        newResult1 = res.map(o => o.emp_first_name + " " + o.emp_last_name + "-" + o.employeeid).filter((v, i, s) => s.indexOf(v) === i).sort();
        resHero = $scope.$root.sort(res, "projectid");
        newResult1.forEach(o => {
          const hero = o.split("-");
          $scope.myDiary.heroes.push({ name: hero[0], id: hero[1], data: resHero.filter(j => j.employeeid === parseInt(hero[1])) });
        });
        $scope.tblheader2 = [];
        var headerLength = 1;
        var flags = [], output = [], inserton = [], weekly = [], l = res[0].logged_hours.length, i;
        for (i = 0; i < l; i++) {
          if (flags[res[0].logged_hours[i].dates]) continue;
          flags[res[0].logged_hours[i].dates] = true;
          output.push(res[0].logged_hours[i].dates);
          inserton.push(res[0].logged_hours[i].inserton);
        }
        for (let k = 0; k < numOfWeeks; k++) {
          try {
            headerLength++;
            var node = document.createElement("th");
            var node2 = document.createElement("th");
            var textnode;
            var textnode2;
            let num0 = parseInt(k) + 1;
            textnode = document.createTextNode('Week-' + num0 + ' (' + $scope.weekDays[k] + ')');
            textnode2 = document.createTextNode('Week-' + num0 + ' (' + $scope.weekDays[k] + ')');
            node.appendChild(textnode);
            if ($scope.filter.proj_id != 0) {
              node2.appendChild(textnode2);
            }
            if (document.querySelector("#myDiaryDataTableView2 thead tr") != null) {
              document.querySelector("#myDiaryDataTableView2 thead tr").appendChild(node);
              node.setAttribute("class", "weeks");
            }
            if ($scope.filter.proj_id != 0) {
              if (document.querySelector("#myDiaryDataTableView2 thead tr") != null) {
                document.querySelector("#myDiaryDataTableView2 thead tr").appendChild(node2);
                node2.setAttribute("class", "weeks");
              }
            }
          }
          catch (e) {
            console.error(e);
          }
        }


        $scope.$root.callDataTable("#myDiaryDataTableView2", $scope.numOfWeeksArr.length * 100, (t) => {
          $scope.dTable2 = t;
        }, { orientation: 'landscape' });

        $scope.callConsolidated();

        vServices.callApi("invoice/singleInvoice?projId=" + $scope.filter.proj_id, "GET", {}).then(res => {
          if (res) {
            $scope.invoiceData = res[0];
          }
        });

      }

    };

    $scope.reportView = (view) => {
      $scope.reportViewModel = view;
      document.getElementById('blackout').style.display = 'block';
      $scope.dateChanged(false);
    }

    $scope.getWeekDaysOfMonth = (year, month, weekNumber, startDayOfWeek) => {
      const firstDayOfMonth = new Date(year, month - 1, 1);
      const firstWeekdayOfMonth = firstDayOfMonth.getDay();
      const daysInMonth = new Date(year, month, 0).getDate();
      const daysInFirstWeek = 7 - ((firstWeekdayOfMonth - startDayOfWeek + 7) % 7);
      const firstDayOfWeek = new Date(year, month - 1, 1 + daysInFirstWeek + (weekNumber - 2) * 7);
      let weekdaysInWeek = 0;
      var cnt = 7 - startDayOfWeek - 1;
      for (let i = 0; i < cnt; i++) {
        const day = new Date(firstDayOfWeek.getTime() + (i * 24 * 60 * 60 * 1000));
        if (day.getMonth() === month - 1 && day.getDay() >= 1 && day.getDay() <= 5) { // Monday to Friday
          weekdaysInWeek++;
        }
      }
      return weekdaysInWeek;
    }

    $scope.getSaturdaysAndSundays = (year, month) => {
      const daysInMonth = new Date(year, month, 0).getDate();
      const results = [];

      for (let day = 1; day <= daysInMonth; day++) {
        const date = new Date(year, month - 1, day);
        if (date.getDay() === 0 || date.getDay() === 6) {
          results.push(date);
        }
      }

      return results;
    }

    const getData = (f, t, h, r, pid) => {
      f = moment($scope.filter.monthyear).clone().startOf('month').format('DD-MM-YYYY');
      t = moment($scope.filter.monthyear).clone().endOf('month').format('DD-MM-YYYY');
      vServices.callApi("mydiary/unfilledclone?date=" + f + "&todate=" + t + "&minHours=" + h + "&rc_name=" + r + "&proj_id=" + pid + '&timezone=' + $scope.filter.timezn, "GET", {}).then(res => {
        console.log('isLocked', res);
        if (res) {
          $scope.tempArry = res;
          if ($scope.reportViewModel != '3') {
            convertDataForMyDiary(res);
          }
          if ($scope.reportViewModel == '3') {
            convertDataForMyDiaryWeekly(res);
          }
        }
      });
    }

    $scope.checkIfLocked = () => {

    }

    $scope.dateChanged = (first = false) => {
      if (!first) {
        $scope.showLoader = true;
        document.getElementById('blackout').style.display = 'block';
        $scope.showBtn = false;
        $scope.showLockDiv = $scope.filter.project.id > 0 ? true : false;
        if (!$scope.filter.fromDate) toastr.error("Please provide valid FromDate");
        else if (!$scope.filter.toDate) toastr.error("Please provide valid toDate");
        else {
          let f = moment($scope.filter.monthyear).clone().startOf('month').format('DD-MM-YYYY');
          let t = moment($scope.filter.monthyear).clone().endOf('month').format('DD-MM-YYYY');
          let year = moment($scope.filter.monthyear).format('YYYY');
          let bill_month = moment($scope.filter.monthyear).format('MMMM');


          vServices.callApi("mydiary/check_iflocked?bill_month=" + bill_month + '&year=' + year + "&todate=" + t + "&proj_id=" + $scope.filter.proj_id, "GET", {}).then(res => {
            console.log(res);
            if (res.length > 0)
              $scope.isLocked = res.length > 0 ? true : false;
            getData($scope.filter.fromDate, $scope.filter.toDate, $scope.filter.minHours, $scope.filter.rc_name, $scope.filter.proj_id);
          });
        }
      }
    };


    $scope.projectByRevenue = (rev_id) => {
      vServices.callApi("myDiary/allmyDiaryProjects?rev_id=" + rev_id, "GET", {}).then(res => convertDataForProject(res));
    };

    $scope.changeConsolidatedData = () => {
      $scope.callConsolidated();
    }

    $scope.callConsolidated = () => {
      var cData = $scope.myDiary.default;
      let tData = [];
      // console.log(cData);
      tData = cData.map(x => {
        return {
          'empId': x.employeeid,
          'empName': x.emp_first_name + ' ' + x.emp_last_name,
          'loggedhour': x.logged_hours
        }
      });
      tData.forEach(i => {
        var totalDays = 0;
        var totalHours = 0;
        i.loggedhour.forEach(x => {
          var temp = 0;
          const dayOfWeek = moment(x.inserton).day();
          const leaves = x.logtype.split(',');
          const isLorH = leaves.includes('16') || leaves.includes('17') || leaves.includes('22') || leaves.includes('23') ? false : true;
          if (x.prebilled > 0 && !x.logtype.includes('24') && isLorH && dayOfWeek != 0 && dayOfWeek != 6) {
            totalDays += 1;
            temp = x.prebilled ? parseFloat(x.prebilled) : 0;
          } else if (x.prebilled > 0 && x.logtype.includes('24') && isLorH && dayOfWeek != 0 && dayOfWeek != 6) {
            totalDays += 0.5;
            temp = x.prebilled ? parseFloat(x.prebilled) : 0;
          } else {
            totalDays += 0;
          }
          totalHours += temp;
        })
        i.totalDays = totalDays;
        i.totalMonthHours = totalHours;
        var fd = moment($scope.filter.monthyear).clone().startOf('month').format('DD-MM-YYYY');
        var td = moment($scope.filter.monthyear).clone().endOf('month').format('DD-MM-YYYY');
        vServices.callApi("myDiary/getHeroBillingDetails?projId=" + $scope.filter.proj_id + '&empId=' + i.empId + '&f=' + fd + '&t=' + td, "GET", {}).then(res => {
          if (res.length > 0) {
            if (res[0].billing_type) {
              i.billing_rate = res[0].billing_rate ? parseFloat(res[0].billing_rate) : 0;
              if (res[0].billing_type == '1') {
                i.total = parseFloat(i.billing_rate) * parseFloat(totalHours);
              } else {
                let z = parseFloat(totalHours) / 8;
                console.log(parseFloat(totalHours));
                i.total = parseFloat(i.billing_rate) * z;
              }
            } else {
              i.billing_rate = 0;
              i.total = 0;
            }
            i.billing_type = res[0].billing_type;
            $scope.billingType = res[0].billing_type == '1' ? 'Hourly' : 'Daily';
          } else {
            i.billing_rate = 0;
            i.total = 0;
            i.billing_type = '1';
            $scope.billingType = 'Hourly';
          }
          i.profilename = res[0].profilename ? res[0].profilename : '';
        });
      });
      $scope.consolidatedData = tData;
      console.log(tData);
    }

    const init = () => {
      $scope.loggedintz = 'Asia/Kolkata';
      vServices.callApi("/account/all_revenue_centers", "GET", {}).then(function (res) {
        if (res && res.length > 0) {
          $scope.revenueCenters = res;
        }
      });

    };

    $scope.saveCurrentDateData = (empId, proj_id, date, preVal, preIndex, oldVal, tz) => {
      $scope.showLoader = true;
      document.getElementById('blackout').style.display = 'block';
      var data = date + '_' + proj_id + '_' + empId;
      vServices.callApi("/mydiary/saveSingleDiaryByMngr", "POST", { myval: JSON.stringify({ 'prebilled': preVal, 'data': data, 'tz': tz, 'loggedintz': $scope.filter.timezn }) }).then(function (res) {
        if (res) {
          $scope.showLoader = false;
          document.getElementById('blackout').style.display = 'none';
          // toastr.success('Hours updated successfully');#28a745
          document.getElementById(preIndex).style = 'none';
          document.getElementById(preIndex).className = " form-control text-bold  is-valid ng-not-empty ng-touched ";
          // Current Week Data
          $scope.WeeklySumFunc($scope.prebilled);
        }
      });
    }

    $scope.WeeklySumFunc = (res) => {
      const yr = moment($scope.filter.monthyear).format('YYYY');
      const mnt = moment($scope.filter.monthyear).format('MM');
      const firstDayOfMonth = new Date(yr, mnt - 1, 1).getDay();
      const secondDayOfMonth = new Date(yr, mnt - 1, 2).getDay();
      const lastDayM = moment($scope.filter.monthyear).clone().endOf('month').format('DD-MM-YYYY');
      const lastDay = moment(lastDayM, 'DD-MM-YYYY').day();
      $scope.lastDay = lastDay;
      res.forEach(i => {
        let countPrebilled = 0;
        let countHours = 0;
        let temArrHours = [];
        let temArrPrebilledHours = [];
        let totalBillingDays = 0;
        let weeklySumHero = 0;
        let weeklySumMngr = 0;
        let daysCounter = 0;
        let weekCountInMonth = 0;
        let weekDays = '';
        i.logged_hours.forEach((j, index) => {
          totalBillingDays += 1;
          const leaves = j.logtype.split(',');
          j.dayType = leaves;
          const dayOfWeek = moment(j.inserton).day();
          const empOnLeave = leaves.includes('16') || leaves.includes('17') || leaves.includes('22') || leaves.includes('23') ? false : true;
          if (!j.prebilled && (dayOfWeek !== 0 || dayOfWeek !== 6) && empOnLeave) {
            let hour = j.hours ? parseFloat(j.hours) : 0;
            countHours = parseFloat(hour);
            countPrebilled = 0;
          }
          if (j.prebilled && (dayOfWeek !== 0 || dayOfWeek !== 6) && empOnLeave) {
            let prebilled = j.prebilled ? parseFloat(j.prebilled) : 0;
            let hour = j.hours ? parseFloat(j.hours) : 0;
            countPrebilled = parseFloat(prebilled);
            countHours = parseFloat(hour);
          }
          if (dayOfWeek !== 0 && dayOfWeek !== 6 && empOnLeave) { // exclude Saturday and Sunday
            weeklySumHero += countHours;
            weeklySumMngr += countPrebilled;
            weekDays += ',' + moment(j.inserton).format('DD');
            daysCounter++;
          }
          if ((dayOfWeek == 6 && ((firstDayOfMonth == 0 && moment(j.inserton).format('DD') > 1) || (secondDayOfMonth == 0 && moment(j.inserton).format('DD') > 2) || (firstDayOfMonth != 0 && secondDayOfMonth != 0))) || index === i.logged_hours.length - 1) { // Sunday or end of month
            temArrHours.push({ 'hours': weeklySumHero, 'preHours': weeklySumMngr });
            temArrPrebilledHours.push({ 'preHours': weeklySumMngr });
            var len = weekDays.slice(1).split(',').length - 1;
            var dys = weekDays.slice(1).split(',')[0] + '-' + weekDays.slice(1).split(',')[len];
            j.lastWeekData = { 'hours': weeklySumHero, 'preHours': weeklySumMngr, 'days': dys.toString() };
            $scope.weekDays.push(dys.toString());
            weeklySumHero = 0;
            weeklySumMngr = 0;
            daysCounter = 0;
            weekCountInMonth += 1;
            weekDays = '';
          }
          j.currentDay = moment(j.inserton).day();
          j.lastDayOfMonth = index === i.logged_hours.length - 1;
        });
        i.totalBillingDays = totalBillingDays;
        i.countHours = countHours;
        i.weeklyHours = temArrHours;
        i.weeklyPrebilled = temArrPrebilledHours;
        i.weekCountInMonth = weekCountInMonth;
        $scope.numOfWeeks = weekCountInMonth;
      });
      $scope.myDiary.default = res;
      $scope.prebilled = res;
      $scope.callConsolidated();
    }

    $scope.locknNotify = () => {
      if (confirm("Do you really want to lock the data !")) {
        document.getElementById('blackout').style.display = 'block';
        $scope.showLoader = true;
        let f = moment($scope.filter.monthyear).clone().startOf('month').format('DD-MM-YYYY');
        let t = moment($scope.filter.monthyear).clone().endOf('month').format('DD-MM-YYYY');
        let p = $scope.project.find(x => x.id == $scope.filter.proj_id);
        let bill_month = moment($scope.filter.monthyear).format('MMMM');
        let year = moment($scope.filter.monthyear).format('YYYY');
        console.log(bill_month);

        vServices.callApi("mydiary/lock_monthly_billing?bill_month=" + bill_month + "&year=" + year + "&rc_id=" + $scope.filter.rc_name + "&proj_id=" + $scope.filter.proj_id + '&projname=' + p.name, "GET", {}).then(res => {
          if (res) {
            $scope.isLocked = true;
            document.getElementById('blackout').style.display = 'none';
            $scope.showLoader = false;
          }
        });
      }
    }

    $scope.unlockMonthlyBilling = () => {
      if (confirm("Do you really want to unlock the data !")) {
        document.getElementById('blackout').style.display = 'block';
        $scope.showLoader = true;
        let f = moment($scope.filter.monthyear).clone().startOf('month').format('DD-MM-YYYY');
        let t = moment($scope.filter.monthyear).clone().endOf('month').format('DD-MM-YYYY');
        let bill_month = moment($scope.filter.monthyear).format('MMMM');
        let year = moment($scope.filter.monthyear).format('YYYY');
        let p = $scope.project.find(x => x.id == $scope.filter.proj_id);
        vServices.callApi("mydiary/unlock_monthly_billing?bill_month=" + bill_month + "&year=" + year + "&proj_id=" + $scope.filter.proj_id + '&projname=' + p.name, "GET", {}).then(res => {
          if (res) {
            $scope.isLocked = false;
            document.getElementById('blackout').style.display = 'none';
            $scope.showLoader = false;
          }
        });
      }
    }

    $scope.PreBilledSave = () => {
      if (confirm("Do you really want to save and update the data !")) {
        $scope.prebilled.forEach(i => {
          i.logged_hours.forEach(j => {
            j.emp_id = i.employeeid;
            j.proj_id = $scope.filter.proj_id;
            const leaves = j.logtype.split(',');
            const dayOfWeek = moment(j.inserton).day();
            const isLorH = leaves.includes('16') || leaves.includes('17') || leaves.includes('22') || leaves.includes('23') ? false : true;
            let p = j.prebilled && j.prebilled != 0 && isLorH ? j.prebilled : 0;
            j.prebilled = j.prebilled && j.prebilled != 0 && isLorH ? p : j.hours;
          });
        });
        $scope.showLoader = true;
        $scope.showBtn = false;
        document.getElementById('blackout').style.display = 'block';
        getJson(JSON.stringify($scope.prebilled)).then((_data) => {
          vServices.callApi("mydiary/updatePrebilled2", "POST", { myval: JSON.stringify(_data) }).then(function (res) {
            if (res) {
              toastr.success('Data updated successfully');
              $scope.showLoader = false;
              document.getElementById('blackout').style.display = 'none';
              $scope.showBtn = true;
              $scope.dateChanged(false);
            }
          })
        }).catch((err) => {
          console.log(25, err);
        });
      }
    }


    const isFloat = (n) => {
      return Number(n) === n && n % 1 !== 0;
    }
    const isInt = (n) => {
      return Number(n) === n && n % 1 === 0;
    }

    $scope.OnChangePrebilled = (empId, pIndex, proj_id, date, mngr_hours, oldVal, logtype, tz) => {
      let mVal = mngr_hours ? parseFloat(mngr_hours) : 0;
      let oVal = oldVal ? parseFloat(oldVal) : 0;
      let preIndex = 'prebilled' + empId + pIndex;
      // let preVal = parseFloat(document.getElementById(preIndex).value);

      if (mVal >= 0) {
        if ((isFloat(mVal) || isInt(mVal)) && (mVal >= 0 && mVal <= 24) && !isNaN(mVal)) {
          if (logtype.includes('24') && mVal > 4) {
            toastr.error('Cannot update more than 4 hours on half day.');
            document.getElementById(preIndex).value = 0;
          } else {
            document.getElementById(preIndex).style.border = '2px solid rgb(122 123 123)';
            document.getElementById(preIndex).style.backgroundImage = `url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'><path fill='rgb(122 123 123)' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/></svg>")`;
            document.getElementById(preIndex).style.backgroundRepeat = 'no-repeat';
            document.getElementById(preIndex).style.backgroundPosition = 'center right calc(0.375em + 0.1875rem)';
            document.getElementById(preIndex).style.backgroundSize = 'calc(0.75em + 0.375rem) calc(0.75em + 0.375rem)';
            $scope.saveCurrentDateData(empId, proj_id, date, mVal, preIndex, oldVal, tz);
          }
        } else {
          document.getElementById(preIndex).style.border = '2px solid #ff1e1e';
          document.getElementById(preIndex).style.backgroundPosition = 'center right calc(0.375em + 0.1875rem)';
          document.getElementById(preIndex).style.backgroundSize = 'calc(0.75em + 0.375rem) calc(0.75em + 0.375rem)';
          // document.getElementById(preIndex).value = 0;
        }
      } else {
        document.getElementById(preIndex).style.border = '2px solid #ff1e1e';
        document.getElementById(preIndex).style.backgroundPosition = 'center right calc(0.375em + 0.1875rem)';
        document.getElementById(preIndex).style.backgroundSize = 'calc(0.75em + 0.375rem) calc(0.75em + 0.375rem)';
        document.getElementById(preIndex).value = 0;
      }

    }
    init();

    const getJson = (jsonArr) => {
      const final_json = {};
      return new Promise((resolve, reject) => {
        let json = JSON.parse(jsonArr);
        for (let i = 0; i < json.length; i++) {
          const jsonElement = json[i];
          for (let j = 0; j < jsonElement.logged_hours.length; j++) {
            const logged_hour = jsonElement.logged_hours[j];
            const prebilled = logged_hour.prebilled ? logged_hour.prebilled : 0;
            if (final_json[prebilled] === undefined) {
              final_json[prebilled] = [];
            }

            const uuid = `${logged_hour.inserton}_${logged_hour.proj_id}_${logged_hour.emp_id}`;
            if (final_json[prebilled].indexOf() === -1) {
              final_json[prebilled].push(uuid);
            }
            // console.log(logged_hour.prebilled,"\t", logged_hour.inserton,logged_hour.proj_id,logged_hour.emp_id);
            if (j === jsonElement.logged_hours.length - 1 && i === json.length - 1) {
              // console.log("done");
              resolve(final_json);
            }
          }
        }
      });
    }



  }]);
