'use strict';

angular.module('payment', [])
    .controller('PaymentCtrl', ['$scope', 'AppConfig', 'session', 'Util', 'exchangeRate', 'moment', 'currencyUnit',
        '$uibModal', 'cardType', '$q', '$state', 'paymentType', 'configServer', '$rootScope', 'Patterns',
        function ($scope, AppConfig, session, Util, exchangeRate, moment,
                  currencyUnit, $uibModal, cardType, $q, $state, paymentType, configServer, $rootScope, Patterns) {


            $scope.currentUser = session.getUser();
            $scope.currentLang = session.getCurrentLanguage();
            $scope.script_pattern = Patterns.SCRIPT_PATTERN;
            $scope.pageOptions = [
                {id: 1, name: "5", value: 5},
                {id: 2, name: "10", value: 10},
                {id: 3, name: "20", value: 20},
                {id: 4, name: "50", value: 50}
            ];
            $scope.pageSize = $scope.pageOptions[0];

            $scope.pageSizeListCard = $scope.pageOptions[0];

            $scope.currentPage = 1;
            $scope.currentPageCard = 1;
            $scope.isSort = false;
            $scope.sortField = "createDate";

            $scope.pageChanged = function () {
                $scope.getListPaymentHistory();
            };

            $scope.pageChangedCard = function () {
                $scope.getListCard();
            };

            $scope.recordChangedCard = function () {
                $scope.currentPageCard = 1;
                $scope.getListCard();
            };

            $scope.recordChanged = function () {
                $scope.currentPage = 1;
                $scope.getListPaymentHistory();
            };

            $scope.doSort = function (sortCase) {
                $scope.getListPaymentHistory(sortCase);
            };

            $scope.formatDateTime = function (date) {
                return Util.formatDateBasedOnDiff(date, "", $scope.currentUser.lang, $scope.currentUser.time_zone);
            };

            var param = {
                payment_type: 0,
                asc_sort: false,
                page_size: 20,
                page_number: 1,
                sort_field: "createDate"
            };

            //get list payment history
            $scope.getListPaymentHistory = function (sortCase) {
                $scope.team_id = $scope.currentUser.team_id;
                if (sortCase) {
                    if ($scope.sortField === sortCase) {
                        $scope.isSort = !$scope.isSort;
                    } else {
                        $scope.isSort = true;
                    }
                    param.asc_sort = $scope.isSort;
                    param.sort_field = sortCase;
                    $scope.sortField = sortCase;
                }
                param.page_number = $scope.currentPage;
                param.page_size = $scope.pageSize.value;

                Util.createRequest(configServer.API_URL + "/payments/team/" + $scope.team_id + "/histories", "GET", param, function (response) {
                    var status = response.status;
                    if (status === 200) {
                        $scope.results = [];
                        $scope.items = response.data.content;
                        console.log($scope.items);
                        
                        $scope.totalItemsPayment = response.data.total_elements;
                        $scope.totalPage = Math.ceil($scope.totalItemsPayment / $scope.pageSize.value);

                        $scope.items.forEach(function (item) {
                            var paymentInfo = {
                              createdDate: $scope.formatDateTime(item.create_date),
                              totalPrice: item.total_price,
                              // user_price_id: item.user_price.user_price_id,
                              // storage_price_id: item.storage_price.storage_price_id,
                              currency: item.pricing_package.currency,
                              payment_info_id: item.payment_info_id,
                              status: '',
                              statusTranslate: '',
                            };
                            console.log('paymentInfo', paymentInfo);

                            if (item.pricing_package.currency === 'VND') {
                              paymentInfo.currencyInfo = currencyUnit.VND;
                            } else if (item.pricing_package.currency === 'YEN') {
                              paymentInfo.currencyInfo = currencyUnit.YEN;
                            } else {
                              paymentInfo.currencyInfo = currencyUnit.USD;
                            }

                            // handle status
                            if (item.status === 1) {
                                paymentInfo.status = "Succeeded";
                                paymentInfo.statusTranslate = Util.translate("LABEL.SUCCEEDED");
                            }
                            if (item.status === 2) {
                                paymentInfo.status = "Failed";
                                paymentInfo.statusTranslate = Util.translate("LABEL.FAILED");
                            }
                            $scope.results.push(paymentInfo);
                        });

                        
                    } else {
                        Util.createToast({className: 'danger', content: 'SERVER_ERROR.' + status});
                    }
                }, function (error) {
                    Util.createToast({
                        className: 'danger',
                        content: 'SERVER_ERROR.' + error.status
                    });
                });
            };

            $scope.getListPaymentHistory();

            //get list card
            $scope.getListCard = function () {
                $scope.team_id = $scope.currentUser.team_id;
                var param = {
                    page_number: $scope.currentPageCard,
                    page_size: $scope.pageSizeListCard.value
                };

                Util.createRequest(configServer.API_URL + "/payments/cards", "GET", param, function (response) {
                    var status = response.status;
                    if (status === 200) {
                        if ($scope.currentUser.payment_type === paymentType.ONLINE) {
                            if (response.data.content.length === 0 && AppConfig.TURN_ON_ADD_CARD) {
                                Util.createToast({className: 'danger', content: 'TEAM_PAYMENT.CREATE_CARD_MGS'});
                            }
                            $scope.listCard = response.data.content;
                            $scope.totalItemsCard = response.data.total_elements;
                            $scope.totalPage = Math.ceil($scope.totalItemsCard / $scope.pageSizeListCard.value);
                        }
                    } else {
                        Util.createToast({className: 'danger', content: 'SERVER_ERROR.' + status});
                    }
                }, function (error) {
                    Util.createToast({
                        className: 'danger',
                        content: 'SERVER_ERROR.' + error.status
                    });
                });
            };

            $scope.getListCard();

            //get card type
            $scope.getCardType = function (number) {

                var content;
                switch (number) {
                    case cardType.UNKNOWN.id:
                        content = cardType.UNKNOWN.value;
                        break;
                    case cardType.VISA.id:
                        content = cardType.VISA.value;
                        break;
                    case cardType.MASTERCARD.id:
                        content = cardType.MASTERCARD.value;
                        break;
                    case cardType.AMERICAN_EXPRESS.id:
                        content = cardType.AMERICAN_EXPRESS.value;
                        break;
                    case cardType.DINERS_CLUB.id:
                        content = cardType.DINERS_CLUB.value;
                        break;
                    case cardType.DISCOVER.id:
                        content = cardType.DISCOVER.value;
                        break;
                    case cardType.JCB.id:
                        content = cardType.JCB.value;
                        break;
                    case cardType.UNIONPAY.id:
                        content = cardType.UNIONPAY.value;
                        break;
                    default:
                        content = cardType.UNKNOWN.value;
                        break;
                }
                return content;
            };

            $scope.selectedCard = {
                id: ''
            };
            $scope.totalItemsCard = 10;

            $scope.$on("get_list_card", getListCard);

            function getListCard(event, value) {
                $scope.currentPageCard = 1;
                $scope.getListCard();
                $scope.selectedCard.id = '';
            }

            //change radio card
            $scope.checkChangRadio = function (card) {
                if (card.is_active === 1) {
                    return;
                } else {
                    $scope.openModal(card.card_id);
                }
            };

            // active card
            $scope.openModal = function (cardId) {
                return $uibModal.open({
                    backdrop: 'static',
                    keyboard: false,
                    templateUrl: 'components/modal-template/confirm_active_modal.html',
                    controller: ['$scope', '$uibModalInstance', '$translate', '$rootScope', function ($scope, $uibModalInstance, $translate, $rootScope) {
                        $translate(['COMMON.BUTTON_CANCEL', 'COMMON.BUTTON_OK', 'TEAM_PAYMENT.ACTIVE', 'TEAM_PAYMENT.ACTIVE_MSG']).then(function (translations) {

                            $scope.opts = {
                                title: translations['TEAM_PAYMENT.ACTIVE'],
                                message: translations['TEAM_PAYMENT.ACTIVE_MSG'],
                                lblAccept: translations['COMMON.BUTTON_OK'],
                                lblDismiss: translations['COMMON.BUTTON_CANCEL']
                            };

                            $scope.onClose = function () {
                                $uibModalInstance.close();
                                $rootScope.$broadcast("get_list_card");
                            };

                            $scope.onAccept = function () {
                                $rootScope.$broadcast("is_loading_spinner");
                                Util.createRequest(configServer.API_URL + "/payments/card/" + cardId, "PUT", {}, function (response) {
                                    if (response.status === 200) {
                                        Util.createToast({
                                            className: 'success',
                                            content: 'COMMON.MESSAGE.ACTIVE_SUCCESS_MESSAGE'
                                        });
                                        $rootScope.$broadcast("not_loading_spinner");
                                    } else {
                                        if (response.status === 2713) {
                                            var errCode = response.data.split(" - ");

                                            var errorText = Util.replaceTranslateStripError("STRIPE_ERROR." + errCode[0], 'CARD_INFO.ERROR_CODE.ACTIVATE_CARD_FAIL')

                                            Util.createToast({
                                                className: 'danger',
                                                content: errorText
                                            });
                                        } else {
                                            Util.createToast({
                                                className: 'danger',
                                                content: 'SERVER_ERROR.' + response.status
                                            });
                                        }
                                        $rootScope.$broadcast("not_loading_spinner");
                                    }
                                    $rootScope.$broadcast("get_list_card");
                                }, function (error) {
                                    Util.createToast({
                                        className: 'danger',
                                        content: 'SERVER_ERROR.' + error.status
                                    });
                                });
                                $uibModalInstance.close();
                            }
                        });

                    }]
                });
            };

            $scope.isShowLoading = false;
            $scope.$on("is_loading_spinner", isLoadingSpinner);

            function isLoadingSpinner(event, value) {
                $scope.isShowLoading = true;
            }

            $scope.$on("not_loading_spinner", notLoadingSpinner);

            function notLoadingSpinner(event, value) {
                $scope.isShowLoading = false;
            }

            // delete card
            $scope.openModalDelete = function (cardId) {
                return $uibModal.open({
                    backdrop: 'static',
                    keyboard: false,
                    templateUrl: 'components/modal-template/confirm_delete_modal.html',
                    controller: ['$scope', '$uibModalInstance', '$translate', '$rootScope', function ($scope, $uibModalInstance, $translate, $rootScope) {
                        $translate(['COMMON.BUTTON_CANCEL', 'COMMON.BUTTON_OK', 'TEAM_PAYMENT.DELETE_CARD', 'TEAM_PAYMENT.DELETE_CARD_MSG']).then(function (translations) {

                            $scope.opts = {
                                title: translations['TEAM_PAYMENT.DELETE_CARD'],
                                message: translations['TEAM_PAYMENT.DELETE_CARD_MSG'],
                                lblAccept: translations['COMMON.BUTTON_OK'],
                                lblDismiss: translations['COMMON.BUTTON_CANCEL']
                            };

                            $scope.onClose = function () {
                                $uibModalInstance.close();
                            };

                            $scope.onAccept = function () {
                                $rootScope.$broadcast("is_loading_spinner");
                                Util.createRequest(configServer.API_URL + "/payments/card/" + cardId, "DELETE", {}, function (response) {
                                    if (response.status === 200) {
                                        Util.createToast({
                                            className: 'success',
                                            content: 'COMMON.MESSAGE.DELETE_SUCCESS_MESSAGE'
                                        });
                                        $rootScope.$broadcast("not_loading_spinner");
                                    } else {
                                        if (response.status === 2713) {
                                            var errCode = response.data.split(" - ");

                                            var errorText = Util.replaceTranslateStripError("STRIPE_ERROR." + errCode[0], 'CARD_INFO.ERROR_CODE.DELETE_CARD_FAIL')

                                            Util.createToast({
                                                className: 'danger',
                                                content: errorText
                                            });
                                        } else {
                                            Util.createToast({
                                                className: 'danger',
                                                content: 'SERVER_ERROR.' + response.status
                                            });
                                        }
                                        $rootScope.$broadcast("not_loading_spinner");
                                    }
                                    $rootScope.$broadcast("get_list_card");
                                }, function (error) {
                                    Util.createToast({
                                        className: 'danger',
                                        content: 'SERVER_ERROR.' + error.status
                                    });
                                });

                                $uibModalInstance.close();
                            }
                        });

                    }]
                });
            };

            $scope.goBack = function () {
                window.history.back();
            };

            $scope.currentLang = session.getUser().lang;

            $scope.cardInfo = {
                cardholderName: "",
                cardNumber: "",
                cvc: "",
                address1: "",
            };
            // Create a Stripe client.
            var stripe = Stripe(configServer.PUBLIC_KEY_STRIPE);

            // Create an instance of Elements.
            var elements = stripe.elements();

            // Custom styling can be passed to options when creating an Element.
            // (Note that this demo uses a wider set of styles than the guide below.)
            var style = {
                base: {
                    color: '#32325d',
                    fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
                    fontSmoothing: 'antialiased',
                    fontSize: '16px',
                    '::placeholder': {
                        color: '#aab7c4'
                    }
                },
                invalid: {
                    color: '#fa755a',
                    iconColor: '#fa755a'
                }
            };

            // Create an instance of the card Element.
            var card = elements.create('card', {style: style, hidePostalCode: true});

            // Add an instance of the card Element into the `card-element` <div>.
            card.mount('#card-element');

            // Handle real-time validation errors from the card Element.
            card.on('change', function (event) {
                $rootScope.$broadcast("handleInputStripe", event);
                var displayError = document.getElementById('card-errors');
                if (event.error) {
                    displayError.textContent = Util.replaceTranslateStripError("CARD_INFO.ERROR_CODE." + event.error.code.toUpperCase());
                } else {
                    displayError.textContent = '';
                }
            });

            $scope.$on('handleInputStripe', checkInput);
            $scope.isComplete = false

            function checkInput(event, item) {
                $scope.isComplete = item.complete;
                $scope.$apply();
            }

            $scope.$on('handleErrorCreateToken', checkError);

            function checkError(event, item) {
                if (item.error.code !== undefined && item.error.code !== null) {
                    $scope.submitting = false;
                    $scope.$apply();
                }
            }

            // Handle form submission.
            $scope.submitting = false;
            var form = document.getElementById('payment-card');
            form.addEventListener('click', function (event) {
                $scope.submitting = true;
                event.preventDefault();
                var data = {
                    name: $scope.cardInfo.cardholderName,
                    address_line1: $scope.cardInfo.address1,
                };
                stripe.createToken(card, data).then(function (result) {
                    if (result.error) {
                        // Inform the user if there was an error.
                        var errorElement = document.getElementById('card-errors');
                        errorElement.textContent = Util.replaceTranslateStripError("CARD_INFO.ERROR_CODE." + result.error.code.toUpperCase());
                        $rootScope.$broadcast("handleErrorCreateToken", result);
                    } else {
                        // Send the token to your server.
                        $scope.createCard(result.token.id);
                    }
                });
            });

            // show loading spinner
            $scope.isShowLoading = false;
            $scope.createCard = function (tokenId) {
                $scope.isShowLoading = true;
                var param = {
                    card_token: tokenId,
                    user_price_id: 0,
                    storage_price_id: 0,
                };

                Util.createRequest(configServer.API_URL + "/teams/" + session.getUser().team_id, "GET", {}, function (response) {
                    if (response && response.status === 200) {
                        param.storage_price_id = response.data.storage_price_id;
                        param.user_price_id = response.data.user_price_id;
                        Util.createRequest(configServer.API_URL + "/payments/team/" + session.getUser().team_id + "/new_card",
                            "POST", param, function (response) {
                                if (response && response.status === 200) {
                                    Util.createToast({
                                        className: 'success',
                                        content: 'COMMON.MESSAGE.ADD_SUCCESS_MESSAGE'
                                    });
                                    $scope.getListCard();
                                    $scope.cancelAddCard();
                                    $scope.isShowLoading = false;
                                    $scope.submitting = false;
                                } else {
                                    if (response.status === 2713) {
                                        var errCode = response.data.split(" - ");

                                        var errorText = Util.replaceTranslateStripError("STRIPE_ERROR." + errCode[0], 'CARD_INFO.ERROR_CODE.CARD_DECLINED')

                                        Util.createToast({
                                            className: 'danger',
                                            content: errorText
                                        });
                                    } else {
                                        Util.createToast({
                                            className: 'danger',
                                            content: 'SERVER_ERROR.' + response.status
                                        });
                                    }
                                    $scope.submitting = false;
                                    $scope.isShowLoading = false;
                                }
                            }, function (error) {
                                $scope.submitting = false;
                                $scope.isShowLoading = false;
                                Util.createToast({
                                    className: 'danger',
                                    content: 'SERVER_ERROR.' + error.status
                                });
                            });
                    } else {
                        Util.createToast({
                            className: 'danger',
                            content: 'SERVER_ERROR.' + response.status
                        });
                        $scope.submitting = false;
                        $scope.isShowLoading = false;
                    }
                }, function (error) {
                    $scope.isShowLoading = false;
                    $scope.submitting = false;
                    Util.createToast({
                        className: 'danger',
                        content: 'SERVER_ERROR.' + error.status
                    });
                });
            }

            $scope.isShowAddCard = false;
            $scope.openAddCard = function () {
                this.payment.$setPristine();
                this.payment.$setUntouched();
                $scope.cardInfo = {
                    cardholderName: "",
                    cardNumber: "",
                    cvc: "",
                    address1: "",
                };
                $scope.isShowAddCard = true;
            };
            $scope.cancelAddCard = function () {
                card.clear();
                $scope.isShowAddCard = false;
            };
        }
    ]);
