window.onload = function () {

  'use strict';

  // var screenWidth = $(window).width();
  // var screenHeight =  $(window).height();
  var screenWidth = 988;
  var screenHeight = 438;
  var contextPath = $("#contextPath").val(); //请求前缀
  var Cropper = window.Cropper;
  var console = window.console || {
    log: function () {}
  };
  var container = document.querySelector('.img-container');
  var image = container.getElementsByTagName('img').item(0);
  var actions = document.getElementById('actions');
  var isUndefined = function (obj) {
    return typeof obj === 'undefined';
  };
  var options = {
    minContainerHeight: screenHeight,
    minContainerWidth: screenWidth,
    aspectRatio: '', //裁剪框比例 1：1
    viewMode: 1, //显示
    guides: false, //裁剪框虚线 默认true有
    dragMode: "move",
    build: function (e) { //加载开始
      //可以放你的过渡 效果
    },
    built: function (e) { //加载完成
      $("#containerDiv").show();
      $("#imgEdit").show();
    },
    zoom: function (e) {
      console.log(e.type, e.detail.ratio);
    },
    background: true, // 容器是否显示网格背景
    movable: true, //是否能移动图片
    cropBoxMovable: true, //是否允许拖动裁剪框
    cropBoxResizable: true, //是否允许拖动 改变裁剪框大小
  };
  var cropper = new Cropper(image, options);

  function preventDefault(e) {
    if (e) {
      if (e.preventDefault) {
        e.preventDefault();
      } else {
        e.returnValue = false;
      }
    }
  }

  // Tooltip
  $('[data-toggle="tooltip"]').tooltip();


  if (typeof document.createElement('cropper').style.transition === 'undefined') {
    $('button[data-method="rotate"]').prop('disabled', true);
    $('button[data-method="scale"]').prop('disabled', true);
  }

  // Methods
  actions.querySelector('.docs-buttons').onclick = function (event) {
    var e = event || window.event;
    var target = e.target || e.srcElement;
    var result;
    var input;
    var data;

    if (!cropper) {
      return;
    }

    while (target !== this) {
      if (target.getAttribute('data-method')) {
        break;
      }

      target = target.parentNode;
    }

    if (target === this || target.disabled || target.className.indexOf('disabled') > -1) {
      return;
    }

    data = {
      method: target.getAttribute('data-method'),
      target: target.getAttribute('data-target'),
      option: target.getAttribute('data-option'),
      secondOption: target.getAttribute('data-second-option')
    };

    if (data.method) {
      if (typeof data.target !== 'undefined') {
        input = document.querySelector(data.target);

        if (!target.hasAttribute('data-option') && data.target && input) {
          try {
            data.option = JSON.parse(input.value);
          } catch (e) {
            console.log(e.message);
          }
        }
      }

      if (data.method === 'getCroppedCanvas') {
        data.option = JSON.parse(data.option);
      }

      result = cropper[data.method](data.option, data.secondOption);

      switch (data.method) {

        case 'scaleX':
          console.log(scaleX, 'ccc');
        case 'scaleY':
          console.log(scaleY, 'ddd');
          target.setAttribute('data-option', -data.option);
          break;

        case 'getCroppedCanvas':
          if (result) {
            console.log(result, 'aaa');
            var fileImg = result.toDataURL('image/jpg');
            // console.log(fileImg.width,fileImg.height,'bbb');
            // $("#showImg").attr("src",fileImg).show();
            var typeImg = "image/" + '';
            if($("#state").val()==1){
            	var formData = new FormData();
            	var coverFile = upload(fileImg, typeImg || "image/png");
            	 formData.append("filedata", coverFile.get("pictures"));
            	 //coverFile.get("pictures");
            	 if(coverFile.get("pictures").size>1024*1024*1024){
 						layer.alert('图片大小须在1M以内!');
 						return false;
 					};
            	 $("#imgCutConfirm").attr("disabled",true);
            	 $.ajax({
     				url: contextPath + '/admin/enter/uploadImage',
     				type: "POST",
     				data: formData,
    				cache: false, // 不缓存
    				processData: false, // 告诉jQuery不要去处理发送的数据
    				contentType: false, // 告诉jQuery不要去设置Content-Type请求头
     				success: function (data) {
     					if(data.code == 200 && data.data){
     						 var $dom = $(".announcement-item").eq($(".small-notice-item.current").index())
     		            	 $(".small-notice-item.current .s-notice-cover").css("background-image", "url(" + fileImg + ")");
     		                 $dom.find("#showImg").attr("src", fileImg);
     		                 $dom.find("#showImg").data("url",data.data.preview);
     		            	 $dom.find(".img-wrapper").css("background-image", "url(" + fileImg + ")");
     		            	 $dom.find("#photoBtn").val("更换图片");
     		            	 
     		            	 $dom.find("#inputImage").val("");
     		            	$("#imgCutConfirm").attr("disabled",false);
     		            	var typeImg = "image/" + '';
     		   				var $dom = $(".announcement-item").eq($(".small-notice-item.current").index()).find("#showImg");
//     		   				if($dom.attr('src')){
//     		   					if((upload($dom.attr('src'), typeImg || "image/png").get("pictures")).size>1024*1024*1024){
//     		   						layer.alert('图片大小须在1M以内!');
//     		   						return false;
//     		   					};
     		   				$("#containerDiv").hide();
     						$("#imgEdit").hide();
     						$("#getCroppedCanvasModal").modal("hide");
//     		   				}
     					}else{
     						$("#imgCutConfirm").attr("disabled",false);
     						layer.msg(data.msg);
     					}
     				},
     				error: function(err){
     					alert("上传图片失败！")
     					$("#imgCutConfirm").attr("disabled",false);
     				}
     			});
            }else if($("#state").val()==2 && $("#content").val()==1 ){//图文
            	 $("#graphic #showImg").attr("src", fileImg);
                 //控制图片大小不大于1M
                 // if ((upload(fileImg, typeImg || "image/png").get("pictures")).size < 1024 * 1024) {
                   console.log('图片小于1M')
                   $("#graphic .img-wrapper").css("background-image", "url(" + fileImg + ")");
                   $("#graphic").find("#showImg").attr("src", fileImg);
                   $("#graphic #photoBtn").val("更换图片");
                   $("#graphic #inputImage").val("");
                 // }else{
                 //   console.log('图片大于1M')
                 //   layer.alert('图片大小须在1M以内!');
                 // }
            }else if($("#state").val()==2 && $("#content").val()==2 ){//跳转链接
	           	 $("#link #showImg").attr("src", fileImg);
	           	 $("#link").find("#showImg").attr("src", fileImg);
	             //控制图片大小不大于1M
	             // if ((upload(fileImg, typeImg || "image/png").get("pictures")).size < 1024 * 1024) {
	               console.log('图片小于1M')
	               $("#link .img-wrapper").css("background-image", "url(" + fileImg + ")");
	               $("#link #photoBtn").val("更换图片");
	               $("#link #inputImage").val("");
	             // }else{
	             //   console.log('图片大于1M')
	             //   layer.alert('图片大小须在1M以内!');
	             // }
        }
          }

          break;

        case 'destroy':
          $("#inputImage").val("");
          $("#containerDiv").hide();
          $("#imgEdit").hide();
          break;
      }

      if (typeof result === 'object' && result !== cropper && input) {
        try {
          input.value = JSON.stringify(result);
        } catch (e) {
          console.log(e.message);
        }
      }

    }
  };

  // Import image
  var inputImage = document.getElementById('inputImage');
  var URL = window.URL || window.webkitURL;
  var blobURL;

  if (URL) {
    inputImage.onchange = function () {
      var files = this.files;
      var file;
      
      if (cropper && files && files.length) {
        file = files[0];

        if (/^image\/\w+/.test(file.type)) {
          blobURL = URL.createObjectURL(file);
          cropper.reset().replace(blobURL);
        } else {
          window.alert('Please choose an image file.');
        }
      }
      $(inputImage).find("img").hide();
    };
  } else {
    inputImage.disabled = true;
    inputImage.parentNode.className += ' disabled';
  }

};