import {FormInput} from "../controller.js";

/**
 * 日期时间组件
 * @param {[type]} dataModel [description]
 */
export default class DateTime extends FormInput {

  constructor(__tfp, dataModel, parent, inputType) {
    if(inputType) {
      super(__tfp, inputType, dataModel, parent);
    } else {
      super(__tfp, "DateTime", dataModel, parent);
    }
  }

  //属性
  get value() { return this.dataModel.value }
  set value(value) {
    this.dataModel.value = value;
    if(this._jqObj) {
      this._jqObj.find("input").val(value);
    }
    if(!this._tfp.isDesigning) {
      this.valueOnChange();
      this.exeEventHandler("onChange", value);
    }
  }

  get iconUrl() {
    return this._tfp.rootPath+"/src/components/"+this.type.toLowerCase()
      +"/images/icon-24-"+this._tfp.curPage.contentColorMode+".png";
  }
  set iconUrl(value) {}

  get showIcon() { return this.dataModel.showIcon }
  set showIcon(value) { 
    this.dataModel.showIcon = value ? true : false;
    if(this._jqObj) {
      if(this.dataModel.showIcon) {
        if(this._jqObj.find("img").length==0) {
          this._jqObj.append("<img src=\""+this.iconUrl+"\" />");
        }
      } else {
        this._jqObj.find("img").remove();
      }
      this.resetWidth();
    }
  }

  get showSecond() { return this.dataModel.showSecond }
  set showSecond(value) { 
    this.dataModel.showSecond = value ? true : false;
    if(this._jqObj) {
      this.resetWidth();
      if(this.dataModel.defaultNow && this._tfp.isDesigning) {
        this._jqObj.find("input").val(this.getCurDateTime());
      }
    }
  }

  get defaultNow() { return this.dataModel.defaultNow }
  set defaultNow(value) { 
    this.dataModel.defaultNow = value ? true : false;
    if(this._jqObj) {
      if(this.dataModel.defaultNow && this._tfp.isDesigning) {
        this._jqObj.find("input").val(this.getCurDateTime());
      } else {
        this._jqObj.find("input").val("");
      }
    }
  }

  getIptWidth() {
    let iptWidth = 90;
    if(this.dataModel.type=="DateTime") {
      iptWidth = 130;
      if(this.dataModel.showSecond) iptWidth = 150;
    }
    return iptWidth;
  }

  resetWidth() {
    let iptWidth = this.getIptWidth();
    let cptWidth = iptWidth;
    if(this.showIcon) cptWidth += 30;
    this._jqObj.find("input").css("width", iptWidth+"px");
    this._jqObj.css("width", cptWidth+"px");
    this._jqObj.css("min-width", cptWidth+"px");
    if(!this.dataModel.styles) this.dataModel.styles = {};
    this.dataModel.styles["width"] = cptWidth+"px";
    this.dataModel.styles["min-width"] = cptWidth+"px";
  }

  clear() {
    this.value = "";
    this.closePicker();
  }

  closePicker() {
    $(".tfp-datetime-picker").remove();
    $("body").unbind("click", this.closePicker);
  };

