<template>
  <view class="mine">
    <scroll-view scroll-y 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">{{dataForm.account}}</view>
          </view>
					<view class="bottom_list_item">
					  <view class="name"><text class="required newicon newicon-bitian"></text>姓名</view>
					  <view class="value no-mar">{{dataForm.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" @click="selectDepartment">
<!-- 					  <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 class="form_item"> -->
						  <view class="title select"><text class="required newicon newicon-bitian"></text>报修科室：</view>
						  <view class="value category">
						    <text class="categoryName ellipsis-multiline">{{dataForm.departmentName}}</text>
						    <!-- <text class="newicon newicon-weibiaoti2010104"></text> -->
						  </view>
						<!-- </view> -->
					</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(dataForm.phone)">{{dataForm.phone}}</view>
          </view>
        </view>
      </view>
    </scroll-view>
    <view class="foot_common_btns">
			<button @click="addInfo" type="default" class="primaryButton btn">保存</button>
    </view>
  </view>
</template>

<script setup>
  import { ref, reactive } from 'vue'
  import { onLoad, onShow, onHide, onTabItemTap } from '@dcloudio/uni-app'
  import { api_userSave, api_user, api_department, api_getDictionary ,api_branch, api_systemConfiguration} from "@/http/api.js"
  import { defaultColor } from '@/static/js/theme.js'
  import { useSetTitle } from '@/share/useSetTitle.js'
  import { useMakePhoneCall } from '@/share/useMakePhoneCall.js'
  import { useLoginUserStore } from '@/stores/loginUser'
  import { useIncidentNumStore } from '@/stores/incidentNum'
  import { repositoryListSearchStore } from '@/stores/repositorySearch'
  import { useSetTabbar } from '@/share/useSetTabbar.js'
	
  useSetTitle();
  const loginUserStore = useLoginUserStore();
  const incidentNumStore = useIncidentNumStore();
  const { makePhoneCall }  = useMakePhoneCall();
  const repositorySearchStore = repositoryListSearchStore();
  const { setTabbar }  = useSetTabbar();
	
  // 主题颜色
  const primaryColor = ref(defaultColor)
  
	const deptRepair = ref(null)
	
	const deptData = ref([])
	
	const branchData = ref([])
	
	const commonDeptName = ref(null)
	
	const commonDeptData = ref(null)
	
	const dataForm = reactive({
		name:loginUserStore.loginUser.user.name,
		account:loginUserStore.loginUser.user.account,
		phone:loginUserStore.loginUser.user.phone,
	  dept: '',
		departmentName:'',
		branch:'',
		commonDeptName:'',
		commonDeptData:'',
		dataType:false
	})
	
	const operationType = ref(null)
	
	const userTypes = ref(null)
	
	const userData = reactive(loginUserStore.loginUser.user)
	
	const commonDeptDTO = ref([])
	
	// 是否提交
	const isSubmit = ref(false)
	
  // 数据
  const dataInfo = reactive({
    num: 0,
  })
  
  // 保存
  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
		dataForm.departmentName = null
		dataForm.commonDeptName = null
		dataForm.commonDeptData = null
		commonDeptName.value = null
		commonDeptData.value = null
		// getRepairTypes()
	}
	
	// 跳转到科室
	function selectDepartment(){
		if(commonDeptName.value){
			dataForm.dataType = true
		}else{
			dataForm.dataType = false
		}
		uni.setStorageSync('configData',JSON.stringify(dataForm))
	  uni.navigateTo({
	    url: `/pages/searchDept/searchDept?type=config&branchId=${dataForm.branch}`
	  })
	}
	
	// 获取科室列表
	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=home`
		})
	}
	
  // 初始化
  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)
				let data = uni.getStorageSync('configData')
				if(operationType.value=='selectDept'){
					if(data){
						data = JSON.parse(data)
						dataForm.name = data.name
						dataForm.account = data.account
						dataForm.phone = data.phone
						dataForm.dept = data.dept
						dataForm.departmentName = data.departmentName
						dataForm.branch = Number(data.branch)
						dataForm.commonDeptName = data.commonDeptName
						dataForm.commonDeptData = data.commonDeptData
						if(data.dataType){
							commonDeptData.value = data.commonDeptData
							commonDeptName.value = data.commonDeptName
						}
					}	
				}else 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
						dataForm.departmentName = item.dept.dept
					}
					// 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('/')
						dataForm.commonDeptName = commonDeptName.value
						dataForm.commonDeptData = commonDeptData.value
					}
		    }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
							dataForm.departmentName = user.dept.dept
						}
					// }
					if(user.commonDeptDTO){
						let name = []
						for(let i of user.commonDeptDTO){
							name.push(i.dept)
						}
						commonDeptData.value = user.commonDept
						commonDeptName.value = name.join('/')
						dataForm.commonDeptName = commonDeptName.value
						dataForm.commonDeptData = commonDeptData.value
					}
					// getRepairTypes()
				}
		  }else{
		    uni.showToast({
		      icon: 'none',
		      title: res.msg || '请求数据失败！'
		    });
		  }
		})
	}
	
	onHide(opt=>{
		dataInfo.num = 0
		dataForm.branch = null
	})
	
	onShow((option) => {
		userTypes.value = JSON.parse(uni.getStorageSync('groupData')) 
		onLoadFn()
		if(dataInfo.num==0){
			getUserInfo()
		}
		for(let i = 0; i<7; i++){
			setTabbar(i)
		}
	})
			
  onLoad((option) => {
		userTypes.value = JSON.parse(uni.getStorageSync('groupData')) 
		onLoadFn();
		dataInfo.num = 1
		if(option && option.configType){
			operationType.value = option.configType
		}
		if(option.data){
			let data = JSON.parse(option.data)
			commonDeptData.value = data.data.join(',')
			commonDeptName.value = data.name.join('/')
			commonDeptDTO.value = data.name
			dataForm.commonDeptData = data.data.join(',')
			dataForm.commonDeptName = data.name.join('/')
			let data2 = uni.getStorageSync('configData')
			if(data2){
				data2 = JSON.parse(data2)
				dataForm.dept = data2.dept
				dataForm.departmentName = data2.departmentName
				dataForm.branch = data2.branch
			}
			// getRepairTypes()
		}else{
			getUserInfo()
		}
		for(let i = 0; i<7; i++){
			setTabbar(i)
		}
  })
  
  onTabItemTap(e => {
    // onLoadFn();
  })
</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>
page{
  height: calc(100vh - var(--window-bottom));
  background-color: #EBEBEB;
}
.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;
					}
        }
      }
    }
  }
}
</style>
