<template>
	<view class="home">
		<view v-if="tabsIndex1==1">
			<view class="home_item" v-if="isDept.valueconfig==1">
				<view class="title">科室报修</view>
				<view class="content">
					<view @click="repairsView(1,'pending,handler,reassign')">
						<view class="con-title">处理中</view>
						<view class="con-value">{{repairData.deptHandlerCount}}</view>
					</view>
					<view @click="repairsView(1,'close0')">
						<view class="con-title">待评价</view>
						<view class="con-value">{{repairData.deptCloseCount}}</view>
					</view>
					<view>
						<view class="con-title">本月维修费用(元)</view>
						<view class="con-value-gr">{{repairData.deptCurrentMonthPrice || 0}}</view>
					</view>
				</view>
			</view>
			<view class="home_item">
				<view class="title">我的报修</view>
				<view class="content">
					<view @click="repairsView(0,'pending,handler,reassign')">
						<view class="con-title">处理中</view>
						<view class="con-value">{{repairData.userHandlerCount}}</view>
					</view>
					<view @click="repairsView(0,'close0')">
						<view class="con-title">待评价</view>
						<view class="con-value">{{repairData.userCloseCount}}</view>
					</view>
				</view>
			</view>
	<!-- 		<view class="home_item">
				<uni-notice-bar show-icon scrollable background-color="#ffffff" color="#000"
				:text="noticeData" />
			</view> -->
			<view class="home_item home-disp">
				<view class="bottom-left" @click="addRepairs">
					<view class="bottom-left-box">
						<text class="newicon newicon-kuaisubaoxiu icon"></text>
						<view>快速报修</view>
					</view>
				</view>
				<view class="bottom-right mar-t-20">
					<view class="bottom-right-item" v-if="isRepair.valueconfig==1" @click="scanCodes">
						<text class="newicon newicon-saoma icon"></text>
						<view class="name1">扫资产报修</view>
					</view>
					<view class="bottom-right-item" @click="repository">
						<text class="newicon newicon-zhishiku1 icon"></text>
						<view class="name2">知识库</view>
					</view>
				</view>
			</view>
		</view>
		<view v-if="tabsIndex2==1" class="mine">
			<view class="body">
			  <view class="bottom">
			    <view class="bottom_name">个人信息</view>
			    <view class="bottom_list">
			      <view class="bottom_list_item">
			        <view class="name"><text class="required newicon newicon-bitian"></text>工号</view>
			        <view class="value no-mar">{{loginUserStore.loginUser.user.account}}</view>
			      </view>
						<view class="bottom_list_item">
						  <view class="name"><text class="required newicon newicon-bitian"></text>姓名</view>
						  <view class="value no-mar">{{loginUserStore.loginUser.user.name}}</view>
						</view>
						<view class="bottom_list_item">
						  <view class="name"><text class="required newicon newicon-bitian"></text>院区名称</view>
							<uni-data-picker class="value" placeholder="请选择院区名称"
								v-model="dataForm.branch" :localdata="branchData" @change="branchChange"
								:clear-icon="false" :class="{formRed: isSubmit && !dataForm.branch}">
							</uni-data-picker>
							<text class="newicon newicon-youjiantou icon"></text>
						</view>
						<view class="bottom_list_item" v-if="deptRepair.valueconfig==1">
						  <view class="name"><text class="required newicon newicon-bitian"></text>科室名称</view>
							<uni-data-picker class="value" placeholder="请选择报修科室"
								v-model="dataForm.dept" :localdata="deptData" 
								:clear-icon="false" :class="{formRed: isSubmit && !dataForm.dept}">
							</uni-data-picker>
							<text class="newicon newicon-youjiantou icon"></text>
						</view>
						<view class="bottom_list_item" v-if="deptRepair.valueconfig==1" @click="deptSelect">
						  <view class="name">常用科室</view>
						  <view class="value">{{commonDeptName}}</view>
							<text class="newicon newicon-youjiantou icon"></text>
						</view>
			      <view class="bottom_list_item">
			        <view class="name"><text class="required newicon newicon-bitian"></text>联系电话</view>
			        <view class="value no-mar" @click="makePhoneCall(loginUserStore.loginUser.user.phone)">{{loginUserStore.loginUser.user.phone}}</view>
			      </view>
			    </view>
			  </view>
			</view>
			<view class="foot_common_btns fixed-btn">
				<button @click="addInfo" type="default" class="primaryButton btn">保存</button>
			</view>
		</view>
		<view class="bottom-tabs">
			<view class="tabs-list" @click="tabsClick1">
				<img src="/static/img/icon_incidentList.png" v-if="tabsIndex1==0" alt="">
				<img src="/static/img/icon_incidentList_active.png" v-if="tabsIndex1==1" alt="">
				<view class="tabs-title" :class="tabsIndex1==1?'active-class':''">我的报修</view>
			</view>
			<view class="tabs-list" @click="tabsClick2">
				<img src="/static/img/icon_my.png" v-if="tabsIndex2==0" alt="">
				<img src="/static/img/icon_my_active.png" v-if="tabsIndex2==1" alt="">
				<view class="tabs-title" :class="tabsIndex2==1?'active-class':''">设置</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { SM } from "@/http/http.js"
	import { ref, reactive } from 'vue'
	import { onLoad ,onShow, onHide, onPullDownRefresh} from '@dcloudio/uni-app'
	import { api_systemConfiguration, api_userSave, api_user, api_department, api_repairScanCode, api_getNotice, api_getCount } from "@/http/api.js"
	import { useSetTitle } from '@/share/useSetTitle.js'
	import { repositoryListSearchStore } from '@/stores/repositorySearch'
	import { useLoginUserStore } from '@/stores/loginUser'
	import { useMakePhoneCall } from '@/share/useMakePhoneCall.js'
	import { useIncidentNumStore } from '@/stores/incidentNum'
	useSetTitle();
	
	// 数据
	const isDept = ref({})
	const isRepair = ref({})
	const isPublic = ref({})
	const noticeData = ref('')
	const repairData = ref({})
	const tabsIndex1 = ref(1)
	const tabsIndex2 = ref(0)
	const repositorySearchStore = repositoryListSearchStore();
	
	
	const loginUserStore = useLoginUserStore();
	const incidentNumStore = useIncidentNumStore();
	const { makePhoneCall }  = useMakePhoneCall();

	const deptRepair = ref(null)
	
	const deptData = ref([])
	
	const branchData = ref([])
	
	const commonDeptName = ref(null)
	
	const commonDeptData = ref(null)
	
	const dataForm = reactive({
	  dept: '',
		branch:''
	})
	
	const userTypes = ref(null)
	
	const userData = reactive(loginUserStore.loginUser.user)
	
	const commonDeptDTO = ref([])
	
	// 是否提交
	const isSubmit = ref(false)
	
	// 数据
	const dataInfo = reactive({
	  num: 0,
	})
	
	function tabsClick1(){
		tabsIndex1.value=1
		tabsIndex2.value=0
		getCount()
		setTimeout(_=>{
			let data = JSON.parse(uni.getStorageSync('sysData'))
			isDept.value = data.find(i=>i.keyconfig=='deptRepair')
			isRepair.value = data.find(i=>i.keyconfig=='cmdbRepair')
			isPublic.value = data.find(i=>i.keyconfig=='publicRepair')
		},0)
	}
	
	function tabsClick2(){
		tabsIndex2.value=1
		tabsIndex1.value=0
		getUserInfo()
	}
	
	// 知识库
	function repository(){
		repositorySearchStore.clearRepositoryListSearchData()
		uni.navigateTo({
		  url: `/pages/repository/repository?type=view&entranceType=repairs`
		})
	}
	
	// 报修列表
	function repairsView(type,value){
	  uni.navigateTo({
	    url: `/pages/repair/repairsList?type=${type}&value=${value}`
	  })
	}
	
	// 获取报修数量
	function getCount(){
		uni.showLoading({
		  title: "加载中",
		  mask: true,
		});
		api_getCount({}).then(res=>{
			uni.hideLoading();
			repairData.value = res.data
		})
	}
	
	// 快速报修
	function addRepairs(){
		if(isDept.value.valueconfig==0 && isPublic.value.valueconfig==0){
			uni.showToast({
				icon: 'none',
			  title: '请先开启科室报修或公共报修'
			});
			return
		}
		uni.setStorageSync('repairsType','subpage')
		uni.navigateTo({
		  url: '/pages/repair/rapidRep'
		})
	}
	
	// 扫资产报修
	function scanCodes(){
		uni.showLoading({
		  title: "加载中",
		  mask: true,
		});
		SM().then((res) => {
			api_repairScanCode({
				code:res
			}).then((res2) => {
			  uni.hideLoading();
			  if (res2.state == 200) {
					uni.navigateTo({
					  url: `/pages/repair/rapidRep?property=${res2.data.name}&assetId=${res2.data.id}`
					})
			  } else {
			    uni.showToast({
			      icon: 'none',
			      title: res2.msg || '请求数据失败!'
			    });
			  }
			});
		})
	}
	
	// 获取文本内容
	function getHtml(data) {
	  const tempDiv = document.createElement('div');
	  tempDiv.innerHTML = data.content;
		noticeData.value = tempDiv.textContent || tempDiv.innerText || '';
	}
	
	
	// 保存
	function addInfo(){
		if(!dataForm.branch){
			uni.showToast({
			  icon: 'none',
			  title: '院区不能为空'
			});
			return
		}
		
		if(!dataForm.dept){
			uni.showToast({
			  icon: 'none',
			  title: '报修科室不能为空'
			});
			return
		}
		
		uni.showLoading({
		  title: "加载中",
		  mask: true,
		});
	  isSubmit.value = true
		userData.currentHospital.id = dataForm.branch
		userData.commonDeptName = commonDeptName.value
		userData.dept={
			id:dataForm.dept
		}
		let arr = []
		for(let i of commonDeptDTO.value){
			arr.push({
				dept:i
			})
		}
		let postData = {
			...loginUserStore.loginUser.user,
			// ...userData,
			hospital:{
				id:dataForm.branch
			},
			dept:{
				id:dataForm.dept
			},
			commonDept:commonDeptData.value,
			commonDeptDTO:arr
		}
		api_userSave({
		  user: postData,
		}).then(res => {
		  uni.hideLoading();
			if(res.status == 200){
				loginUserStore.setLoginUser(postData);
				uni.showToast({
				  icon: 'none',
				  title: '保存成功'
				});
			}else{
				uni.showToast({
				  icon: 'none',
				  title: res.msg || '请求数据失败!'
				});
			}
		})
	}
	
	// 选择院区
	function branchChange(){
		dataForm.dept = null
		commonDeptName.value = null
		commonDeptData.value = null
		getRepairTypes()
	}
	
	// 获取科室列表
	function getRepairTypes(){
	  uni.showLoading({
	    title: "加载中",
	    mask: true,
	  });
	  let postData = {
			department: {
			  hospital: dataForm.branch?dataForm.branch:loginUserStore.loginUser.user.currentHospital.id,
			},
			idx:0,
			sum:9999
		}
	  api_department(postData).then(res => {
	    uni.hideLoading();
	    res = res.list || [];
	    deptData.value = res.map(v => ({
	      text: v.dept,
	      value: v.id,
	    }));
	  })
	}
	
	// 获取院区列表
	function getBranch(){
		let arr = loginUserStore.loginUser.hospital.filter(i=>i.parent==undefined)
		branchData.value = arr.map(v => ({
		  text: v.hosName,
		  value: v.id,
		}));
	}
	
	// 选择常用科室
	function deptSelect(){
		uni.setStorageSync('configData',JSON.stringify(dataForm))
		let data = commonDeptData.value ? 
		commonDeptData.value : loginUserStore.loginUser.user.commonDept
		if(!data){
			data = 'none'
		}
		let deptId = dataForm.branch?dataForm.branch:loginUserStore.loginUser.user.currentHospital.id
		uni.navigateTo({
		  url: `/pages/repair/deptSelect?data=${JSON.stringify(data)}&commonDeptName=${commonDeptName.value}&deptId=${deptId}&type=subpage`
		})
	}
	
	// 初始化
	function onLoadFn(){
		let data = JSON.parse(uni.getStorageSync('sysData'))
		deptRepair.value = data.find(i=>i.keyconfig=='deptRepair')
		getBranch()
	}
	
	function getUserInfo(){
		let user = loginUserStore.loginUser.user
		let userId = null
		if(user.currentHospital.parent){
			userId = user.currentHospital.parent.id
		}else{
			userId = user.currentHospital.id
		}
		let postData = {
		  idx: 0,
		  sum: 999,
		  user: {
				hospital:{
					id:userId
				},
		    name: user.name,
				userTypeIds: String(userTypes.value.map(v => v.id))
		  }
		}
		api_user(postData).then(res => {
		  if(res.status == 200){
		    let item = res.list.find(i=>i.id==user.id)
		    if(item){
					if(item.hospital.parent){
						dataForm.branch = item.hospital.parent.id
					}else{
						dataForm.branch = item.hospital.id
					}
					if(item.dept){
						dataForm.dept = item.dept.id
					}
					getRepairTypes()
					let id = []
					let name = []
					if(item.commonDeptDTO){
						for(let i of item.commonDeptDTO){
							id.push(i.id)
							name.push(i.dept)
						}
						commonDeptData.value = id.join(',')
						commonDeptName.value = name.join('/')
					}
		    }else{
					// let data = uni.getStorageSync('configData')
					// if(data){
					// 	data = JSON.parse(data)
					// 	dataForm.dept = data.dept
					// 	dataForm.branch = data.branch
					// }else{
						if(user.currentHospital.parent){
							dataForm.branch = user.currentHospital.parent.id
						}else{
							dataForm.branch = user.currentHospital.id
						}
						if(user.dept){
							dataForm.dept = user.dept.id
						}
					// }
					if(user.commonDeptDTO){
						let name = []
						for(let i of user.commonDeptDTO){
							name.push(i.dept)
						}
						commonDeptData.value = user.commonDept
						commonDeptName.value = name.join('/')
					}
					getRepairTypes()
				}
		  }else{
		    uni.showToast({
		      icon: 'none',
		      title: res.msg || '请求数据失败!'
		    });
		  }
		})
	}
	
	onHide(opt=>{
		dataInfo.num = 0
		dataForm.branch = null
	})
	
	onLoad((option) => {
		userTypes.value = JSON.parse(uni.getStorageSync('groupData'))
		onLoadFn();
		dataInfo.num = 1
		if(option.type==2){
			if(option.data){
			  tabsIndex1.value = 0
			  tabsIndex2.value = 1
				let data = JSON.parse(option.data)
				commonDeptData.value = data.data.join(',')
				commonDeptName.value = data.name.join('/')
				commonDeptDTO.value = data.name
				let data2 = uni.getStorageSync('configData')
				if(data2){
					data2 = JSON.parse(data2)
					dataForm.dept = data2.dept
					dataForm.branch = data2.branch
				}
				getRepairTypes()
			}else{
				getUserInfo()
			}
		}else{
			tabsIndex1.value = 1
			tabsIndex2.value = 0
			getCount()
			setTimeout(_=>{
				let data = JSON.parse(uni.getStorageSync('sysData'))
				isDept.value = data.find(i=>i.keyconfig=='deptRepair')
				isRepair.value = data.find(i=>i.keyconfig=='cmdbRepair')
				isPublic.value = data.find(i=>i.keyconfig=='publicRepair')
			},0)
		}
		
	})
	
	onPullDownRefresh(_=>{
		uni.stopPullDownRefresh();
	})
	
	onShow((option) => {
		userTypes.value = JSON.parse(uni.getStorageSync('groupData'))
		onLoadFn()
		if(dataInfo.num==0){
			getUserInfo()
		}
	})
	

