<template>
	<view class="patientInformationInfo" v-if="Object.keys(infoDATA).length > 0">
		<view class="page_head">
			<view class="title">{{ infoDATA.patientName }}<text class="patientCode">{{ infoDATA.residenceNo }}({{ infoDATA.bedNum }})</text></view>
			<view class="info">
        <view class="bedNum" v-if="infoDATA.tripTypeDTO">
        	<text class="info_h">陪检方式</text>
        	<text class="info_b">{{ infoDATA.tripTypeDTO ? infoDATA.tripTypeDTO.inspectMode : '' }}</text>
        </view>
				<view :class="(infoDATA.careLevel || infoDATA.illnessState)?'bedNum':'waitingCount'">
					<text class="info_h">待检查数</text>
					<text class="info_b">{{ infoDATA.watingCount }}</text>
				</view>
				<view class="bedNum" v-if="infoDATA.careLevel">
					<text class="info_h">护理等级</text>
					<text class="info_b">{{ infoDATA.careLevel.name }}</text>
				</view>
				<view class="waitingCount" v-if="infoDATA.illnessState">
					<text class="info_h">病情级别</text>
					<text class="info_b">{{ infoDATA.illnessState.name }}</text>
				</view>
			</view>
      <view class="remark">
        <text class="remarkTitle">注意事项：</text><text class="remarkInfo">{{infoDATA.remark}}</text>
      </view>
		</view>
    <scroll-view v-if="!isEmpty" scroll-y class="scrollContent">
      <view class="page_item" v-for="(inspects, key, index) in infoDATA.inspectListMap" :key="key">
        <view class="splitLine">
          <view class="splitLineFlex">
            <view class="splitLineBox"></view>
          </view>
          <view>{{key}}</view>
          <view class="splitLineFlex">
            <view class="splitLineBox"></view>
          </view>
        </view>
        <checkbox-group @change="checkboxChange($event, key)">
          <view class="page_item_info" :class="{mt0: i === 0}" v-for="(item, i) in inspects" :key="item.id">
            <label class="page_item_info_title" style="display: inline-block;width: 100%;">
              <checkbox color="#49B856" :value="item.id + ''" :checked="item.checked" />
              检查项目：<text class="bold">{{ item.inspectName }}</text></label>
            <view class="page_item_info_title"><text :class="{red: !item.execDept}">检查科室：</text><text>{{ item.execDept ? item.execDept.dept : "" }}<text class="newicon newicon-weibiaoti2010104 fz28" @click="changeExecDept(item)" v-if="item.inspectState.value == 1 || item.inspectState.value == 30"></text></text></view>
            <view class="page_item_info_title btn row">
              <view><text :class="{red: !item.yyTime}">预约时间：</text><text>{{ item.yyTime | filterSecondDate }}</text><text v-if="item.reservationNumber">（{{ item.reservationNumber }}）</text><text class="newicon newicon-weibiaoti2010104" @click="changeYyTime(item)" v-if="item.inspectState.value == 1 || item.inspectState.value == 30"></text></view>
            </view>
            <view class="page_item_info_title row">
              <view>是否紧急：<text :class="{red:item.priority===1||item.priority==='1'}">{{ (item.priority===1||item.priority==='1')?'是':'否' }}</text></view>
              <view>状态：<text v-if="item.inspectState">{{ item.inspectState.name }}</text></view>
            </view>
            <view class="buildOrder" @click="build(item)" v-if="!item.gdId&&(item.inspectState.value==1||item.inspectState.value==30)">建单</view>
          </view>
        </checkbox-group>
      </view>
    </scroll-view>
		<view v-if="isEmpty" class="zwsj">
			<image class="zwsj-img" mode="widthFix" src="../../static/img/zanwushuju.png"></image>
			<view class="zwsj-txt">暂无检查信息</view>
		</view>
    <view class="page_item_btns">
      <view class="page_item_btn" hover-class="seimin-btn-hover" @click="buildOrders()">批量陪检</view>
      <view class="toolbar" @click="Scanning()">
        <text class="toolbar-icon newicon newicon-saoma"></text>
        <text class="toolbar-sao">扫一扫</text>
      </view>
    </view>
    <!-- 弹窗 -->
    <showModel :title="models.title" :icon="models.icon" :disjunctor="models.disjunctor" :content="models.content"
      @ok="ok" @cancel="cancel" @know="know" :operate="models.operate"></showModel>
    <!-- 弹窗 -->
    <inspectRemoveModel :title="models1.title" :icon="models1.icon" :disjunctor="models1.disjunctor" :content="models1.content" @know="know1" :operate="models1.operate" @ok="ok1" @cancel="cancel1" :yy="currentInspect.yyTime"></inspectRemoveModel>
    <!-- 弹窗 -->
    <inspectExecDeptModel :title="models2.title" :icon="models2.icon" :disjunctor="models2.disjunctor" :content="models2.content" @know="know2" :operate="models2.operate" @ok="ok2" @cancel="cancel2" :execDeptList="currentInspect.inspectCheckType && currentInspect.inspectCheckType.deptList" :execDeptId="currentInspect.execDeptId"></inspectExecDeptModel>
	</view>
