<template>
  <view class="specimenChecking">
    <view class="title">请您确认一下科室标本数量！</view>
    <view class="page_item_wrap" v-for="item in list" :key="item.deptId">
      <view class="page_item">
        <view class="page_item_top">
          <template v-if="taskTypeConfig.speExpandTube == 1">
            <uni-collapse :border="false">
						<uni-collapse-item titleBorder="none" :open="taskTypeConfig.speDefaultExpandTube == 1">
							<template v-slot:title>
								<view class="page_item_cont_title_coll" @click.stop="gotoDetail(item)">
									<view class="page_item_top-inner">
                    <view class="L_text">{{item.deptName}}</view>
										<view class="page_item_top_R">
											<view class="L_iocn" style="margin-right: 20rpx;">{{item.speNum}}</view>
										</view>
									</view>
								</view>
							</template>
							<view class="content">
								<view class="list" v-for="x in item.tubeTypeDataList" :key="x.id" @click="viewSpe(item, x.tubeTypeId)">
									{{x.tubeTypeName}}：<text class="underline-item">{{x.speNum}}</text>
								</view>
							</view>
						</uni-collapse-item>
					</uni-collapse>
          </template>
          <template v-else>
            <view class="page_item_cont_title_coll" @click.stop="gotoDetail(item)">
              <view class="page_item_top-inner">
                  <view class="L_text">{{item.deptName}}</view>
                <view class="page_item_top_R">
                  <view class="L_iocn">{{item.speNum}}</view>
                </view>
              </view>
            </view>
          </template>
        </view>
        <!-- <view class="page_item_cont">
          <view class="page_item_cont_T">
            <view class="page_item_cont_title">
              <view>
                标本数量
              </view>
              <view class="text_big">{{item[2]}}</view>
            </view>
          </view>
        </view> -->
        <!-- <view class="L"></view>
        <view class="R"></view> -->
      </view>
      <!-- <view class="L-l"></view> -->
      <!-- <view class="R-l"></view> -->
    </view>
    <view class="foot_btn2">
      <view class="btn2" @click="createOrder">确认数量并建单</view>
      <view class="btn2" @click="goto()">返回</view>
    </view>
    <!-- 修改标本数量弹窗 -->
    <changeSpeNum v-if="changeSpeModels.disjunctor" :operate="{ok:'确认数量',check:'详细核对',cancel:'取消'}" :title="changeSpeModels.title" :content="changeSpeModels.content"
      :disjunctor="changeSpeModels.disjunctor" @ok="changeSpeOk" @check="changeSpeCheck" @cancel="changeSpeCancel" :num="speNumChange">
    </changeSpeNum>
    <!-- 弹窗 -->
    <showModel :title="models.title" :icon="models.icon" :disjunctor="models.disjunctor" :content="models.content"
      @ok="ok" @no="no" @cancel="cancel" @know="know" :operate="models.operate"></showModel>
  </view>
