"use strict";

appCore.controller("ProjectAddCtrl", ["$state", "$scope", "$http", "$timeout", "vServices", "filterFilter",
    function ($state, $scope, $http, $timeout, vServices, filterFilter) {
        const stateInfo = $state.current;
        $scope.$root.page.title = "Create New Project";
        $scope.btn = {name: "Create Project", icon: "fa-save", screen: "Add"};
        $scope.params = $state.params;
        const forFocus = (d) => $(document).find("#" + d).focus();
        //controller: "ProjectAddCtrl",data: {requiresLogin: true},name: "projectAdd",templateUrl: "app/templates/projects/projectAdd.html?t=1564918701850",url: "/projects/add",
        $scope.today = moment().format("DD-MM-YYYY");
        $scope.projStatus = [
            {label: "Select", value: ""},
            {label: "Active", value: "active"},
            {label: "Inactive", value: "inactive"},
            {label: "Hold", value: "hold"},
            {label: "Delivered", value: "delivered"},
            {label: "Upcoming", value: "upcoming"},
        ];
        $scope.projectType = [{label: "Select", value: ""}];
        $scope.billing_type = [{'value':1,'label':'Hourly'},{'value':2,'label':'Daily'}];
        $scope.projNature = [
            {label: "Select", value: ""},
            {label: "Development", value: "development"},
            {label: "Support", value: "support"},
            {label: "Both", value: "both"}
        ];
        $scope.project = {
            id: 0,
            proj_name: "",
            proj_notification_email: "",
            proj_sendnotifications: false,
            proj_description: "",
            proj_start_date: moment().format("DD-MM-YYYY"),
            proj_expected_end_date: "",
            proj_status: $scope.projStatus[0].value,
            proj_code: "",
            proj_estimate_effort: [],
            proj_account: 1,
            proj_manager: 0,
            proj_type:$scope.projectType[0].value,
            proj_billing_type : $scope.billing_type[0].value,
            proj_nature: $scope.projNature[0].value
        };
        $scope.estimateTeamEffortOptions = [];
        $scope.projectManagerOptions = [];
        $scope.accountOptions = [];
        

        $scope.estimateTeamEffort = [];
        $scope.addEffort = () => {
            if ($scope.estimateTeamEffortOptions.length > 0)
                $scope.estimateTeamEffort.push({desg_id: $scope.estimateTeamEffortOptions[0].id, desg_qty: 1, desg_hours: 8, desg_date: $scope.today});
        };
        $scope.removeEffort = (idx) => $scope.estimateTeamEffort.splice(idx, 1);

        $scope.createProject = () => {
            if (!$scope.project.proj_account || typeof $scope.project.proj_account === "object") {
                toastr.warning("Please select the account", "Required", {timeOut: 5000});
                forFocus("proj_account");
                return false;
            }
            if (!$scope.project.proj_name) {
                toastr.warning("Please fill project name", "Required", {timeOut: 5000});
                forFocus("proj_name");
                return false;
            }
            if (!$scope.project.proj_manager) {
                toastr.warning("Please select project manager", "Required", {timeOut: 5000});
                forFocus("proj_manager");
                return false;
            }
            if ($scope.estimateTeamEffort && $scope.estimateTeamEffort.length > 0 && !$scope.estimateTeamEffort[0].desg_id) {
                toastr.warning("Please select Min. Team Effort", "Required", {timeOut: 5000});
                return false;
            }
            if (!$scope.project.proj_type) {
                toastr.warning("Please select project type", "Required", {timeOut: 5000});
                forFocus("proj_type");
                return false;
            }

            /*if ($scope.project.proj_start_date && moment($scope.project.proj_expected_end_date,'DD-MM-YYYY') < moment($scope.project.proj_start_date,'DD-MM-YYYY')) {
             toastr.warning('Expected end date should be post date from start date', 'Required', {timeOut: 5000});
             forFocus('proj_expected_end_date');
             return false
             }*/
            if (typeof $scope.project.proj_expected_end_date === "undefined") $scope.project.proj_expected_end_date = "";
            $scope.project.proj_estimate_effort = JSON.stringify($scope.estimateTeamEffort);

            $scope.project.proj_sendnotifications = $scope.project.proj_sendnotifications ? $scope.project.proj_sendnotifications.toString() : "false";
            if (!$state.params.projectid) {
                vServices.callApi("project/add", "POST", $scope.project).then(function (res) {
                    if (res) {
                        toastr.success(res, "Success!", {timeOut: 5000});
                        $scope.$root.updateMenu();
                        $state.go("projectList", {}, {reload: true});
                    }
                });
            }
            else {
                vServices.callApi("project/edit", "PUT", $scope.project).then(function (res) {
                    if (res) $scope.project = res;
                    $state.go("projectView", {projectid: $state.params.projectid}, {reload: true});
                });
            }
        };

        const init = function () {
            vServices.callApi("designation/all", "GET", {}).then(function (res) {
                if (res) {
                    $scope.estimateTeamEffortOptions = res;
                    $scope.estimateTeamEffortOptions.unshift({"id": 0, "desg_name": "Select", "desg_description": null});
                    if (!$state.params.projectid)
                        $scope.estimateTeamEffort.push({desg_id: $scope.estimateTeamEffortOptions[0].id, desg_qty: 1, desg_hours: 8, desg_date: $scope.today});
                }
            });
            vServices.callApi("account/all", "GET", {}).then(function (res) {
                if (res) {
                    $scope.accountOptions = res;
                    $scope.accountOptions.unshift({"accountid": 0, "acc_company_name": "Select", "acc_last_name": ""});
                    if ($scope.project.accountid || typeof $scope.params.accountid !== "undefined") {
                        const accountId = parseFloat($scope.params.accountid ? $scope.params.accountid : $scope.project.accountid ? $scope.project.accountid : 0);
                        for (let i = 0; i < $scope.accountOptions.length; i++) {
                            if (parseFloat($scope.accountOptions[i].accountid) === parseFloat(accountId)) {
                                $scope.project.proj_account = $scope.accountOptions[i].accountid;
                            }
                        }
                    }
                    else {
                        $scope.project.proj_account = $scope.accountOptions[0].accountid;
                    }
                }
            });

            vServices.callApi("employee/manager/all", "GET", {}).then(function (res) {
                if (res) {
                    $scope.projectManagerOptions = res;
                    $scope.projectManagerOptions.unshift({"employeeid": 0, "emp_first_name": "Select", "emp_last_name": ""});
                    if (!$state.params.projectid) {
                        $scope.project.proj_manager = $scope.projectManagerOptions[0].employeeid;
                    }
                    else {
                        for (let i = 0; i < $scope.projectManagerOptions.length; i++) {
                            if (parseFloat($scope.projectManagerOptions[i].employeeid) === parseFloat($scope.project.employeeid)) {
                                $scope.project.proj_manager = $scope.projectManagerOptions[i].employeeid;
                            }
                        }
                    }
                }
            });
        };

        if ($state.params.projectid) {
            $scope.btn = {name: "Edit Project", icon: "fa-pen", screen: "Edit"};
            $scope.$root.page.title = "Edit Project";
            vServices.callApi("project/" + $state.params.projectid, "GET").then(function (res) {
                if (res) $scope.project = res;
                init();
            });
            vServices.callApi("project/designation/" + $state.params.projectid, "GET").then(function (res) {
                if (res)
                    $scope.estimateTeamEffort = res.map((o) => {
                        o.desg_qty = o.designation_qty;
                        o.desg_hours = o.designation_hours;
                        return o;
                    });
            });

        }
        else {
            init();
        }

        vServices.callApi("project/projectType_master", "GET", {}).then((res) => {
            $scope.projectType = res;
        });
    }
]);
