/**
  * 上传图片
  *
  *
  **/

function takePhoto(obj)
{
    var allowNum = $(obj).attr('imgMaxNum');
    var num = $(obj).parent().parent().find(".imgthumb").length;
    if(num >= allowNum){
        customToast(lang('5600010'), 2000);
        return false;
    }
    FNPhotograph.open({
        path: 'fs://savePath',
        album: true,
        quality: 'medium'
    }, function(ret) {
        // console.log(JSON.stringify(ret));
        if (ret.eventType == 'takePhoto') {
            FNPhotograph.close();
            compress(ret.imagePath, function(blob) {
                uploadimg(blob,obj);
            });
        } else if (ret.eventType == 'close') {
            FNPhotograph.close();
        }
    });
}

function uploadimg(base64img,obj) {
    $.ajax({
        url: host + "/tpm/Upload/UploadThumbnail",
        timeout: 30000,
        data: JSON.stringify({
            "image": base64img
        }),
        type: 'POST',
        success: function(data) {
            api.hideProgress();
            var html = '<div class="imgthumb"> <div class="photo-badge deletephoto" data-value="' + host + '/' + data.data + '">x</div> <div class="imgin"><img src="' + host + '/' + data.data +
                '" style="width:100%;height:100%;"></div> </div>';
            var imgarrstr = $(obj).parent().parent().find('input').val();
            var imgarr = [];
            if (imgarrstr.length > 0) {
                imgarr = imgarrstr.split(",");
            }
            imgarr.push(host + "/" + data.data);
            $(obj).parent().parent().find('input').val(imgarr.join(","));
            $(obj).parent().append(html);
            $(obj).parent().parent().find('.imgin').unbind("click");
            $(obj).parent().parent().find('.imgin').click(function() {
                fnOpenLightBoxThisCon(this);
            });
            listen_deletephoto(obj);
        },
        error: function(ret) {
            console.log(JSON.stringify(ret));
        }
    })
}

function listen_deletephoto(obj) {
      $(obj).parent().parent().find('.deletephoto').click(function(){
          var val = $(this).attr("data-value");
          $(this).parent().remove();
          var imgarrstr = $(obj).parent().parent().find('input').val();
          var imgarr = [];
          if (imgarrstr.length > 0) {
              imgarr = imgarrstr.split(",");
              var index = imgarr.indexOf(val);
              if (index > -1) {
                  imgarr.splice(index, 1);
              }
          }
          $(obj).parent().parent().find('input').val(imgarr.join(","));
    });
}