</template>
<script>
	import {
		get,
		post,
		SM,
		webHandle
	} from "../../http/http.js";
	export default {
		data() {
			return {
        currentInspect: {},
        SMFlag: true,
        isEmpty: true,
				options: {},
				infoDATA: {},
				// 弹窗model1
				models1: {
				  disjunctor: false,
				},
        // 弹窗model1
        models2: {
          disjunctor: false,
        },
        // 建单的对象
        jdItem: [],
        // 弹窗model
        models: {
          disjunctor: false,
        },
			};
		},
		methods: {
      // 选择楼栋
      checkboxChange: function(e, key) {
        var dataList = this.infoDATA.inspectListMap[key],
            values = e.detail.value;
        for (var i = 0, lenI = dataList.length; i < lenI; ++i) {
          const item = dataList[i]
          if (values.includes(item.id + '')) {
            this.$set(item, 'checked', true)
          } else {
            this.$set(item, 'checked', false)
          }
        }
      },
      // 批量陪检
      buildOrders(){
        let list = Object.values(this.infoDATA.inspectListMap).flat().filter(v => v.checked);
        console.log(list);
        if(list.length){
          // 只要有一个没有检查科室
          let inspectDTO = list.find(v => !v.execDept);
          if(inspectDTO){
            this.models = {
              disjunctor: true,
              title: "提示",
              content: `<span class="red">${inspectDTO.inspectName || ''}</span>没有检查科室，不能建单`,
              icon: "warn",
              operate: {
                know: "返回",
              },
            };
            return;
          }
          this.jdItem = list;
          this.models = {
            disjunctor: true,
            title: "提示",
            content: `您选择<span class="red">${this.infoDATA.patientName || ""}</span>患者<span class="red">${list.length}</span>项检查，是否确认建单？`,
            icon: "warn",
            operate: {
              ok: "确定",
              cancel: "取消",
            },
          };
        }else{
          uni.showToast({
            icon: "none",
            title: "至少选择一个检查！",
          });
        }
      },
      // 建单
      build(data) {
        console.log(data);
        if(!data.execDept){
          this.models = {
            disjunctor: true,
            title: "提示",
            content: `<span class="red">${data.inspectName || ''}</span>没有检查科室，不能建单`,
            icon: "warn",
            operate: {
              know: "返回",
            },
          };
          return;
        }
        this.jdItem = [data];
        this.models = {
          disjunctor: true,
          title: "提示",
          content: `您即将创建<span class="red">${data.patientName || ""}</span>患者前往<span class="red">${ data.execDept ? data.execDept.dept : "" }</span>进行<span class="red">${data.inspectName || ""}</span>检查，您确认吗？`,
          icon: "warn",
          operate: {
            ok: "确定",
            cancel: "取消",
          },
        };
      },
      //建单后返回
      know() {
        this.models.disjunctor = false;
        this.getInfo(this.infoDATA.patientCode);
      },
      //建单确定
      ok() {
        this.models.disjunctor = false;
        let postData = {
          deptId: this.infoDATA.department.id
        };
        let taskId;
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
        post("/nurse/getDeptTaskType", postData).then((result) => {
          if (result.status == 200) {
            let obj = result.data.allTaskTypes.filter(
              (item) => item.associationType.value == "inspect"
            );
            if (obj.length) {
              taskId = obj[0].id;
              let postData = {
                workOrder: {
                  sourceId: 4,
                  taskType: {
                    id: taskId,
                    isHalfInspect: obj[0].isHalfInspect === 1 ? 1 : 0
                  },
                  createDept: this.infoDATA.department.id,
                  startDept: {
                    id: this.infoDATA.department.id
                  },
                  patient: {
                    patientCode: this.infoDATA.patientCode
                  },
                  checkList: this.jdItem,
                  goods: "",
                  worker: {
                    id: uni.getStorageSync("userData").user.id
                  },
                  workerStartOrderFlag: 1,
                },
              };
              //根据检查的紧急度加急
              this.jdItem.forEach(v => {
                if (v.priority === 1 || v.priority === '1') {
                  postData.workOrder["urgentDetails"] = {
                    checkStatus: {
                      id: 329
                    },
                    urgentReason: '系统根据检查信息，自动进行加急',
                  };
                }
              })

              post("/api/startOrder", postData).then((res) => {
                uni.hideLoading();
                let msg = res.msg;
                let icon = "error";
                if (res.status == 200) {
                  msg = "建单成功";
                  icon = "success";
                }
                this.models = {
                  disjunctor: true,
                  content: msg,
                  icon: icon,
                  operate: {
                    know: "返回",
                  },
                };
              });
            } else {
              uni.hideLoading();
              this.models = {
                disjunctor: true,
                content: "建单失败,科室未开通！",
                icon: "error",
                operate: {
                  know: "返回",
                },
              };
            }
          } else {
            uni.hideLoading();
            uni.showToast({
              icon: "none",
              title: result.msg || "接口获取数据失败！",
            });
          }
        });
      },
      //建单取消
      cancel() {
        this.models.disjunctor = false;
      },
      // 扫一扫
      Scanning(qrcodePrefix = '') {
        if (!this.SMFlag) {
          return;
        }
        this.SMFlag = false;
        SM().then((content) => {
          this.SMFlag = true;
          this.getInfo(content);
        }).catch(err => {
          this.SMFlag = true;
        });
      },
			// 修改预约时间->返回
			know1() {
			  this.models1.disjunctor = false;
			},
			// 修改预约时间->确定
			ok1(data) {
				console.log(data);
				const { yyTime} = data;//暂时这样
				if (!yyTime) {
				  //没有填写预约时间
				  uni.showModal({
				    title: "提示",
				    content: "请填写预约时间！",
				    showCancel: false,
				    success: function(res) {
				      if (res.confirm) {
				        console.log("用户点击确定");
				      } else if (res.cancel) {
				        console.log("用户点击取消");
				      }
				    },
				  });
				  return;
				}
			  this.models1.disjunctor = false;
			  let postData = {
			    inspectCode: this.currentInspect.inspectCode,
			  	yyTime
			  };
			  uni.showLoading({
			    title: '加载中',
			    mask: true,
			  })
			  post('/workerOrder/updateInspectYytime', postData).then(res => {
			    uni.hideLoading();
			    if (res.status == 200) {
						this.getInfo(this.options.patientCode);
			    } else {
			      uni.showToast({
			        icon: "none",
			        title: "修改失败",
			      });
			    }
			  })
			},
			// 修改预约时间->取消
			cancel1() {
			  this.models1.disjunctor = false;
			},
			// 修改预约时间
			changeYyTime(item) {
			  this.currentInspect = item;
			  this.models1 = {
			    disjunctor: true,
			    content: `您要修改[${item.inspectName||''}]的预约时间`,
			    icon: "warn",
			    operate: {
			      ok: "确定",
			      cancel: "取消",
			    },
			  };
			},
      // 修改检查科室
      changeExecDept(item) {
        this.currentInspect = item;
        if(this.currentInspect.inspectCheckType){
          this.currentInspect.inspectCheckType.deptList = this.currentInspect.inspectCheckType.deptList || [];
        }
        this.models2 = {
          disjunctor: true,
          content: `请选择[${item.patientName||''}]检查项目的检查科室`,
          icon: "warn",
          operate: {
            ok: "确定",
            cancel: "取消",
          },
        };
      },
      // 修改检查科室->返回
      know2() {
        this.models2.disjunctor = false;
      },
      // 修改检查科室->确定
      ok2(data) {
      	console.log(data);
      	const { execDeptId } = data;
        this.models2.disjunctor = false;
        let postData = {
          "id": this.currentInspect.id,
          "execDeptId": execDeptId
        };
        
        uni.showLoading({
          title: '加载中',
          mask: true,
        })
        post('/simple/data/updData/inspect', postData).then(res => {
          uni.hideLoading();
          if (res.status == 200) {
            this.getInfo(this.options.patientCode);
          } else {
            uni.showToast({
              icon: "none",
              title: "修改失败",
            });
          }
        })
      },
      // 修改检查科室->取消
      cancel2() {
        this.models2.disjunctor = false;
      },
			// 请求详细页面的数据
			getInfo(patientCode) {
				uni.showLoading({
					title: "加载中",
					mask: true,
				});
				post("/nurse/workOrder/getPatientInspectInfo", {
					patientCode,
          queryInspect: 1,
				}).then((res) => {
					uni.hideLoading();
					if (res.status == 200) {
            res.data.inspectListMap = res.data.inspectListMap || {};
            this.isEmpty = Object.keys(res.data.inspectListMap).length === 0;
						this.infoDATA = res.data;
					} else {
						uni.showToast({
							icon: "none",
							title: res.msg || "接口获取数据失败！",
						});
					}
				});
			},
		},
		onLoad(options) {
			this.options = options;
			this.getInfo(this.options.patientCode);
			// #ifdef APP-PLUS
			webHandle("no", "app");
			// #endif
			// #ifdef H5
			webHandle("no", "wx");
			// #endif
		},
    onShow() {
      this.SMFlag = true;
    }
	};
