var imgarr = [], UIAlbumBrowser= "";
var pageId="", pageRecordParentId= "", recordParentId= "",
templateId="", templateName="",departmentId="",userId= "",userName= "";
var i = 0;
// // 记录模版内容
// function recodeContent(id,recodeId) {
//   var param={
//     pageId:'f8bdc7c051f14b6ea690081f55043384',
//     pageRecordId:'064cfd8b66cd42169606ab78f283f0b4',
//     recordParentId:'',
//   }
//   $http.fnReuestDataNologing(UrlRouter.getInspection,'','get',param,function (ret,err) {
//     if (ret.code === '200') {
//       pageRecordParentId = ret.data.parentId;
//       templateId = ret.data.recordTemplate.id
//       templateName = ret.data.recordTemplate.templateName
//       $apis.html(recode_content, '#addRecodeTemplate',ret.data.recordTemplate);
//       // $apis.CloseUILoading();
//     }
//   })
// }
// 录音
// 删除录音
function delAudio(that) {
    $(that).hide();
    $(that).parent().find('.upload-btn').show();
    $(that).parent().parent().find('audio').remove();
}
// 视频
// 删除视频
function delVedio(that) {
    $(that).hide();
    $(that).parent().find('.upload-btn1').show();
    $(that).parent().parent().find('video').remove();
}
// 状态
function checkbox(el,list,titles) {
    var itmes = {title:'',value:''},itmesArray = [];
    for (var j= 0;j<list.length;j++) {
        itmes = {};
        itmes.title = list[j].statusContent;
        itmes.value = list[j].id;
        itmesArray.push(itmes)
    }

    setTimeout(function () {
      $('#'+el).select({
          title: titles,
          multi: true,
          items: itmesArray
      });
    },1000)
    return ''
}
// 记录项多选-单选
function checkboxRecord(el,list) {
    var itmes = {title:'',value:''},itmesArray = [],idArray=[],titleArray=[];
    for (var j= 0;j<list.length;j++) {
        itmes = {};
        if (list[j].isDefault === true) {
          titleArray.push(list[j].itemValue)
          idArray.push(list[j].id)
        }
        itmes.title = list[j].itemValue;
        itmes.value = list[j].id;
        itmesArray.push(itmes)
    }
    setTimeout(function () {
      $("#"+el).select({
          multi: true,
          items: itmesArray
      });
      $("#"+el).attr("data-values",idArray.join(','))
      $("#"+el).attr("value",titleArray.join(','))
    },1000)
    return ''
}
function radioRecord(el,list) {
    var itmes = {title:'',value:''},itmesArray = [],idArray=[],titleArray=[];
    for (var j= 0;j<list.length;j++) {
        itmes = {};
        if (list[j].isDefault === true) {
          titleArray.push(list[j].itemValue)
          idArray.push(list[j].id)
        }
        itmes.title = list[j].itemValue;
        itmes.value = list[j].id;
        itmesArray.push(itmes)
    }
     setTimeout(function () {
       $("#"+el).select({
           multi: false,
           items: itmesArray
       });
       $("#"+el).attr("data-values",idArray.join(','))
       $("#"+el).attr("value",titleArray.join(','))
     },1000)
    return ''
}
//状态
// 多选
function statusCheckbox(el,list,titles) {
  var itmes = {title:'',value:''},itmesArray = [];
  for (var j= 0;j<list.length;j++) {
      itmes = {};
      itmes.title = list[j].statusContent;
      itmes.value = list[j].id;
      itmesArray.push(itmes)
  }
  setTimeout(function () {
    $("#"+el).select({
        title: titles,
        multi: true,
        items: itmesArray
    });
  },1000)
  return ''
}
// 单选
function statusRadio(el,list,titles) {
  var itmes = {title:'',value:''},itmesArray = [];
  for (var j= 0;j<list.length;j++) {
      itmes = {};
      itmes.title = list[j].statusContent;
      itmes.value = list[j].id;
      itmesArray.push(itmes)
  }
  setTimeout(function () {
    $("#"+el).select({
        title: titles,
        multi: false,
        items: itmesArray
    });
  },1000)
  return ''
}
// 上传图片
function uploadImg(type,that) {
   if (type == 'remote') {
     api.getPicture({
         sourceType: 'camera'
     }, function(ret, err){
         if(ret && ret.data!=""){
             uploadHead(ret.data,that);
         }
     });
   }else {
     api.actionSheet({
         title: '选择',
         cancelTitle: '取消',
         buttons: ['相机','相册']
     }, function(ret, err) {
         if (ret.buttonIndex !=3) {
             var type = 'camera';
             if(ret.buttonIndex == 1){
                 type = 'camera';
                 api.getPicture({
                     sourceType: type
                 }, function(ret, err){
                     if(ret && ret.data!=""){
                         uploadHead(ret.data,that);
                     }
                 });
             }else {
                 type = 'album';
                 // 支持多图片上传，UIAlbumBrowser模块获取图片路径
                 changeImageUrl(that)
             }
         }
     });
   }
}
// upload img
function uploadHead(imgUrl,that){
    api.showProgress({
      title: '',
      text: '上传中...',
      modal: true
    });
    api.ajax({
        url:UrlRouter.uploadFile,
        method: 'post',
        data: {
            files: {
                file:imgUrl
            }
        }
    },function(ret, err){
        if (ret) {
            if(ret.code === '200'){
                var html = `<div class="img-item file-width" img-Url="${ret.data.fullURL}">
                              <img src="${ret.data.fullURL}" alt="">
                            </div>`;
                $api.append(that.parentNode,html);
                api.toast({
                    msg: '上传成功',
                    duration: 2000,
                    location: 'top'
                });
                api.hideProgress()
            }else {
                api.hideProgress()
                api.toast({
                    msg: '上传失败',
                    duration: 2000,
                    location: 'top'
                });
            }
        } else {
            api.hideProgress()
            api.toast({
                msg: '网络错误',
                duration: 2000,
                location: 'top'
            });
        }
    });

}
// 获取相册图片路径
function changeImageUrl(el) {
    UIAlbumBrowser.imagePicker({
        max: 9,
        styles: {
            bg: '#000000',
            //cameraImg: 'widget://res/cameraImg.png',
            mark: {
                position: 'top_right',
                size: 20
            },
            nav: {
                bg: '#000000',
                cancelColor: '#fff',
                cancelSize: 16,
                nextStepColor: '#7fff00',
                nextStepSize: 16
            },
            thumbnail: {
                w: 100,
                h: 100
            }
        },
        animation: true,
    }, function(ret) {
        if (ret.eventType == 'nextStep') {
            UIAlbumBrowser.closePicker();
            if (ret.list && ret.list.length > 0) {
                imgarr = ret.list;
                // 转换缩略图路径 ios
                UIAlbumBrowser_transPath(el);
            }
        }
        if (ret.originalPath && ret.originalPath.length > 0) {
            uploadHead(ret.originalPath,el)
        }
    });
}
// 转换缩略图路径 ios
function UIAlbumBrowser_transPath(el) {
    UIAlbumBrowser.transPath({
        path: imgarr[i].path
    }, function(ret, err) {
        if (ret) {
            i++;
            if (i < imgarr.length) {
                UIAlbumBrowser_transPath(el);
            } else {
                i = 0;
            }
            uploadHead(ret.path,el)
        }
    });
}
// 上传文件
// 浏览手机文件夹,获取文件路径
// 上传文件
function uploadFile(el,fileUrl) {
    api.showProgress({
      title: '',
      text: '上传中...',
      modal: true
    });
    api.ajax({
        url: UrlRouter.uploadFile,
        method: 'post',
        data: {
            files: {
                file:fileUrl
            }
        }
    },function(ret, err){
        if (ret) {
            api.hideProgress()
            if(ret.code === '200'){
                api.toast({
                    msg: '上传成功',
                    duration: 2000,
                    location: 'top'
                });
                var fileType = ret.data.fileName.substr(ret.data.fileName.length-3,3);
                if (
                    fileType == 'ppt' ||
                    fileType == 'ptx' ||
                    fileType == 'lsx' ||
                    fileType == 'xls' ||
                    fileType == 'doc' ||
                    fileType == 'ocx' ||
                    fileType == 'zip' ||
                    fileType == 'rar' ||
                    fileType == 'pdf'
                ){
                    var html = `<div class="file-item-add file-width" file-Url="${ret.data.fullURL}" file-Name="${ret.data.fileName}">
                              <img src="../../icon/${ret.data.fullURL.substr(ret.data.fullURL.length-3,3)}.png"/>
                              <p>${ret.data.fileName}</p>
                          </div>`;
                    $api.append(el.parentNode,html);
                }else {
                    api.toast({
                        msg: '文件格式不对',
                        duration: 2000,
                        location: 'top'
                    });
                }
            }else {
                api.toast({
                    msg: '上传失败',
                    duration: 2000,
                    location: 'top'
                });
            }
        } else {
            api.hideProgress()
            api.toast({
                msg: '网络错误',
                duration: 2000,
                location: 'top'
            });
        }
    });
}
// 上传音频
function uploadAudio(el,fileUrl) {
    api.showProgress({
      title: '',
      text: '上传中...',
      modal: true
    });
    api.ajax({
        url: UrlRouter.uploadFile,
        method: 'post',
        data: {
            files: {
                file:fileUrl
            }
        },
        timeout:60
    },function(ret, err){
        if (ret) {
            api.hideProgress()
            if(ret.code === '200'){
                api.toast({
                    msg: '上传成功',
                    duration: 2000,
                    location: 'top'
                });
                var fileType = ret.data.fileExt;
                if (
                    fileType == 'm4a' ||
                    fileType == 'mp3' ||
                    fileType == 'amr' ||
                    fileType == 'AMR' ||
                    fileType == 'WAV' ||
                    fileType == 'wav' ||
                    fileType == 'AWB' ||
                    fileType == 'awb'
                ){
                    $(el).hide();
                    $(el).parent().find('.del-btn').show();
                    var html = `<audio src="${ret.data.fullURL}" controls></audio>`;
                    $(el).parent().parent().find('.audio-content').html(html)
                }else {
                    api.toast({
                        msg: '音频格式不对',
                        duration: 2000,
                        location: 'top'
                    });
                }
            }else {
                api.toast({
                    msg: '上传失败',
                    duration: 2000,
                    location: 'top'
                });
            }
        } else {
            api.hideProgress()
            api.toast({
                msg: '网络错误',
                duration: 2000,
                location: 'top'
            });
        }
    });
}
// 上传视频
function uploadVedio(el,fileUrl) {
    api.showProgress({
      title: '',
      text: '上传中...',
      modal: true
    });
    api.ajax({
        url: UrlRouter.uploadFile,
        method: 'post',
        data: {
            files: {
                file:fileUrl
            }
        },
        timeout:60
    },function(ret, err){
        if (ret) {
            api.hideProgress()
            if(ret.code === '200'){
                api.toast({
                    msg: '上传成功',
                    duration: 2000,
                    location: 'top'
                });
                var fileType = ret.data.fileExt;
                if (
                    fileType == 'mp4' ||
                    fileType == 'avi' ||
                    fileType == 'wmv' ||
                    fileType == '3gp' ||
                    fileType == 'mkv' ||
                    fileType == 'flv' ||
                    fileType == 'rmvb'
                ){
                    $(el).hide();
                    $(el).parent().find('.del-btn').show();
                    var html = `<video controls="controls" style="width: 100%;height: 200px;">
                        <source src="${ret.data.fullURL}">
                        当前不支持播放该视频
                    </video>`;
                    $(el).parent().parent().find('.audio-content').html(html)
                }else {
                    api.toast({
                        msg: '视频格式不对',
                        duration: 2000,
                        location: 'top'
                    });
                }
            }else {
                api.toast({
                    msg: '上传失败',
                    duration: 2000,
                    location: 'top'
                });
            }
        } else {
            api.hideProgress()
            api.toast({
                msg: '网络错误',
                duration: 2000,
                location: 'top'
            });
        }
    });
}
//提交
function mvalidate() {
  var isOptionals = $('.isOptionals')
  var opnum=0,eachnum=0;
  isOptionals.each(function (index) {
   if ($(this).attr('isOptional') == 'true'){
      ++opnum;
   }
   if ($(this).attr('isOptional') == 'true' && $(this).parent().find('.isOptional').val() !== "") {
    ++eachnum
    }
  })
  if (opnum == eachnum) {
    return true;
  }else {
    return false;
  }
}
function submitRecode() {
  if (mvalidate()) {
    // api.showProgress({
    //   title: '',
    //   text: '提交中...',
    //   modal: true
    // });
    // 检查项
    var inspectTremA = $('.checked'),checkItemArray = [];
    var obj = {checkItemId:'',instanceValue:''}
    for (var i = 0; i < inspectTremA.length; i++) {
      obj = {}
      if (inspectTremA[i].checked) {
          obj.checkItemId = inspectTremA[i].value
          obj.instanceValue = true;
          checkItemArray.push(obj)
      }
    }
    // 记录项
    var inutItme =[],recordTrems = $('.recordTrems'),inputObj = {inputId:'',inputValue:''},changeInput = $('.changeInput');
     //// 1.文本, 时间，日期，数字
     recordTrems.each(function () {
         inputObj = {};
         var inputValue = $(this).val(),
         inputId = $(this).attr('recordTrem-id'),
         datetime = $(this).attr('data-datetime');
         if (datetime) {
           inputObj.inputId = inputId;
           inputObj.inputValue = inputValue.replace("T"," ");
         }else {
           inputObj.inputId = inputId;
           inputObj.inputValue = inputValue;
         }
         inutItme.push(inputObj);
     });
     //2.多选,单选
     changeInput.each(function () {
        inputObj = {};
        inputObj.inputId = $(this).attr('recordTrem-id');
        inputObj.inputValue = $(this).attr('data-values');
        inutItme.push(inputObj);
     });
     //3.录音
     var mp3_wrap = $('.mp3_wrap');
     mp3_wrap.each(function () {
          inputObj = {};
          inputObj.inputId = $(this).attr('recordTrem-id');
          inputObj.inputValue = $(this).find('audio').attr('src');
          inutItme.push(inputObj);
      });
     //4.视频
     var mp4_wrap = $('.mp4_wrap');
     mp4_wrap.each(function () {
          inputObj = {};
          inputObj.inputId = $(this).attr('recordTrem-id');
          inputObj.inputValue = $(this).find('video>source').attr('src');
          inutItme.push(inputObj);
      });
     //5.文件
     var fileList_warp = $('.fileList_warp'),fileArray = [],fileName = [],num = 0;
     fileList_warp.each(function (index) {
        inputObj = {};
        fileArray= [];
        inputObj.inputId = $(this).attr('recordTrem-id');
        var fileList = $(this).find('.file-item-add');
        fileList.each(function () {
            fileArray.push($(this).attr('file-Url')+"-"+$(this).attr('file-Name'));
        });
        inputObj.inputValue = fileArray.join(',');
        inutItme.push(inputObj);
     });
     //6.图片
     var photoFile = $('.photoFile'),photoArray = [];
     var isOptional = true
     photoFile.each(function () {
          inputObj = {};
          photoArray =[];
          inputObj.inputId = $(this).attr('recordTrem-id');
          var photoList = $(this).find('.img-item');
          photoList.each(function () {
              photoArray.push($(this).attr('img-Url'));
          });
          inputObj.inputValue = photoArray.join(',');
          if ($(this).attr('isOptional') === "true" && inputObj.inputValue =="") {
              isOptional = false
          }
          inutItme.push(inputObj);
      });
      if (isOptional === false) {
        return api.toast({
            msg: '请上传带*号的图片',
            duration: 2000,
            location: 'top'
        });
      }
    // 状态项
    // 状态
    var moreStatusA = $('.moreStatusA'),statusA = [],statusObj = {statusId:"",statusValue:''};
    moreStatusA.each(function () {
        statusObj = {};
        statusObj.statusId = $(this).attr('statusId');
        statusObj.statusValue = $(this).attr('data-values');
        statusA.push(statusObj);
    });
    var filterl= inutItme.filter(function (item) {
        if (item.inputValue != undefined){
            return item.inputValue !=""
        }
    });
    var param= {
        checkItems: checkItemArray,
        createBy: userId,
        createName: userName,
        inputs:filterl,
        pageId:pageId,
        pageRecordParentId:pageRecordParentId,
        recordParentId:recordParentId,
        status:statusA.length !=0? statusA : [],
        statusContent:$('.statusContent').val(),
        templateId:templateId,
        templateName:templateName,
        departmentId:departmentId,
        spName:spName,
        lng:lon,
        lat:lat
    }
    $.ajax({
      url: UrlRouter.addRecordInstance,
      type: 'post',
      contentType:'application/json;charset=UTF-8',
      dataType: 'json',
      data: JSON.stringify(param),
      success: function (ret) {
        if(ret.code === '200') {
          $('.submit-btn').attr('disabled','disabled')
          api.hideProgress()
          $event.openTabLayout('recodeDetails'+Math.random(),'recodeDetails','记录详情',{recordParentId:ret.data});
        }else if (ret.code == 422) {
          api.hideProgress()
          api.alert({
              title: '提示',
              msg: '请填写记录项',
          });
        }
      },
      error:function (err) {
        api.hideProgress()
        api.toast({
          msg: err,
          duration: 3000,
          location: 'top'
        });
      }
    })
  }else {
    api.toast({
      msg: '请填写带*号的内容！',
      duration: 3000,
      location: 'top'
    });
  }
}
// 定位初始化
var  spName = '',lon='',lat='';
function getLonLat(flag) {
  if (flag) {
    api.showProgress({
        title: '提示',
        text: '定位中...',
    });
  }
  var aMap = api.require('aMap');
  aMap.getLocation(function(ret, err) {
      if (ret.status) {
        api.hideProgress();
        lon= ret.lon; lat=ret.lat;
        aMap.getNameFromCoords({
            lon: ret.lon,
            lat: ret.lat
        }, function(ret, err) {
            if (ret.status) {
                spName = ret.address
                $apis.html(position_warp, '#mapTemplate',ret);
            } else {
              api.toast({
                  msg: '请打开手机定位',
                  duration: 2000,
                  location: 'top'
              });
            }
        });
      } else {
        api.hideProgress();
        api.toast({
            msg: '定位失败请重新定位',
            duration: 2000,
            location: 'top'
        });
      }
  });
  return '';
}