</template>
<script>
  import showModel from "../../components/showModel/showModel.vue";
  import {
    get,
    post,
    webHandle
  } from "../../http/http.js";
  export default {
    components: {
      showModel,
    },
    data() {
      return {
        hosId: uni.getStorageSync('userData').user.currentHospital.id,
        taskTypeConfig: {},
        // 弹窗model
        models: {
          disjunctor: false,
        },
        list: [],
        msg: {}, //页面展示信息
        // 修改标本数量弹窗model
        changeSpeModels: {
          disjunctor: false,
        },
        speNumChange: 0,
        changeSpeObj: {},
      };
    },
    methods: {
      // 获取配置
			getSpecimenTaskTypeConfig(){
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
        post("/simple/data/fetchDataList/taskTypeConfig", {
          "idx": 0,
          "sum": 1,
          "taskTypeConfig": {
            "taskTypeDTO": {
              "hosId": {
                  "id": this.hosId
              },
              "associationType": {
                  "key": "association_types",
                  "value": "specimen"
              }
            }
          }
        }).then((result) => {
          uni.hideLoading();
          if (result.status == 200) {
            if(result.list.length){
              this.taskTypeConfig = result.list[0] || {};
            }else{
              uni.showToast({
                icon: "none",
                title: "请配置标本配送任务类型！",
              });
            }
          } else {
            uni.showToast({
              icon: "none",
              title: result.msg || "接口获取数据失败！",
            });
          }
        });
      },
			viewSpe(item, tubeTypeId){
				this.speNumChange = item.speNum;
				this.changeSpeObj = {
				  infoDATA: this.msg,
				  id: item.deptId,
				  endDepts:this.msg.targetDept,
				}
				uni.navigateTo({
				  url: `../../pages/specimenCheckingDetail/specimenCheckingDetail?infoDATA=${encodeURIComponent(JSON.stringify(this.changeSpeObj.infoDATA))}&id=${this.changeSpeObj.id}&endDepts=${this.changeSpeObj.endDepts}&tubeTypeId=${tubeTypeId}`,
				});
			},
      //确认数量并建单-返回
      know() {
        this.models.disjunctor = false;
      },
      //确认数量并建单-确定
      ok() {
        this.models.disjunctor = false;
        const speNumNot0Depts = this.list.filter(v => v.speNum !== 0);
        const speNumNot0DeptsStr = speNumNot0Depts.map(v => v.deptId).toString();
        uni.showLoading({
          mask: true,
          title: '加载中'
        })
        post(`/workerOrder/createQuickOrder`, {
          id: this.msg.id,
          notEmptyEndDeptIds: speNumNot0DeptsStr || undefined,
        }).then((res) => {
          uni.hideLoading();
          if (res.status == 200) {
            if (res.type === 'plan-spe-ddd-2') {
              //需要扫描标本
              uni.navigateTo({
                url: `../../pages/scanning_code/scanning_code?type=${res.associationTypeName}&type1=${res.type}&id=${res.id}&deptCode=${res.deptCode}&dept=${res.deptName}&accountObj=undefined&endDepts=${this.msg.targetDept}&deptId=${res.deptId}`,
              });
            } else {
              uni.navigateTo({
                url: "../receiptpage/receiptpage",
              });
            }
          } else {
            uni.showToast({
              icon: "none",
              title: res.msg || "接口获取数据失败！",
            });
          }
        });
      },
      //确认数量并建单-否
      no() {
        this.models.disjunctor = false;
        this.createOrderFun();
      },
      //确认数量并建单-取消
      cancel() {
        this.models.disjunctor = false;
      },
      // 数量核对 start
      // 修改标本数量-核对
      changeSpeCheck(){
        this.changeSpeModels.disjunctor = false;
        uni.navigateTo({
          url: `../../pages/specimenCheckingDetail/specimenCheckingDetail?infoDATA=${encodeURIComponent(JSON.stringify(this.changeSpeObj.infoDATA))}&id=${this.changeSpeObj.id}&endDepts=${this.changeSpeObj.endDepts}`,
        });
      },
      // 修改标本数量-确认
      changeSpeOk(data) {
        console.log(data);
        const pathUrl = uni.getStorageSync("path");
        const {
          speNum,
          reason,
          imageValue
        } = data;
        this.changeSpeModels.disjunctor = false;
        uni.showLoading({
          mask: true,
          title: "加载中",
        });
        let postData = {
          checkDept: this.changeSpeObj.endDepts, //终点科室
          transDeptId: this.changeSpeObj.infoDATA.startDept,
          gdId: this.changeSpeObj.infoDATA.uuid,
          deptId: this.changeSpeObj.id == "undefined" ?
            this.changeSpeObj.infoDATA.startDept : this.changeSpeObj.id,
          specimensNum: speNum,
          modifyReason: reason,
        };
        post("/api/updateCheckDeptSpecimensNum", postData).then((res) => {
          if (res.status == 200) {
            console.log(imageValue);
            if (!imageValue.length) {
              uni.hideLoading();
              if (this.changeSpeObj.t == "big") {
                if (this.changeSpeObj.gdState == 4) {
                  // 待到达
                  uni.navigateTo({
                    url: `../../pages/receiptpage/receiptpage`,
                  });
                } else if (this.changeSpeObj.gdState == 5) {
                  // 待送达
                  if (res.type1 === "plan-spe-ddd-2") {} else {
                    let content = `本工单已签到<strong class="red">${
                    res.scanSet ? res.scanSet.join("、") : ""
                  }</strong>，剩余需签到科室<strong class="red">${
                    res.notScanSet ? res.notScanSet.join("、") : ""
                  }</strong>，您确定完成工单吗？`;
                    uni.navigateTo({
                      url: `../scanning/scanning?type=${res.type}&type1=${
                      res.type1
                    }&id=${encodeURIComponent(
                      JSON.stringify([res.gdid])
                    )}&content=${content}`,
                    });
                  }
                }
              } else if (this.changeSpeObj.t == "small") {
                if (this.changeSpeObj.id == "undefined") {
                  //快捷建单建单进入
                  uni.navigateTo({
                    url: `../../pages/receiptpage/receiptpage`,
                  });
                } else {
                  if (this.changeSpeObj.gdState == 4) {
                    // 待到达
                    uni.navigateTo({
                      url: `../../pages/receiptpage/receiptpage`,
                    });
                  } else if (this.changeSpeObj.gdState == 5) {
                    // 待送达
                    if (res.type1 === "plan-spe-ddd-2") {} else {
                      let content = `本工单已签到<strong class="red">${
                      res.scanSet ? res.scanSet.join("、") : ""
                    }</strong>，剩余需签到科室<strong class="red">${
                      res.notScanSet ? res.notScanSet.join("、") : ""
                    }</strong>，您确定完成工单吗？`;
                      uni.navigateTo({
                        url: `../scanning/scanning?type=${res.type}&type1=${
                        res.type1
                      }&id=${encodeURIComponent(
                        JSON.stringify([res.gdid])
                      )}&content=${content}`,
                      });
                    }
                  }
                }
              } else {
                uni.navigateTo({
                  url: `../../pages/specimenChecking/specimenChecking?infoDATA=${encodeURIComponent(
                  JSON.stringify(this.changeSpeObj.infoDATA)
                )}`,
                });
              }
              return;
            }
            let n = 0;
            imageValue.forEach((v) => {
              // 图片上传 start
              console.log("压缩前");
              let canvasWidth = v.image.width; //图片原始长宽
              let canvasHeight = v.image.height;
              let img = new Image();
              img.src = v.path;
              let canvas = document.createElement("canvas");
              let ctx = canvas.getContext("2d");
              canvas.width = canvasWidth;
              canvas.height = canvasHeight;
              ctx.drawImage(img, 0, 0, canvasWidth, canvasHeight);
              canvas.toBlob(
                (fileSrc) => {
                  let tp = window.URL.createObjectURL(fileSrc);
                  console.log("压缩后");
                  n++;
                  uni.uploadFile({
                    url: pathUrl +
                      "/common/common/uploadAttachment/specimenPhotos/" +
                      res.deptSpecimensNumId +
                      "/666",
                    filePath: tp,
                    name: "file",
                    formData: {
                      filename: v.name,
                    },
                    success: (uploadFileRes) => {
                      console.log(uploadFileRes);
                      if (--n === 0) {
                        uni.hideLoading();
                        uni.showModal({
                          title: "提示",
                          content: "修改成功！",
                          showCancel: false,
                          success: (result) => {
                            if (result.confirm) {
                              console.log("用户点击确定", this.changeSpeObj.t);
                              if (this.changeSpeObj.t == "big") {
                                if (this.changeSpeObj.gdState == 4) {
                                  // 待到达
                                  uni.navigateTo({
                                    url: `../../pages/receiptpage/receiptpage`,
                                  });
                                } else if (this.changeSpeObj.gdState == 5) {
                                  // 待送达
                                  if (res.type1 === "plan-spe-ddd-2") {} else {
                                    let content = `本工单已签到<strong class="red">${
                                    res.scanSet ? res.scanSet.join("、") : ""
                                  }</strong>，剩余需签到科室<strong class="red">${
                                    res.notScanSet ? res.notScanSet.join("、") : ""
                                  }</strong>，您确定完成工单吗？`;
                                    uni.navigateTo({
                                      url: `../scanning/scanning?type=${res.type}&type1=${
                                      res.type1
                                    }&id=${encodeURIComponent(
                                      JSON.stringify([res.gdid])
                                    )}&content=${content}`,
                                    });
                                  }
                                }
                              } else if (this.changeSpeObj.t == "small") {
                                if (this.changeSpeObj.id == "undefined") {
                                  //快捷建单建单进入
                                  uni.navigateTo({
                                    url: `../../pages/receiptpage/receiptpage`,
                                  });
                                } else {
                                  if (this.changeSpeObj.gdState == 4) {
                                    // 待到达
                                    uni.navigateTo({
                                      url: `../../pages/receiptpage/receiptpage`,
                                    });
                                  } else if (this.changeSpeObj.gdState == 5) {
                                    // 待送达
                                    if (res.type1 === "plan-spe-ddd-2") {} else {
                                      let content = `本工单已签到<strong class="red">${
                                      res.scanSet ? res.scanSet.join("、") : ""
                                    }</strong>，剩余需签到科室<strong class="red">${
                                      res.notScanSet ? res.notScanSet.join("、") : ""
                                    }</strong>，您确定完成工单吗？`;
                                      uni.navigateTo({
                                        url: `../scanning/scanning?type=${res.type}&type1=${
                                        res.type1
                                      }&id=${encodeURIComponent(
                                        JSON.stringify([res.gdid])
                                      )}&content=${content}`,
                                      });
                                    }
                                  }
                                }
                              } else {
                                uni.navigateTo({
                                  url: `../../pages/specimenChecking/specimenChecking?infoDATA=${encodeURIComponent(
                                  JSON.stringify(this.changeSpeObj.infoDATA)
                                )}`,
                                });
                              }
                            } else if (result.cancel) {
                              console.log("用户点击取消");
                            }
                          },
                        });
                      }
                    },
                    fail: (err) => {
                      n--;
                      console.error(err);
                      uni.hideLoading();
                      uni.showToast({
                        icon: "none",
                        title: "上传失败",
                        duration: 2000,
                      });
                    },
                  });
                },
                "image/jpeg",
                0.3
              );
              // 图片上传 end
            });
          } else {
            uni.hideLoading();
            uni.showToast({
              icon: "none",
              title: res.msg || "接口获取数据失败！",
            });
          }
        });
      },
      // 修改标本数量-取消
      changeSpeCancel() {
        this.changeSpeModels.disjunctor = false;
      },
      // 修改标本数量弹窗
      showChangeSpe() {
        this.changeSpeModels = {
          title: "修改标本数量",
          disjunctor: true,
        };
      },
      // 数量核对 end
      // 获取列表
      getList() {
        uni.showLoading({
          mask: true,
          title: '加载中'
        })
        let postData = {
          startDept: this.msg.startDept,
          targetDept: this.msg.targetDept,
          uuid: this.msg.uuid
        }; //起点科室id，选择的科室ids
        post(`/api/getDeptSpecimensNum`, postData).then((res) => {
          uni.hideLoading();
          uni.stopPullDownRefresh();
          if (res.status == 200) {
            this.list = res.data;
          } else {
            uni.showToast({
              icon: "none",
              title: res.msg || "接口获取数据失败！",
            });
          }
        });
      },
      // 跳转到详情页
      gotoDetail(item) {
        this.speNumChange = item.speNum;
        this.changeSpeObj = {
          infoDATA: this.msg,
          id: item.deptId,
          endDepts:this.msg.targetDept,
        }
        this.showChangeSpe();
      },
      // 返回
      goto() {
        uni.navigateTo({
          url: `../../pages/receiptpage/receiptpage`,
        });
      },
      // 确认数量并建单-方法
      createOrderFun(){
        uni.showLoading({
          mask: true,
          title: '加载中'
        })
        post(`/workerOrder/createQuickOrder`, {
          id: this.msg.id,
        }).then((res) => {
          console.log(res)
          uni.hideLoading();
          if (res.status == 200) {
            if (res.type === 'plan-spe-ddd-2') {
              //需要扫描标本
              uni.navigateTo({
                url: `../../pages/scanning_code/scanning_code?type=${res.associationTypeName}&type1=${res.type}&id=${res.id}&deptCode=${res.deptCode}&dept=${res.deptName}&accountObj=undefined&endDepts=${this.msg.targetDept}&deptId=${res.deptId}`,
              });
            } else {
              uni.navigateTo({
                url: "../receiptpage/receiptpage",
              });
            }
          } else {
            uni.showToast({
              icon: "none",
              title: res.msg || "接口获取数据失败！",
            });
          }
        });
      },
      // 确认数量并建单
      createOrder() {
        console.log(this.list);
        const speNum0Depts = this.list.filter(v => v.speNum === 0);
        const speNumNot0Depts = this.list.filter(v => v.speNum !== 0);
        if(!speNumNot0Depts.length){
          uni.showModal({
            title: '提示',
            content: "您所有科室本轮配送均无标本，无法建单！",
            showCancel: false,
            success: (res) => {
              if (res.confirm) {
                console.log('用户点击确定');
              } else if (res.cancel) {
                console.log('用户点击取消');
              }
            }
          });
        }else{
          if(speNum0Depts.length){
            const speNum0DeptsName = speNum0Depts.map(v => v.deptName).toString();
            this.models = {
              disjunctor: true,
              title: "提示",
              content: `您有科室本轮配送无标本，是否清除。科室分别为:<span class="red">${speNum0DeptsName}</span>`,
              icon: "warn",
              operate: {
                ok: "是",
                no: '否',
                cancel: "取消",
              },
            };
          }else{
            uni.showModal({
              title: '提示',
              content: "您确认建单吗？",
              success: (res) => {
                if (res.confirm) {
                  console.log('用户点击确定');
                  this.createOrderFun();
                } else if (res.cancel) {
                  console.log('用户点击取消');
                }
              }
            });
          }
        }
      },
    },
    onLoad(options) {
      console.log(options, "快捷建单");
      this.msg = JSON.parse(options.infoDATA);
      this.getList();
      this.getSpecimenTaskTypeConfig();
      // #ifdef APP-PLUS
      webHandle("no", "app");
      // #endif
      // #ifdef H5
      webHandle("no", "wx");
      // #endif
    },
    onPullDownRefresh() {
      this.getList();
    },
  };
