document.addEventListener('focusout', function(e) {window.scrollTo(0, 0)});
angular.module('checklistController', []).controller('checklistCtrl', function($scope, $timeout, Users, Checklists, Services, //
    $ionicModal, $cordovaFile, $cordovaActionSheet, $cordovaCamera, $cordovaFileTransfer, $cordovaImagePicker, $ionicScrollDelegate, //
    $ionicLoading, $cordovaToast, Appointmentchecklists, Login, $interval,Orders,Ordertypes,Callaheads,Flexiblecustomers,Orderstatuses,//
    Appointments,Opportunities) {
    $scope.answers = {};
    $scope.confirm = {};
    $scope.tier = tier;
    $scope.confirmprocess = {};
    $scope.checklist_id = '';
    $scope.app_id = 0;
    $scope.customer_id = 0;
    $scope.appstatus_id = '';
    $scope.prev_logic = '';
    $scope.question_logic = '';
    $scope.currentIdLogin = currentIdLogin;
    $scope.tochecklist = false;
    $scope.thread = [];
    $scope.paymenthistories = {};
    $scope.invoice={};
    $scope.from_order = false;
    $scope.monthNames = [{
        name: 'January',
        value: 1
    }, {
        name: 'February',
        value: 2
    }, {
        name: 'March',
        value: 3
    }, {
        name: 'April',
        value: 4
    }, {
        name: 'May',
        value: 5
    }, {
        name: 'June',
        value: 6
    }, {
        name: 'July',
        value: 7
    }, {
        name: 'August',
        value: 8
    }, {
        name: 'September',
        value: 9
    }, {
        name: 'October',
        value: 10
    }, {
        name: 'November',
        value: 11
    }, {
        name: 'December',
        value: 12
    }];
    $scope.ChargeDate = [{
        amount: '',
        ChargeDate: '',
        transaction_id: null,
        status: null
    }];
    $scope.goquest = {index:0,finish:false};
    $scope.isSubmit = false;
    $scope.fw_note_on_checklist = '';

    $scope.openPopup = function() {
        showTarget('#checklistPopupConfirm');
    }
    $scope.openPopupSubmit = function () {
        showTarget('#checklistPopupSubmitConfirm');
    }
    $scope.loadConfirm = function() {
        $scope.confirmdata = [{"id":1,"title":"Was this appointment to install previously sold product?","type":"yesno","model":"installapp","fields":[{"label":"Yes","checklist":9},{"label":"No","confirm":2}]},{"id":2,"title":"Is there an Invoice or Estimate?","type":"select","model":"invoiceestimate","fields":[{"id":1,"label":"Invoice","confirm":3},{"id":2,"label":"Estimate","confirm":4},{"id":3,"label":"Other","confirm":5}]},{"id":3,"title":"Are there items on the invoice that are not marked installed?","type":"yesno","model":"markednotinstalled","fields":[{"label":"Yes","confirm":6},{"label":"No","confirm":7}]},{"id":4,"title":"Did you leave estimate for a door?","type":"yesno","model":"leaveestimate","fields":[{"label":"Yes","confirm":8},{"label":"No","confirm":8}]},{"id":5,"title":"Is this a new Customer?","type":"yesno","model":"leaveestimate","fields":[{"label":"Yes","confirm":9},{"label":"No","confirm":10}]},{"id":6,"title":"Do we need to Schedule a return trip to install any items?","type":"yesno","model":"installedcorrect","fields":[{"label":"Yes","confirm":11},{"label":"No","quit":12}]},{"id":7,"title":"Is there a Balance Due on the Invoice that is not for a new door or section?","type":"yesno","model":"balancedue","fields":[{"label":"Yes","checklist":4},{"label":"No","confirm":13}]},{"id":8,"title":"When should we follow up?","type":"datetime","model":"followup","confirm":16,"fields":[{"label":"Datetime"}]},{"id":9,"title":"Why there was not an Estimate completed?","type":"text","model":"reasonnotcomplete","checklist":6,"fields":[{"label":"Why?"}]},{"id":10,"title":"Is there a Quality Issue to report?","type":"yesno","model":"qualityissue","fields":[{"label":"Yes","checklist":5},{"label":"No","confirm":17}]},{"id":11,"title":"On the return Trip, will we be installing a door or section?","type":"yesno","model":"didyousell","fields":[{"label":"Yes","confirm":14},{"label":"No","confirm":15}]},{"id":13,"title":"Is there any Billing attention needed?","type":"yesno","model":"billingattention","fields":[{"label":"Yes","checklist":4},{"label":"No","confirm":16}]},{"id":14,"title":"Are the door/panel you sold instock?","type":"yesno","model":"soldinstock","fields":[{"label":"Yes","checklist":1},{"label":"No","checklist":3}]},{"id":15,"title":"Are the item to be installed instock?","type":"yesno","model":"installedinstock","fields":[{"label":"Yes","checklist":1},{"label":"No","checklist":2}]},{"id":16,"title":"Is it a new Customer?","type":"yesno","model":"newcustomer","fields":[{"label":"Yes","confirm":17},{"label":"No","confirm":10}]},{"id":17,"title":"Is there a Safety Issue to report?","type":"yesno","model":"safetyissue","fields":[{"label":"Yes","checklist":10},{"label":"No","checklist":6}]},{"id":18,"title":"Is there an estimate or Invoice?","type":"select","model":"theei","fields":[{"id":1,"label":"Estimate","confirm":20},{"id":2,"label":"Invoice","confirm":19}]},{"id":19,"title":"Did you sell a door or Panel?","type":"yesno","model":"doorpanel","fields":[{"id":1,"label":"Yes","checklist":8},{"id":1,"label":"No","checklist":7}]},{"id":20,"title":"Did you leave estimate for a door?","type":"yesno","model":"doorpanel","fields":[{"id":1,"label":"Yes","checklist":8},{"id":1,"label":"No","confirm":21}]},{"id":21,"title":"Is the invoice paid in full?For estimates select yes","type":"select","model":"completed","fields":[{"id":1,"label":"Yes","complete":100},{"id":2,"label":"No","complete":100,"createtask":"flowuptask"},{"id":3,"label":"Other","complete":100}]},{"id":22,"title":"Is there a Balance Due in the Invoice that is not for a new door or section?","type":"yesno","model":"balancedueIn","fields":[{"id":1,"label":"Yes","checklist":4},{"id":1,"label":"No","confirm":23}]},{"id":23,"title":"Is there any Billing attention needed?","type":"yesno","model":"attentionneeded","fields":[{"id":1,"label":"Yes","checklist":4},{"id":1,"label":"No","confirm":24}]},{"id":24,"title":"Do we need to Schedule A follow up appointment?","type":"yesno","model":"attentionneeded","fields":[{"id":1,"label":"Yes","addTask":1000},{"id":1,"label":"No","complete":100}]}];
        $scope.openPopup();
    }
    // $scope.loadConfirm();
    $scope.confirmyesno = function(item) {
        if (item.checklist) {
            //$ionicLoading.show({ template: templateLoading });
            //$timeout(function() { $ionicLoading.hide();}, 1000);
            closeTarget('#checklistPopupConfirm');
            showTarget('#checklistPopup');
            $scope.getChecklists(item.checklist, '', '');
            $scope.tochecklist = true;
            $scope.confirmprocess[$scope.confirm.model] = {
                id: $scope.confirm.id,
                confirm: item
            };
        }
        if (item.confirm) {
            $scope.tochecklist = false;
            $scope.confirmprocess[$scope.confirm.model] = {
                id: $scope.confirm.id,
                confirm: item
            };
            $scope.confirm = _.findWhere($scope.confirmdata, {
                id: item.confirm
            });
        }
        if (item.complete) {
            closeTarget("#checklistPopupConfirm");
            $scope.finishChecklist();
        }
        if (item.addTask) {
            closeTarget("#checklistPopupConfirm");
            $scope.createTask('Door Installation', '');
            $scope.finishChecklist();
        }
        if (item.quit) {
            window.location = 'order.html#/board/order/' + $scope.customer_id + '/0/order/null/0';
        }
        if (item.createtask == "flowuptask") {
            closeTarget("#checklistPopupConfirm") ;
            $scope.createTask('Quality Follow Up', '');
        }
    }
    $scope.confirmcreatetask = function() {
        if (!$scope.confirmprocess[$scope.confirm.model]) {
            $cordovaToast.showLongTop('Please fill information');
        } else {
            if ($scope.confirm.checklist) {
                closeTarget("#checklistPopupConfirm");
                $scope.getChecklists($scope.confirm.checklist, '', '');
                $scope.tochecklist = true;
                $scope.confirmprocess[$scope.confirm.model] = {
                    id: $scope.confirm.id,
                    confirm: $scope.confirm
                };
                $scope.createTask('Service quality', '');
                // closePopupById('questionpopup');
                //$('#reasonnotcomplete').parent().parent().parent().parent().parent().parent().parent().parent().parent().parent().parent().find('.close-title-button').trigger("click");
            }
            if ($scope.confirm.confirm) {
                $scope.createTask('Tech/Inside Sales', $scope.confirmprocess[$scope.confirm.model]);
                $scope.tochecklist = false;
                $scope.confirmprocess[$scope.confirm.model] = {
                    id: $scope.confirm.id,
                    confirm: $scope.confirm
                };
                $scope.confirm = _.findWhere($scope.confirmdata, {
                    id: $scope.confirm.confirm
                });
            }
        }
    }
    $scope.createTask = function(action, date) {
        $ionicLoading.show({ template: templateLoading })
        Appointmentchecklists.createTaskAuto($scope.app_id, action, $scope.currentIdLogin, date).success(function(data) {
            if (data.status) { $ionicLoading.hide(); }
        });
    }
    $scope.confirmselect = function() {
        if (!$scope.confirmprocess[$scope.confirm.model]) {
           $cordovaToast.showLongTop("Please select one!");
           return;
       } else {
        if ($scope.confirmprocess[$scope.confirm.model].checklist) {
            $scope.getChecklists(item.checklist, '', '');
            $scope.tochecklist = true;
            $scope.confirmprocess[$scope.confirm.model] = { id: $scope.confirm.id, confirm: item };
        }
        if ($scope.confirmprocess[$scope.confirm.model].confirm) {
            $scope.tochecklist = false;
            $scope.confirm = _.findWhere($scope.confirmdata, { id: $scope.confirmprocess[$scope.confirm.model].confirm });
            $scope.confirmprocess[$scope.confirm.model] = { id: $scope.confirm.id, confirm: $scope.confirmprocess[$scope.confirm.model] };
        }

        if ($scope.confirm.model == "completed") {
            closeTarget('#checklistPopupConfirm');
            closeTarget('#checklistPopup');
            if ($scope.confirmprocess.completed.complete) {
                }
                if ($scope.confirmprocess.completed.createtask == 'flowuptask') {
                    $scope.createTask('Quality Follow Up', '');
                }
                $scope.finishChecklist();
            }

        }
    }
    $scope.getParents = function() {
        Checklists.getSelect().success(function(data) {
            $scope.parents = data;
        });
    }
    //$scope.getParents();
    $scope.prevQuestion = function(index) {
        var curr = $scope.checklists.questions[index];
        curr.show = false;
        console.log($scope.thread);
        $scope.thread.pop();
        console.log($scope.thread);
        $scope.checklists.questions[curr.prevquestion - 1].show = true;
    }
    $scope.getInvoice = function() {
        Orders.getByAppointment($scope.app_id).success(function(data) {
            $scope.invoices = data;
        });
    }
    $scope.nextQuestion = function(index) {
        var ispush = _.findWhere($scope.thread, {
            id: (index + 1)
        });
        if (!ispush) {
            $scope.thread.push({
                id: index + 1,
                question: $scope.checklists.questions[index]
            });
        }
        console.log($scope.checklists.questions[index]);
        console.log($scope.answers);
        var curr = $scope.checklists.questions[index];
        var next = [];
        var require = [];
        for (var i = 0; i < curr.fields.length; i++) {
            var field = curr.fields[i];
            var type = field.type;
            switch (type) {
                case 'radio':
                var radio = $scope.validateRadio(field, require, next);
                next = radio.next;
                require = radio.require;
                break;
                case 'checkbox':
                // require = $scope.variableCheckbox(field, require);
                var checkboxs = $scope.variableCheckbox(field, require, next);
                next = checkboxs.next;
                require = checkboxs.require;
                break;
                case 'select':
                if (field.modelselect) {
                    if (!$scope.answers[field.model]) {
                        require.push(true);
                    }
                }
                break;
                case 'datetime':
                case 'time':
                case 'file':
                case 'text':
                case 'dropselect':
                case 'textselect':
                require = $scope.validateSingle(field, require);
                break;
            }
        };
        if (require.length > 0) {
           $cordovaToast.showLongTop("Please fill all question");
            //them notify vao day ho anh cai, phan nay kiem soat viec user co dien day du thong tin hay ko.
        } else {
            if (curr.finish) { // submit len server
                $scope.openPopupSubmit();
            } else { //next
                if (next.length > 0) {
                    var nextques = $scope.checklists.questions[(next[0] - 1)];
                    nextques.show = true;
                    nextques.prevquestion = index + 1;
                    curr.show = false;
                    $scope.goquest.index =  nextques.prevquestion;
                } else {
                    var nextques = $scope.checklists.questions[curr.nextquestion - 1];
                    nextques.show = true;
                    nextques.prevquestion = index + 1;
                    $scope.goquest.index =  nextques.prevquestion ;
                    curr.show = false;
                }
            }
        }
        return false;
    }

    $scope.nextQuestionVirtual = function(){
        $scope.nextQuestion($scope.goquest.index);
    }

    $scope.prevQuestionVirtual = function(){
      $scope.prevQuestion($scope.goquest.index);
  }
  $scope.validateRadio = function(field, require, next) {
    if (!angular.isArray(require)) {
        require = [];
    }
    if (!$scope.answers[field.model]) {
        require.push(true)
    } else {
            if ($scope.answers[field.model].options) { //kiem tra tuy chon cau tra loi
                for (var j = 0; j < $scope.answers[field.model].options.length; j++) {
                    var option = $scope.answers[field.model].options[j];
                    if (option.type == 'file') {
                        var files = $scope.answers[option.model];
                        if (files) {
                            for (var i = 0; i < files.length; i++) {
                                var file = files[i];
                                if (file.$error) {
                                    toastr.error("File invalid, please select again!");
                                    require.push(true);
                                    break;
                                }
                            };
                        }
                    }
                    if (!$scope.answers[option.model]) {
                        require.push(true);
                        break;
                    }
                };
            }
            if ($scope.answers[field.model].nextquestion) { //nextquestion nam trong model neu truong hop radio
                next.push($scope.answers[field.model].nextquestion);
            }
        }
        return {
            require: require,
            next: next
        };
    }
    $scope.validateSingle = function(field, require) {
        if (!angular.isArray(require)) {
            require = [];
        }
        if (field) {
            if (!$scope.answers[field.model]) {
                if ($scope.answers[field.modelselect]) {
                    if ($scope.answers[field.modelselect].id == field.valueselect) {
                        require.push(true);
                    }
                } else { //truong hop khong fai dieu kien
                    require.push(true);
                }
            }
            if (field.options) {
                for (var k = 0; k < field.options.length; k++) {
                    var option = field.options[k];
                    if ($scope.answers[option.modelselect]) {
                        if ($scope.answers[option.modelselect].id == option.valueselect) {
                            if (!$scope.answers[option.model]) {
                                require.push(true);
                            }
                        }
                    }
                }
            }
        }
        return require;
    }
    $scope.variableCheckbox = function(field, require, next) {
        if (!angular.isArray(require)) {
            require = [];
        }
        console.log($scope.answers);
        var check = 0;
        for (var j = 0; j < field.data.length; j++) {
            var data = field.data[j];
            if ($scope.answers[data.model]) {
                check += 1;
                if (_.has(data, 'nextquestion')) { // kiem tra co nextquestion
                    next.push(data.nextquestion);
                }
                if (_.has(data, 'options')) { // kiem tra cau hoi tuy chon
                    for (var k = 0; k < data.options.length; k++) {
                        var option = data.options[k];
                        if (option.type == 'file') {
                            var files = $scope.answers[option.model];
                            if (files) {
                                for (var i = 0; i < files.length; i++) {
                                    var file = files[i];
                                    if (file.$error) {
                                        toastr.error("File invalid, please select again!");
                                        require.push(true);
                                    }
                                };
                            }
                        }
                        if (!$scope.answers[option.model]) {
                            require.push(true);
                            break;
                        }
                    };
                }
            };
        };
        if (check == 0) {
            require.push(true);
        }
        return {
            require: require,
            next: next
        };
    }
    $scope.changeSelect = function(item) {
        // start thuandinh populate email customer
        if (item.label == 'Need to send Invoice') {
            $scope.getAddressCustomer(item);
        }
        console.log($scope.answers);
        // end thuandinh populate email customer
        if (item.action) {
            var action = item.action;
            switch (action) {
                case "payment":
                showTarget("#selectInvoice") ;
                $scope.getInvoice();
                break;
            }
        }
    }
    $scope.getAddressCustomer = function(item) {
        Users.getAddressCustomer($scope.customer_id).success(function(data) {
            $scope.answers['email'] == undefined ? $scope.answers['email'] = data.email : '';
            $scope.answers['address'] == undefined ? $scope.answers['address'] = data.address : '';
        });
    }
    $scope.changeRadio = function(item, index, radioValue, parentIndex) {
        var curr = item[index];
        _.each(item, function(f) {
            if (curr.id != f.id) {
                return f.show = false;
            }
        });
        item[index].show = true;
        _.each(item[index].options, function(opt) { //tim tat cac model phu thuoc.
        });
        item[index].checked = true;
        if (radioValue.label.toLowerCase() == 'yes') {
            $scope.nextQuestion(parentIndex);
        }

    }
    $scope.changeCheckbox = function(item) {
            if ($scope.answers[item.model]) { //kiem tra model
                $scope.uncheckAllCheckbox(item);
                item.show = true;
            } else {
                item.show = false;
            }
        }
        //thuandinh check/uncheck
        $scope.uncheckAllCheckbox = function(item) {
            console.log(item);
            $scope.answers[item.model + 'quantity']
            if ($scope.answers[item.model + 'quantity'] == '' || !$scope.answers[item.model + 'quantity']) {
                $scope.answers[item.model + 'quantity'] = 1
            }
            if (item.model == 'rnotpurchase12') {
                for (var i = 0; i < $scope.answers['notpurchase'].length; i++) {
                    $scope.answers[$scope.answers['notpurchase'][i].model] = [];
                }
            } else {
                $scope.answers['rnotpurchase12'] = [];
            }
        }
        $scope.getKeyFile = function() {
            var keys = _.keys($scope.answers);
            var keyfiles = [];
            for (var i = 0; i < keys.length; i++) {
                var key = keys[i];
                var currkey = $scope.answers[key];
            if (angular.isArray(currkey)) { //checkbox se xay ra truong hop nay
                for (var j = 0; j < currkey.length; j++) {
                    var item = currkey[j];
                    if (item.options) {
                        for (var k = 0; k < item.options.length; k++) {
                            var option = item.options[k];
                            if (option.type == 'file') {
                                keyfiles.push({
                                    key: key,
                                    model: option.model
                                });
                            }
                        }
                    }
                };
            } else {
                if (currkey) {
                    if (currkey.options) {
                        for (var j = 0; j < currkey.options.length; j++) {
                            var option = currkey.options[j];
                            if (option.type == 'file') {
                                keyfiles.push({
                                    key: key,
                                    model: option.model
                                });
                            }
                        }
                    }
                }
            }
        };
        return keyfiles;
    }
    $scope.submit = function() {
        var files = [];
        var keyfiles = $scope.getKeyFile();
        for (var i = 0; i < keyfiles.length; i++) {
            var item = keyfiles[i];
            files = files.concat($scope.answers[item.model]);
            var filenames = _.pluck($scope.answers[item.model], 'name');
            var currkey = $scope.answers[item.key];
            if (angular.isArray(currkey)) {
                for (var j = 0; j < currkey.length; j++) {
                    var item2 = currkey[j];
                    if (item2.options) {
                        for (var k = 0; k < item2.options.length; k++) {
                            var option = item2.options[k];
                            if (option.type == 'file' && item.model == option.model) {
                                option.filelists = filenames;
                            }
                        }
                    }
                };
            } else {
                if (currkey.options) {
                    for (var j = 0; j < currkey.options.length; j++) {
                        var option = currkey.options[j];
                        if (option.type == 'file' && item.model == option.model) {
                            option.filelists = filenames;
                        }
                    }
                }
            }
        };
        if (keyfiles.length > 0) {
            $scope.submitonfile(files);
        } else {
            $scope.submitNonefile([]);
        }
        closeTarget('#checklistPopupSubmitConfirm');
        showTarget('#checklistPopup');
    }
        // edit by haudao
        $scope.submitonfile = function(files) {
            $scope.uploadedFile = [];
            $scope.files = files;
            var results = [];
            angular.forEach(files, function(file) {
                if (file != null) {
                    var arrFileName = file.split("/");
                    var fileName = arrFileName[arrFileName.length - 1];
                    if (storeInCloud) {
                        $scope.fileUploadData = {};
                        $scope.fileUploadData.type = 'image/jpeg';
                        $scope.fileUploadData.name = fileName;
                        $scope.fileUploadData.bucket = bucketName;
                        $scope.fileUploadData.acl = aclConfig;
                        $scope.fileUploadData.for = 'checklists';
                        $scope.fileUploadData.appId = $scope.app_id;
                        Login.getConfigFileUpload($scope.fileUploadData).success(function(data) {
                            var Uoptions = {};
                            Uoptions.fileKey = "file";
                            Uoptions.fileName = data.folder + '/' + fileName;
                            Uoptions.mimeType = 'image/jpeg';
                            Uoptions.chunkedMode = false;
                            Uoptions.headers = {
                                connection: "close"
                            };
                            Uoptions.params = {
                                "Key": data.folder + '/' + fileName,
                                "AWSAccessKeyId": data.awsAccessKeyId,
                                "acl": data.acl,
                                "Policy": data.policy,
                                "Signature": data.signature,
                                "success_action_status": data.successActionStatus,
                                "Content-Type": 'image/jpeg'
                            };
                            $cordovaFileTransfer.upload('http://' + bucketName + '.s3.amazonaws.com/', file, Uoptions).then(function(return_data) {
                                var size = 0;
                                try {
                                    $scope.fileLocation = return_data.headers.Location;
                                    size = return_data.bytesSent;
                                } catch (e) {
                                    $scope.jsonObject = xml2json.parser(return_data.response);
                                    $scope.fileLocation = $scope.jsonObject.postresponse.location;
                                    size = return_data.bytesSent;
                                }
                                $scope.fileUploadData = {};
                                $timeout(function() {
                                    results.push({
                                        name: fileName,
                                        path: $scope.fileLocation,
                                        status: true
                                    });
                                    var arrFileSplit = fileName.split(".");
                                    var fileExt = arrFileSplit[arrFileSplit.length - 1];
                                    $scope.uploadedFile.push({
                                        name: fileName,
                                        path: $scope.fileLocation,
                                        extension: fileExt,
                                        size: size
                                    });
                                    if (results.length == files.length) {
                                        $scope.submitNonefile(results);
                                    }
                                });
                            }, function(err) {
                                console.log(err);
                                $ionicLoading.hide();
                            }, function(progress) {
                                $ionicLoading.show({
                                    template: templateLoading
                                });
                            });
                        });
                    } else {
                        var options = {
                            fileName: fileName,
                            fileKey: "file",
                            params: {
                                data: $scope.app_id
                            },
                            mimeType: 'image/jpeg',
                            chunkedMode: false
                        };
                        $cordovaFileTransfer.upload(url_server + 'checklists', file, options).then(function(e) {
                            $ionicLoading.hide();
                            $timeout(function() {
                                console.log(e.response);
                                var response = JSON.parse(e.response);
                                console.log(response);
                                results.push(response.data)
                                if (results.length == files.length) {
                                    $scope.submitNonefile(results);
                                }
                            });
                        }, function(err) {
                            console.log(err);
                        // $scope.errorMsg = err.??; 
                        $ionicLoading.hide();
                    }, function(progress) {
                        $ionicLoading.show({
                            template: templateLoading
                        });
                    });
                    }
                }
            });
}

    // end edit
    $scope.submitNonefile = function(file_maps) {
        var keyfiles = $scope.getKeyFile();
        for (var i = 0; i < keyfiles.length; i++) {
            var item = keyfiles[i];
            var filenames = _.pluck($scope.answers[item.model], 'name');
            var currkey = $scope.answers[item.key];
            if (angular.isArray(currkey)) {
                for (var j = 0; j < currkey.length; j++) {
                    var item2 = currkey[j];
                    if (item2.options) {
                        for (var j = 0; j < item2.options.length; j++) {
                            var option = item2.options[j];
                            if (option.type == 'file' && item.model == option.model) {
                                _.each(option.filelists, function(item, index) {
                                    var map = _.findWhere(file_maps, {
                                        name: item
                                    });
                                    if (map) {
                                        option.filelists[index] = map.path;
                                        return item;
                                    } else {
                                        return item;
                                    }
                                });
                            }
                        }
                    }
                };
            } else {
                if (currkey.options) {
                    for (var j = 0; j < currkey.options.length; j++) {
                        var option = currkey.options[j];
                        if (option.type == 'file' && item.model == option.model) {
                            _.each(option.filelists, function(item, index) {
                                var map = _.findWhere(file_maps, {
                                    name: item
                                });
                                if (map) {
                                    option.filelists[index] = map.path;
                                    return item;
                                } else {
                                    return item;
                                }
                            });
                        }
                    }
                }
            }
        };
        $scope.buildanswer();
        var html = $scope.buildanswer2();
        var last = $scope.confirm;
        $scope.checklist9();
        $scope.addAppointmentchecklistsData = {
            title: $scope.checklists.title,
            pdf: html,
            prev_cell: last.id,
            checklist_id: $scope.checklist_id,
            appointment_id: $scope.app_id,
            appointmentstatus_id: 0,
            answers: angular.toJson($scope.answers),
            questions: angular.toJson($scope.checklists),
            filelists: file_maps
        };
        $scope.createAppointmentchecklists();
    }
    $scope.checklist9 = function() {
        if ($scope.checklist_id == 9 && $scope.tier.t1) {
            for (var k in $scope.answers) {
                if ($scope.answers.hasOwnProperty(k)) {
                    var item = $scope.answers[k];
                    if (item.label == 'No' && item.checked == true) {
                        $scope.answers['needToSetup'] = {
                            id: 1
                        };
                        return;
                    }
                }
            }
            $scope.answers['needToSetup'] = {
                id: 0
            };
        }
    }
    $scope.getlastestcell = function() {
        $scope.loadConfirm();
        $ionicLoading.show({
            template: templateLoading
        })
                // Login.checkLogin().success(function(data) {
                    Appointmentchecklists.getlastestcell({
                        appointment_id: $scope.app_id
                    }).success(function(data) {
                        $(".modal-backdrop").remove('active');
                        $ionicLoading.hide();
                        data.prev_cell = '';
                        if (data.prev_cell) {
                            if (data.checklist_id == 10) {
                                $scope.confirm={id:17};
                                $scope.getChecklists(6, '', '');
                            } else if (data.prev_cell) {
                                $scope.nextconfirm(data.prev_cell);
                            }
                        } else {
                            $scope.getNetConfirm(1);
                        }
                    }).error(function(data, status, headers, config) {
                        $ionicLoading.hide();
                        console.log('error status: ' + status);
                        $cordovaToast.showLongTop('Connection Error!!!');
                    });
            // })
        }
        //$scope.getlastestcell();
        // edit by haudao
        $scope.replaceTime = function(str) {
            var arrData = JSON.parse(str);
            if (arrData['time'] != undefined && arrData['date']) {
                arrData['time'] = moment(arrData['time']).format('hh:mmA');
                var date = moment(arrData['date']).format('MMMM DD,YYYY');
                var time = moment(arrData['time'], 'hh:mmA').format('HH:mm:ss');
                var datetime = date + ' ' + time;
                datetime = new Date(datetime);
                if (arrData['description'].indexOf('strTimeReplace') > -1) {
                    arrData['description'] = arrData['description'].replace('strTimeReplace', datetime);
                }
            }
            return JSON.stringify(arrData);
        }
        // end edit
        $scope.createAppointmentchecklists = function() {
            $scope.addAppointmentchecklistsData.storeInCloud = storeInCloud;
            if (storeInCloud) {
                $scope.addAppointmentchecklistsData.uploadedFile = [];
                $scope.addAppointmentchecklistsData.uploadedFile = $scope.uploadedFile;
            }
            $ionicLoading.show({
                template: templateLoading
            });
            $scope.addAppointmentchecklistsData.answers = $scope.replaceTime($scope.addAppointmentchecklistsData.answers);
            Appointmentchecklists.save($scope.addAppointmentchecklistsData).success(function(data) {
                $ionicLoading.hide();
                if ($scope.addAppointmentchecklistsData.checklist_id == 10) {
                    $scope.getChecklists(6, '', '');
                } else if (data.prev) {
                    $scope.nextconfirm(data.prev);
                }
                if (data.status) {
                    if (data.prev == 22) {
                        $timeout(function() {
                            closeTarget('#checklistPopup');
                            closeTarget('#checklistPopupConfirm');
                        }, 2000)
                    }
                    $scope.addAppointmentchecklistsData = {};
                } else {
                }
            });
        }
        $scope.nextconfirm = function(prev) {
            switch (prev) {
                case 1:
                case "1":
                $scope.getNetConfirm(22);
                break;
                case 10:
                case "10":
                $scope.getNetConfirm(17);
                break;
                case 17:
                case "17":
                $scope.getNetConfirm(18);
                break;
                case 20:
                case "20":
                $scope.getNetConfirm(21);
                break;
                case 19:
                case "19":
                $scope.getNetConfirm(21);
                break;
                case 13:
                case "13":
                $scope.getNetConfirm(16);
                break;
                case 14:
                case 15:
                case "14":
                case "15":
                $scope.getNetConfirm(7);
                break;
                case 7:
                case "7":
                $scope.getNetConfirm(16);
                break;
                case 9:
                case 21:
                case 22:
                case 23:
                case "9":
                case "21":
                case "22":
                case "23":
                $scope.finishChecklist();
                break;
            }
        }
        $scope.getNetConfirm = function(id) {
            var current = _.findWhere($scope.confirmdata, {
                id: id
            });
            if (current) {
                $scope.confirm = current;
                $timeout(function() {
                // openPopupById('#questionpopup');
                showTarget('#checklistPopupConfirm');
                $('.callback_app').parent().parent().parent().parent().parent().parent().find('.close-title-button').click(function() {
                    $('#contentArea').show();
                    // openPopupById('#popupAppointmentDetail');
                    if ($('#contentArea').is(":visible") == true) {
                        $('#content2').hide();
                    } else {
                        $('#content2').show();
                    }
                })
            }, 100);
            }
            if ($('#contentArea').is(":visible") == true) {
                $('#content2').hide();
            } else {
                $('#content2').show();
            }
        }
        $scope.buildanswer2 = function() {
            var html = '';
            for (var i = 0; i < $scope.thread.length; i++) {
                var item = $scope.thread[i];
                var itemBackground = i % 2 == 0 ? '#EAF1F2' : '#F8F8F8'
                html += "<div style='background: " + itemBackground + "; padding: 0px 0 15px; margin-bottom: 2px;'>";
                html += "<div style='width: 100%; background: transparent; border-left: 0px solid transparent; border-top: 0px solid #ddd; border-bottom: 1px solid #ddd; padding: 7px 15px 6px; font-weight: bold; font-size: 17px; line-height: 17px; font-family: arial; color: #000; text-transform: uppercase; margin-left: -0px; margin-bottom: 10px;'>Question " + item.id + ": </div>";
                html += "<div style='padding: 0 15px; font-weight: bold; font-size: 16px; font-family: arial; color:  #3a6258; margin-bottom: 15px;'>" + item.question.question + "</div>";
                html += "<div style='text-align: right; padding: 0 20px; font-weight: bold; font-size: 16px; font-family: arial; color:#B07236; margin-bottom: 5px;'>";
                for (var j = 0; j < item.question.fields.length; j++) {
                    var item2 = item.question.fields[j];
                    var type = item2.type;
                    switch (type) {
                        case 'radio':
                        html += $scope.getAnswerRadio(item2);
                        break;
                        case 'checkbox':
                        html += $scope.getAnswerCheckbox(item2);
                        break;
                        case 'select':
                        html += $scope.getAnswerSelect(item2);
                        break;
                    }
                };
                html += "</div>";
                html += "</div>";
            };
            return html;
        }
        $scope.getAnswerRadio = function(item2) {
            var des = '';
            var answer = $scope.answers[item2.model];
            if (answer.label == 'No' && $scope.checklist_id == 9 && $scope.tier.t1) {
                des += "<div><span style=\"display: inline-block;background:#FDFF5C; padding: 2px 10px;\">" + answer.label + "</span></div>";
            } else {
                des += answer.label;
            }
            if (answer.options) {
                for (var j = 0; j < answer.options.length; j++) {
                    var opt = answer.options[j];
                    des += ' (' + $scope.answers[opt.model] + ')';
                }
            }
            return des + "\r\n";
        }
        $scope.getAnswerCheckbox = function(item2) {
            var des = '';
            var answer = $scope.answers[item2.model];
            if (answer) {
                for (var i = 0; i < answer.length; i++) {
                    var item = answer[i];
                    des += item.label;
                    if (item.options) {
                        for (var j = 0; j < item.options.length; j++) {
                            var opt = item.options[j];
                            des += ' (' + $scope.answers[opt.model] + ')';
                        }
                    }
                    if (i < answer.length - 1) {
                        des += "\r\n";
                    }
                };
            }
            return des + "\r\n";
        }
        $scope.getAnswerSelect = function(item2) {
            var des = '';
            var answer = $scope.answers[item2.model];
            des += answer.label;
            if (answer.children) {
                for (var j = 0; j < answer.children.length; j++) {
                    var opt = answer.children[j];
                    des += ' (' + $scope.answers[opt] + ')';
                }
            }
            return des + "\r\n";
        }
        $scope.buildanswer = function() {
            var keys = _.keys($scope.answers);
            var descripction = '';
            var prevQuest = {};
            prevQuest.question = '';
            for (var i = 0; i < keys.length; i++) {
                var key = keys[i];
                var question = $scope.getQuestion(key);
            //console.log(question);
            if (question) {
                if (prevQuest.question != question.question) { //tim hai model nhung thuoc tren mot cau hoi...
                    descripction += question.question + '\r\n';
                }
                prevQuest = question;
                if (angular.isArray($scope.answers[key])) {
                    var models = $scope.answers[key];
                    for (var j = 0; j < models.length; j++) {
                        var model = models[j];
                        descripction += '\t' + model.label;
                        if (model.options) {
                            for (var k = 0; k < model.options.length; k++) {
                                var option = model.options[k];
                                if (option.type == 'text') {
                                    descripction += '>>' + $scope.answers[option.model];
                                    console.log($scope.answers[option.model]);
                                }
                                if (option.type == 'file') {
                                    descripction += ">>";
                                    for (var l = 0; l < option.filelists.length; l++) {
                                        descripction += option.filelists[l] + ',';
                                    }
                                }
                            };
                        }
                        descripction += '\r\n';
                    }
                } else {
                    var models = $scope.answers[key];
                    if (models.label) {
                        descripction += '\t' + models.label;
                    } else {
                        if (key == 'time' || key == 'datetime' || key=='date') {
                            if (key == 'datetime'||key=='date') {
                                $scope.answers[key] = moment($scope.answers[key]).format("MM/DD/YYYY").toString();
                                descripction += '\t' + moment(models).format(conFig.formatDate);
                            }
                            if (key == 'time') {
                                descripction += '\t' + 'strTimeReplace';
                            }
                        } else {
                            descripction += '\t' + models;
                        }
                    }
                    if (models.options) {
                        for (var j = 0; j < models.options.length; j++) {
                            var option = models.options[j];
                            if (option.type == 'text') {
                                descripction += '>>' + $scope.answers[option.model];
                                console.log($scope.answers[option.model]);
                            }
                            if (option.type == 'file') {
                                descripction += ">>";
                                for (var l = 0; l < option.filelists.length; l++) {
                                    descripction += option.filelists[l] + ',';
                                }
                            }
                        };
                    }
                    descripction += '\r\n';
                }
            }
        };
        $scope.answers['description'] = descripction;
    }
    $scope.getQuestion = function(key) {
        for (var j = 0; j < $scope.checklists.questions.length; j++) { //tim cau hoi co model phu hop
            var question = $scope.checklists.questions[j];
            for (var k = 0; k < question.fields.length; k++) {
                var item3 = question.fields[k];
                if (item3.model == key) {
                    return question;
                }
                if (item3.options) {
                    for (var i = 0; i < item3.options.length; i++) {
                        var item4 = item3.options[i];
                        if (item4.model == key) {
                            return question;
                        }
                    };
                }
            };
        };
        return null;
    }
    $scope.check_invoice = function(invoice) {
        showTarget('#addpayment');
        // $scope.Cash = {};
        // $scope.Check = {};
        // $scope.CC_Manual = {};
        // $scope.Prepaid = {};
        // $scope.Payment_Plan = {};
        // $scope.Signature = '';
        // $scope.Cash_check=0;
        // $scope.Check_check=0;
        // $scope.CC_Manual_check=0;
        // $scope.Prepaid_check=0;
        // $scope.Payment_Plan_check=0;
        //$('.tblloaderroot').show();
        //console.log(invoice);
        $scope.invoice = invoice;
        Ordertypes.check_invoice(invoice.id).success(function(data) {
            if (data.status) {
                $scope.Payment_Plan = data.customer_address;
                $scope.getInvoice();
            } else {
               $cordovaToast.showLongTop($scope.notification);
               window.location = data.url;
           }
       });
    }
    $scope.historyDate = '';
    $scope.Add_Payment = function() {
        var required_form = 2;
        if ($('#required_Payment_Plan').val() == 0) {
            required_form--;
        }
        $scope.paymenthistories.Payment_Plan = {};
        $scope.paymenthistories.Payment_Plan.method = 'Payment Plan';
        $scope.paymenthistories.Payment_Plan.cardtype = $scope.Payment_Plan.Card_Type;
        $scope.paymenthistories.Payment_Plan.cardnumber = $scope.Payment_Plan.Card_Number;
        $scope.paymenthistories.Payment_Plan.order_id = $scope.invoice.id;
        $scope.paymenthistories.Payment_Plan.customerInfo = $scope.Payment_Plan;
        $scope.paymenthistories.Payment_Plan.chargedate = $scope.ChargeDate;
        $scope.paymenthistories.invoiceId = $scope.invoice.id;
        $scope.paymenthistories.date = $scope.historyDate;
        $scope.createBraintree($scope.paymenthistories, required_form);
    }
    $scope.list_paymenthistory = [];
    $scope.checkinsertpaymenthistory = 0;
    $scope.createBraintree = function(paymenthistories, required_form) {
        if (required_form == 2) {
            Ordertypes.sentDataPayment(paymenthistories).success(function(data) {
                $scope.paymenthistories = {};
                if (data.status) {
                    $scope.payment_success = data.success;
                    $scope.payment_error = data.error;
                    if (data.arrIdHistory.length > 0) {
                       $cordovaToast.showLongTop(data.msg);
                       if ($scope.checkinsertpaymenthistory == 0) {
                        $scope.list_paymenthistory = data.arrIdHistory;
                    } else {
                        for (var i = 0; i < data.arrIdHistory.length; i++) {
                            $scope.list_paymenthistory.push(data.arrIdHistory[i]);
                        }
                    }
                    $scope.historyDate = data.date;
                    if (data.error.length > 0) {
                        openPopup('#popupPaymentprocess');
                        $scope.checkinsertpaymenthistory = 1;
                    } else {
                        openPopup('#popupTerms_of_conditions');
                        $scope.checkinsertpaymenthistory = 0;
                    }
                    $plan = 0;
                    for (var i = 0; i < data.success.length; i++) {
                        $plan++;
                        if ($plan == $scope.ChargeDate.length) {
                            $scope.Payment_Plan.Card_Number = '';
                            $scope.Payment_Plan.month = '';
                            $scope.Payment_Plan.year = '';
                            $scope.Payment_Plan.CVV2_Codes = '';
                            $('.log').html('Please input card number.');
                            $('#Payment_Plan').slideUp(100);
                            $('#Payment_Plan').find('input').removeAttr('required');
                            $('#Payment_Plan').find('select').removeAttr('required');
                            $scope.Payment_Plan_check = 0;
                        }
                        $scope.ChargeDate[data.success[i]['value']] = {
                            amount: '',
                            ChargeDate: '',
                            transaction_id: null,
                            status: null
                        };
                    }
                } else {
                   $cordovaToast.showLongTop('Add Payment Error!');
               }
           } else {
              $cordovaToast.showLongTop(data.msg);
          }
                // if (data.status) {
                //     toastr.success(data.msg);
                //     if (data.arrIdHistory.length > 0) {
                //         if (data.arrIdHistory.length > 0) {
                //             $('.Payment_form').closest('.row').find('> div').slideUp(100);
                //             openPopup('#popupSignature');
                //             $('#popupAddPayment').find('input').removeAttr('required');
                //             $('#popupAddPayment').find('select').removeAttr('required');
                //             $scope.paymenthistories = {};
                //             $scope.ChargeDate = [{ amount: '', ChargeDate: '', transaction_id: null, status: null }];
                //             $scope.list_paymenthistory = data.arrIdHistory;
                //             toastr.success('Add Payment Successfull!');
                //         } else {
                //             toastr.error('Add Payment Not Null!');
                //         }
                //     }
                // } 
                // else {
                //     toastr.error(data.msg);
                //     $scope.paymenthistories = data.originalData;
                //     if (typeof (data.originalData.Payment_Plan) != "undefined" && data.originalData.Payment_Plan !== null) {
                //         $scope.ChargeDate = data.originalData.Payment_Plan.chargedate;
                //         $scope.paymentPlanCheckHide = true;
                //     }
                //     if (typeof (data.originalData.CC_Manual) != "undefined" && data.originalData.CC_Manual !== null) {
                //         $scope.CC_Manual = data.originalData.CC_Manual.customerInfo;
                //         $scope.CC_ManualHide = true;
                //     }
                //     $scope.paymenthistories.historyInsertedId = data.originalData.historyInsertedId;
                // }
            });
} else {
    toastr.error('Invalid card number');
}
}
$scope.clearhistory = function() {
    $scope.checkinsertpaymenthistory = 0;
}
$scope.Terms_of_conditions = function() {
    $scope.checkinsertpaymenthistory = 0;
    closePopupById('popupTerms_of_conditions');
    openPopup('#popupSignature');
}
$scope.popupSignature = function() {
    $('#popupSignature #signaturePayment').signature();
    $('#popupSignature #signatureResign').click(function() {
        $('#popupSignature #signaturePayment').signature('clear');
    })
    $('#popupSignature #saveSignature').click(function() {
        var sign = $('#popupSignature #signaturePayment').signature('toSVG');
            // $scope.insertSignature(sign);
        })
    $(function() {
        $('#card_number').validateCreditCard(function(result) {
            if (result.valid == true && result.length_valid == true && result.luhn_valid == true) {
                $scope.Payment_Plan.Card_Type = result.card_type.name;
                $('.log').html(result.card_type.name + '<img class="icon_opportunities" src="resources/images/icons/checked-form-2-green.png" style="width:20px" />');
                $('#required_Payment_Plan').val(1);
            } else {
                $('.log').html('Please input card number.');
                $('#required_Payment_Plan').val(0);
            }
        });
    });
}
$scope.year_select = function() {
    var year = [];
        min = parseInt(new Date().getFullYear()); //Make string input int
        max = min + 10;
        for (var i = min; i < max; i++) {
            year.push(i);
        }
        $scope.yearName = year;
    };
    $scope.insertSignature = function() {
        var sign = $('#popupSignature #signaturePayment').signature('toSVG');
        Ordertypes.insertSignature($scope.list_paymenthistory, sign).success(function(data) {
            $scope.checkinsertpaymenthistory = 0;
            if (data.status) {
                toastr.success(data.msg);
                $('#signaturePaymentShow').html('');
                $('#signaturePaymentShow').html(data);
                $scope.list_paymenthistory = {};
                closePopupById('popupSignature');
            } else {
                toastr.error(data.msg);
            }
        });
    }
    $scope.year_select();
    $scope.requiredAmount = function (value, action, index) {
        // $scope.Cash.Amount = $scope.requiredfloat(value);
        switch (action) {
            case 'Cash':
                //$scope.requiredfloat(value) == 0 ? $scope.Cash.Amount = 0 : 
                $scope.Cash.Amount = $scope.requiredfloat(value);
                break;
                case 'Check':
                //$scope.requiredfloat(value) == 0 ? $scope.Check.Amount = '' : 
                $scope.Check.Amount = $scope.requiredfloat(value);
                break;
                case 'Prepaid':
                //$scope.requiredfloat(value) == 0 ? $scope.Prepaid.Amount = '' : 
                $scope.Prepaid.Amount = $scope.requiredfloat(value);
                break;
                case 'CC_Manual':
                //$scope.requiredfloat(value) == 0 ? $scope.CC_Manual.Amount = '' : 
                $scope.CC_Manual.Amount = $scope.requiredfloat(value);
                break;
                case 'Prepaid':
                //$scope.requiredfloat(value) == 0 ? $scope.Prepaid.Amount = '' : 
                $scope.Prepaid.Amount = $scope.requiredfloat(value);
                break;
                case 'ChargeDate':
                //$scope.requiredfloat(value) == 0 ? $scope.ChargeDate[index].amount = '' : 
                $scope.ChargeDate[index].amount = $scope.requiredfloat(value);
                break;
                case 'Payment_Plan':
                //$scope.requirednumber(value) == 0 ? $scope.Payment_Plan.Card_Number = '' : 
                $scope.Payment_Plan.Card_Number = $scope.requirednumber(value);
                $('#Payment_Plan_Card_Number').validateCreditCard(function (result) {
                    if (result.valid == true && result.length_valid == true && result.luhn_valid == true) {
                        $scope.Payment_Plan.Card_Type = result.card_type.name;
                        $('.pplogs').html(result.card_type.name + '<img class="icon_opportunities" src="resources/images/icons/checked-form-2-green.png" style="width:20px" />');
                        $('#required_Payment_Plan').val(1);
                    } else {
                        $('.pplogs').html('Please input card number.');
                        $('#required_Payment_Plan').val(0);
                    }
                });
                break;
                case 'CC_Manual_cart':
                //$scope.requirednumber(value) == 0 ? $scope.CC_Manual.card_number = '' : 
                $scope.CC_Manual.card_number = $scope.requirednumber(value);
                $('#CC_Manual_card_number').validateCreditCard(function (result) {
                    if (result.valid == true && result.length_valid == true && result.luhn_valid == true) {
                        $scope.CC_Manual.Card_Type_cc = result.card_type.name;
                        $('.logs').html(result.card_type.name + '<img class="icon_opportunities" src="resources/images/icons/checked-form-2-green.png" style="width:20px" />');
                        $('#required_CC_Manual').val(1);
                    } else {
                        $('#required_CC_Manual').val(0);
                        $('.logs').html('Please input card number.');
                    }
                });
                break;
            }
        }
        $scope.addRowChargeDate = function(id, action) {
            if ($scope.ChargeDate.length < 3) {
                $scope.ChargeDate.push({
                    amount: '',
                    ChargeDate: '',
                    transaction_id: null,
                    status: null
                });
            }
            setTimeout(function() {
                $scope.$apply(function(val) {
                    $scope.required_form(id, action);
                });
            }, 100);
        }
        $scope.removeItemChargeDate = function(index) {
            if ($scope.ChargeDate.length > 1) {
                $scope.ChargeDate.splice(index, 1);
            }
        }
        $scope.requiredfloat = function(value) {
            if (value.length == 0) {
                value = 0;
            } else {
                var item_length = value.toString().split('.').length;
                value = value.toString().replace(/[^0-9-.]/g, '');
                if (item_length > 1 && value.toString().split('.')[1] != '' || item_length > 2) {
                    value = parseFloat(parseFloat(value).toFixed(2));
                }
                if (item_length == 1) {
                    value = parseFloat(value);
                }
            }
            if (isNaN(value) == true) {
                value = 0;
            }
            return value;
        };
        $scope.required_form = function(id, action) {
            if (action == 1) {
                $('#' + id).find('input').attr("required", "true");
                $('#' + id).find('select').attr("required", "true");
            } else {
                $('#' + id).find('input').removeAttr('required');
                $('#' + id).find('select').removeAttr('required');
            }
            $('.Address_2').removeAttr('required');
        }
        //checklist-quality.html?id=7&app_id = 1&&appstatus_id=1
        $scope.getChecklists = function(id, app_id, appstatus_id) {
            showTarget('#checklistPopup');
            $scope.thread = [];
        //$scope.app_id = 98913;
        $scope.answers = {};
        $scope.tochecklist = true;
        var data = Checklists.show(id)
        $scope.checklist_id = data.id;
        for (var i = 0; i < data.questions.length; i++) {
            var item = data.questions[i];
            for (var j = 0; j < item.fields.length; j++) {
                var getdata = item.fields[j].getdata;
                switch (getdata) {
                    case "userAMRS":
                    var test = JSON.parse(Users.getUserAMRS());
                    item.fields[j].data = test.data;
                    break;
                    case "servicesProduct":
                    var test = JSON.parse(Services.getchecklist());
                    item.fields[j].data = test.data;
                    break;
                    case "getappointmentstype":
                    var test = JSON.parse(Users.getappointmentstype());
                    item.fields[j].data = test.data;
                    break;
                    case "getcustomertype":
                    var test = JSON.parse(Users.getcustomertype());
                    item.fields[j].data = test.data;
                    break;
                }
            };
        };
        $timeout(function() {
            $scope.checklists = data;
        }, 10);
    };
    // $scope.getChecklists(8, 98913, '');
    // $scope.getChecklists(9, '', '');
    /*$scope.getSelectChecklists = function(){
        Checklists.getSelect().success(function(data){
            $scope.selectChecklists = data;
        });
    }
    $scope.getSelecChecklists();*/
    /*
    xem demo upload file tai day:
    http://jsfiddle.net/danialfarid/1m6fn6re/
    $scope.upload = function (file) {
        Upload.upload({
            url: '/todo',
            fields: $scope.todoData,
            file: file
        }).progress(function (evt) {
            var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
            console.log('progress: ' + progressPercentage + '% ' + evt.config.file.name);
        }).success(function (data, status, headers, config) {
            console.log('file ' + config.file.name + 'uploaded. Response: ' + data);
        }).error(function (data, status, headers, config) {
            console.log('error status: ' + status);
        })
    };
    */
    $scope.upload = function(files) {
        //console.log(files);
    }
    $scope.sizeChanged = function() {
        $scope.searchChecklists.rows = $scope.entryLimit;
        checklists_pagesize.val($scope.searchChecklists.rows);
        localStorage.setItem('checklists_pagesize', $scope.searchChecklists.rows);
        $scope.searchChecklists.current_page = 1;
        $scope.getChecklists();
    }
    $scope.pageChanged = function() {
        console.log($scope.currentPage);
        $scope.searchChecklists.current_page = $scope.currentPage;
        $scope.getChecklists();
    };
    //$scope.getChecklists();
    $scope.setPage = function(pageNo) {
        $scope.currentPage = pageNo;
        console.log('doi page');
    };
    $scope.addChecklistsData = {};
    $scope.createChecklists = function() {
        Checklists.save($scope.addChecklistsData).success(function(data) {
            $scope.addChecklistsData = {};
            $scope.getChecklists();
            if (data.status) {
                toastr.success(data.msg);
            } else {
                toastr.error(data.msg);
            }
        });
    }
    $scope.editChecklistsData = {};
    $scope.editChecklists = function(id) {
        $('.loader').show();
        Checklists.show(id).success(function(data) {
            $('.loader').hide();
            $scope.editChecklistsData = data;
        });
    }
    $scope.updateChecklists = function() {
        var id = $scope.editChecklistsData.id;
        $('.loader').show();
        Checklists.update(id, $scope.editChecklistsData).success(function(data) {
            $('.loader').hide();
            if (data.status) {
                $scope.editChecklistsData = {};
                //$('#modal_edit_checklists').modal('hide');
                toastr.success(data.msg);
            } else {
                toastr.error(data.msg);
            }
            $scope.getChecklists();
        });
    }
    $scope.deleteChecklistsData = {};
    $scope.confrimChecklists = function(id, title, content) {
        $scope.deleteChecklistsData = {
            id: id
        };
        var confirm = $.confirm(title, '<div class="text-content baseline">' + content + '</div>', {
            messageType: 'warning',
            titleIcon: 'remove',
            overlayTransparent: .75
        }, function() {
            $scope.deleteChecklists(id, confirm);
        });
    }
    $scope.deleteChecklists = function(id, confirm) {
        Checklists.destroy(id).success(function(data) {
            $scope.deleteChecklistsData = {};
            if (data.status) {
                $.notification('<div class="text-content">' + data.msg + '</div>', {
                    messageType: 'message-success',
                    autoClose: true
                });
                confirm.switchStateDialog("close");
            } else {
                $.notification('<div class="text-content">' + data.msg + '</div>', {
                    messageType: 'message-success',
                    autoClose: true
                });
                confirm.switchStateDialog("close");
            }
            $scope.getChecklists();
        });
    }
    $scope.getUserLogin = function() {
        return Login.getUserLogin().success(function(data) {
            if (data == false) {
                localStorage.setItem("login_status", "1");
                redirectTo('index.html');
            } else {
                var displayname = (data.first_name != null ? data.first_name : '') + ' ' + (data.last_name == null ? '' : data.last_name);
                if ($.trim(displayname) == "") {
                    $scope.displayname = "Hello, " + data.email;
                } else {
                    $scope.displayname = "Hello, " + displayname;
                }
            }
        });
    }
        //$scope.getUserLogin();
        $scope.logout = function() {
            return Login.logout().success(function(data) {
                $window.location.href = url_login;
            });
        }
        $scope.checkLogin = function() {
            return Login.checkLogin().success(function(data) {
                if (data.status == false) {
                    $window.location.href = url_login;
                }
            });
        }
        $scope.checklistKeyPress = function($event, $index) {
            if ($event.keyCode == 13) {
                $scope.nextQuestion($index);
            }
        }
        // edit by haudao
        $scope.openActionSheet = function(optModel) {
            var options = {
            // title: 'What do you want with this image?',
            buttonLabels: ['Camera', 'Photo'],
            addCancelButtonWithLabel: 'Cancel',
            androidEnableCancelButton: true,
        };
        $cordovaActionSheet.show(options).then(function(index) {
            if (index == 1) {
                $scope.takePicture(optModel);
            } else if (index == 2) {
                $scope.selectPicture(optModel);
            }
        });
    }
    $scope.imageURI = '';
    $scope.takePicture = function(optModel) {
        var options = {
            quality: 100,
            destinationType: Camera.DestinationType.NATIVE_URI,
            sourceType: Camera.PictureSourceType.CAMERA,
            // allowEdit: true,
            // targetWidth: 500,
            // targetHeight: 500,
            encodingType: Camera.EncodingType.JPEG,
            popoverOptions: CameraPopoverOptions,
            saveToPhotoAlbum: true
        };
        $cordovaCamera.getPicture(options).then(function(imageData) {
            console.log(imageData);
            $timeout(function(){
               $scope.answers[optModel] = imageData;

           },100)
            window.plugins.Base64.encodeFile(imageData, function(base64) {
                $scope.imageURI = base64;
                // console.log('file base64 encoding: ' + base64);
            }); 
            //>>>.>>> file:///storage/emulated/0/Pictures/IMG_20161208_183126.jpg
        }, function(err) {
            console.log(err);
            // $cordovaToast.showLongTop(err);
            $cordovaToast.showLongTop(err);
        });
    }
    $scope.getFileName = function(name){
        if(!name){
            return '';
        }
        var index = name.lastIndexOf('/');
        return name.substring(index+1);
    }
    $scope.selectPicture = function(optModel) {
        var options = {
            maximumImagesCount: 1,
            width: 0,
            height: 0,
            quality: 100
        };
        $cordovaImagePicker.getPictures(options).then(function(results) {
               // console.log(results);
               
               $timeout(function(){
                 $scope.answers[optModel] = results[0];

             },100)
               window.plugins.Base64.encodeFile(results[0], function(base64) {
                $scope.imageURI = base64;
                    // console.log('file base64 encoding: ' + base64);
                });
                //>>>>>["file:///data/data/rgd.com.ionicframework.crmapp495368/cache/tmp_1-2040984539.jpg",
                //      "file:///data/data/rgd.com.ionicframework.crmapp495368/cache/tmp_41273410515.jpg",
                //      "file:///data/data/rgd.com.ionicframework.crmapp495368/cache/tmp_7-2073889061.jpg"]
                // $scope.dataFileMan.oFile = results;
            }, function(err) {
                console.log(err);
                // $cordovaToast.showLongTop(err);
                $cordovaToast.showLongTop(err);
            });
    }

    $scope.dataChecklists = {};
    $scope.contentChecklist = {};
    // end edit
    $scope.requiredcvv = function (value, action) {
        if (!value)
            return 0;
        if (value.length == 0) {
            value = '';
        }
        value = value.toString().replace(/[^0-9]/g, '');
        // if (isNaN(value) == true) {
        //     value = 0;
        // }
        value = value.substring(0, 4);
        if (action == 'Payment_Plan') {
            $scope.Payment_Plan.CVV2_Codes = value;
        } else {
            $scope.CC_Manual.CVV2_Code = value;
        }
    };

    $scope.requirednumber = function (value) {
        if (!value)
            return 0;
        if (value.length == 0) {
            value = 0;
        }
        value = parseInt(value.toString().replace(/[^0-9]/g, ''));
        if (isNaN(value) == true) {
            value = 0;
        }
        return value;
    };

    $scope.setValueCC_Manual_month_cc = function (value) {
        var index = _.findLastIndex($scope.monthNames, {
            value: parseInt(value)
        });
        if (index >= 0)
            $scope.Input_value.CC_Manual_month_cc = $scope.monthNames[index].name;
    }

    $scope.finishChecklist = function(){
        if($scope.isSubmit){
            $cordovaToast.showLongTop("The request is in processing, please wait until it's completed.");
            return;
        }
        $scope.isSubmit = true;
        $ionicLoading.show({ template: templateLoading });
        Appointmentchecklists.finishChecklist({appId:$scope.app_id}).success(function (data) {
            $scope.isSubmit = false;
            if (data.status) {
                $scope.addAppointmentchecklistsData = {};
                delete $scope.uploadedFile;
                $cordovaToast.showLongTop(data.msg);
                $ionicLoading.hide();
                if($scope.from_order == true){
                    $scope.$emit('closeappointment', { action: "closeappointment", from_order:true , appointment_id:$scope.app_id});
                }else{
                    $scope.$emit('closeappointment', { action: "closeappointment", from_order:false, appointment_id:$scope.app_id});
                }
            }else{
                $cordovaToast.showLongTop(data.msg);
                $ionicLoading.hide();
            }
        });
    }

    $scope.fw_note_exist = '';
    $scope.last_checklist_id = 0;
    $scope.toSchedule = false;
    $scope.showRowDateTime = false;
    $scope.isSubmitButton = true;
    $scope.isShowButton = false;
    $scope.show_item_decline_text = false;
    $scope.show_fw_note = false;
    $scope.show_describe = false;
    $scope.dataAddAppointment = {};

    $scope.getChecklistsNew = function(id){
        showTarget('#checklistPopup');
        var data = Checklists.show(id);
        return data;
    };

    $scope.changeNote = function(val){
        $scope.fw_note_on_checklist = val;
    };
    $scope.nextChecklist = function(id){
        var next = true;
        for (var i = 0; i < $scope.checklists.questions.length; i++) {
            var curr = $scope.checklists.questions[i];
            for (var j = 0; j < curr.fields.length; j++) {
                var field = curr.fields[j];
                var type = field.type;
                var check = $scope.validateAnswer(field);
            }
            if(!check){
                next = false;
                break;
            }
        }
        if(next){
            if($scope.fw_note !='' && $scope.fw_note_exist != $scope.fw_note_on_checklist && id==1){
                var dataFW = {
                    appointment_id:$scope.app_id,
                    fw_note:$scope.fw_note_on_checklist
                };
                $ionicLoading.show({
                    template: templateLoading
                })
                Appointmentchecklists.saveFWNote(dataFW).success(function(data){
                    $ionicLoading.hide();
                });
            }
            if(id==3){
                if($scope.show_describe){
                    if($scope.checklists.describe_detail && $scope.checklists.describe_detail.length > 0){
                        var datMail = {
                            customer_id:$scope.customer_id,
                            appointment_id:$scope.app_id,
                            text:$scope.checklists.describe_detail
                        }
                        $ionicLoading.show({
                            template: templateLoading
                        })
                        Appointmentchecklists.sendmail(datMail).success(function(data){
                            $ionicLoading.hide();
                        });
                    }else{
                        $cordovaToast.showLongTop('Please input Describe in Detail !');
                        return;
                    }
                } 
            }
            if(id==2){
                if($scope.show_item_decline_text && (!$scope.checklists.item_decline_text || $scope.checklists.item_decline_text.length == 0)){
                    $cordovaToast.showLongTop('Please answers all question !');
                    return;
                }
            }
            $scope.createChecklistsDetail(id);
            $scope.isShowButton = false;  
            data = $scope.getChecklistsNew(id+1);
            $scope.checklist_id = data.id;
            $timeout(function () {
                $scope.checklists = data;
            }, 10);
        }
    }
    $scope.openCreateToSchedule = function(id){
        $scope.last_checklist_id = id;
        var nextChecklist = id+1;
        var data = $scope.getChecklistsNew(nextChecklist);
        $scope.checklist_id = data.id;
        $timeout(function () {
            $scope.checklists = data;
        }, 10);
        if($scope.checklist_id == 5){
            $scope.refreshAppointmentType();
            setTimeout(function() {
                if($scope.showRowDateTime){
                    $scope.checklists.title = $scope.checklists.title + 'We Have a Date and Time';
                }else{
                    $scope.checklists.title = $scope.checklists.title + 'No Date and Time';
                }
            }, 50);   
        }
    }

    $scope.createChecklistsDetail = function(checklist_id){
        var dataAppChecklist = {};
        dataAppChecklist.data = $scope.getDataChecklists(checklist_id);
        dataAppChecklist.checklist_id = checklist_id;
        dataAppChecklist.appointment_id = $scope.app_id;
        if(checklist_id == 4){
            dataAppChecklist.getdata = true;
        }else{
            dataAppChecklist.getdata = false;
        }
        $ionicLoading.show({
            template: templateLoading
        });
        Appointmentchecklists.save(dataAppChecklist).success(function (data) {
            $ionicLoading.hide();
            $scope.answers = {};
            $scope.allDataChecklist = data.dataChecklist;
        });
    }

    $scope.getDataChecklists = function(checklist_id){
        var data = $scope.getChecklistsNew(checklist_id);
        var array_question = data.questions;
        var dataChecklists = [];
        var keys = _.keys($scope.answers);
        for (var i = 0; i < keys.length; i++) {
            var key = keys[i];
            var question = $scope.getQuestionChecklist(key,array_question);
            if($scope.answers.purchased != undefined && $scope.answers.purchased.id == '7'){
                var answer = $scope.answers[key].label + ' | ' + $scope.checklists.item_decline_text;
            }else if($scope.answers.issue != undefined && $scope.answers.issue.id == '1'){
                var answer = $scope.answers[key].label + ' | ' + $scope.checklists.describe_detail;
            }else{
                var answer = $scope.answers[key].label;
            }
            dataChecklists.push({question : question.question, answer : answer});
        }
        return dataChecklists;
    }

    $scope.getQuestionChecklist = function (key,array_question) {
        for (var j = 0; j < array_question.length; j++) {//tim cau hoi co model phu hop
            var question = array_question[j];
            for (var k = 0; k < question.fields.length; k++) {
                var item3 = question.fields[k];

                if (item3.model == key) {
                    return question;
                }
                if (item3.options) {
                    for (var i = 0; i < item3.options.length; i++) {
                        var item4 = item3.options[i];
                        if (item4.model == key) {
                            return question;
                        }
                    };
                }
            };
        };
        return null;
    }

    $scope.validateAnswer = function(field){
        if(!$scope.answers.hasOwnProperty(field.name) || $scope.answers[field.name] == undefined){
            $cordovaToast.showLongTop("Please answers all question");
            return false;
        }else{
            if($scope.answers.appnotes != undefined && $scope.answers.appnotes.id == '2'&& $scope.fw_note_on_checklist == '' ){
                $cordovaToast.showLongTop("Please answers all question");
                return false;
            }else if($scope.answers.purchased != undefined && $scope.answers.purchased.id == '7' && $scope.checklists.item_decline_text == ''){
                $cordovaToast.showLongTop("Please answers all question");
                return false;
            }else if($scope.answers.issue != undefined && $scope.answers.issue.id == '1' && $scope.checklists.describe_detail == ''){
                $cordovaToast.showLongTop("Please answers all question");
                return false;
            }else{
                return true;
            }
        }
    }
    $scope.changeSelectOption = function (item, name) {
        if(item == undefined){
            $scope.isShowButton = false;
            return;
        }        
        if(name == 'issue' && item.id == '1'){
            $scope.show_describe = true;
        }else{
            $scope.show_describe = false;
            $scope.checklists.describe_detail = '';
        }
        if(name == 'purchased' && item.id == '7'){
            $scope.show_item_decline_text = true;
        }else{
            $scope.show_item_decline_text = false;
            $scope.checklists.item_decline_text = '';
        }
        if(name == 'returntrip' && item.id == '3'){
            $scope.isSubmitButton = true;
            $scope.showRowDateTime = false;
        }else{
            $scope.isSubmitButton = false;
            if(item.id == '1' ){
                $scope.showRowDateTime = true;
            }else{
                $scope.showRowDateTime = false;
            }
        }
        if(name == 'returntrip' && item.id){
            $scope.isShowButton = true;
        }
    }

    $scope.changeRadioOption = function (item, index, name) {
        var curr = item[index];
        _.each(item, function (f) {
            if (curr.id != f.id) {
                return f.show = false;
            }
        });
        item[index].show = true;
        item[index].checked = true;
        if(name == 'appnotes'){
            index == 1 ? $scope.show_fw_note = true : $scope.show_fw_note = false;
            if($scope.show_fw_note){
                $scope.fw_note = $scope.fw_note_on_app;
                $scope.fw_note_exist = $scope.fw_note_on_app;
            }else{
                $scope.fw_note = '';    
            }
        }
    }

    $scope.fisnishCheckListNone = function(checklist_id){
        var dataAppChecklist = {};
        dataAppChecklist.data = $scope.getDataChecklists(checklist_id);
        dataAppChecklist.checklist_id = checklist_id;
        dataAppChecklist.appointment_id = $scope.app_id;
        dataAppChecklist.getdata = true;
        $ionicLoading.show({ template: templateLoading });
        Appointmentchecklists.save(dataAppChecklist).success(function (data) {
            $scope.checklist_id = 0;
            $scope.answers = {};
            $scope.allDataChecklist = data.dataChecklist;
            var pdfcontent = $scope.buildPdfFile();
            setTimeout(function() {
                var dataCreatePdf = {
                    pdf:pdfcontent,
                    app_id:$scope.app_id,
                    customer_id:$scope.customer_id
                };
                Appointments.createPdfFile(dataCreatePdf).success(function(response){
                    $ionicLoading.hide();
                    if($scope.from_order == true){
                        $scope.$emit('closeappointment', { action: "closeappointment", from_order:true , appointment_id:$scope.app_id});
                    }else{
                        $scope.$emit('closeappointment', { action: "closeappointment", from_order:false , appointment_id:$scope.app_id});
                    }
                });
            }, 200); 
        });     
    }

$scope.finishChecklistNew = function(){
    $ionicLoading.show({ template: templateLoading });
    if($scope.dataAddAppointment.appointmentgroup_id == null || $scope.dataAddAppointment.appointmentgroup_id == ''){
        $cordovaToast.showLongTop('Please fill all the required information.!!!');
        return;
    }
    $scope.addAppointmentsDataCopy = angular.copy($scope.dataAddAppointment);
    $scope.addAppointmentsDataCopy.officeapptnote = $scope.fw_note_on_checklist;
    $scope.addAppointmentsDataCopy.customer_id = $scope.customer_id;
    $scope.addAppointmentsDataCopy.customertype_id = $scope.customertype_id;
    if($scope.showRowDateTime){
        $scope.addAppointmentsDataCopy.arrivalwindow = moment($('#arrivalwindowView').val(), 'hh:mmA').format('HH:mm:ss');
        $scope.addAppointmentsDataCopy.endarrivalwindow = moment($('#endarrivalwindowView').val(), 'hh:mmA').format('HH:mm:ss');
        $scope.addAppointmentsDataCopy.nothomeutil = moment($('#nothomeutilView').val(), 'hh:mmA').format('HH:mm:ss');
        $scope.addAppointmentsDataCopy.dateofappt = $('#formCreateToSchedule #dateofappt').val();
        $startTimeCheck = moment($scope.addAppointmentsDataCopy.arrivalwindow, 'hh:mmA').format('HH:mm:ss');
        $endTimeCheck = moment( $scope.addAppointmentsDataCopy.endarrivalwindow, 'hh:mmA').format('HH:mm:ss');
        if($startTimeCheck < '06:00:00' || $endTimeCheck > '22:00:00'){
            $ionicLoading.hide();
            $cordovaToast.showLongTop('The appointment cannot be scheduled outside 6AM-10PM');
            return;
        }
        var check = validateTime($scope.addAppointmentsDataCopy.arrivalwindow, $scope.addAppointmentsDataCopy.endarrivalwindow);
        if (!check.status) {
            $ionicLoading.hide();
            $cordovaToast.showLongTop('End time must be greater than start time');
            return;
        }
    }
    $scope.addAppointmentsDataCopy.addby_id = $scope.currentIdLogin;
    if($scope.fw_note_on_checklist != ''){
        $scope.addAppointmentsDataCopy.officeapptnote = $scope.fw_note_on_checklist;
    }
    $scope.addAppointmentsDataCopy.current_app_id = $scope.app_id;
    $scope.createChecklistsDetail($scope.last_checklist_id);
    $ionicLoading.show({ template: templateLoading });
    Appointments.createToSchedule($scope.addAppointmentsDataCopy).success(function(data) {
        if (data.status) {
            $scope.fw_note_on_checklist = '';
            $scope.dataAddAppointment = {};
            var pdfcontent = $scope.buildPdfFile();
            setTimeout(function() {
                var dataCreatePdf = {
                    pdf:pdfcontent,
                    app_id:$scope.app_id,
                    new_app_id:data.appointment_id,
                    customer_id:$scope.customer_id
                };
                Appointments.createPdfFile(dataCreatePdf).success(function(response){
                    $cordovaToast.showLongTop(data.msg);
                    $ionicLoading.hide();
                    if($scope.from_order == true){
                        $scope.$emit('closeappointment', { action: "closeappointment",from_order:true ,'appointment_id':$scope.app_id});
                    }else{
                        $scope.$emit('closeappointment', { action: "closeappointment",from_order:false,'appointment_id':$scope.app_id});
                    }
                });
            }, 200);
        }else{
            $cordovaToast.showLongTop(data.msg);
            $ionicLoading.hide();
        }
    }).error(function (data, status, headers, config) {
        $ionicLoading.hide();
        console.log('error status: ' + status);
        $cordovaToast.showLongTop('Connection Error!!!');
    });
}
$scope.validateFormCreateToSchedule = function () {
    var exitLoop = false;
    if (formValidate.$invalid) {
        $cordovaToast.showLongTop('Please fill all the required information.!!!');
        return;
    }
    $scope.finishChecklistNew();
}

$scope.getSelectFieldworker = function() {
    Users.getSelectFieldworker().success(function(data) {
        $scope.fieldworkerSelect = data;
        $scope.getCallaheads();
    });
}
$scope.getCallaheads = function() {
    Callaheads.getSelect().success(function(data) {
        $scope.callaheads = data;
        $scope.getFlexiblecustomers();
    });
}
$scope.getFlexiblecustomers = function() {
    Flexiblecustomers.getSelect().success(function(data) {
        $scope.flexiblecustomers = data;
            $scope.dataAddAppointment.flexiblecustomer_id = '3'; //possibly
            var flexiblecustomer = _.findWhere($scope.flexiblecustomers, {id: '3'});
            if(flexiblecustomer){
                $('input[name=selectedFlexName]').val(flexiblecustomer.name);
            }
            $scope.getAllOrders();
        });
}

$scope.getAllOrders = function(){
    var params = {
        search: '',
        customer_id: $scope.customer_id
    };
    $scope.order_idapp = {};
    Orders.getSelect2(params).success(function(data) {
        var diff = differentArray(data);
        var invoiceCreate = _.findWhere(diff,{appointment_id : $scope.app_id});
        if(invoiceCreate){
            $scope.dataAddAppointment.order_id = invoiceCreate.id;
            $scope.orderData = diff;
        }else if (!invoiceCreate && $scope.order_id != '0') {
            $scope.dataAddAppointment.order_id = $scope.order_id;
            $scope.orderData = diff;
        }else{
            var NAdata = {id:'0',name:'N/A',};
            diff.unshift(NAdata);
            $scope.orderData = diff;
            $scope.dataAddAppointment.order_id = '0';
        }
        var item =  _.findWhere($scope.orderData, {id: $scope.dataAddAppointment.order_id});
        if(item){
            $('input[name=selectedInvoiceNumber]').val(item.name);
        }
    });
}
$scope.refreshAppointmentType = function() {
    var params = {
        search: ''
    };
    $ionicLoading.show({template: templateLoading});
    Opportunities.getAppointmentType(params).success(function(data) {
        $ionicLoading.hide();
        var diff = differentArray(data, $scope.addAppointmentsData.appointmentgroup_id);
        $scope.AppointmentType = diff;
        $scope.getSelectFieldworker();
    });
}

$scope.$watch('dataAddAppointment.dateofappt', function (val) {

    if($scope.showRowDateTime){
        var appDate = moment(val).format('MM/DD/YYYY');
        $('#formCreateToSchedule #dateofappt').val(appDate);
    }
});

$scope.buildPdfFile = function(){
    var html = '';
    for (var i = 0; i < $scope.allDataChecklist.length; i++) {
        var item = $scope.allDataChecklist[i];
        var itemBackground = i % 2 == 0 ? '#EAF1F2' : '#F8F8F8'
        html += "<div style='background: " + itemBackground + "; padding: 0px 0 15px; margin-bottom: 2px;'>";
        html += "<div style='padding: 0 15px; font-weight: bold; font-size: 16px; font-family: arial; color:  #3a6258; margin-bottom: 15px;'>" + item.questions + "</div>";
        html += "<div style='text-align: right; padding: 0 20px; font-weight: bold; font-size: 16px; font-family: arial; color:#B07236; margin-bottom: 5px;'>";
        
        html += "<div><span style=\"display: inline-block; padding: 2px 10px;\">"+item.answers+"</span></div>";

        html += "</div>";
        html += "</div>";
    };
    return html;
}

$scope.$on('reload_app_status', function(event, args) {
    $scope.$emit('order_load_app', {
        action: "order_load_app"
    });
});

$scope.backToAppointment = function(){
    closeTarget('#checklistPopup');
    $scope.fw_note_on_checklist = '';
    $scope.checklists.describe_detail = '';
    $scope.checklists.item_decline_text = '';
    $scope.last_checklist_id = 0;
    $scope.toSchedule = false;
    $scope.showRowDateTime = false;
    $scope.isSubmitButton = true;
    $scope.isShowButton = false;
    $scope.show_item_decline_text = false;
    $scope.show_fw_note = false;
    $scope.show_describe = false;
    $scope.dataAddAppointment = {};
}

    /*=========================================*/
    $scope.$on('checklist-popup', function(event, args) {
        showTarget('#checklistPopup');
        $scope.app_id = args.appointment_id;
        $scope.customer_id = args.customer_id;
        $scope.appointmentgroup_id = args.appointmentgroup_id;
        $scope.order_id = args.order_id;
        $scope.fw_note_on_app = args.fw_note;
        $scope.fw_note_on_checklist = args.fw_note;
        $scope.customertype_id = args.customertype_id;
        $scope.currentPageChecklist = 1;
        $scope.isSubmitChecklist = false;
        $scope.upload_to_appointment_id = angular.copy($scope.app_id);
        if(args.from_order == true){
            $scope.from_order = args.from_order;
        }else{
            $scope.from_order = false;
        }
        $scope.contentChecklist = {
            title: 'Select All That Apply',
            current_app_type: args.appointmentgroup_id,
            appointment_note: $scope.fw_note_on_app,
            add_photo_cb: 'no',
            images: [],
        };
        $scope.checklistData = {};
        Users.getSelectFieldworker().success(function(data) {
            $scope.fieldworkerSelect = data;
        });
        Opportunities.getAppointmentType({search:''}).success(function(data) {
            $scope.appointmentTypes = data;
        })
        $scope.getCurrentChecklistOfApp();
    });
    $scope.getCurrentChecklistOfApp = function(){
        $ionicLoading.show({
            template: templateLoading
        })
        Appointmentchecklists.getlastestcell({
            appointment_id: $scope.app_id
        }).success(function(result) {
            $(".modal-backdrop").remove('active');
            $ionicLoading.hide();
            $scope.data_to_schedule = _.where(result.data_appointment, {
                fieldworker: null
            });
            $scope.data_appointment = _.filter(result.data_appointment, function(val) {
                return parseInt(val.fieldworker) > 0;
            });
            $scope.check_item_invoice_consumable = result.consumable_items.length ? true : false;
            $scope.consumable_lists = result.consumable_lists;
            setTimeout(async function () {
                await $scope.$apply(function (val) {
                    if(result.checklist_output){
                        $scope.checklistData = result.checklist_output;
                    }else{
                        $scope.checklistData = {
                            appointment_id: $scope.app_id,
                            return_trip_cb: 'no',
                            safety_quality_cb: 'no',
                            appointment_note_cb: 'no',
                            appt_change_cb: 'no',
                        };
                        !$scope.fw_note_on_app || !$scope.fw_note_on_app.length ? $scope.checklistData.appointment_note_cb = 'yes' : '';
                    }
                    let consumable_items = result.consumable_items;
                    $scope.consumable_items = [];
                    _.each(consumable_items, function(item, index){
                        for(var i = 0; i < item.quantity; i++){
                            let _item = angular.copy(item)
                            _item.consumable_lists = _.where($scope.consumable_lists, {product_id:_item.product_id});
                            _item.index = index;
                            if(_item.name.toLowerCase().indexOf('vertical track') > -1){
                                let _i = i >= 3 ? i%3 : i;
                                if(_i == 0){
                                    console.log('left')
                                    let _f = _.filter(_item.consumable_lists,function(v){
                                        return v.name.toLowerCase().indexOf('(left)') > -1;
                                    });
                                    if(_f.length){
                                        _item.consumed_1 = _f[0].used_item_id;
                                        _item.consumed_name_1 = _f[0].name;
                                    }
                                }else if(_i == 1){
                                    console.log('right')
                                    let _f = _.filter(_item.consumable_lists,function(v){
                                        return v.name.toLowerCase().indexOf('(left)') > -1;
                                    });
                                    if(_f.length){
                                        _item.consumed_1 = _f[0].used_item_id;
                                        _item.consumed_name_1 = _f[0].name;
                                    }
                                }
                            }
                            $scope.consumable_items.push(_item);
                        }
                    });
                });
            });
            $scope.appointmentphotos = result.appointmentphotos;
        }).error(function(data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });
    };
    $scope.continueNextPage = function(currentPageChecklist){
        if(currentPageChecklist == 2 && $scope.checklistData.return_trip_cb == 'yes' && !$scope.contentChecklist.date && !$scope.contentChecklist.time && !$scope.checklistData.return_length && !$scope.checklistData.return_trip_user){
            $cordovaToast.showLongTop('Please Fill In Info');
            return;
        }
        if(currentPageChecklist == 1 && $scope.checklistData.return_trip_cb == 'no' && $scope.checklistData.safety_quality_cb == 'no' && $scope.checklistData.appointment_note_cb == 'no' && $scope.checklistData.appt_change_cb == 'no' && $scope.contentChecklist.add_photo_cb == 'no'){
            if(currentPageChecklist == 1 && !$scope.check_item_invoice_consumable){
                $scope.saveChecklist(true);
            }else{
                $scope.currentPageChecklist = angular.copy(currentPageChecklist + 2);
            }
        }else{
            $scope.contentChecklist.title = 'Fill In Info';
            $scope.currentPageChecklist = angular.copy(currentPageChecklist + 1);
            if($scope.currentPageChecklist == 2 && $scope.checklistData.appt_change_cb == 'yes'){
                setTimeout(function() {
                    let apptype = _.findWhere($scope.appointmentTypes, {id:$scope.appointmentgroup_id});
                    $("input[name='seletedCurrentAppointmentType']").val(apptype ? apptype.name : '');
                }, 500);
            }
        }
    };
    $scope.submitChecklistPage = function(formValidate){
        if (formValidate && formValidate.$invalid) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        if($scope.checklistData.appt_change_cb == 'yes' && $scope.checklistData.suggest_note.length <= 10){
            $cordovaToast.showLongTop('Please include more reasoning');
            return;
        } else {
            if($scope.contentChecklist.appointment_note != '' && $scope.fw_note != $scope.contentChecklist.appointment_note){
                var dataFW = {
                    appointment_id:$scope.app_id,
                    fw_note: $scope.contentChecklist.appointment_note
                };
                Appointmentchecklists.saveFWNote(dataFW).success(function(data){});
            }
            if($scope.contentChecklist.add_photo_cb == 'yes'){
                if ($scope.files.length == 0) {
                    $cordovaToast.showLongTop('please select at least one file to upload.!!!');
                    return;
                }else{
                    $scope.dataFiles = angular.copy($scope.files);
                    $scope.upLoadFileProgressChecklist($scope.dataFiles, 0);
                    $scope.continueSaveChecklist();
                }
            }else{
                $scope.continueSaveChecklist();
            }
        }
    };
    $scope.continueSaveChecklist = function(){
        if(!$scope.check_item_invoice_consumable){
            $scope.saveChecklist(true);
        } else {
            $scope.saveChecklist();
            $scope.currentPageChecklist = angular.copy($scope.currentPageChecklist + 1);
        }
    };
    $scope.saveChecklist = function(complete = false){
        if($scope.isSubmitChecklist){
            $cordovaToast.showLongTop("The request is in processing, please wait until it's completed.");
            return;
        }
        $scope.isSubmitChecklist = true;
        let objParam = angular.copy($scope.checklistData);
        $ionicLoading.show({ template: templateLoading });
        Appointmentchecklists.saveChecklist(objParam).success(function (data) {
            $scope.isSubmitChecklist = false;
            $ionicLoading.hide();
            if(data.status){
                $cordovaToast.showLongTop(data.msg);
                complete ? $scope.completeChecklist() : '';
            }else{
                $cordovaToast.showLongTop(data.msg);
            }
        });
    };
    $scope.completeChecklist = function(){
        if($scope.checklistData.return_trip_cb == 'yes'){
            let addAppointmentsDataCopy = {
                customer_id: $scope.customer_id,
                appointmentgroup_id: $scope.appointmentgroup_id,
                customertype_id: $scope.customertype_id,
                addby_id: $scope.currentIdLogin,
                current_app_id: $scope.app_id,
                from_checklist: true,
            };
            if($scope.checklistData.return_trip_user && !$scope.contentChecklist.date && !$scope.contentChecklist.time){
                addAppointmentsDataCopy.prefieldworker = $scope.checklistData.return_trip_user;
            }
            if(!$scope.checklistData.return_trip_user && ($scope.contentChecklist.date || $scope.contentChecklist.time)){
                addAppointmentsDataCopy.fieldworker = 3779;
                addAppointmentsDataCopy.dateofappt = $scope.contentChecklist.date;
                addAppointmentsDataCopy.arrivalwindow = $scope.contentChecklist.time;
                addAppointmentsDataCopy.endarrivalwindow = moment($scope.contentChecklist.time.toLowerCase(), 'hh:mma').add(Number($scope.checklistData.return_length), 'hours').format('hh:mmA');
                $scope.checklistData.return_trip_date_time = moment($scope.contentChecklist.date, 'MM/DD/YYYY').format('YYYY-MM-DD') +' '+ moment($scope.contentChecklist.time.toLowerCase(), 'hh:mma').format('HH:mm:ss');
            }
            if($scope.checklistData.return_trip_user && ($scope.contentChecklist.date || $scope.contentChecklist.time)){
                addAppointmentsDataCopy.fieldworker = $scope.checklistData.return_trip_user;
                addAppointmentsDataCopy.dateofappt = $scope.contentChecklist.date;
                addAppointmentsDataCopy.arrivalwindow = $scope.contentChecklist.time;
                addAppointmentsDataCopy.endarrivalwindow = moment($scope.contentChecklist.time.toLowerCase(), 'hh:mma').add(Number($scope.checklistData.return_length), 'hours').format('hh:mmA');
                $scope.checklistData.return_trip_date_time = moment($scope.contentChecklist.date, 'MM/DD/YYYY').format('YYYY-MM-DD') +' '+ moment($scope.contentChecklist.time.toLowerCase(), 'hh:mma').format('HH:mm:ss');
            }
            Appointments.createToSchedule(addAppointmentsDataCopy).success(function(data) {
                if (data.status) {
                    $cordovaToast.showLongTop(data.msg);
                    $scope.saveChecklist();
                    $scope.$emit('closeappointment', { action: "closeappointment",from_order:true ,'appointment_id':$scope.app_id});
                }else{
                    $cordovaToast.showLongTop(data.msg);
                }
            });
        }else{
            $scope.$emit('closeappointment', { action: "closeappointment",from_order:true ,'appointment_id':$scope.app_id});
        }   
    };
    $scope.$watch('contentChecklist.time', function(time) {
        if (time) {
            $scope.checklistData.return_length = '3';
        }
    });
    $scope.$watch('contentChecklist.date', function (val) {
        if(val){
            var appDate = moment(val).format('MM/DD/YYYY');
            $('#formCreateToSchedule #dateofappt').val(appDate);
        }
    });
    $scope.openPicturePicker = function() {
        var options = {
            maximumImagesCount: 50,
            width: 0,
            height: 0,
            quality: 100
        };
        $cordovaImagePicker.getPictures(options).then(function(results) {
            results.forEach(function(itm) {
                var filename = itm.substr(itm.lastIndexOf('/') + 1);
                $scope.files.push({
                    name: filename,
                    type: 'image/jpeg',
                    localURL: itm
                });
            })
        });
    };
    $scope.upLoadFileProgressChecklist = function(files, index) {
        var item = files[index];
        var d = new Date();
        item.fullName = d.getTime() + "." + item.name.substr(item.name.lastIndexOf('.') + 1);
        item.fullName = item.fullName.split('#').join('t');
        $scope.fileUploadData = {};
        $scope.fileUploadData.name = item.fullName;
        $scope.fileUploadData.type = item.type;
        $scope.fileUploadData.bucket = bucketName;
        $scope.fileUploadData.acl = aclConfig;
        $scope.fileUploadData.for = 'app';
        $scope.fileUploadData.appointment_id = $scope.upload_to_appointment_id;
        $scope.fileUploadData.customer_id = $scope.customer_id;
        $ionicLoading.show({
            template: templateLoading
        });
        Login.getConfigFileUpload($scope.fileUploadData).success(function(data) {
            var Uoptions = {};
            Uoptions.fileKey = "file";
            Uoptions.fileName = data.folder + '/' + $scope.fileUploadData.name;
            Uoptions.mimeType = item.type;
            Uoptions.chunkedMode = false;
            Uoptions.headers = {
                connection: "close"
            };
            Uoptions.params = {
                "Key": data.folder + '/' + item.fullName,
                "AWSAccessKeyId": data.awsAccessKeyId,
                "acl": data.acl,
                "Policy": data.policy,
                "Signature": data.signature,
                "success_action_status": data.successActionStatus,
                "Content-Type": item.type
            };
            $cordovaFileTransfer.upload('http://' + bucketName + '.s3.amazonaws.com/', item.localURL, Uoptions).then(function(return_data) {
                try {
                    $scope.fileLocation = return_data.headers.Location;
                } catch (e) {
                    $scope.jsonObject = xml2json.parser(return_data.response);
                    $scope.fileLocation = $scope.jsonObject.postresponse.location;
                }
                item.locationFile = decodeURIComponent($scope.fileLocation);
                $scope.fileUploadData = {};
                $scope.addFileManagerChecklist(item, index);
            }, function(err) {
                console.log(err);
                $ionicLoading.hide();
                $cordovaToast.showLongTop('Upload file ' + item.fullname + ' fail!!!');
            }, function(progress) {
                $ionicLoading.show({
                    template: templateLoading
                });
            });
        }).error(function(data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });
    };
    $scope.addFileManagerChecklist = function(item, index) {
        item.customer_id = $scope.customer_id;
        item.appointment_id = $scope.upload_to_appointment_id;
        item.phoneApp = true;
        if (item.type == 'image/jpeg') {
            item.extension = 'jpg';
        } else {
            item.extension = item.name.substr(item.name.lastIndexOf('.') + 1);
        }
        item.file_name = item.fullName;
        item.file_type = item.extension;
        item.file_size = item.size ? item.size : '';
        item.filedes = item.file_des ? item.file_des : '';
        var options = {
            fileName: item.fullName,
            fileKey: "file",
            params: item,
            mimeType: item.type,
            chunkedMode: false
        };
        options.headers = headers;
        $cordovaFileTransfer.upload(url_server + 'appointments/upLoadFileMan', item.localURL, options).then(function(e) {
            $ionicLoading.hide();
            if (index == $scope.dataFiles.length - 1) {
                $scope.files = [];
            }
            var results = JSON.parse(e.response);
            if (results.status) {
                $ionicLoading.hide();
                $cordovaToast.showLongTop('Upload file ' + item.fullName + ' successful!!!');
                if (index < $scope.dataFiles.length - 1) {
                    index++;
                    $scope.upLoadFileProgressChecklist($scope.dataFiles, index);
                }
            } else {
                $cordovaToast.showLongTop(results.msg);
            }
        }, function(err) {
            console.log(err);
            $ionicLoading.hide();
            $cordovaToast.showLongTop('Upload file ' + item.fullName + ' fail!!!');
        }, function(progress) {
            $ionicLoading.show({
                template: templateLoading
            });
        });
    };
    $scope.changeConsumedPart = function(index, indexpart, consumed){
        if(indexpart == 1){
            $scope.consumable_items[index].consumed_1 = consumed;
        }else{
            $scope.consumable_items[index].consumed_2 = consumed;
        }
        let _consumed1 = _.findWhere($scope.consumable_items[index].consumable_lists,{used_item_id:$scope.consumable_items[index].consumed_1});
        _consumed1 ? $scope.consumable_items[index].consumed_name_1 = _consumed1.name : '';
        let _consumed2 = _.findWhere($scope.consumable_items[index].consumable_lists,{used_item_id:$scope.consumable_items[index].consumed_2});
        _consumed2 ? $scope.consumable_items[index].consumed_name_2 = _consumed2.name : '';
        if(_consumed1 && _consumed2 && (_consumed1.name.toLowerCase().indexOf("black") > -1 && _consumed2.name.toLowerCase().indexOf("black") > -1 
            || _consumed1.name.toLowerCase().indexOf("red") > -1 && _consumed2.name.toLowerCase().indexOf("red") > -1) 
            && _consumed1.name.substring(0,_consumed1.name.indexOf(" ")) != _consumed2.name.substring(0,_consumed2.name.indexOf(" ")) ){
            $scope.consumable_items[index].highlight = true;
        }else{
            $scope.consumable_items[index].highlight = false;
        }
    };
    $scope.submitThirdPage = function(formValidate){
        if (formValidate && formValidate.$invalid) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        if($scope.isSubmitChecklist){
            $cordovaToast.showLongTop("The request is in processing, please wait until it's completed.");
            return;
        }
        $scope.isSubmitChecklist = true;
        let objParam = angular.copy($scope.checklistData);
        objParam.consumed_parts = angular.copy($scope.consumable_items);
        $ionicLoading.show({ template: templateLoading });
        Appointmentchecklists.saveConsumedPart(objParam).success(function (data) {
            $scope.isSubmitChecklist = false;
            $ionicLoading.hide();
            if(data.status){
                $scope.saveChecklist(true);
            }else{
                $cordovaToast.showLongTop(data.msg);
            }
        });
    };

})
