$(function() {
  var tpl = {
    'initPhotoTpl': '<div class="photo-list-wp clearfloat">\
                        <div class="photo-list clearfloat">\
                        <%if(facePicList){%>\
                          <%for(var i=0;i<facePicList.length;i++){%>\
                            <div class="photo-item photo-item-init" data-imageid="<%=facePicList[i].imageId%>">\
                              <div class="photo-item-img" style="background-image: url(<%=facePicList[i].imageUrl%>)"></div>\
                              <div class="del-btn"></div>\
                            </div>\
                          <%}%>\
                          <%}%>\
                        </div>\
                        <div class="photo-btn">\
                          <input class="photo-file" type="file"/>\
                        </div>\
                      </div>',
    'photoTpl': '<div class="photo-item photo-item-add" data-url="<%=imageUrl%>">\
                    <div class="photo-item-img" style="background-image: url(<%=url%>)"></div>\
                    <div class="del-btn"></div>\
                </div>'
  }
  var openId = sessionStorage.getItem("openId");
  var userId = GetQueryString("userId");
  var organizationId = $('#organizationId').val() || (sessionStorage.getItem("orgId") || '')
  var virId = $('#developId').val() || (sessionStorage.getItem("virId") || '')
  // 修改的部分取接口拿，不在sessionli取
  var userName, addressId, deptId, deptName, address, facePicList
  
  
  var initImageUrlids = [];//初始的人脸id
  var _data; //部门数据集合
  getUserInfo()
  renderImg()  //人脸
  ajaxGetSection(); //部门
  $(".userName").val(userName);
  $('body').on('change', '.section', function(event) {
    event.preventDefault();
    /* Act on the event */
    var id = $(this).val()
    if (!id) {
      $('.address_p').text('')
    } else {
      $.each(_data, function(index, el) {
        if (el.id == deptId) {
          $('.address_p').text(el.address)
        }
      });
    }
  });
  $(".certain-modify").on("click", function() {
    let name = $(".userName").val();
    let deptId = $(".section").val();
    let deptName = $(".section option:selected").text();
    let addressId = $(".address").val();
    if (!name) {
      layer.open({
        content: '请输入姓名',
        skin: 'msg',
        time: 2 //2秒后自动关闭
      });
      return false
    }
    ajaxModify(userId, name, addressId, deptId, deptName);
  })
  //上传识别图片
  $("body").on("change", '.photo-file', function() {
    var file = $(this)[0].files[0];
    var fileName = $(this)[0].value;
    var suffixIndex = fileName.lastIndexOf(".");
    var suffix = fileName.substring(suffixIndex + 1).toUpperCase();
    if ($(".photo-item").length == 3) {
      layer.open({
        content: '识别图片最多上传3张!',
        skin: 'msg',
        time: 2 //2秒后自动关闭
      });
      return false;
    }
    if (suffix != "BMP" && suffix != "JPG" && suffix != "JPEG" && suffix != "PNG" && suffix != "GIF") {
      layer.open({
        content: '请上传图片（格式BMP、JPG、JPEG、PNG等）!',
        skin: 'msg',
        time: 2 //2秒后自动关闭
      });
      return false;
    }
    lrz(file, {
      quality: 0.8, //设置压缩率   
      width: 400
    }).then(function(results) {
      upload(results.base64);
    });
  });
  // 删除图片
  $('body').on("click",".del-btn", function () {
    $(this).closest(".photo-item").remove();
    if ($(".photo-item").length < 3) {
      $(".photo-btn").css("display", "block")
    }
  })
  // 拿用户信息
  function getUserInfo(){
    $.ajax({
      url: $("#contextPath").val() + "/wechat/appUser/getUserInfo",
      type: "POST",
      dataType: "json",
      data: {
        openId: openId,
        organizationId: organizationId
      },
      async: false,
      timeout: 30000,
      success: function(data) {
        userName = data.data.userName || '';
        addressId =  data.data.addressId || ''
        deptId =  data.data.deptId || ''
        deptName =  data.data.deptName || ''
        address =  data.data.address || ''
        facePicList = data.data.facePicList
      },
      error: function(xhr, textStatus) {
      }
    });
  }
  /**
   * 上传人脸识别图片
   * @param file file文件
   */
  function upload(clearBase64) {
    $.ajax({
      url: $("#contextPath").val() + "/wechat/appUser/validateImage",
      type: "POST",
      dataType: "json",
      data: {
        imageUrl: clearBase64,
        virtualArchId: virId
      },
      timeout: 30000,
      beforeSend: function(xhr) {

      },
      success: function(data) {
        if (data.flag) {
          $(".photo-list").append(template.render(tpl.photoTpl)(data));
          if ($(".photo-item").length == 3) {
            $(".photo-btn").css("display", "none")
          }
          $(".del-btn").on("click", function() {
            $(this).closest(".photo-item").remove();

            $(".photo-file").val("");
            if ($(".photo-item").length < 3) {
              $(".photo-btn").css("display", "block")
            }
          })
        } else {
          layer.open({
            content: data.desc,
            skin: 'msg',
            time: 2
          });
        }
      },
      error: function(xhr, textStatus) {

      }
    });
  }
  //确认修改请求
  function ajaxModify(userId, userName, addressId, deptId, deptName) {
    var imageUrlidsArr = []
    var removeUrlidsArr = []
    var addimgUrls = ''
    for (var i = 0; i < $(".photo-item-add").length; i++) {
        if ($(".photo-item-add")[i].getAttribute("data-url")) {
          addimgUrls += $(".photo-item-add")[i].getAttribute("data-url") + ",";
        }
      }
    for (var i = 0; i < $(".photo-item-init").length; i++) {
      imageUrlidsArr.push($(".photo-item-init")[i].getAttribute("data-imageid"));
    };
    // 塞选出剩下的初始id和移除的id
    if(!imageUrlidsArr.length){
      removeUrlidsArr = initImageUrlids
    }else{
      $.each(initImageUrlids,function(index, el) {
        if(imageUrlidsArr.indexOf(el) == -1){
          removeUrlidsArr.push(el)
        }
      });
    }
    // console.log(addimgUrls)
    // console.log(imageUrlidsArr)
    // console.log(removeUrlidsArr)
    $.ajax({
      url: $("#contextPath").val() + "/wechat/appUser/modifyUserInfo",
      type: "POST",
      data: {
        userId: userId,
        userName: userName,
        addressId: addressId,
        deptId: deptId,
        deptName: deptName,
        addimgUrls:addimgUrls,
        imageUrlids:imageUrlidsArr.join(','),
        removeUrlids:removeUrlidsArr.join(',')
      },
      success: function(data) {
        if (data.code == "200") {
          window.history.go(-1);
        } else {
          layer.open({
            content: data.msg,
            skin: 'msg',
            time: 2
          });
        }
      },
      error: function(data) {}
    });
  }
  // 获取部门和地址列表
  function ajaxGetSection(callback) {
    $.ajax({
      url: $("#contextPath").val() + "/wechat/appUser/getDept",
      type: "POST",
      data: {
        orgId: organizationId,
        virId: virId
      },
      success: function(data) {
        var html = ''
        if (data.code == "200") {
          _data = data.data
          if (_data) {
            $.each(_data, function(index, el) {
              if (el.id == deptId) {
                html += '<option value="' + el.id + '" selected>'
                $('.address_p').text(el.address)
              } else {
                html += '<option value="' + el.id + '">'
              }
              html += el.name
              html += '</option>'
            });
            $('.section').append(html) 
          }
        } else {
          layer.open({
            content: data.msg,
            skin: 'msg',
            time: 2
          });
        }
      },
      error: function(data) {}
    });
  }
  function renderImg(){
    var _facePicList = facePicList || ''
    $(".item-con").append(template.render(tpl.initPhotoTpl)({facePicList:_facePicList}));
    if ($(".photo-item").length) {
      for (var i = 0; i < $(".photo-item-init").length; i++) {
        initImageUrlids.push($(".photo-item-init")[i].getAttribute("data-imageid"));
      }
    }
  }
  /**
   * 获取url的参数
   * @param name 参数名
   */
  function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
  }
})