</script>
<style lang="less" scoped>
	/deep/ .uni-collapse-item--border{
		border-bottom-color: #fff !important;
	}

	/deep/ .uni-collapse-item__title-arrow{
		margin-right: 0 !important;
	}

  .specimenChecking {
    padding-bottom: 100rpx;

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

    .page_item_wrap {
      width: 100%;
      height: auto;
      box-sizing: border-box;
      position: relative;
      margin-bottom: 16rpx;

      .page_item {
        margin-top: 16rpx;
        margin-bottom: 124rpx;
        background: #fff;
        border-radius: 8rpx;
        margin: 0 20rpx;
        border: 2rpx solid #e5e9ed;
        position: relative;
        overflow: hidden;
        padding: 0 16rpx;

        .L {
          width: 40rpx;
          height: 40rpx;
          border-radius: 50%;
          background: #f9fafb;
          position: absolute;
          left: -20rpx;
          top: 68rpx;
          border: 2rpx solid #e5e9ed;
        }

        .R {
          width: 40rpx;
          height: 40rpx;
          border-radius: 50%;
          background: #f9fafb;
          position: absolute;
          float: right;
          right: -20rpx;
          top: 68rpx;
          border: 2rpx solid #e5e9ed;
        }

        .starting {
          width: 50rpx;
          height: 50rpx;
          color: #fff;
          background: #49b856;
          display: inline-block;
          border-radius: 50%;
          text-align: center;
          line-height: 46rpx;
          font-size: 32rpx;
          margin-right: 6rpx;
        }

        .End {
          width: 50rpx;
          height: 50rpx;
          color: #fff;
          background: #39b199;
          display: inline-block;
          border-radius: 50%;
          text-align: center;
          line-height: 46rpx;
          font-size: 32rpx;
          margin-right: 6rpx;
        }

        .page_item_top {
          // height: 88rpx;
          // border-bottom: 2rpx dashed #e5e9ed;
          padding: 20rpx 16rpx;

					.page_item_cont_title_coll{
						display: flex;
						justify-content: space-between;
						align-items: center;
						margin-right: 8rpx;

						.page_item_top-inner {
						  display: flex;
						  justify-content: space-between;
						  align-items: center;
						  height: 100%;
							width: 100%;

						  .page_item_top_L {
						    .emergencys {
						      background: #ff3b53 !important;
						      width: 124rpx !important;
						    }

						    .emergency {
						      background: #ff3b53 !important;
						    }

						    .emergency1 {
						      background: #49b856 !important;
						    }

						    .page_item_cont_start {
						      text-align: center;
						      height: 44rpx;
						      width: 104rpx;
						      line-height: 44rpx;
						      border-radius: 8rpx;
						      background: #49b856;
						      color: #fff;
						      display: inline-block;
						    }

						    .L_time {
						      color: #6cc076;
						      font-size: 32rpx;
						    }

						    .L_text {
						      font-size: 32rpx;
						      font-weight: 700;
						    }
						  }

						  .page_item_top_R {
						    font-size: 32rpx;

						    .L_iocn {
						      color: rgb(7, 134, 60);
						      font-size: 36rpx;
						      font-weight: 700;
						    }
						  }
						}
					}

					.content{
						display: flex;
						flex-wrap: wrap;
						.list{
							font-size: 28rpx;
							height: 60rpx;
							line-height: 60rpx;
							width: 50%;
							border-bottom: 1rpx solid #E6E6E6;
						}
					}
        }

				.underline-item{
					// text-decoration: underline;
					// margin-right: 40rpx;
				}

        .page_item_cont {
          min-height: 90rpx;
          padding: 0 16rpx;
          text-align: left;
          position: relative;

          .text_big {
            font-size: 32rpx;
            font-weight: 700;
            margin-top: 10rpx;

            p {
              font-weight: 700;
              line-height: 1.5;
            }
          }

          .page_item_cont_T {
            padding-top: 28rpx;
            font-size: 28rpx;

            .page_item_cont_title {
              height: 100%;
              font-size: 32rpx;
              display: flex;
              justify-content: space-between;
            }
          }

          .page_item_cont_B {
            padding-top: 28rpx;
            margin-bottom: 28rpx;

            .page_item_cont_title {
              font-size: 32rpx;
              display: flex;
              justify-content: space-between;
            }

            .page_item_cont_title1 {
              height: 60rpx;
              line-height: 60rpx;
              font-size: 32rpx;
              padding-left: 64rpx;
            }
          }
        }

        .page_item_foot {
          border-top: 2rpx dashed #e5e9ed;
          border-bottom: 2rpx dashed #e5e9ed;
          padding: 28rpx 16rpx;
          text-align: left;

          .page_item_foot_text {
            font-size: 32rpx;
            margin-bottom: 20rpx;

            .text1 {
              color: rgb(102, 102, 102);
            }

            .text2 {
              float: right;
              font-weight: 700;
            }
          }
        }

        #infos {
          display: none;
        }

        .page_item_infos {
          padding-bottom: 20rpx;
          border-bottom: 2rpx dashed #e5e9ed;

          .page_item_info2 {
            text-align: left;
            line-height: 60rpx;
            font-size: 32rpx;
            padding-left: 16rpx;

            .page_item_foot_text {
              font-size: 32rpx;
              margin-bottom: 20rpx;

              .text1 {
                color: rgb(102, 102, 102);
              }

              .text2 {
                float: right;
                font-weight: 700;
              }
            }
          }
        }
      }

      .L-l {
        width: 2rpx;
        height: 40rpx;
        background: #f9fafb;
        position: absolute;
        left: 20rpx;
        top: 72rpx;
      }

      .R-l {
        width: 2rpx;
        height: 40rpx;
        background: #f9fafb;
        position: absolute;
        right: 20rpx;
        top: 72rpx;
      }
    }

    .foot_btn2 {
      position: fixed;
      bottom: 0;
      width: 100vw;
      padding: 0 20rpx;
      box-sizing: border-box;
      line-height: 66rpx;
      height: 100rpx;
      border-top: 2rpx solid #e5e9ed;
      background: #f9fafb;
      text-align: center;
      display: flex;
      justify-content: center;
      align-items: center;

      .btn2 {
        height: 66rpx;
        flex: 1;
        margin: 16rpx 16rpx 0;
        background-image: linear-gradient(to right, #72c172, #3bb197);
        color: #fff;
        border-radius: 8rpx;
        font-size: 32rpx;
      }
    }
  }
</style>