  showPicker() {
    let offset = this._jqObj.offset();
    let val = new Date();
    if(this.dataModel.value) val = new Date(this.dataModel.value);
    let width = 240;
    if(this.type=="DateTime") width = this.showSecond ? 393 : 343;
    let html = "<div class=\"tfp-datetime-picker\" data-cptid=\""+this.id+"\" data-value=\""
      +val.format("yyyy-MM-dd")+"\" style=\"top: "+(offset.top+31)
      +"px; left:"+offset.left+"px; width: "+width+"px; display:none;\">";
    let imgDir = this._tfp.rootPath+"/src/components/datetime/images/";
    html += "<div style=\"width:100%;height:30px;border-bottom: 1px solid #CCCCCC;\">"
      +"<div class=\"tfp-datetime-picker-header\">"
      +"<div style=\"width:16px; margin-left:5px;\" title=\"上一年\">"
      +"<img src=\""+imgDir+"double-arrow-left-"+this._tfp.curPage.contentColorMode+".png\"></div>"
      +"<div style=\"width:16px;\" title=\"上一月\"><img src=\""+imgDir
        +"arrow-left-"+this._tfp.curPage.contentColorMode+".png\"></div>"
      +"<div style=\"width:166px; text-align:center;\"><span>"+val.getFullYear()
      +"</span> 年 <span>"+(val.getMonth()+1)+"</span> 月</div>"
      +"<div style=\"width:16px;\" title=\"下一月\"><img src=\""+imgDir
        +"arrow-right-"+this._tfp.curPage.contentColorMode+".png\"></div>"
      +"<div style=\"width:16px;\" title=\"下一年\"><img src=\""+imgDir
        +"double-arrow-right-"+this._tfp.curPage.contentColorMode+".png\"></div>"
      +"</div>";
    if(this.type=="DateTime") {
      html += "<div class=\"tfp-datetime-picker-time-value\" "
        +"style=\"width: "+(this.showSecond ? 150 : 100)+"px;\">"
        +this.getTimeValue()+"</div>";
    }
    html += "</div><div style=\"width:100%;height:230px;\">";
    html += "<div class=\"tfp-datetime-picker-grid\">";
    html += "<div class=\"tfp-datetime-picker-grid-header\">";
    html += "<div>一</div><div>二</div><div>三</div><div>四</div><div>五</div><div>六</div><div>日</div>"
    html += "</div>";
    html += "</div>";
    if(this.type=="DateTime") {
      html += "<div class=\"tfp-datetime-picker-time-list\" "
        +"style=\"width: "+(this.showSecond ? 151 : 101)+"px;\">";
      html += this.getTimePickerHtml();
      html += "</div>";
    }
    html += "</div>";
    html += "<div class=\"tfp-datetime-picker-footer\"><span>清空</span>"
      +"<span style=\"color:#003399;\">今天</span>";
    if(this.type=="DateTime") html += "<input type=\"button\" value=\"确定\" />";
    html += "</div></div>";
    $("body").append(html);
    this.setDatePickerValue(val);
    let datetimePicker = $(".tfp-datetime-picker");
    let that = this;
    $(".tfp-datetime-picker-header").find("img").each(function(index) {
      $(this).click(function() {
        if(index==0) {
          that.toPrevYear();
        } else if(index==1) {
          that.toPrevMonth();
        } else if(index==2) {
          that.toNextMonth();
        } else if(index==3) {
          that.toNextYear();
        }
        event.stopPropagation();
      });
    });
    let footer = datetimePicker.find(".tfp-datetime-picker-footer");
    footer.find("span").eq(0).click(function() {
      that.clear();
    });
    footer.find("span").eq(1).click(function() {
      that.toToday();
    });
    datetimePicker.click(function() {
      event.stopPropagation();
    });
    datetimePicker.fadeIn("slow");
    if(this.type=="DateTime") {
      let timeList = $(".tfp-datetime-picker-time-list").find("ul");
      timeList.each(function() {
        $(this).find("li").each(function() {
          $(this).click(function() {
            $(this).parent().find("li").css("background-color", "");
            $(this).parent().find("li").css("color", "");
            $(this).css("background-color", "#3399FF");
            $(this).css("color", "#FFFFFF");
            $(this).parent().attr("data-value", $(this).html());
            let timeValue = timeList.eq(0).attr("data-value")+":"+timeList.eq(1).attr("data-value");
            if(that.showSecond) timeValue += ":"+timeList.eq(2).attr("data-value");
            $(".tfp-datetime-picker-time-value").html(timeValue);
            event.stopPropagation();
          });
        });
        $(this).get(0).scrollTop = parseInt($(this).attr("data-value"))*25;
      });
      footer.find("input").eq(0).click(function() {
        that.onCheckDateTime();
      });
    }
    $("body").bind("click", this.closePicker);
  }

  onCheckDateTime() {
    let val = $(".tfp-datetime-picker").attr("data-value");
    if(this.type=="DateTime") {
      let time = $(".tfp-datetime-picker-time-value").html();
      if(!time || time=="") time = "00:00";
      val += " "+time;
    }
    this.value = val;
    this.closePicker();
  }

  setDatePickerValue(date) {
    $(".tfp-datetime-picker").attr("data-value", date.format("yyyy-MM-dd"));
    $(".tfp-datetime-picker-header").find("span").eq(0).text(date.getFullYear());
    $(".tfp-datetime-picker-header").find("span").eq(1).text(date.getMonth()+1);

    let firstDate = new Date(date.format("yyyy-MM-01"));
    let curWeek = firstDate.getDay();
    if(curWeek==0) curWeek = 7;
    curWeek--;
    if(curWeek>0) firstDate.setDate(firstDate.getDate()-curWeek);
    
    let grid = $(".tfp-datetime-picker-grid");
    grid.find(".tfp-datetime-picker-grid-row").remove();
    
    var index = 0;
    for(var i=0;i<6;i++) {
      let rowHtml = "<div class=\"tfp-datetime-picker-grid-row\">";
      for(var j=0;j<7;j++) {
        let dateTmp = new Date(firstDate.format("yyyy-MM-dd"));
        dateTmp.setDate(dateTmp.getDate()+index);
        let style = "";
        if(dateTmp.format("yyyy-MM-dd")==date.format("yyyy-MM-dd")) {
          style = "color:#FFFFFF; background-color:#3366FF;";
        } else if(dateTmp.format("yyyy-MM")!=date.format("yyyy-MM")) {
          style = "color:#999999;";
        }
        rowHtml += "<div data-value=\""+dateTmp.format("yyyy-MM-dd")
          +"\" style=\""+style+"\">"+dateTmp.format("dd")+"</div>";
        index++;
      }
      rowHtml += "</div>";
      grid.append(rowHtml);
    }
    let that = this;
    grid.find(".tfp-datetime-picker-grid-row").each(function(){
      $(this).find("div").click(function() {
        if(that.type=="DateTime") {
          $(".tfp-datetime-picker-grid-row").find("div").each(function() {
            let dateTmp = $(this).attr("data-value");
            let curDate = $(".tfp-datetime-picker").attr("data-value");
            if(dateTmp==curDate) {
              $(this).css("background-color", "");
              if(dateTmp.substr(0, 7)!=curDate.substr(0, 7)) {
                $(this).css("color", "#999999");
              } else {
                $(this).css("color", "");
              }
              return false;
            }
          });
          $(".tfp-datetime-picker").attr("data-value", $(this).attr("data-value"));
          $(this).css("background-color", "#3366FF");
          $(this).css("color", "#FFFFFF");
          event.stopPropagation();
        } else {
          that.value = $(this).attr("data-value");
          that.closePicker();
        }
      });
    });
  }

