<template>
	<view class="handler">
		<view class="body view-body">
			<view class="form_item column">
				<view class="title"><text class="required newicon newicon-bitian"></text>故障描述：</view>
				<uni-easyinput class="value" type="textarea" v-model="dataInfo.description" placeholder="请输入故障描述" :class="{formRed: isSubmit && !dataInfo.description.trim()}" />
			</view>
		<!-- 	<view class="candidate">
				<view class="candidate-item" v-for="item in candidateData" :key="item" @click="itemCandidate(item)">{{item.name}}</view>
			</view> -->
			<view class="form_item" v-if="cmdbRepair.valueconfig==1">
				<view class="title select">关联资产：</view>
				<input class="item-input" disabled placeholder="请扫描资产卡二维码" v-model="dataInfo.property"/>
				<text class="newicon newicon-saoma icon" @click="scanCodes"></text>
			</view>
			<view class="form_item">
				<view class="title">照片录像：</view>
				<view class="value">
					<uni-file-picker ref="handlerImgRef" v-model="dataInfo.handlerImgList"
					 limit="4" @success="handlerImgSuccess" file-mediatype="all" mode="grid"
					@fail="handlerImgFail" @select="handlerImgSelect" @delete="handlerImgDelete">
					</uni-file-picker>
					<view class="imgTips">(支持JPG/PNG格式图片，单张大小10M以内，录像支持30秒）</view>
				</view>
			</view>
			<view class="form_item">
				<view class="title">录音：</view>
				<view class="chunk" v-if="!dataInfo.localId" @touchstart.stop="examineRecord($event)">点击录音</view>
				<view class="chunk-2" v-if="dataInfo.localId">
					<view class="chunk-2-2" @click="playAudio">
						<view>播放录音</view>
						<image v-if="isPlayOut==1" class="chunk-img" src="../../static/img/audio_play.gif" mode=""></image>
					</view>
					<icon class="chunk-icon" type="clear" size="22" @click="clearRec"/>
				</view>
			</view>
		</view>
		<view class="foot_common_btns">
			<button @click="goBackOrToList" type="default" class="cancelButton btn">返回</button>
			<button @click="submit" type="default" class="primaryButton btn">下一步</button>
		</view>
		<view class="mask-class" v-if="isrecordType">
			<view class="mask-box">
				<image class="mask-img" src="../../static/img/audio_play.gif" mode=""></image>
			</view>
			<view class="mask-bottom">
				<view class="mask-bottom-txt" @touchend.stop="recStop($event)">结束录音</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { SM } from "@/http/http.js"
  import { ref, reactive, computed } from 'vue'
  import NumberModal from '@/components/NumberModal.vue';
  import { onLoad } from '@dcloudio/uni-app'
  import { generateNumberArray } from '@/utils/index.js'
  import { api_group, api_repairScanCode, api_incidentDetail, api_getSolution, api_user, api_incidentTask, api_branch, api_dutyDepartment, api_getDictionary, api_querySummaryDoc, api_addSummaryDoc } from "@/http/api.js"
  import { defaultColor } from '@/static/js/theme.js'
  import { useSetTitle } from '@/share/useSetTitle.js'
  import { useMakePhoneCall } from '@/share/useMakePhoneCall.js'
  import { useUploadFile } from '@/share/useUploadFile.js'
  import { useGoBack } from '@/share/useGoBack.js'
  import { useLoginUserStore } from '@/stores/loginUser'
  import { useHandlerStore } from '@/stores/handler'
	import { post } from "@/http/http.js"
	import wx from 'weixin-jsapi'
	// import Recorder from 'recorder-core';
	// import 'recorder-core/src/engine/mp3';
 //  import 'recorder-core/src/engine/mp3-engine';
 //  import 'recorder-core/src/engine/wav';
 //  import 'recorder-core/src/extensions/waveview';
			
  useSetTitle();
  const loginUserStore = useLoginUserStore();
  const handlerStore = useHandlerStore();
  const { makePhoneCall }  = useMakePhoneCall();
  const { uploadFile }  = useUploadFile();
  const { goBack }  = useGoBack();
  let rec = null
  let wave = null
  // 主题颜色
  const primaryColor = ref(defaultColor)
	
  // 数据
  const dataInfo = reactive({
    tabs: [
      // {id: 5, name: '故障处理', value: 'doing', num: ''},
      // {id: 6, name: '延期处理', value: 'overtime', num: ''},
    ],
    tabActiveValue: 0,//当前选择的tab
    incidentId: undefined,//事件ID
    incidentData: {},//事件对象
    description: '',//故障描述
		property:'', //资产
		assetId:null,//资产id
    handlerImgList: [],//处理图片列表
		localId:'' ,//录音本地id
		serverId:'',//录音服务器id
  })
  
	// 故障处理用是否提供备用机
	const newProvideBackupMachine = ref(0)
	
	// 知识库id
	const solutionId = ref(null)
	
  // 是否提交
  const isSubmit = ref(false)
  
  // 处理图片
  const handlerImgRef = ref(null)
	
  const ifShow = ref(false)
	
	const listStyles = ref({
		// 是否显示边框
		border: true,
		// 是否显示分隔线
		dividline: true,
		// 线条样式
		borderStyle: {
			width:1,
			color:'blue',
			radius:2
		}
	})

				
  const candidateData = ref([
		{name:'马桶肃杀'},
		{name:'马桶肃杀'},
		{name:'马桶肃杀'},
		{name:'马桶肃杀'},
		{name:'马桶肃杀'},
		{name:'马桶肃杀'},
		{name:'马桶肃杀'},
		{name:'马桶肃杀'},
		{name:'马桶肃杀'},
	])
  
	const cmdbRepair = ref(null)
	
	const recwave = ref(null);
	
	// 是否播放完毕
	const isPlayOut = ref(null);
	
	// 录音状态
	const isrecordType = ref(false);
	
	const longPressTimer = ref(null); // 长按定时器
	
	const touchStartTime = ref(0); // 触摸开始时间
				
  // 上一步或者返回列表
  function goBackOrToList(){
		uni.setStorageSync('repairData','')
    goBack();
  }
	
	function itemCandidate(item){
		dataInfo.description = item.name
	}
	
	// 开始录音
	function recOpen() {
		let param = {
		  requestUrl: location.href.split('#')[0]
		};
		post("/wechat/getJsConfig", param).then(res => {
		  if (res) {
		    wx.config({
		      debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
		      appId: res.appId, // 必填，企业号的唯一标识，此处填写企业号corpid
		      timestamp: res.timestamp, // 必填，生成签名的时间戳
		      nonceStr: res.nonceStr, // 必填，生成签名的随机串
		      signature: res.signature, // 必填，签名，见附录1
		      jsApiList: res.jsApiList // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
		    });
		    wx.ready(function() {
					// 开始录音
					wx.startRecord({
						success: function(res) {	
							isrecordType.value = true
						},					
						cancel: function() {
							alert('用户拒绝授权录音');
						}
					});
					
					// 录音录音自动停止接口
					wx.onVoiceRecordEnd({
						complete: function (res) {
							dataInfo.localId = res.localId;
						}
					})
					
					// 监听语音播放完毕接口
					wx.onVoicePlayEnd({
						success: function (res) {
							dataInfo.localId = res.localId; // 返回音频的本地ID
							isPlayOut.value = 2
						},
						fail:function(res){
							
						},
						complete: function(res) {
							dataInfo.localId = res.localId; // 返回音频的本地ID
							isPlayOut.value = 2
						}
					});
		    });
		  }
		})
	}
	
	// 开始录音
	function examineRecord(e) {
		// touchStartTime.value = e.timeStamp;
		// 设置长按定时器
		// longPressTimer.value = setTimeout(() => {
			// 长按事件处理
			recOpen()
		// }, 300);
	}
	
	// 结束录音
	function recStop(e) {
		// clearTimeout(longPressTimer.value);
		// 如果手指松开时间太短，则不是长按
		// const touchEndTime = e.timeStamp;
		// if (touchEndTime - touchStartTime.value < 1000) {
		// 	// 处理快速点击
		// 	uni.showToast({
		// 	  icon: 'none',
		// 	  title: '长按时间太短'
		// 	});
		// 	return
		// }
		if(isrecordType.value){
			wx.stopRecord({
				success: function (res) {
					dataInfo.localId = res.localId;
					isrecordType.value = false
				}
			});
		}
	}
	
	// 播放录音
	function playAudio(){
		wx.playVoice({
		    localId: dataInfo.localId, // 需要播放的音频的本地ID，由stopRecord接口获得
				success: function (res) {
					isPlayOut.value = 1
				}
		})
	}
	
	// 删除录音
	function clearRec(){
		dataInfo.localId = null
		isPlayOut.value = 2
	}
	
	// 上传录音
	function uploadAudio(){
		wx.uploadVoice({
			localId: dataInfo.localId, // 需要上传的音频的本地ID，由stopRecord接口获得
			isShowProgressTips: 1, // 默认为1，显示进度提示
			success: function (res) {
				dataInfo.serverId = res.serverId; // 返回音频的服务器端ID
				setTimeout(_=>{
					uni.setStorageSync('repairData',JSON.stringify(dataInfo))
					uni.navigateTo({
					  url: `/pages/repair/rapidRepNext`,
					});
				},100)
			}
		});
	}
	
	// 扫码资产码
	function scanCodes(){
		uni.showLoading({
		  title: "加载中",
		  mask: true,
		});

		SM().then((res) => {
			api_repairScanCode({
				code:res
			}).then((res2) => {
			  uni.hideLoading();
			  if (res2.state == 200) {
			    dataInfo.property = res2.data.name
					dataInfo.assetId = res2.data.id
			  } else {
			    uni.showToast({
			      icon: 'none',
			      title: res2.msg || '请求数据失败！'
			    });
			  }
			});
		})
	}
	
  // 上传处理图片成功
  function handlerImgSuccess(e){
    dataInfo.handlerImgList.forEach(v => {
      v.url = v.path;
    })
    console.log('上传成功',dataInfo.handlerImgList);
    let handlerOrder$ = handlerOrder();
    let requestList = [handlerOrder$];
    dataInfo.handlerImgList.forEach(v => {
      let handlerOrderImg$ = handlerOrderImg(v);
      requestList.push(handlerOrderImg$);
    })
    
    Promise.all(requestList).then(resList => {
      uni.hideLoading();
      console.log(resList);
      if(resList[0].state == 200){
        uni.showToast({
        	icon: 'none',
          title: '处理成功',
          mask: true,
        });
      }else{
        uni.showToast({
          icon: 'none',
          title: resList[0].msg || '请求数据失败！'
        });
      }
    })
  }
  
  // 上传处理图片失败
  function handlerImgFail(e){
    dataInfo.handlerImgList.forEach(v => {
      v.url = v.path;
    })
    console.log(dataInfo.handlerImgList);
  }
  
	
  // 选择上传图片
  function handlerImgSelect(e){
		console.log(6666,e.tempFiles)
		// 10*1024*1024 //10M
		if(e.tempFiles[0].extname=='mp4' ||
			e.tempFiles[0].extname=='avi' || 
			e.tempFiles[0].extname=='mpeg' || 
			e.tempFiles[0].extname=='wmv' ||
			e.tempFiles[0].extname=='mov' ||
			e.tempFiles[0].extname=='3gp' ||
			e.tempFiles[0].extname=='flv' ||
			e.tempFiles[0].extname=='mkv'
			){
				let item = dataInfo.handlerImgList.findIndex(i=>i.extname==e.tempFiles[0].extname)
				if(item!=-1){
					uni.showToast({
						icon: 'none',
						title: '只能上传一个视频文件'
					});
					dataInfo.handlerImgList = dataInfo.handlerImgList.splice(item,1);
				}else{
					dataInfo.handlerImgList = dataInfo.handlerImgList.concat(e.tempFiles);
				}
			}else{
				dataInfo.handlerImgList = dataInfo.handlerImgList.concat(e.tempFiles);
				
				if(e.tempFiles[0].extname=='png' || 
					e.tempFiles[0].extname=='jpg' || 
					e.tempFiles[0].extname=='gif' ||
					e.tempFiles[0].extname=='mp4' ||
					e.tempFiles[0].extname=='avi' || 
					e.tempFiles[0].extname=='mpeg' || 
					e.tempFiles[0].extname=='wmv' ||
					e.tempFiles[0].extname=='mov' ||
					e.tempFiles[0].extname=='3gp' ||
					e.tempFiles[0].extname=='flv' ||
					e.tempFiles[0].extname=='mkv'
					){
					}else{
						uni.showToast({
							icon: 'none',
						  title: '不支持此类型文件'
						});
						let item = dataInfo.handlerImgList.findIndex(i=>i.uuid==e.tempFiles[0].uuid)
						dataInfo.handlerImgList.splice(item,1);
					}
			}
  }
  
  // 删除上传图片
  function handlerImgDelete(e){
    dataInfo.handlerImgList = dataInfo.handlerImgList.filter(v => e.tempFile.uuid != v.uuid);
    console.log(dataInfo.handlerImgList);
  }
  
  // 获取事件详情
  function getIncidentDetail(){
		if(uni.getStorageSync('repairData')){
			let data = JSON.parse(uni.getStorageSync('repairData'))
			if(data){
				dataInfo.description = data.description
				dataInfo.property = data.property
				dataInfo.assetId = data.assetId
				dataInfo.handlerImgList = data.handlerImgList
				dataInfo.recBlob = data.recBlob
			}
		}
  }
  
  // 下一步
  function submit(){
		isSubmit.value = true;
		if(dataInfo.description==''){
		  uni.showToast({
		  	icon: 'none',
		    title: '请选择输入故障描述'
		  });
		  return;
		}
		if(dataInfo.localId){
			uploadAudio()
		}else{
			uni.setStorageSync('repairData',JSON.stringify(dataInfo))
			uni.navigateTo({
			  url: `/pages/repair/rapidRepNext`,
			});
		}
  }
  
  // 处理提交事件
  function handlerOrder(){
		dataInfo.incidentData.returnBackupMachine = dataInfo.returnBackupMachine
    let postData = {
      incident: dataInfo.incidentData
    }
    postData.incident.description = dataInfo.description;
		if(dataInfo.assetId){
			postData.incident.assetId = dataInfo.assetId;
		}else{
			delete postData.incident.assetId 
		}
    return api_incidentTask(dataInfo.tabActiveValue, postData);
  }
  
  // 处理图片
  function handlerOrderImg(imgObj){
    return uploadFile(imgObj, 'wechatRequesterIncident', dataInfo.incidentId)
  }
	
  onLoad((option) => {
		let data = JSON.parse(uni.getStorageSync('sysData'))
		cmdbRepair.value = data.find(i=>i.keyconfig=='cmdbRepair')
		if(option){
			if(option.property && option.assetId){
				dataInfo.property = option.property
				dataInfo.assetId = option.assetId
			}
		}
    getIncidentDetail();
  })
</script>

<style lang="scss" scoped>
.mask-class{
	position: fixed;
	width: 100%;
	height: 100%;
	top: 0;
	left: 0;
	background: rgba(0,0,0,0.3);
	display: flex;
	justify-content: center;
	align-items: center;
	.mask-box{
		height: 160rpx;
		padding: 0 25%;
		background: #95EC6A;
		border-radius: 25rpx;
		display: flex;
		align-items: center;
		.mask-img{
			width: 100rpx;
			height: 100rpx;
			position: relative;
			background-color: transparent;
			mix-blend-mode: multiply;
		}
	}
	.mask-bottom{
		position: absolute;
		bottom: 0;
		width: 100%;
		height: 300rpx;
		color: #A5A5A5;
		background: #eee;
		text-align: center;
		border-top-left-radius: 30rpx;
		border-top-right-radius: 30rpx;
		.mask-bottom-txt{
			margin-top: 50rpx;
			font-weight: 500;
		}
	}
}
.handler{
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
	padding: 0 30rpx;
  .head{
    height: 88rpx;
    display: flex;
    position: fixed;
    z-index: 99;
    width: 100%;
    background-color: #fff;
    font-size: 30rpx;
    .tab{
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      border-bottom: 4rpx solid transparent;
      &.active{
        color: $uni-primary;
        border-color: $uni-primary;
      }
    }
  }
  .body{
    box-sizing: border-box;
    flex: 1;
    min-height: 0;
    &.bg{
      background-color: #F7F7F7;
    }
    .summaryItem{
      &:first-of-type{
        .summaryItem_head{
          border-bottom: 1rpx solid #DDDDDD;
        }
      }
      .summary_total{
        padding: 20rpx 0;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .summaryItem_head{
        padding: 24rpx;
        font-size: 26rpx;
        color: #3A3A3A;
      }
      .summaryItem_body{
        font-size: 30rpx;
        background-color: #fff;
        .summaryItem_bodyItem{
          padding: 24rpx;
          border-bottom: 1rpx solid #DDDDDD;
          .summaryItem_bodyItem_top{
            display: flex;
            justify-content: space-between;
            align-items: center;
            .value{
              padding-left: 48rpx;
              flex-shrink: 0;
            }
          }
          .summaryItem_bodyItem_bottom{
            margin-top: 24rpx;
            display: flex;
            justify-content: space-between;
            align-items: center;
            .name{
              text-align: right;
              flex: 1;
            }
            .value{
              width: 240rpx;
              text-align: right;
              padding-left: 48rpx;
              flex-shrink: 0;
            }
          }
        }
      }
      .summaryItem_foot{
        font-size: 30rpx;
        background-color: #fff;
        &.total{
          margin-top: 24rpx;
        }
        .summaryItem_foot_total{
          padding: 24rpx 0;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        .summaryItem_foot_add{
          border-top: 1rpx solid #DDDDDD;
          padding: 24rpx 0;
          display: flex;
          justify-content: center;
          align-items: center;
          .newicon-icon-test{
            font-size: 30rpx;
            font-weight: bold;
          }
        }
      }
    }
    .form_item_column{
      padding-top: 24rpx;
      min-height: 86rpx;
      .form_item{
        padding-top: 0;
        min-height: auto;
      }
    }
		.candidate{
			display: flex;
			flex-wrap: wrap;
			.candidate-item{
				padding: 6rpx 15rpx;
				font-size: 26rpx;
				color: #949494;
				background: #E9E9E9;
				border-radius: 50rpx;
				margin-right: 20rpx;
				margin-top: 15rpx;
			}
		}
    .form_item{
      display: flex;
      align-items: center;
      padding-top: 24rpx;
      min-height: 86rpx;
			position: relative;
			.chunk{
				width: 100%;
				height: 70rpx;
				line-height: 70rpx;
				text-align: center;
				background: #F7F8FA;
				box-shadow: 0px 3px 6px 1px rgba(0,0,0,0.16);
				border-radius: 10rpx;
			}
			.chunk-2{
				width: 100%;
				height: 70rpx;
				display: flex;
				align-items: center;
				.chunk-2-2{
					flex: 1;
					height: 70rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					background: #F3FAF7;
					.chunk-img{
						width: 80rpx;
						height: 80rpx;
						position: relative;
						background-color: transparent;
						mix-blend-mode: multiply; /* 根据需要选择合适的混合模式 */
					}

				}
				.chunk-icon{
					margin-left: 20rpx;
				}
			}
      &.column{
        height: auto;
        flex-direction: column;
        align-items: flex-start;
				.import-rep{
					padding: 5rpx 10rpx;
					border-radius: 50rpx;
					background: #d1fcd5;
					color: #49b856;
					font-size: 24rpx;
				}
        .title{
          margin-right: 0;
        }
				.title-width{
					width: 100%;
				}
				.title-fl-sb{
					display: flex;
					justify-content: space-between;
					width: 100%;
				}
        .value{
          margin-top: 10rpx;
          // padding-left: 20rpx;
          box-sizing: border-box;
        }
        .tips{
          padding: 24rpx;
          text-align: center;
          font-size: 22rpx;
          color: #909399;
          width: 100%;
          box-sizing: border-box;
        }
      }
      .title{
        font-size: 26rpx;
        display: flex;
        align-items: center;
        margin-right: 12rpx;
        flex-shrink: 0;
        &.select{
          width: calc(5em + 20rpx);
        }
      }
      .value{
        width: 100%;
        &.category{
          width: 100%;
          display: flex;
          justify-content: space-between;
          align-items: center;
          .categoryName{
            font-size: 26rpx;
            color: #555;
            flex: 1;
          }
          .newicon-weibiaoti2010104{
            color: $uni-primary;
            margin-left: 24rpx;
          }
        }
        .imgTips{
          color: #909399;
          font-size: 22rpx;
					margin-top: 10rpx;
        }
      }
			.item-input{
				border: 1px solid #DBDBDB;
				height: 70rpx;
				line-height: 70rpx;
				padding: 0 10rpx;
				border-radius: 4rpx;
				width: 100%;
				font-size: 14px;
			}
			.icon{
				position: absolute;
				right: 20rpx;
				color: #49b856;
			}
      .synergeticNames{
        font-size: 26rpx;
        margin-right: 24rpx;
      }
      .synergeticAdd{
        flex-shrink: 0;
      }
    }
  }
}
</style>
