///define(['app'], function (app) {
(function () {

  var app = angular.module("myApp");

  app.factory("myFactory", [
    '$rootScope', '$http', '$window', '$location', 'ngDialog', 'VS4Library',
    function ($rootScope, $http, $window, $location, ngDialog, VS4Library) {

      var svc = {};

      $rootScope._AppVersion = 0.3;

      svc.AppVersion = function () {
        return $rootScope._AppVersion;
      };

      //Not Share command
      svc.calcQuantityCalc = function (unitCalc, quantity, quantity2, quantity3, quantityBase, useUnit2AsCutMode) {
        var qty = 0;
        switch (Number(unitCalc)) {
          case 1:
            return quantity2;
          case 2:
            return quantity3;
          case 3: //เหมา
            return 1;
          case 4:// หน่วยหลัก
            return quantityBase;
          default:
            if (useUnit2AsCutMode === 1) {
              return quantity - quantity2;
            } else {
              return quantity;
            }
        }
      }

      svc.validDiscountText = function (iDiscountText, iDiscountDecimal, lastList) {
        return iDiscountTextList;
      }

      // Private Function ValidDiscountText(ByVal iDiscountText As String, Optional ByVal iDiscountDecimal As Integer = 5, Optional ByVal LastList As Boolean = False) As String
      //   Dim nd As String
      //   Dim d As String
      //   Dim PF As String
      //   Dim SF As String
      //   Dim DTRIM As String
      //   Dim i As Integer

      //     nd = ""
      //     'd = Trim$(Replace(Replace(Replace(Replace(Replace(iDiscountText, "@@", "@"), "%%", "%"), " ", ""), "-", ""), ",", ""))
      //     d = Trim$(Replace(Replace(Replace(Replace(iDiscountText, "@@", "@"), "%%", "%"), " ", ""), ",", ""))

      //     Select Case UCase$(d)
      //      Case "AU", "AN", "A54", "DU", "DN"
      //         If LastList Then nd = UCase$(d) Else nd = ""

      //      Case Else
      //         If Left$(d, 1) = "@" Then d = Right$(d, Len(d) - 1): PF = "@" Else PF = ""
      //         If Right$(d, 1) = "%" Then d = Left$(d, Len(d) - 1): SF = "%" Else SF = ""
      //         If SF = "%" Then PF = ""
      //         Dim DV As Double
      //         If PF = "" And SF = "" Then
      //             DV = std.StrVal2(d, 2)
      //          Else
      //             DV = std.StrVal2(d, iDiscountDecimal)
      //         End If

      //         If DV = 0 Then
      //             nd = ""
      //          Else
      //             If PF = "" And SF = "" Then
      //                 DTRIM = FormatNumber(DV, 2, vbTrue)
      //              Else
      //                 DTRIM = FormatNumber(DV, iDiscountDecimal, vbTrue)
      //             End If

      //             If InStr(1, DTRIM, ".") > 0 Then

      //                 For i = 1 To iDiscountDecimal
      //                     If Right$(DTRIM, 1) = "0" Then DTRIM = Left$(DTRIM, Len(DTRIM) - 1)
      //                     If Right$(DTRIM, 1) = "." Then Exit For
      //                 Next

      //                 If Right$(DTRIM, 1) = "." Then DTRIM = Left$(DTRIM, Len(DTRIM) - 1)
      //             End If

      //             nd = PF & DTRIM & SF
      //         End If

      //     End Select
      //     '    For i = 1 To iDiscountDecimal
      //     '        If Right$(nd, 1) = "0" Then nd = Left$(nd, Len(nd) - 1)
      //     '    Next
      //     '    If Right$(nd, 1) = "." Then nd = Left$(nd, Len(nd) - 1)
      //     ValidDiscountText = nd

      // End Function

      svc.validDiscountTextList = function (iDiscountTextList, iDiscountDecimal) {
        return iDiscountTextList;
      }

      // Function ValidDiscountTextList(ByVal iDiscountTextList As String, Optional ByVal iDiscountDecimal As Integer = 1) As String
      //   Dim d As String
      //   Dim nd As String
      //   Dim ad() As String
      //   Dim i As Long
      //   Dim li As Long
      //   Dim x As String
      //   Dim lad() As String

      //     d = Trim$(iDiscountTextList)
      //     nd = ""

      //     If d <> "" Then
      //         lad = Split(d, "&")
      //         For li = 0 To UBound(lad)
      //             ad = Split(lad(li), "+")
      //             For i = 0 To UBound(ad)
      //                 x = ValidDiscountText(Trim$(ad(i)), iDiscountDecimal, UBound(ad) = i)
      //                 If x <> "" Then
      //                     If nd = "" Then nd = x Else nd = nd & " +" & x
      //                 End If
      //             Next
      //         Next
      //     End If

      //     ValidDiscountTextList = Replace(nd, " ", "")

      // End Function

      svc.getValueDiscountText = function (iUnitPrice, iDiscountText, iQuantity) {
        var dc = 0;
        var pf = "";
        var sf = "";
        var d = iDiscountText.trim();
        var dl = d.left(1);
        var dr = d.right(1);
        if (d.left(1) === "@") { d = d.right(d.length - 1); pf = "@"; }
        if (d.right(1) === "%") { d = d.left(d.length - 1); sf = "%"; }
        if (sf === "%") { pf = ""; }
        dv = VS4Library.cDbl(d);
        q = iQuantity;
        if (q === 0 || q === "undefined") { q = 1; }
        if (dv !== 0) {
          if (pf === "" && sf === "") {
            dc = dv;
          } else if (pf === "Q" && sf === "") {
            dc = dv * q;
          } else if (pf === "" && sf === "%") {
            dc = (dv / 100) * iUnitPrice * q;
          }
        }
        return Math.round(dc * 100) / 100;;
      }

      svc.getValueDiscountTextList = function (iUnitPrice, iDiscountTextList, iQuantity) {
        var td = svc.validDiscountTextList(iDiscountTextList, 8);
        var tdc = 0;
        var lu = iUnitPrice;
        var q = iQuantity;
        if (q == 0) q = 1;
        if ((td !== "") && (td != null)) {
          td = td.replace(/&/g, "+");
          ad = td.split("+");
          for (var i = 0; i < ad.length; i++) {
            var d = ad[i];
            switch (d.toUpperCase()) {
              case "AU":
              case "AN":
              case "A54":
              case "DU":
              case "DN":
                break;

              default:
                if (d.substring(1, 1) == "@") {
                  d.substring(2, d.length - 1);
                  pf = "@";
                }
                else {
                  pf = "";
                }
                if (d.substring(d.length, 1) == "%") {
                  d.substring(1, d.length - 1);
                  sf = "%";
                }
                else {
                  sf = "";
                }
                dc = svc.getValueDiscountText(lu, ad[i], q);
                lu = lu - (dc / q);
                tdc = tdc + dc;
            }
          }

          var rtdc = tdc.toFixed(0);
          var d = ad[ad.length - 1];
          switch (d.toUpperCase()) {
            case "AU":
            case "DN":
              if (tdc > rtdc) tdc = rtdc;
              break;

            case "AN":
            case "DU":
              if (tdc > rtdc) tdc = rtdc + 1;
              break;

            case "A54":
              var iu = iUnitPrice - tdc;
              var a = iu.toFixed(2);
              var b = iu.toFixed(0);
              if (a > (b + 0.44)) {
                tdc = iUnitPrice - (b + 1);
              }
              else {
                tdc = iUnitPrice - b;
              }
              break;
          }
        }
        return Number(tdc.toFixed(2));
      }

      svc.getWHEREfromStatus = function (status, prefix, approveCode) {
        var mWhere = "";
        if (approveCode === undefined) { var ac = ""; } else { var ac = approveCode; }
        s = Number(VS4Library.cInt(status));
        switch (s) {
          case 1:
            mWhere += " AND (" + prefix + "Flag1=1 AND " + prefix + "CancelStatus<>1 AND " + prefix + "ConfirmStatus=1 AND " + prefix + "ApproveStatus<>1) AND (" + prefix + "ApproveNote='" + ac + "' or " + prefix + "ApproveNote='' or " + prefix + "ApproveNote is null) "
            break;

          case 2:
            mWhere += " AND " + prefix + "Flag1=1 AND " + prefix + "CancelStatus<>1 AND " + prefix + "ConfirmStatus=1"
            break;

          case 3:
            mWhere += " AND " + prefix + "Flag1=1 AND " + prefix + "CancelStatus<>1 AND " + prefix + "ConfirmStatus<>1"
            break;

          case 4:
            mWhere += " AND " + prefix + "Flag1=1 AND " + prefix + "CancelStatus<>1 AND " + prefix + "ApproveStatus<>1"
            break;

          case 5:
            mWhere += " AND " + prefix + "CancelStatus<>1"
            break;

          case 6:
            mWhere += " AND " + prefix + "CancelStatus=1"
            break;

          case 7:
            break;

          default:
            mWhere += " AND " + prefix + "Flag1=1 AND " + prefix + "CancelStatus<>1 AND " + prefix + "ConfirmStatus=1 AND " + prefix + "ApproveStatus=1"
            break;
        }
        return mWhere;
      }

      svc.getStatusDocument = function () {
        var statusDocument = [
          {
            "value": 0,
            "text": "เฉพาะรายการที่อนุมัติแล้ว"
          },
          {
            "value": 1,
            "text": "เฉพาะรายการที่ตรงจสอบแล้ว (รอการอนุมัติ)"
          },
          {
            "value": 2,
            "text": "เฉพาะรายการที่ตรงจสอบแล้ว (ทั้งหมด)"
          },
          {
            "value": 3,
            "text": "เฉพาะรายการปัจจุบัน (รอการตรวจสอบ)"
          },
          {
            "value": 4,
            "text": "เฉพาะรายการปัจจุบัน"
          },
          {
            "value": 5,
            "text": "ทั้งหมด"
          },
          {
            "value": 6,
            "text": "เฉพาะรายการที่ยกเลิก"
          },
          {
            "value": 7,
            "text": "ทั้งหมด (รวมรายการที่ยกเลิก)"
          }
        ];
        return statusDocument;
      }

      svc.getPayType = function () {
        var payType = [
          {
            "value": 0,
            "text": "Sale (ขาย)"
          },
          {
            "value": 1,
            "text": "Premium (แถม)"
          },
          {
            "value": 2,
            "text": "Warranty (เคลมศูนย์)"
          },
          {
            "value": 3,
            "text": "Internal (เคลมบริษัท)"
          },
          {
            "value": 4,
            "text": "Set (ชุด)"
          },
          {
            "value": 5,
            "text": "Check (ตรวจสอบ)"
          }
        ];
        return payType;
      }

      svc.getUnitCalc = function () {
        //Unit1,Unit2,Unit3,Lump,Main
        var unitCalc = [
          {
            "value": 0,
            "text": "หน่วย1"
          },
          {
            "value": 1,
            "text": "หน่วย2"
          },
          {
            "value": 2,
            "text": "หน่วย3"
          },
          {
            "value": 3,
            "text": "เหมา"
          },
          {
            "value": 4,
            "text": "หน่วยหลัก"
          }
        ];
        return unitCalc;
      }

      svc.getStatusNoYes = function () {
        var statusNoYes = [
          {
            "value": 0,
            "text": "No"
          },
          {
            "value": 1,
            "text": "Yes"
          }
        ];
        return statusNoYes;
      }

      svc.getStatusApprove = function () {
        var statusApprove = [
          {
            "value": 0,
            "text": "No"
          },
          {
            "value": 1,
            "text": "Yes"
          },
          {
            "value": 2,
            "text": "Reject"
          }
        ];
        return statusApprove;
      }

      svc.getVATType = function () {
        var vatType = [
          {
            "value": 0,
            "text": "NT"
          },
          {
            "value": 1,
            "text": "EX"
          },
          {
            "value": 2,
            "text": "IN"
          }
        ];
        return vatType;
      }

      svc.getPriceChannel = function () {
        var priceChannel = [
          {
            "value": 0,
            "text": "RETAIL"
          },
          {
            "value": 1,
            "text": "WHOLESALE"
          },
          {
            "value": 2,
            "text": "EXW"
          },
          {
            "value": 3,
            "text": "FOB"
          },
          {
            "value": 4,
            "text": "CIF"
          },
          {
            "value": 5,
            "text": "ราคาปรับปรุง 6"
          },
          {
            "value": 6,
            "text": "ราคาปรับปรุง 7"
          },
          {
            "value": 7,
            "text": "ราคาปรับปรุง 8"
          },
          {
            "value": 8,
            "text": "ราคาปรับปรุง 9"
          },
          {
            "value": 9,
            "text": "ราคาปรับปรุง 10"
          }
        ];
        return priceChannel;
      }

      svc.getOption = function (query, optionNameList, targetList, formData, prefix) {
        svc.selectDataObj("", query, false, "", "", "POST")
          .done(function (e) {
            for (var i = 0; i < e.result.length; i++) {
              var oL = optionNameList.split(",");
              var tL = targetList.split(",");
              for (var j = 0; j < oL.length; j++) {
                if (e.result[i][prefix + "Name"].toUpperCase() == oL[j].toUpperCase()) {
                  var o = e.result[i][prefix + "Type"] == 0 ? e.result[i][prefix + "Text"] : VS4Library.cDbl(e.result[i][prefix + "Value"]);
                  var n = tL[j].split(".");
                  switch (n.length) {
                    case 2:
                      formData[n[0]][n[1]] = o;
                      break;
                    case 3:
                      formData[n[0]][n[1]][n[2]] = o;
                      break;
                    case 4:
                      formData[n[0]][n[1]][n[2]][n[3]] = o;
                      break;
                    default:
                      formData[n[0]] = o;
                  }
                }
              }
            }
          });
      }
      svc.getUserOption = function (userID, optionNameList, targetList, formData) {
        var q = "SELECT TSyUName,TSyUType,TSyUText,TSyUValue FROM VS4TSystemUser ";
        q += " WHERE TSyUUserID=" + userID + " AND TSyUName in ('" + optionNameList.replace(/,/g, "','") + "')";
        svc.getOption(q, optionNameList, targetList, formData, "TSyU");
      }
      svc.getBranchOption = function (branchCode, optionNameList, targetList, formData) {
        var q = "SELECT TSyBName,TSyBType,TSyBText,TSyBValue FROM VS4TSystemBranch ";
        q += " WHERE TSyBTBraCode='" + branchCode + "' AND TSyBName in ('" + optionNameList.replace(/,/g, "','") + "')";
        svc.getOption(q, optionNameList, targetList, formData, prefix, "TSyB");
      }
      svc.getSystemOption = function (optionNameList, targetList, formData) {
        var q = "SELECT TSysName,TSysType,TSysText,TSysValue FROM VS4TSystem ";
        q += " WHERE TSysName in ('" + optionNameList.replace(/,/g, "','") + "')";
        svc.getOption(q, optionNameList, targetList, formData, "TSys");
      }






      //Share command
      svc.isValidInput = function (fielCheck, message, dataType) {
        switch (dataType) {
          case "D":
            if (fielCheck == "" || fielCheck == null || !VS4Library.isDate(fielCheck)) {
              svc.messageBox("", "โปรดระบุ " + message);
              return false;
            }
            break;
          default: //"S"
            if (fielCheck == "" || fielCheck == null) {
              svc.messageBox("", "โปรดระบุ " + message);
              return false;
            }
        }
        return true;
      }

      svc.messageBox = function (title, message) {
        return svc.confirmDialog(title, message, 'MESSAGE');
      };

      svc.errorBox = function (error) {
        var message = error.Message + '   Exception Message: ' + error.ExceptionMessage + '   ExceptionType: ' +
          error.ExceptionType + '   StackTrace: ' + error.Stacktrack;
        return svc.confirmDialog("Error Message", message, 'MESSAGE');
      };

      svc.confirmDialog = function (title, message, displayMode) {
        $rootScope.confirmDialogTitle = title;
        $rootScope.confirmDialogMessage = message;
        if (displayMode != undefined) {
          $rootScope.confirmDialogMode = displayMode;
        } else {
          $rootScope.confirmDialogMode = 'CONFIRM';
        }
        var dialog = ngDialog.open({
          //                     className: 'ngdialog-theme-Custom1',
          //                    plain: true,
          template: '/App/Main/views/Shared/myFactory/confirmDialog/confirmDialog.html',
          controller: 'confirmDialog'
          //                    scope: $rootScope
        });
        return dialog.closePromise;
      };

      svc.templateDialog = function (template, controller, params, className) {
        VS4Library.SetToken();
        $rootScope.templateDialogParams = params;
        var dialog = ngDialog.open({
          //className: className,
          className: 'ngdialog-theme-plain custom-width',
          //                    plain: true,
          template: template,
          controller: controller
          //scope: scope
        });
        return dialog.closePromise;
      };

      svc.painDialog = function (paintHTML, className) {
        var dialog = ngDialog.open({
          //className: className,
          plain: true,
          template: paintHTML,
          //controller: controller
          //scope: scope
        });
        return dialog.closePromise;
      };

      //fieldList =  fieldReturnList ## fieldNameList ## fieldCaptionList ## fieldWidthList ## fieldTypeList
      svc.builtQueryApiObj = function (fieldList, query, distinct, apiController, apiAction, httpMethod, datasourceName) {
        var api = "DataApi";
        var act = "GetAll";
        var method = "GET";
        var ds = "";
        //Dynamic query เหมือน selectDataList
        if (apiController !== undefined && apiController !== "") {
          api = apiController;
        }
        if (httpMethod !== undefined && httpMethod !== "") {
          method = httpMethod;
        }
        if (apiAction !== undefined && apiAction !== "") {
          act = apiAction;
        } else {
          if (method === "POST") {
            act = "Post";
          }
        }
        if (datasourceName !== undefined && datasourceName !== "") {
          ds = datasourceName;
        }

        $rootScope.selectDataList = {
          fieldList: fieldList,
          query: query,
          distinct: distinct,
          apiController: api,
          apiAction: act,
          httpMethod: method,
          datasourceName: ds,
          searchText: '*'
        }
        return $rootScope.selectDataList;
      }

      svc.selectDataList = function (fieldList, query, distinct, apiController, apiAction, httpMethod, datasourceName) {
        svc.builtQueryApiObj(fieldList, query, distinct, apiController, apiAction, httpMethod, datasourceName);
        return svc.templateDialog('/App/Main/views/Shared/myFactory/selectDataList/selectDataList.html?11', 'SelectDataList');
      };

      svc.openNewTab = function (url, data) {
        VS4Library.SetToken();
        tabWindowId = $window.open(url, '_blank');
        // $http.get(url)
        // 	.then(function successCallback(response) {
        // 	    // this callback will be called asynchronously
        // 	    // when the response is available
        // 			tabWindowId.location.href = response.headers('Location');
        // 	  }, function errorCallback(response) {
        // 	    // called asynchronously if an error occurs
        // 	    // or server returns response with an error status.
        // 	  });
      };

      svc.postNewTab = function (url, data) {
        VS4Library.SetToken();
        tabWindowId = $window.open(url, '_blank');
        $http.post(url, data)
          .then(function successCallback(response) {
            // this callback will be called asynchronously
            // when the response is available
            tabWindowId.location.href = response.headers('Location');
          }, function errorCallback(response) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
          });
      };

      svc.batchUpdate = function (controller, data) {
        VS4Library.SetToken();
        return $http.post($rootScope.apiBase + '/api/' + controller + '/BatchUpdate', data);
      }

      svc.create = function (controller, data) {
        VS4Library.SetToken();
        return $http.post($rootScope.apiBase + '/api/' + controller + '/Post', data);
      }

      svc.process = function (controller, action, data) {
        VS4Library.SetToken();
        return $http.post($rootScope.apiBase + '/api/' + controller + '/' + action, data);
      }

      svc.update = function (controller, Id) {
        VS4Library.SetToken();
        return $http.post($rootScope.apiBase + '/api/' + controller + '/Put/' + Id);
      }

      svc.selectDataObj = function (fieldList, query, distinct, apiController, apiAction, httpMethod, datasourceName) {
        svc.builtQueryApiObj(fieldList, query, distinct, apiController, apiAction, httpMethod, datasourceName);
        VS4Library.SetToken();

        var query = ej.Query().addParams("query", $rootScope.selectDataList.query);
        query.addParams("datasourceName", $rootScope.selectDataList.datasourceName);
        //query.from("").select(fieldNameList);

        var dataManger;
        if ($rootScope.selectDataList.httpMethod === "GET") {
          dataManger = ej.DataManager({
            url: $rootScope.apiBase + "/api/" + $rootScope.selectDataList.apiController + "/" + $rootScope.selectDataList.apiAction,
            offline: true,
            crossDomain: true
          });
        } else {
          dataManger = ej.DataManager({
            url: $rootScope.apiBase + "/api/" + $rootScope.selectDataList.apiController + "/" + $rootScope.selectDataList.apiAction,
            adaptor: "UrlAdaptor", //to POST
            offline: true,
            crossDomain: true
          });
        }

        var dmPromise = dataManger.executeQuery(query);
        return dmPromise;
      }

      svc.getReportQuery = function (reportCatelgory, format) {
        VS4Library.SetToken();
        if (format === "") {
          return $http.get($rootScope.apiBase + '/api/ReportApi/GetReportQuery/' + reportCatelgory.replace('/', '__'));
        } else {
          return $http.get('/App_Data/Reports/' + reportCatelgory + '.' + format);
        }
      }

      svc.getAll = function (controller, data) {
        VS4Library.SetToken();
        return $http.get($rootScope.apiBase + '/api/' + controller + '/GetAll');
      }

      svc.getByFilter = function (controller, filter) {
        VS4Library.SetToken();
        return $http.get($rootScope.apiBase + '/api/' + controller + '/GetByFilter/' + filter);
      }

      svc.get = function (controller, Id) {
        VS4Library.SetToken();
        return $http.get($rootScope.apiBase + '/api/' + controller + '/Get/' + Id);
      }

      svc.getById = function (controller, Id) {
        VS4Library.SetToken();
        return $http.get($rootScope.apiBase + '/api/' + controller + '/GetById/' + Id);
      }

      svc.delete = function (controller, Id) {
        VS4Library.SetToken();
        return $http.post($rootScope.apiBase + '/api/' + controller + '/Delete/' + Id);
      }

      return svc;
    }
  ]);

  app.run(function (editableOptions) {
    editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
  });


  ///});
})();
