///define(['app'], function (app) {
(function () {
  var app = angular.module('myApp');
  var cId = 'SelectDataList';
  var cVer = 1;
  ///app.register.controller(cId, [
  app.controller(cId, [
    '$scope', '$rootScope', '$window', '$http', '$q', '$location', '$sce', 'ngDialog', 'VS4Library', 'myFactory',
    function ($scope, $rootScope, $window, $http, $q, $location, $sce, ngDialog, VS4Library, myFactory) {
      var self = this;

      $rootScope.controllerMsg = cId + ' : ' + myFactory.AppVersion() + '.' + cVer;

      var target = document.getElementById('progress');
      var spinner = new Spinner($rootScope.progressOpts).spin(target);

      $scope.selectList = [];
      $scope.selectValue = [];
      $scope.gridData = [];
      $scope.pageSize = 12;
      //$scope.height = "600px";
      //$scope.controllerName = "DataApi";


      var fL = $rootScope.selectDataList.fieldList.split("##");
      var fieldReturnList = [];
      var fieldNameList = [];
      var fieldCaptionList = [];
      var fieldWidthList = [];
      var fieldTypeList = [];

      fieldReturnList = fL[0].split(",");
      fieldNameList = fL[1].split(",");
      var minLength = fieldNameList.length;
      if (fL.length >= 3) {
        fieldCaptionList = fL[2].split(",");
        if (fieldCaptionList.length < minLength) {
          minLength = fieldCaptionList.length
        };
      }
      if (fL.length >= 4) {
        fieldWidthList = fL[3].split(",");
        if (fieldWidthList.length < minLength) {
          minLength = fieldWidthList.length
        };
      }
      if (fL.length >= 5) {
        fieldTypeList = fL[4].split(",");
        if (fieldTypeList.length < minLength) {
          minLength = fieldTypeList.length
        };
      }

      var col = [];
      for (var i = 0; i < minLength; i++) {
        if (i === 0) {
          pk = true;
        } else {
          pk = false;
        }
        var el = {
          field: fieldNameList[i],
          headerText: fieldNameList[i],
          width: 0,
          type: "string",
          // format: "",
          textAlign: ej.TextAlign.Left,
          isPrimaryKey: pk
        };
        if (fL.length >= 3) {
          el.headerText = fieldCaptionList[i];
        }
        if (fL.length >= 4) {
          el.width = fieldWidthList[i];
        }
        if (fL.length >= 5) {
          switch (fieldTypeList[i]) {
            case "C":
              el.textAlign = ej.TextAlign.Center;
              break;

            case "D":
            case "Date":
              el.format = "{0:dd/MM/yyyy}";
              el.textAlign = ej.TextAlign.Center;
              el.type = "date";
              break;
            //
            // case "T":
            // case "Time":
            //   break;
            //
            // case "DT":
            // case "DateTime":
            //   break;

            case "I":
            case "Int":
            case "N0":
            case "Number0":
              el.format = "{0:N0}";
              el.textAlign = ej.TextAlign.Right;
              el.type = "number";
              break;

            case "A":
            case "N2":
            case "Number2":
              el.format = "{0:N2}";
              el.textAlign = ej.TextAlign.Right;
              el.type = "number";
              break;

            case "V":
            case "E":
            case "N5":
            case "Number5":
              el.format = "{0:N5}";
              el.textAlign = ej.TextAlign.Right;
              el.type = "number";
              break;

            default:
          }
        }
        col.push(el);
      }

      function refreshData() {

        // var q = "";
        // var s = $rootScope.selectDataList.searchText;
        // if (s === "" || s === "*" || s === "%") {
        //   q = $rootScope.selectDataList.query;
        // }
        // else {          
        //   var st = '' + $rootScope.selectDataList.searchText.replace(/\*/g, '%');
        //   qs = $rootScope.selectDataList.query.split("ORDER BY");
        //   var stt = " AND " + fieldNameList[0] + " LIKE '" + st + "%'"
        //   q = qs[0] + stt;
        //   if (qs.length > 1) {
        //     q = q + ' ' + q[1];
        //   }
        // }

        var q = "";
        var s = $rootScope.selectDataList.searchText;
        if (s === "" || s === "*" || s === "%") {
          $rootScope.selectDataList.searchText = "*";
          // $scope.$apply();
        }
        var st = '' + $rootScope.selectDataList.searchText.replace(/\*/g, '%');
        qs = $rootScope.selectDataList.query.split(" ORDER BY ");
        var w = qs[0].indexOf(" WHERE ");
        var stt = "";
        if (w == -1) { stt = " WHERE "; } else { stt = " AND "; }

        //must dynamic number of column and type
        stt += " (" + fieldNameList[0] + " LIKE '" + st + "%'"
        if (fieldNameList.length > 1) stt += " OR " + fieldNameList[1] + " LIKE '" + st + "%' ";
        if (fieldNameList.length > 2) stt += " OR " + fieldNameList[2] + " LIKE '" + st + "%' ";
        if (fieldNameList.length > 3) stt += " OR " + fieldNameList[3] + " LIKE '" + st + "%' ";
        stt += ")";

        q = qs[0] + stt;
        if (qs.length > 1) {
          q = q + ' ORDER BY ' + qs[1];
        }


        var query = ej.Query().addParams("query", q);
        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);
        dmPromise.done(function (e) {
          $scope.gridData = e.result;

          $("#GridDialog1").ejGrid({
            dataSource: e.result,
            allowPaging: true,
            allowFiltering: true,
            enableHeaderHover: true,
            pageSettings: {
              pageSize: $scope.pageSize
            },
            editSettings: {
              allowEditing: false,
              allowAdding: false,
              allowDeleting: false
            },
            toolbarSettings: {
              showToolbar: true,
              toolbarItems: []
            },
            filterSettings: {
              filterType: "excel"
            },
            cellSelected: function (args) {
              $scope.select();
            },
            rowSelected: function (args) {
              $scope.select();
            },
            columns: col
          });

          spinner.stop();

          $scope.$apply();

        });
      }
      refreshData();


      $scope.search = function ($event) {
        if ($event.which === 13) {
          //var gridObj = $("#GridDialog1").data("ejGrid");
          // Sends a filtering request to the grid
          //gridObj.filterColumn("OrderID", "equal", "10248", "and", true);

          //Rebuilt DataSource
          refreshData();
        }
      };

      $scope.close = function () {
        ngDialog.closeAll(false);
      };

      $scope.select = function () {
        $scope.selectList = $("#GridDialog1").ejGrid("model.selectedRecords");
        $scope.selectValue = [];
        var len = $scope.selectList.length;
        for (var i = 0; i < len; i++) {
          var v = "";
          for (var ii = 0; ii < fieldReturnList.length; ii++) {
            if (ii > 0) { v += "#$#" }
            if ($scope.selectList[i][fieldReturnList[ii]] instanceof Date) {
              v += moment($scope.selectList[i][fieldReturnList[ii]]).format("YYYY-MM-DD");
            }
            else {
              v += $scope.selectList[i][fieldReturnList[ii]];
            }
          }
          $scope.selectValue.push(v);
        }

        ngDialog.closeAll({
          action: true,
          value: $scope.selectValue
        });
      };


    }
  ]);
  ///});
})();