</script>

<style scoped>
	>>> .uni-data-tree-input{
		width: 100% !important;
	}
	>>> .input-value-border{
		border: none !important;
	}
	>>> .input-value{
		padding:0 !important;
		flex-direction: row-reverse !important;
	}
	>>> .selected-list{
		flex-direction: row-reverse !important;
	}
	>>> .arrow-area{
		display: none !important;
	}
	>>>.uni-data-tree-dialog{
		z-index: 9999;
	}
</style>
<style lang="scss" scoped>
	.home{
		// height: 100vh;
		padding: 20rpx;
		background: #fff;
		.home_item{
			padding: 20rpx;
			box-shadow: 0px 3px 6px 1px rgba(0,0,0,0.16);
			border-radius: 10rpx;
			margin-bottom: 30rpx;
			.title{
			  font-size: 26rpx;
			  color: $uni-primary;
			  padding-left: 18rpx;
			  position: relative;
				margin-bottom: 20rpx;
			  &:before{
			    content: '';
			    width: 8rpx;
			    height: 25rpx;
			    background-color: $uni-primary;
			    position: absolute;
			    left: 0;
			    top: 50%;
			    transform: translateY(-50%);
			  }
			}
			.content{
				display: flex;
				align-items: center;
				justify-content: space-around;
				text-align: center;
				.con-title{
					color: #949494;
					font-size: 24rpx;
					margin-bottom: 15rpx;
				}
				.con-value{
					color: #000;
					font-size: 50rpx;
				}
				.con-value-gr{
					color: #49B856;
					font-size: 50rpx;
				}
			}
			.uni-noticebar{
				margin: 0 !important;
				padding: 0 !important;
			}
		}
		.home-disp{
			display: flex;
			justify-content: space-around;
			.bottom-left{
				height: 380rpx;
				background: linear-gradient( 269deg, #54B99C 0%, #7AC481 100%);
				border-radius: 10rpx;
				flex: 1.5;
				margin-right: 20rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				color: #FFFFFF;
				margin-top: 20rpx;
				.bottom-left-box{
					text-align: center;
					.icon{
						font-size: 100rpx;
						position: relative;
						top: -20rpx;
					}
				}
			}
			.mar-t-20{
				margin-top: 20rpx;
			}
			.bottom-right{
				flex: 2;
				.bottom-right-item{
					height: 175rpx;
					background: #FFFFFF;
					border-radius: 10rpx;
					border: 2rpx solid #6FC073;
					margin-bottom: 20rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					position: relative;
					.icon{
						font-size: 50rpx;
						color: #6FC073;
						position: absolute;
						left: 60rpx;
					}
					.name1{
						font-size: 32rpx;
						position: absolute;
						right: 50rpx;
					}
					.name2{
						font-size: 32rpx;
						position: absolute;
						right: 80rpx;
					}
				}
			}
		}
		.bottom-tabs{
			border-top:1px solid rgba(0, 0, 0, 0.33);
			background: #fff;
			position: fixed;
			width: 100%;
			left: var(--window-left);
			right: var(--window-right);
			display: flex;
			bottom: 0;
			.tabs-list{
				height: 90rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				flex-direction: column;
				flex: 1;
				font-size: 0;
				text-align: center;
				-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
				img{
					width: 48rpx;
					height: 48rpx;
				}
				.tabs-title{
					color: rgb(136, 136, 136);
					font-size: 20rpx;
					line-height: normal;
				}
				.active-class{
					color: #49B856;
				}
			}
		}
	}
	.mine{
	  height: 100%;
	  display: flex;
	  flex-direction: column;
	  justify-content: space-between;
	  .phone-filled{
	    margin-right: 5rpx;
	  }
	  .newicon-xinjian2,
		.newicon-zhishiku{
	    margin-right: 10rpx;
	  }
	  .body{
	    width: 714rpx;
	    height: 100%;
	    margin: 16rpx auto var(--window-bottom) auto;
	    box-sizing: border-box;
	    border-radius: 8rpx;
	    .top{
	      padding: 30rpx;
	      background-color: #fff;
	      .top_name{
	        font-size: 28rpx;
	        font-weight: bold;
	      }
	      .top_count{
	        margin-top: 45rpx;
	        display: flex;
	        align-items: center;
	        justify-content: space-between;
	        .top_count_item{
	          text-align: center;
	          .name{
	            color: #949494;
	            font-size: 22rpx;
	          }
	          .value{
	            font-size: 50rpx;
	            font-weight: bold;
	            margin-top: 15rpx;
	          }
	        }
	      }
	    }
	    
	    .bottom{
	      background-color: #fff;
	      margin-top: 15rpx;
	      .bottom_name{
	        font-size: 26rpx;
	        color: $uni-primary;
	        padding: 21rpx 24rpx;
	      }
	      .bottom_list{
	        .bottom_list_item{
	          border-top: 1rpx solid #DEDEDE;
	          padding: 30rpx 30rpx 30rpx 30rpx;
	          display: flex;
	          justify-content: space-between;
	          align-items: center;
	          font-size: 24rpx;
						position: relative;
	          .value{
	            max-width: 380rpx;
	            color: #333;
	            display: flex;
	            align-items: center;
	            text-align: justify;
							margin-right: 30rpx;
	          }
						.no-mar{
							margin-right:0 !important;
						}
						.icon{
							position: absolute;
							right: 20rpx;
						}
	        }
	      }
	    }
	  }
		.fixed-btn{
			position: fixed;
			bottom: 100rpx;
			left: 0;
		}
	}
</style>