angular.module('signUp', ['vcRecaptcha']).controller('SignUpCtrl', [
  '$scope',
  '$state',
  'Util',
  'AppConfig',
  '$uibModal',
  'session',
  'Patterns',
  '$http',
  'serviceKeyType',
  'configServer',
  '$rootScope',
  '$stateParams',
  'packageUpgrade',
  '$location',
  'currencyUnit',
  'countryCode',
  'currencyInfo',
  function (
    $scope,
    $state,
    Util,
    AppConfig,
    $uibModal,
    session,
    Patterns,
    $http,
    serviceKeyType,
    configServer,
    $rootScope,
    $stateParams,
    packageUpgrade,
    $location,
    currencyUnit,
    countryCode,
    currencyInfo
  ) {
    $scope.language = session.getCurrentLanguage();
    $scope.submitting = false;
    $scope.signUpSuccess = false;
    $scope.showRequiredErr = false;
    $scope.email_pattern = Patterns.EMAIL_PATTERN;
    $scope.script_pattern = Patterns.SCRIPT_PATTERN;
    $scope.acceptPolicy = 1;
    $scope.recaptchaKey = configServer.RECAPTCHA_KEY;
    $scope.gRecaptchaResponse = '';
    $scope.signUpFormAddCard = false;
    $scope.signUpForm1 = true;
    $scope.package = $location.search().pk || PACKAGE_NAME.FREE;
    $scope.currency = $location.search().currency || CURRENCY.USD;
    $scope.billingCycle = $location.search().billing_cycle || BILLING_CYCLE.MONTHLY;

    $scope.isoCodeJapan = countryCode.JPN;
    $scope.currencyInfo;
    $scope.totalPrice = 0;
    $scope.packageDetail = null;
    $scope.numberOfUsers = 1;
    $scope.totalPackagePrice = 0;
    $scope.isAnnuallyBilling = $scope.billingCycle === BILLING_CYCLE.ANNUALLY;
    $scope.showAllFeatures = false;
    $scope.visibleFeatures = [];
    var numberOfUsersTimeoutId = null;
    // Set new value if input change
    $scope.$watch('numberOfUsers', function (newVal, oldVal) {
      console.log('newVal', newVal);
      console.log('oldVal', oldVal);

      // Cancel previous timeout if it exists
      if (numberOfUsersTimeoutId) {
        clearTimeout(numberOfUsersTimeoutId);
        numberOfUsersTimeoutId = null;
      }

      // Kiểm tra nếu giá trị không hợp lệ (undefined hoặc nhỏ hơn minimum_user)
      // Check if newVal is undefined or less than minimum_user
      if (
        newVal === undefined ||
        ($scope.packageDetail &&
          $scope.packageDetail.minimum_user > 0 &&
          parseInt(newVal) < $scope.packageDetail.minimum_user)
      ) {
        // Set a timeout of 1 second to reset the value
        numberOfUsersTimeoutId = setTimeout(function () {
          $scope.$apply(function () {
            $scope.numberOfUsers = ($scope.packageDetail && $scope.packageDetail.minimum_user) || 1;
            console.log('Set numberOfUsers to', $scope.numberOfUsers);
          });
        }, 1000);
      } else {
        // Valid value, do not reset
        console.log('Valid value, keeping numberOfUsers as', newVal);
      }

      // Update features and price
      $scope.getVisibleFeatures();
      $scope.calculateTotalPrice($scope.packageDetail);
    });

    $scope.$watchGroup(['package', 'showAllFeatures'], function () {
      $scope.getVisibleFeatures();
    });

    $scope.createForm = {
      first_name: '',
      last_name: '',
      email: '',
      password: '',
      confirm_password: '',
    };

    /**
     * Lấy danh sách tính năng của gói hiện tại với các giá trị đã được thay thế
     */
    $scope.getCurrentPackageFeatures = function () {
      const currentPackage = $scope.package || 'FREE';
      const numberOfUsers = $scope.numberOfUsers || 1;
      const billingCycle = $scope.billingCycle || BILLING_CYCLE.MONTHLY;
      const packageFeatures = Util.generatePackageFeaturesConfig(
        currentPackage,
        numberOfUsers,
        billingCycle
      );
      return packageFeatures.features;
    };

    /**
     * Lấy danh sách tính năng hiển thị (3 tính năng đầu hoặc tất cả)
     */
    $scope.getVisibleFeatures = function () {
      const features = $scope.getCurrentPackageFeatures();
      $scope.visibleFeatures = $scope.showAllFeatures ? features : features.slice(0, 4);
    };

    /**
     * Chuyển đổi trạng thái hiển thị tất cả tính năng
     */
    $scope.toggleFeatures = function () {
      $scope.showAllFeatures = !$scope.showAllFeatures;
      $scope.getVisibleFeatures();
    };

    $scope.calculateTotalPrice = function (packageDetail) {
      if (!packageDetail || !packageDetail.minimum_user) {
        return 0;
      }
      // Khởi tạo số người dùng nếu chưa có
      // if (!$scope.numberOfUsers || $scope.numberOfUsers < packageDetail.minimum_user) {
      //   setTimeout(function () {
      //     // Đặt lại số người dùng về giá trị tối thiểu
      //     $scope.$apply(function () {
      //       $scope.numberOfUsers = packageDetail.minimum_user;
      //     });
      //   }, 500);
      // $scope.numberOfUsers = packageDetail.minimum_user;
      // console.log('$scope.numberOfUsers', $scope.numberOfUsers);

      // }

      // if ($scope.numberOfUsers < packageDetail.minimum_user) {
      //   $scope.numberOfUsers = packageDetail.minimum_user;
      // }

      // Lấy số người dùng, đảm bảo không nhỏ hơn số tối thiểu
      const usersCount = Math.max($scope.numberOfUsers, packageDetail.minimum_user);
      // Tính giá cơ bản: pricePerUser * minUsers
      let basePrice = packageDetail.price * packageDetail.minimum_user;

      // Tính giá cho thêm người dùng
      let additionalPrice = 0;
      if (usersCount > packageDetail.minimum_user) {
        const additionalUsers = usersCount - packageDetail.minimum_user;
        additionalPrice = additionalUsers * packageDetail.price;
      }

      // Tổng giá = giá cơ bản + giá bổ sung
      let totalPrice = basePrice + additionalPrice;

      // Nhân với 12 tháng
      if ($scope.isAnnuallyBilling) {
        totalPrice = totalPrice * 12;
      }

      // Round to 2 decimal places
      $scope.totalPackagePrice = Math.round(totalPrice * 100) / 100;

      return $scope.totalPackagePrice;
    };

    $scope.getPackageDetail = function ({ package_type, billing_cycle, currency }) {
      var params = {
        pricing_code: package_type || $scope.package || PACKAGE_NAME.FREE,
        billing_cycle: billing_cycle || $scope.billingCycle || BILLING_CYCLE.MONTHLY,
        currency: currency || $scope.currency || CURRENCY.USD,
        console_type: 'SECURE_MAIL',
      };
      Util.createRequest(
        configServer.API_URL + '/pricing/package/detail/public',
        'GET',
        params,
        function (response) {
          var status = response && response.status;
          if (response && response.status === 200) {
            var data = response && response.data;
            $scope.packageDetail = data;

            $scope.numberOfUsers = data.minimum_user || 1;
            $scope.getVisibleFeatures();
            $scope.calculateTotalPrice(data);

            $scope.packageName = data.name || '';
            $scope.price = data.price || 0;
            $scope.currencyType = data.currency || '';

            if ($scope.currencyType === 'YEN') {
              $scope.currencyInfo = currencyUnit.YEN;
            } else if ($scope.currencyType === 'VND') {
              $scope.currencyInfo = currencyUnit.VND;
            } else {
              $scope.currencyInfo = currencyUnit.USD;
            }
          } else {
            Util.createToast({
              className: 'danger',
              content: 'SERVER_ERROR.' + status,
            });
          }
        },
        function (errResponse) {
          Util.createToast({
            className: 'danger',
            content: 'SERVER_ERROR.' + errResponse.status,
          });
        }
      );
    };

    $scope.getPackageDetail({
      package_type: $scope.package,
      billing_cycle: $scope.billingCycle,
      currency: $scope.currency,
    });

    // $scope.getTrialCampaign = function () {
    //   Util.createRequest(
    //     configServer.API_URL + '/companies/' + configServer.COMPANY_ID + '/campaign',
    //     'GET',
    //     {},
    //     function (response) {
    //       console.log('response', response);

    //       var status = response.status;
    //       if (status === 200) {
    //         $scope.isTrialCampaign = response.data;
    //       } else {
    //         Util.createToast({
    //           className: 'danger',
    //           content: 'SERVER_ERROR.' + status,
    //         });
    //       }
    //     },
    //     function (errResponse) {
    //       Util.createToast({
    //         className: 'danger',
    //         content: 'SERVER_ERROR.' + errResponse.status,
    //       });
    //     }
    //   );
    // };
    // $scope.getTrialCampaign();

    $scope.createUser = function (valid) {
      if (!valid) {
        $scope.showRequiredErr = true;
        return;
      }
      $scope.submitting = true;
      var currentTimeZoneOffsetInHours = 0 - new Date().getTimezoneOffset() / 60;

      var params = {
        company_id: configServer.COMPANY_ID,
        first_name: $scope.createForm.first_name,
        last_name: $scope.createForm.last_name,
        email_address: $scope.createForm.email,
        // password_hash: AESEncrypter.encode($scope.createForm.password),
        // confirm_password: AESEncrypter.encode($scope.createForm.confirm_password),
        password_hash: Util.MD5($scope.createForm.password),
        confirm_password: Util.MD5($scope.createForm.confirm_password),
        time_zone: currentTimeZoneOffsetInHours,
        // default_package: true,
        code: $scope.package || PACKAGE_NAME.FREE,
        billing_cycle: $scope.billingCycle || BILLING_CYCLE.MONTHLY,
        currency: $scope.currency || CURRENCY.USD,
        console_type: 'SECURE_MAIL',
        number_of_user: $scope.numberOfUsers || 1,
        use_secure_mail: true,
        use_secure_drive: false,
      };
      $scope.getCountryCode(params);
    };

    $scope.getCountryCode = function (params) {
      if (
        $scope.currency &&
        ($scope.currency.toUpperCase() === currencyInfo.JPY ||
          $scope.currency.toUpperCase() === currencyInfo.YEN ||
          $scope.currency.toUpperCase() === currencyInfo.USD)
      ) {
        // $scope.countryCode =
        //   $scope.currency.toUpperCase() === currencyInfo.JPY ||
        //   $scope.currency.toUpperCase() === currencyInfo.YEN
        //     ? $scope.isoCodeJapan
        //     : null;
        $scope.countryCode =
          $scope.currency.toUpperCase() === currencyInfo.JPY ||
          $scope.currency.toUpperCase() === currencyInfo.YEN
            ? $scope.isoCodeJapan
            : 'EN';

        $scope.validatePackage(params, $scope.countryCode);
      } else {
        Util.createRequest(configServer.API_URL + '/country', 'GET', {}, function (response) {
          $scope.countryCode = response.data.country_code;
          $scope.validatePackage(params, $scope.countryCode);
        });
      }
    };

    $scope.validatePackage = function (params, code) {
      // if ($scope.package && $scope.package.toUpperCase() === packageUpgrade.PRO) {

      // if (code === $scope.isoCodeJapan) {
      //   params.user_price_id = configServer.USER_PRICE_ID_PRO_JA;
      //   params.storage_price_id = configServer.STORAGE_PRICE_ID_PRO_JA;
      // } else {
      //   params.user_price_id = configServer.USER_PRICE_ID_PRO;
      //   params.storage_price_id = configServer.STORAGE_PRICE_ID_PRO;
      // }

      if (
        ($scope.package && $scope.package.toUpperCase() === PACKAGE_NAME.FREE) ||
        !$scope.package
      ) {
        params.package_type = PACKAGE_NAME.FREE;
        params.billing_cycle = BILLING_CYCLE.MONTHLY;
        params.currency = $scope.currency === CURRENCY.YEN ? CURRENCY.YEN : CURRENCY.USD;
        $scope.signUpUser(params);
      } else {
        $scope.signUpFormAddCard = true;
        $scope.signUpForm1 = false;
        $scope.submitting = false;

        // create style input card
        $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.submittingCard = false;
            $scope.submitting = false;
            $scope.$apply();
          }
        }

        // Handle form submission.
        $scope.submittingCard = false;
        var form = document.getElementById('payment-card');
        form.addEventListener('click', function (event) {
          $scope.submittingCard = 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 {
              $scope.submittingCard = false;
              $scope.submitting = false;
              // Send the token to your server.
              params.card_token = result.token.id;
              //show modal confirm
              $scope.showModalConfirm(params, code);
            }
          });
        });

        $scope.cancelAddCard = function () {
          card.clear();
          $scope.signUpForm1 = true;
          $scope.signUpFormAddCard = false;
        };
      }
      // } else {
      // if ($scope.isTrialCampaign) {
      //   if (code === $scope.isoCodeJapan) {
      //     params.user_price_id = configServer.USER_PRICE_ID_PRO_JA;
      //     params.storage_price_id = configServer.STORAGE_PRICE_ID_PRO_JA;
      //   } else {
      //     params.user_price_id = configServer.USER_PRICE_ID_PRO;
      //     params.storage_price_id = configServer.STORAGE_PRICE_ID_PRO;
      //   }
      // } else {
      //   if (code === $scope.isoCodeJapan) {
      //     params.user_price_id = configServer.USER_PRICE_ID_FREE_JA;
      //     params.storage_price_id = configServer.STORAGE_PRICE_ID_FREE_JA;
      //   } else {
      //     params.user_price_id = configServer.USER_PRICE_ID_FREE;
      //     params.storage_price_id = configServer.STORAGE_PRICE_ID_FREE;
      //   }
      // }
      //   $scope.signUpUser(params);
      // }
    };

    // $scope.validatePackage = function (params, code) {
    //   if ($scope.package && $scope.package.toUpperCase() === packageUpgrade.PRO) {
    //     console.log('params', params);
    //     console.log('code', code);
    //
    //     if (code === $scope.isoCodeJapan) {
    //       params.user_price_id = configServer.USER_PRICE_ID_PRO_JA;
    //       params.storage_price_id = configServer.STORAGE_PRICE_ID_PRO_JA;
    //     } else {
    //       params.user_price_id = configServer.USER_PRICE_ID_PRO;
    //       params.storage_price_id = configServer.STORAGE_PRICE_ID_PRO;
    //     }
    //
    //     if ($scope.isTrialCampaign) {
    //       $scope.signUpUser(params);
    //     } else {
    //       $scope.signUpFormAddCard = true;
    //       $scope.signUpForm1 = false;
    //
    //       // create style input card
    //       $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.submittingCard = false;
    //           $scope.submitting = false;
    //           $scope.$apply();
    //         }
    //       }
    //
    //       // Handle form submission.
    //       $scope.submittingCard = false;
    //       var form = document.getElementById('payment-card');
    //       form.addEventListener('click', function (event) {
    //         $scope.submittingCard = true;
    //         event.preventDefault();
    //         var data = {
    //           name: $scope.cardInfo.cardholderName,
    //           address_line1: $scope.cardInfo.address1,
    //         };
    //         stripe.createToken(card, data).then(function (result) {
    //           console.log('result', 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 {
    //             $scope.submittingCard = false;
    //             $scope.submitting = false;
    //             // Send the token to your server.
    //             params.card_token = result.token.id;
    //             //show modal confirm
    //             $scope.showModalConfirm(params, code);
    //           }
    //         });
    //       });
    //
    //       $scope.cancelAddCard = function () {
    //         card.clear();
    //         $scope.signUpForm1 = true;
    //         $scope.signUpFormAddCard = false;
    //       };
    //     }
    //   } else {
    //     if ($scope.isTrialCampaign) {
    //       if (code === $scope.isoCodeJapan) {
    //         params.user_price_id = configServer.USER_PRICE_ID_PRO_JA;
    //         params.storage_price_id = configServer.STORAGE_PRICE_ID_PRO_JA;
    //       } else {
    //         params.user_price_id = configServer.USER_PRICE_ID_PRO;
    //         params.storage_price_id = configServer.STORAGE_PRICE_ID_PRO;
    //       }
    //     } else {
    //       if (code === $scope.isoCodeJapan) {
    //         params.user_price_id = configServer.USER_PRICE_ID_FREE_JA;
    //         params.storage_price_id = configServer.STORAGE_PRICE_ID_FREE_JA;
    //       } else {
    //         params.user_price_id = configServer.USER_PRICE_ID_FREE;
    //         params.storage_price_id = configServer.STORAGE_PRICE_ID_FREE;
    //       }
    //     }
    //     $scope.signUpUser(params);
    //   }
    // };

    $scope.showModalConfirm = function (params, code) {
      return $uibModal.open({
        backdrop: 'static',
        templateUrl: 'components/modal-template/payment_confirm_modal.html',
        resolve: {
          packageDetail: function () {
            return $scope.packageDetail;
          },
          params: function () {
            return params;
          },
          currencyInfo: function () {
            return $scope.currencyInfo;
          },
          totalPrice: function () {
            return $scope.totalPackagePrice;
          },
          numberOfUsers: function () {
            return $scope.numberOfUsers;
          },
          cardInfo: function () {
            return $scope.cardInfo;
          },
        },
        controller: [
          '$scope',
          '$uibModalInstance',
          '$translate',
          '$rootScope',
          'session',
          '$state',
          'Util',
          '$filter',
          'countryCode',
          'packageDetail',
          'params',
          'currencyInfo',
          'totalPrice',
          'numberOfUsers',
          'cardInfo',
          function (
            $scope,
            $uibModalInstance,
            $translate,
            $rootScope,
            session,
            $state,
            Util,
            $filter,
            countryCode,
            packageDetail,
            params,
            currencyInfo,
            totalPrice,
            numberOfUsers,
            cardInfo
          ) {
            $scope.packageDetail = packageDetail;
            params.number_of_user = numberOfUsers;
            $scope.params = params;
            $scope.currencyInfo = currencyInfo;
            $scope.totalPrice = totalPrice;
            $scope.numberOfUsers = numberOfUsers;
            $scope.cardInfo = cardInfo;
            $translate(['COMMON.BUTTON_CANCEL', 'COMMON.BUTTON_OK']).then(function (translations) {
              $scope.isoCodeJapan = countryCode.JPN;

              //get ios code
              // $scope.getPricePackage = function () {
              //   Util.createRequest(
              //     configServer.API_URL + '/usage_package/packages/public',
              //     'GET',
              //     {
              //       company_id: configServer.COMPANY_ID,
              //       currency: code === $scope.isoCodeJapan ? 'YEN' : 'USD',
              //     },
              //     function (response) {
              //       console.log('response', response);
              //       var status = response.status;
              //       if (status === 200) {
              //         $scope.items = response.data;
              //         $scope.results = {
              //           pro: {},
              //           standard: {},
              //         };
              //         $scope.items.storage_prices.forEach(function (item) {
              //           if (code === $scope.isoCodeJapan) {
              //             if (item.storage_price_id === configServer.STORAGE_PRICE_ID_PRO_JA) {
              //               $scope.results.pro.storage_price = item;
              //             }
              //           } else {
              //             if (item.storage_price_id === configServer.STORAGE_PRICE_ID_PRO) {
              //               $scope.results.pro.storage_price = item;
              //             }
              //           }
              //         });
              //         $scope.items.user_prices.forEach(function (item) {
              //           if (code === $scope.isoCodeJapan) {
              //             if (item.user_price_id === configServer.USER_PRICE_ID_PRO_JA) {
              //               $scope.results.pro.user_price = item;
              //             }
              //           } else {
              //             if (item.user_price_id === configServer.USER_PRICE_ID_PRO) {
              //               $scope.results.pro.user_price = item;
              //             }
              //           }
              //         });
              //         $scope.pro = $scope.results.pro;
              //         // $scope.standard = $scope.results.standard;
              //         $scope.totalPrice = 0;
              //         $scope.packageName = '';
              //         if (
              //           params.user_price_id === $scope.pro.user_price.user_price_id &&
              //           params.storage_price_id === $scope.pro.storage_price.storage_price_id
              //         ) {
              //           $scope.packageName = packageUpgrade.PRO;
              //           if ($scope.pro.user_price) {
              //             $scope.totalPrice += $scope.pro.user_price.price;
              //           }
              //           if ($scope.pro.storage_price) {
              //             $scope.totalPrice += $scope.pro.storage_price.price;
              //           }
              //           // $scope.totalPrice = $filter('currency')($scope.totalPrice, '');
              //           if ($scope.pro.user_price.currency === 'VND') {
              //             $scope.currencyType = currencyUnit.VND;
              //           } else if ($scope.pro.user_price.currency === 'YEN') {
              //             $scope.currencyType = currencyUnit.YEN;
              //           } else {
              //             $scope.currencyType = currencyUnit.USD;
              //           }
              //         }
              //       } else {
              //         Util.createToast({
              //           className: 'danger',
              //           content: 'SERVER_ERROR.' + status,
              //         });
              //       }
              //     },
              //     function (errResponse) {
              //       Util.createToast({
              //         className: 'danger',
              //         content: 'SERVER_ERROR.' + errResponse.status,
              //       });
              //     }
              //   );
              // };
              //
              // $scope.getPricePackage();
              $scope.opts = {
                lblAccept: translations['COMMON.BUTTON_OK'],
                lblDismiss: translations['COMMON.BUTTON_CANCEL'],
              };

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

              $scope.onAccept = function () {
                $uibModalInstance.close();
                $rootScope.$broadcast('sign_up_user', params);
              };
            });
          },
        ],
      });
    };

    function getNumberUserByPackageType(packageType) {
      if (!packageType) {
        return 0;
      }

      switch (packageType) {
        case PACKAGE_NAME.TEAM:
          return 5;
        case PACKAGE_NAME.BUSINESS:
          return 20;
        default:
          return 0;
      }
    }

    $scope.$on('sign_up_user', signUpUser);

    function signUpUser(event, value) {
      $scope.signUpUser(value);
    }

    //sign up account
    $scope.signUpUser = function (param) {
      console.log('param', param);
      $scope.submitting = true;
      // Service Use Account - 1: Secure Drive, 2:Secure Mail
      // param.service_key = serviceKeyType.SECURE_MAIL;
      Util.createRequest(
        configServer.API_URL + '/teams/signup',
        'POST',
        param,
        function (response) {
          if (response.status === 200) {
            Util.createToast({
              className: 'success',
              content: 'COMMON.MESSAGE.REGISTER_SUCCESS',
            });
            $scope.signUpSuccess = true;
            if (dataLayer) {
              dataLayer.push({
                event: 'sign_up_success',
              });
            }
          } else {
            if (response.status === 2713) {
              var errCode = response.data.split(' - ');

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

              Util.createToast({
                className: 'danger',
                content: errorText,
              });
            } else {
              Util.createToast({ className: 'danger', content: 'SERVER_ERROR.' + response.status });
            }
          }
          $scope.submittingCard = false;
          $scope.submitting = false;
        },
        function (errResponse) {
          $scope.submitting = false;
          $scope.submittingCard = false;
          Util.createToast({
            className: 'danger',
            content: 'SERVER_ERROR.' + errResponse.status,
          });
        }
      );
    };
    // wrapAgreement register license
    $scope.openModal = function (isTermOfService) {
      return $uibModal
        .open({
          templateUrl: 'components/modal-template/accept_agreement_modal.html',
          size: 'xl',
          controller: [
            '$scope',
            '$uibModalInstance',
            '$translate',
            function ($scope, $uibModalInstance, $translate) {
              $translate(['ACCOUNT.TERMS_AND_CONDITIONS', 'ACCOUNT.PRIVACY_POLICY']).then(function (
                translations
              ) {
                $scope.isTermOfService = isTermOfService;
                $scope.opts = {
                  title: $scope.isTermOfService
                    ? translations['ACCOUNT.TERMS_AND_CONDITIONS']
                    : translations['ACCOUNT.PRIVACY_POLICY'],
                  message: '',
                };

                $scope.onClose = function () {
                  $uibModalInstance.close();
                };
              });
            },
          ],
        })
        .result.catch(function (resp) {
          if (['cancel', 'backdrop click', 'escape key press'].indexOf(resp) === -1) {
            throw resp;
          }
        });
    };

    $scope.doRedirect = function (page) {
      $state.go(page);
    };

    $scope.openNewTab = function (url) {
      window.open(url, '_blank');
    };
  },
]);