</script>
<style lang="less" scoped>
  /deep/ uni-checkbox:not([disabled]) .uni-checkbox-input:hover{
    border-color: #49B856!important;
  }
  .page_item_btns{
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 16rpx;
    margin-bottom: 16rpx;
    .page_item_btn {
      flex: 1;
      height: 88rpx;
      background-image: linear-gradient(to right, #72c172, #3bb197);
      border-radius: 8rpx;
      line-height: 88rpx;
      color: #fff;
      font-size: 36rpx;
      font-weight: 700;
      text-align: center;
      margin-right: 24rpx;
      &:first-of-type{
        margin-left: 24rpx;
      }
    }
    .toolbar {
      flex: 1;
      z-index: 999;
      height: 88rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      box-sizing: border-box;
      border-radius: 4rpx;
      background-color: #E5E8ED;
      margin-right: 24rpx;
    
      .toolbar-icon {
        font-size: 52rpx;
        margin-right: 16rpx;
        color: #07863c;
      }
    
      .toolbar-sao {
        font-size: 36rpx;
        color: #333;
      }
    }
  }
  .newicon-weibiaoti2010104{
    margin-left: 8rpx;
  }
  
	.patientInformationInfo {
    background-color: #F7F7F7;
    display: flex;
    flex-direction: column;
    height: 100vh;
		.zwsj {
      flex: 1;
      min-height: 0;
			text-align: center;

			.zwsj-img {
				width: 560rpx;
			}

			.zwsj-txt {
				font-size: 36rpx;
				font-weight: 700;
				margin-top: 20rpx;
				text-align: center;
			}
		}

		.page_head {
			background-color: #49b856;
			color: #fff;

			.title {
				font-size: 48rpx;
				padding-top: 24rpx;
				text-align: center;
			}

      .remark{
        display: flex;
        margin: 16rpx 27rpx;
        .remarkTitle{
          flex-shrink: 0;
        }
        .remarkInfo{
          flex-shrink: 1;
        }
      }

			.patientCode {
				margin-left: 12rpx;
				font-size: 28rpx;
			}

			.info {
				margin: 8rpx 0;
				height: 80rpx;
				display: flex;
				justify-content: center;
				align-items: center;

				.bedNum,
				.waitingCount {
					width: 300rpx;
					height: 100%;
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;

					.info_h {
						font-size: 30rpx;
					}

					.info_b {
						font-size: 26rpx;
            margin-top: 8rpx;
					}
				}

				.bedNum {
					position: relative;

					&:after {
						content: "";
						position: absolute;
						width: 4rpx;
						height: 50rpx;
						right: -2rpx;
						top: 15rpx;
						background-color: #fff;
					}
				}
			}
		}

    .scrollContent{
      flex: 1;
      min-height: 0;
    }
		.page_item {
			// margin-bottom: 10rpx;
			border-radius: 8rpx;
			overflow: hidden;

      .splitLine{
        height: 50rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #8F8F8F;
        .splitLineFlex{
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: center;
          .splitLineBox{
            width: calc(100% - 48rpx);
            height: 1rpx;
            background-color: #8F8F8F;
          }
        }
      }

			.page_item_info {
        margin-top: 10rpx;
				padding: 20rpx 16rpx;
				text-align: left;
				line-height: 60rpx;
				font-size: 30rpx;
        background: #fff;

        &.mt0{
          margin-top: 0;
        }

        .buildOrder{
          width: 258rpx;
          height: 72rpx;
          background: #49B856;
          border-radius: 6rpx;
          margin: 0 auto;
          color: #FFFFFF;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 30rpx;
        }

				.page_item_info_title {
					font-weight: 700;

					&.btn {
						display: flex;
						button {
							font-size: 28rpx;
							color: #49b856;
							height: 50rpx;
							line-height: 50rpx;
							margin: 0;
						}
					}
          &.row{
            display: flex;
            align-items: center;
            justify-content: space-between;
          }

					text {
						font-weight: normal;

						&.red {
							color: red;
						}

            &.bold{
              font-weight: 700;
            }
					}
				}
			}
		}
	}
</style>
