 ///define(['app'], function (app) {
(function() {
  var app = angular.module('myApp');
  var cId = 'Reports';
  var cVer = 1;
  ///app.register.controller(cId, [
  app.controller(cId, [
    '$scope', '$rootScope', '$http', '$window', '$location', '$q', 'VS4Library', 'myFactory', 'BMFactory', 'FNFactory', 'moment',
    function($scope, $rootScope, $http, $window, $location, $q, VS4Library, myFactory, BMFactory, FNFactory, moment) {
      var self = this;
      $rootScope.controllerMsg = cId + ' : ' + myFactory.AppVersion() + '.' + cVer;

      var click = ej.Autocomplete.prototype._OnDropdownClick;
      ej.Autocomplete.prototype._OnDropdownClick = function(e) {
        click.call(this, e);
        this._trigger("select", {
          value: this.element.val()
        })
      }
      
      $scope.showDataList = function(returnObjNameList, fieldList, query, distinct, apiController, apiAction, httpMethod, datasourceName, dataChangeEvent) {
        if ($scope.runMode == "VIEW" && !$rootScope.loadingDialog) {
          $rootScope.loadingDialog = true;
          myFactory.selectDataList(fieldList, query, distinct, apiController, apiAction, httpMethod, datasourceName).then(function(data) {
            if (data.value.action) {
              if (data.value.value.length > 0) {
                // Multiple field return
                var fL = $rootScope.selectDataList.fieldList.split("##");
                var fRL = fL[0].split(",");
                var oL = returnObjNameList.split(",");
                var l1 = fRL.length;
                var l2 = oL.length;
                if (l1 > l2) {
                  l1 = l2
                };
                var v = data.value.value[0].split("#$#");
                for (var i = 0; i < l1; i++) {
                  $scope.formData[oL[i]] = v[i];
                }

                // Single field return
                //$scope.formData[returnObjNameList] = data.value.value[0];

                if (dataChangeEvent !== undefined) {
                  dataChangeEvent();
                }
              }
            }
            $rootScope.loadingDialog = false;
          });
        }
      };
      
      //0 Private Data
      $scope.formData = {
        reportFullName: '',
        reportQuery: '',
        baseQuery: '',
        baseOrderBy: '',
        where: '',
        parameters: '',
        reportConditions: '',
        toolbarSettings: '',
        autoPrint: false,

        filter01: '',
        filterDate01: VS4Library.GetDateText(),
        // type01: "'",
        filter01_T: '',
        filterDate01_T: VS4Library.GetDateText(),
        filter01dataList: [],
        display01: '',

        filter02: '',
        filterDate02: VS4Library.GetDateText(),
        // type02: "'",
        filter02_T: '',
        filterDate02_T: VS4Library.GetDateText(),
        filter02dataList: [],
        display02: '',

        filter03: '',
        filterDate03: VS4Library.GetDateText(),
        // type03: "'",
        filter03_T: '',
        filterDate03_T: VS4Library.GetDateText(),
        filter03dataList: [],
        display03: '',

        filter04: '',
        filterDate04: VS4Library.GetDateText(),
        // type04: "'",
        filter04_T: '',
        filterDate04_T: VS4Library.GetDateText(),
        filter04dataList: [],
        display04: '',

        filter05: '',
        filterDate05: VS4Library.GetDateText(),
        // type05: "'",
        filter05_T: '',
        filterDate05_T: VS4Library.GetDateText(),
        filter05dataList: [],
        display05: '',

        filter06: '',
        filterDate06: VS4Library.GetDateText(),
        // type06: "'",
        filter06_T: '',
        filterDate06_T: VS4Library.GetDateText(),
        filter06dataList: [],
        display06: '',

        filter07: '',
        filterDate07: VS4Library.GetDateText(),
        // type07: "'",
        filter07_T: '',
        filterDate07_T: VS4Library.GetDateText(),
        filter07dataList: [],
        display07: '',

        filter08: '',
        filterDate08: VS4Library.GetDateText(),
        // type08: "'",
        filter08_T: '',
        filterDate08_T: VS4Library.GetDateText(),
        filter08dataList: [],
        display08: '',

        filter09: '',
        filterDate09: VS4Library.GetDateText(),
        // type09: "'",
        filter09_T: '',
        filterDate09_T: VS4Library.GetDateText(),
        filter09dataList: [],
        display09: '',

        filter10: '',
        filterDate10: VS4Library.GetDateText(),
        // type10: "'",
        filter10_T: '',
        filterDate10_T: VS4Library.GetDateText(),
        filter10dataList: [],
        display10: '',

      };

      $scope.formReady = false;
      $scope.rendering = false;
      $scope.showStandardUI = false;
      $scope.formData.baseQuery = "";

      $scope.title = $location.search().itemPath;
      //var t = $scope.title.split("/");
      //$scope.template = '/App/Main/views/Reports/' + t[t.length-1] + '.html';
      $scope.template = '/App/Main/views/Reports/' + $scope.title + '.html?' + moment().format();
      var params = $location.search();
      
      //1 Private Function

      // myFactory.getReportQuery($scope.title,'json').then(function(response) {
      //   $scope.formData.baseQuery = response.data[0].baseQuery;
      //   $scope.formData.baseOrderBy = response.data[0].baseOrderBy;
      // });

      myFactory.getReportQuery($scope.title, '').then(function(response) {
        if (response.data !== "") {
          var x2js = new X2JS();
          var json = x2js.xml_str2json(response.data.replace('<>', '&lt;&gt;'));
          $scope.formData.baseQuery = json.formData.baseQuery;
          $scope.formData.baseOrderBy = json.formData.baseOrderBy;
          var a = '' + json.formData.reportFullName;
          var b = a.substr(a.length - 4, 4);
          b = b.toUpperCase();
          if (b === ".RDL") {
            a = a.substr(0, a.length - 4);
          }
          if (a !== "" && a !== undefined) {
            $scope.formData.reportFullName = a;
          }
          $scope.formReady = true;
        }
      });
      
      switch ($scope.title) {
        case "FN/RSFNOR91":
        case "FN/RSFNOR92":
          $scope.formData.filter01 = 0;
          $scope.formData.filter02 = VS4Library.GetCTYear();
          var list = [{
            value: "N",
            text: "ปกติ"
          }, {
            value: "Y",
            text: "ยกเลิก"
          }];
          $scope.formData.filter03dataList = list;
          $scope.formData.filter03 = 'N';
          break;

        case "DO/RSDORP02":
          $scope.e_filter01 = function() {
            var fl = "CUST_TYPE_CODE,CUST_TYPE_NAME";
            var fieldList = "CUST_TYPE_CODE,CUST_TYPE_NAME##" + fl + "##รหัสประเภท,ชื่อประเภท##100,200";
            var q = "SELECT " + fl + " FROM VIEW_DO_CUSTOMER_TYPE WHERE CUST_TYPE_CODE<>''";
            $scope.showDataList("filter01,display01", fieldList, q, false, "", "", "POST");
            //$scope.showDataList("filter01", fieldList, q, false, "", "", "POST", "", $scope.e_event01);
          }
          //in fire event on enter
          $scope.e_event01 = function() {
            if ($scope.formData.filter01 !== "") {
              var q = "SELECT CUST_TYPE_NAME FROM VIEW_DO_CUSTOMER_TYPE WHERE CUST_TYPE_CODE='" + $scope.formData.filter01 + "'";
              myFactory.selectDataObj("CUST_TYPE_NAME", q, false, "", "", "POST")
                .done(function(e) {
                  $scope.formData.display01 = e.result[0].CUST_TYPE_NAME;
                });
            }
          }
          $scope.e_filter02 = function() {
            var fl = "CUST_CODE,NAME_CONCAT_THA";
            var fieldList = "CUST_CODE##" + fl + "##รหัสลูกค้า,ชื่อลูกค้า##200,400";
            var q = "SELECT " + fl + " FROM DO_CUSTOMER WHERE CUST_CODE<>''";
            q += formatFilter("S", true, "DO_CUSTOMER.CUST_TYPE_CODE", "=", $scope.formData.filter01, "CUST_TYPE_CODE");
            $scope.showDataList("filter02", fieldList, q, false, "", "", "POST");
          }
          $scope.e_filter02_T = function() {
            var fl = "CUST_CODE,NAME_CONCAT_THA";
            var fieldList = "CUST_CODE##" + fl + "##รหัสลูกค้า,ชื่อลูกค้า##200,400";
            var q = "SELECT " + fl + " FROM DO_CUSTOMER WHERE CUST_CODE<>''";
            q += formatFilter("S", true, "DO_CUSTOMER.CUST_TYPE_CODE", "=", $scope.formData.filter01, "CUST_TYPE_CODE");
            $scope.showDataList("filter02_T", fieldList, q, false, "", "", "POST");
          }
          break;

        default:
          $scope.formData.reportFullName = "";
          $scope.showStandardUI = true;
          $scope.formReady = true;
      }
            
      $scope.showREPORT = function() {

      };


      //Set buttons
      $scope.runMode = "VIEW";
      refreshControl();

      $scope.showQuery = false;
      $scope.toggleQuery = function() {
        $scope.showQuery = !$scope.showQuery;
      };

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


      function formatFilterP(iValue, iconditionName, iValidData, iDefaultValue, iValueFormat, iconditionLabel) {
        pp = "";
        vv = iValue;
        // tt = "";
        // if (iValidData !== undefined && iValidData !== null) {
        //   vv = VS4Library.GetValueByValue($scope.formData.filter02dataList,vv,iDefaultValue);
        //   tt = VS4Library.GetTextByValue($scope.formData.filter02dataList,vv);
        // }
        if (iValueFormat !== "" && iValueFormat !== undefined && iValueFormat !== null) {
          if (iconditionLabel !== undefined && iconditionLabel !== null) {
            pp = ";" + iconditionName + "=" + vv;
            pp += ";" + iconditionName + "_F" + "=" + iValueFormat;
          } else {
            pp = ";" + iconditionName + "=" + vv;
            pp += ";" + iconditionName + "_F" + "=" + iValueFormat;
          }
        } else {
          // if (tt !== ""){
          //   pp = ";" + iconditionName + "=" + vv;
          //   pp += ";" + iconditionName + "_F" + "=" + tt;
          // }else{
          pp = ";" + iconditionName + "=" + vv;
          // }
        };
        return pp;
      }

      // ifieldType = D(Date), T(Time), DT(DateTime), S(String), I(Int)
      function formatFilter(ifieldType, iRequire, iFieldName, iCondition, iValue, iconditionName, iValidData, iDefaultValue, iValueFormat, iconditionLabel) {
        p = "";
        o = "";
        t = "";
        f = "";
        // var f = iFieldName.split(".");
        // fn = f[f.length-1];
        fn = "";
        if (iconditionName !== undefined && iconditionName !== null) {
          fn = iconditionName
        };
        v = "";
        if (iValue !== undefined && iValue !== null) {
          v = iValue;
        };
        if (iValueFormat !== undefined && iValueFormat !== null) {
          f = iValueFormat;
        };
        if (iValidData !== undefined && iValidData !== null) {
          v = VS4Library.GetValueByValue(iValidData, v, iDefaultValue);
          f = VS4Library.GetTextByValue(iValidData, v);
        }

        switch (ifieldType) {
          case "D":
          case "Date":
            if (iRequire === true) {
              if (!VS4Library.isDate(v)) {
                t = VS4Library.GetDateText();
              } else {
                t = VS4Library.cDate(v);
              }
              //o = " AND DATEADD(dd, DATEDIFF(dd, 0, " + iFieldName + "), 0) " + iCondition + " " + "'" + VS4Library.formatDate2Query(t) + "'";
              o = " AND " + iFieldName + " " + iCondition + " " + "'" + VS4Library.formatDate2Query(t) + "'";
              p = ";" + fn + "=" + VS4Library.formatDate2Query(t);
            } else {
              if (v !== "") {
                if (VS4Library.isDate(v)) {
                  //o = " AND DATEADD(dd, DATEDIFF(dd, 0, " + iFieldName + "), 0) " + iCondition + " " + "'" + VS4Library.formatTextDate2Query(v) + "'";
                  o = " AND " + iFieldName + " " + iCondition + " " + "'" + VS4Library.formatTextDate2Query(v) + "'";
                  p = ";" + fn + "=" + VS4Library.formatTextDate2Query(v);
                }
              }
            }
            break;
            // case "T":
            // case "Time":
            //   break;
            //
            // case "DT":
            // case "DateTime":
            //   break;
            //
          case "I":
          case "Int":
          case "N0":
          case "Number0":
            if (iRequire === true) {
              y = VS4Library.cInt(v);
              o = " AND " + iFieldName + " " + iCondition + " " + y;
              p = ";" + fn + "=" + y;
            } else {
              if (v !== "") {
                y = VS4Library.cInt(v);
                o = " AND " + iFieldName + " " + iCondition + " " + y;
                p = ";" + fn + "=" + y;
              }
            }
            break;

          case "A":
          case "N2":
          case "Number2":
            if (iRequire === true) {
              y = VS4Library.cDbl(v);
              o = " AND " + iFieldName + " " + iCondition + " " + y;
              p = ";" + fn + "=" + y;
            } else {
              if (v !== "") {
                y = VS4Library.cDbl(v);
                o = " AND " + iFieldName + " " + iCondition + " " + y;
                p = ";" + fn + "=" + y;
              }
            }
            break;

          case "V":
          case "E":
          case "N5":
          case "Number5":
            if (iRequire === true) {
              y = VS4Library.cDbl(v);
              o = " AND " + iFieldName + " " + iCondition + " " + y;
              p = ";" + fn + "=" + y;
            } else {
              if (v !== "") {
                y = VS4Library.cDbl(v);
                o = " AND " + iFieldName + " " + iCondition + " " + y;
                p = ";" + fn + "=" + y;
              }
            }
            break;

          case "P":
            p = ";" + fn + "=" + v;
            break;

          default:
            if (iRequire === true) {
              o = " AND " + iFieldName + " " + iCondition + " " + "'" + v + "'";
              p = formatFilterP(v, fn, iValidData, iDefaultValue, f, iconditionLabel);
            } else {
              if (v !== "") {
                o = " AND " + iFieldName + " " + iCondition + " " + "'" + v + "'";
              }
              p = formatFilterP(v, fn, iValidData, iDefaultValue, f, iconditionLabel);
            }
        }
        $scope.formData.where += o;
        if (p !== "" && fn !== "") {
          $scope.formData.reportConditions += p;
        }
        return o;
      }

      generateQuery = function() {
        var params = $location.search();
        //$location.path('/ReportViewer').search('itemPath', params.itemPath);

        //2 Private Execute
        $scope.formData.where = "";
        $scope.formData.reportConditions = "LANGUAGE=TH";
        switch ($scope.title) {
          case "FN/RSFNOR91":
          case "FN/RSFNOR92":
            formatFilter("I", true, "YEAR", "=", $scope.formData.filter01, "YEAR");
            formatFilter("I", false, "SEMESTER", "=", $scope.formData.filter02, "SEMESTER");
            formatFilter("S", false, "EDUCATION_TYPE", "=", $scope.formData.filter03, "EDUCATION_TYPE");
            formatFilter("P", true, "", "", $scope.formData.filter04, "REPORT_MODE");
            switch ($scope.formData.filter04) {
              case "1":
                formatFilter("S", true, "FAC_CODE", "=", $scope.formData.filter06, "FAC_CODE");
                formatFilter("S", false, "OWN_MAJOR_CODE", ">=", $scope.formData.filter07, "OWN_MAJOR_CODE");
                formatFilter("S", false, "OWN_MAJOR_CODE", "<=", $scope.formData.filter07_T, "OWN_MAJOR_CODE_T");
                break;
              default:
                formatFilter("S", false, "FAC_CODE", ">=", $scope.formData.filter05, "FAC_CODE");
                formatFilter("S", false, "FAC_CODE", "<=", $scope.formData.filter05, "FAC_CODE_T");
                break;
            }
            formatFilter("D", false, "RECEIPT_DATE", ">=", $scope.formData.filterDate08, "RECEIPT_DATE");
            formatFilter("D", false, "RECEIPT_DATE", "<=", $scope.formData.filterDate08_T, "RECEIPT_DATE_T");
            break;

          case "DO/RSDORP11":
            var o = "";
            var p = "";
            switch ($scope.formData.filter01) {
              case "01":
                o += " AND CHECK_IN_START_DATE IS NULL";
                p = ";IS_CHECK_IN=1";
                break;
              case "3":
                p = ";IS_CHECK_IN=";
                break;
            }
            $scope.formData.where += o;
            $scope.formData.reportConditions += p;
            break;

          case "FN/RSFNOR95":
            formatFilter("P", true, "", "", $scope.formData.filter05, "AGING_DAY");
            var d = VS4Library.cDbl($scope.formData.filter05);
            if (d > 0) {
              $scope.formData.where += " AND DOC_DATE < DATEADD(dd, -" + d + ", DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0))";
            }
            formatFilter("S", true, "CUST_TYPE", "=", $scope.formData.filter06, "CUST_TYPE");
            break;

          case "FN/RSFNOR61":
            //Multiple checkbox
            var w = "";
            if ($scope.formData.filter03 === "Y") {
              if (w !== "") {
                w += " OR ";
              }
              w += "FN_RECEIPT_MASTER.RECEIPT_CODE" + " Like '%R%'";
            }
            if ($scope.formData.filter04 === "Y") {
              if (w !== "") {
                w += " OR ";
              }
              w += "FN_RECEIPT_MASTER.RECEIPT_CODE" + " Like '%B%'";
            }
            if ($scope.formData.filter05 === "Y") {
              if (w !== "") {
                w += " OR ";
              }
              w += "FN_RECEIPT_MASTER.RECEIPT_CODE" + " Like '%C%'";
            }
            if (w !== "") {
              $scope.formData.where += " AND (" + w + ")";
            }
            break;

          default:

        }
        

        if ($scope.formData.baseQuery !== "") {
          $scope.formData.reportQuery = $scope.formData.baseQuery + $scope.formData.where;
          if ($scope.formData.baseOrderBy !== '') {
            $scope.formData.reportQuery += ' ORDER BY ' + $scope.formData.baseOrderBy;
          }
        } else {
          $scope.formData.reportQuery = "";
        }
        $window.sessionStorage.reportQuery = $scope.formData.reportQuery;
        $window.sessionStorage.reportConditions = $scope.formData.reportConditions;
      };

      $scope.preview = function() {
        generateQuery();
        myFactory.openNewTab("#/ReportViewer?itemPath=" + params.itemPath + "", $scope.formData);
      }

      function reportPDF() {
          $scope.rendering = true;
          generateQuery();
          var data = {
            itemPath : params.itemPath,
            params : null,
            sqlMain : window.sessionStorage.reportQuery,
            conditions : window.sessionStorage.reportConditions
          };
          VS4Library.SetToken();
          var deferred = $q.defer();
          $http.post($rootScope.apiBase + '/api/RenderApi/renderPDFReport',data).then(function (response) {
              window.open($rootScope.apiBase + '/api/RenderApi/GetPDFReport/' + response.data, '_self', '');
              deferred.resolve(response);
              $scope.rendering = false;
          } , function (error) { //data, status, headers, config
              deferred.reject('Failed generate pdf');
              $scope.rendering = false;
          });

          return deferred.promise;
      };

      $scope.reportPDF = function ()
      {
          reportPDF();
      }


      $scope.cancel = function() {
        var r = confirm("ต้องการยกเลิกการแก้ไข ใช่หรือไม่ ?");
        if (r === true) {
          if ($scope.runMode === "EDIT") {
            $scope.runMode = "VIEW";
            refreshControl();
          } else { //ADD
            $window.history.back();
          }
        }
      };

      $scope.submit = function() {
        $scope.runMode = "VIEW";
        refreshControl();
      };

      //FILL DATA
      function refreshControl() {

        setButtons("EDIT", $scope.runMode);

        // this form only
        var col = [{
            field: "f1",
            headerText: "Column",
            width: 250
          }, {
            field: "f2",
            headerText: "Filter (ใช้ , เลือกแบบหลายรหัส ใช้ -- เลือกแบบช่วง ใช้ * หน้าหรือหลังตัวอักษร เพื่อค้นหาแบบ LIKE)",
            width: 800
          }

        ];
        var query = ej.Query();
        showGrid("#Grid1", [], query, "", col, $scope.runMode, 10);
      }

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