  getTimeValue() {
    let date;
    if(!this.dataModel.value) {
      date = new Date();
      if(this.showSecond) {
        return date.format("HH:mm:ss");
      } else {
        return date.format("HH:mm");
      }
    }
    if(this.showSecond) {
      date = new Date(this.dataModel.value);
      return date.format("HH:mm:ss");
    } else {
      date = new Date(this.dataModel.value+":00");
      return date.format("HH:mm");
    }
  }

  getTimePickerHtml() {
    let html = "";
    let vals = this.getTimeValue().split(":");
    html += "<ul data-value=\""+(vals.length>0 ? vals[0] : "00")+"\" style=\"height:230px;\">";
    for(var i=0;i<24;i++) {
      let hour = i<10 ? "0"+i : i+"";
      html += "<li";
      if(vals.length>0 && hour==vals[0]) html += " style=\"background-color: #3399FF;color: #FFFFFF;\"";
      html += ">"+hour+"</li>";
    }
    html += "</ul>";
    html += "<ul data-value=\""+(vals.length>1 ? vals[1] : "00")+"\" style=\"height:230px;\">";
    for(var i=0;i<60;i++) {
      let minute = i<10 ? "0"+i : i+"";
      html += "<li";
      if(vals.length>1 && minute==vals[1]) html += " style=\"background-color: #3399FF;color: #FFFFFF;\"";
      html += ">"+minute+"</li>";
    }
    html += "</ul>";
    if(this.showSecond) {
      html += "<ul data-value=\""+(vals.length>2 ? vals[2] : "00")+"\" style=\"height:230px;\">";
      for(var i=0;i<60;i++) {
        let second = i<10 ? "0"+i : i+"";
        html += "<li";
        if(vals.length>2 && second==vals[2]) html += " style=\"background-color: #3399FF;color: #FFFFFF;\"";
        html += ">"+second+"</li>";
      }
      html += "</ul>"; 
    }
    return html;
  }

  toToday() {
    this.setDatePickerValue(new Date());
    event.stopPropagation();
  }

  toPrevYear() {
    let date = new Date($(".tfp-datetime-picker").attr("data-value"));
    date.setYear(date.getFullYear()-1);
    this.setDatePickerValue(date);
  }

  toPrevMonth() {
    let date = new Date($(".tfp-datetime-picker").attr("data-value"));
    date.setMonth(date.getMonth()-1);
    this.setDatePickerValue(date);
  }

  toNextYear() {
    let date = new Date($(".tfp-datetime-picker").attr("data-value"));
    date.setYear(date.getFullYear()+1);
    this.setDatePickerValue(date);
  }

  toNextMonth() {
    let date = new Date($(".tfp-datetime-picker").attr("data-value"));
    date.setMonth(date.getMonth()+1);
    this.setDatePickerValue(date);
  }

  getCurDateTime() {
    if(this.type=="Date") return (new Date()).format("yyyy-MM-dd");
    if(this.type=="DateTime") {
      if(this.showSecond) {
        return (new Date()).format("yyyy-MM-dd HH:mm:ss");
      } else {
        return (new Date()).format("yyyy-MM-dd HH:mm");
      }
    }
  }

  initRuntime() {
    let that = this;
    this._jqObj.click(function(){
      if(that.dataModel.readonly || that.dataModel.disabled) return;
      if($(".tfp-datetime-picker").length>0) {
        let cptId = $(".tfp-datetime-picker").attr("data-cptid");
        if(cptId==that.id) return;
        that.closePicker();
      }
      that.showPicker();
      event.stopPropagation();
    });
    if(this.dataModel.defaultNow && !this.dataModel.value) {
      this.dataModel.value = this.getCurDateTime();
      this._jqObj.find("input").val(this.dataModel.value);
    }
  }
}