<template>
  <view class="specimenCheckingDetail">
    <view class="page_header" v-if="modifyReason || imgs.length">
      <view class="page_header_item" v-if="modifyReason">
        <view class="page_header_title"> 修改原因： </view>
        <view class="page_header_content">
          {{ modifyReason }}
        </view>
      </view>
      <view class="page_header_item" v-if="imgs.length">
        <view class="page_header_title"> 图片列表： </view>
        <view class="page_header_content">
          <image v-for="(item, i) in imgs" :key="i" :src="item" @click="previewImage(i)" mode="widthFix"
            @error="close(i)"></image>
        </view>
      </view>
    </view>
    <view class="page_item_wrap" v-for="item in list" :key="item.id">
      <view class="page_item">
        <view class="page_item_top">
          <view class="page_item_top-inner">
            <view class="page_item_top_L">
              <view class="L_text">{{ item.scode }}<text v-if="item.stype">({{item.stype.name}})</text></view>
            </view>
            <view class="page_item_top_R">
              <view class="L_iocn">
                <text :style="{color:item.urgent == 1?'red':'green'}">{{item.urgent == 1 ? "急" : "普"}}</text>
                <button type="primary" size="mini" class="back" @click="back(item, msg.uuid)" v-if="options.t">
                  退回
                </button>
              </view>
            </view>
          </view>
        </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.specimenDesc || "无" }}</view>
            </view>
            <view class="page_item_cont_title">
              <view> 患者姓名 </view>
              <view class="text_big">{{ item.patientName }}<text v-if="item.bedNum">({{item.bedNum}})</text></view>
            </view>
            <view class="page_item_cont_title">
              <view> 住院号 </view>
              <view class="text_big">{{item.residenceNo||'无'}}</text></view>
            </view>
            <view class="page_item_cont_title">
              <view class="text_big">{{
                item.sickRoom ? item.sickRoom.dept : "无"
              }}</view>
              <text style="width: 4em;text-align: center;" class="icon_transport transport-arrow-right-full"></text>
              <view class="text_big">{{
                item.checkDept ? item.checkDept.dept : "无"
              }}</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="showChangeSpe()">修改数量</view>
      <view class="btn2" @click="goto()">返回</view>
    </view>
    <!-- 修改标本数量弹窗 -->
    <changeSpeNum v-if="changeSpeModels.disjunctor" :title="changeSpeModels.title"
      :disjunctor="changeSpeModels.disjunctor" @ok="speOk" @cancel="speCancel" :num="speNum">
    </changeSpeNum>
    <!-- 退回弹窗 -->
    <backModel v-if="backModels.disjunctor" :title="backModels.title" :disjunctor="backModels.disjunctor" @ok="backOk"
      @cancel="backCancel"></backModel>
    <!-- 填写交接人账号弹窗 -->
    <selectAccount v-if="hosModels.disjunctor" :title="hosModels.title" :disjunctor="hosModels.disjunctor" @ok="hosOk"
      @cancel="hosCancel">
    </selectAccount>
    <!-- 弹窗 -->
    <showModel :title="models.title" :icon="models.icon" :disjunctor="models.disjunctor" :content="models.content"
      :operate="models.operate" @know="know"></showModel>
  </view>
</template>
<script>
  import {
    get,
    post,
    webHandle
  } from "../../http/http.js";
  export default {
    data() {
      return {
        res: {},
        backStatus: "",
        workOrderId: 0,
        backSpecimen: {},
        backParams: {},
        imgs: [],
        // --------------------
        speNum: 0,
        modifyReason: "",
        options: {},
        selectDeptId: null,
        msg: {}, //传递的信息
        list: [],
        targetDeptShow: [], //目标科室
        // 修改标本数量弹窗model
        changeSpeModels: {
          disjunctor: false,
        },
        // 退回弹窗model
        backModels: {
          disjunctor: false,
        },
        // 填写交接人账号弹窗model
        hosModels: {
          disjunctor: false,
        },
        // 弹窗model
        models: {
          disjunctor: false,
        },
      };
    },
    methods: {
      close(i) {
        this.imgs.splice(i, 1);
      },
      know() {
        this.models.disjunctor = false;
        this.backModels.disjunctor = false;
        if (this.models.icon === "success") {
          this.getList();
        }
      },
      // 退回
      back(specimen, workOrderId) {
        this.backSpecimen = specimen;
        this.backStatus = "back";
        this.workOrderId = workOrderId;
        this.showBack();
      },
      // 退回
      backHandler(specimen, workorderId, data) {
        console.log(specimen);
        const {
          reasonForReturn,
          remarks
        } = this.backParams;
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
        let postData = {
          deptId: this.selectDeptId == "undefined" ?
            this.msg.startDept : this.selectDeptId,
          reasonForReturn: reasonForReturn.id,
          remarks,
          scode: specimen.scode,
          hosId: uni.getStorageSync("userData").user.currentHospital.id,
          speState: specimen.speState ? specimen.speState.id : undefined,
          handoverId: data ? data.accountId : undefined,
          handoverName: data ? data.accountName : undefined,
          gdId: workorderId || undefined,
        };
        post("/workerOrder/returnSpecimen", postData).then((res) => {
          uni.hideLoading();
          if (res.state == 200) {
            this.models = {
              disjunctor: true,
              title: "提示",
              content: `标本退回成功`,
              icon: "success",
            };
          } else {
            this.models = {
              disjunctor: true,
              title: "提示",
              content: `标本退回失败`,
              icon: "error",
            };
          }
        });
      },
      // 填写交接人账号-确认
      hosOk(data) {
        console.log(data);
        const {
          accountName,
          account,
          accountId
        } = data;
        if (!accountName && !account) {
          //没有填写交接人
          uni.showModal({
            title: "提示",
            content: "请填写交接人账号！",
            showCancel: false,
            success: function(res) {
              if (res.confirm) {
                console.log("用户点击确定");
              } else if (res.cancel) {
                console.log("用户点击取消");
              }
            },
          });
          return;
        } else if ((!accountName && account) || (accountName && !account)) {
          //没有填写交接人
          uni.showModal({
            title: "提示",
            content: "请填写正确的交接人账号！",
            showCancel: false,
            success: function(res) {
              if (res.confirm) {
                console.log("用户点击确定");
              } else if (res.cancel) {
                console.log("用户点击取消");
              }
            },
          });
          return;
        }
        this.hosModels.disjunctor = false;
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
        console.log(this.backStatus, "this.backStatus");
        if ((this.backStatus = "back")) {
          // 退回
          this.backHandler(this.backSpecimen, this.msg.uuid, data);
        }
      },
      // 填写交接人账号-取消
      hosCancel() {
        this.hosModels.disjunctor = false;
      },
      // 填写交接人账号弹窗
      showSelectAccount() {
        this.hosModels = {
          title: "填写交接人账号",
          disjunctor: true,
        };
      },
      // 退回-确认
      backOk(data) {
        console.log(data);
        this.backParams = data;
        this.hosModels.disjunctor = false;
        let postData = {
          idx: 0,
          sum: 1,
          hospitalConfig: {
            hosId: uni.getStorageSync("userData").user.currentHospital.id,
            key: "returnSpecimenWhetherHandover",
          },
        };
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
        post("/simple/data/fetchDataList/hospitalConfig", postData).then(
          (result) => {
            uni.hideLoading();
            if (result.status == 200) {
              if (result.list[0].value == 1 && this.backParams.reasonForReturn.extra1 == 1) {
                this.backCancel();
                this.showSelectAccount();
              } else {
                this.backHandler(this.backSpecimen, this.workOrderId);
              }
            } else {
              uni.showToast({
                icon: "none",
                title: "请求失败！",
              });
            }
          }
        );
      },
      // 退回-取消
      backCancel() {
        this.backModels.disjunctor = false;
      },
      // 退回弹窗
      showBack() {
        this.backModels = {
          title: "退回",
          disjunctor: true,
        };
      },
      previewImage(index) {
        //uniapp预览轮播图
        uni.previewImage({
          current: index, //预览图片的下标
          urls: this.imgs, //预览图片的地址，必须要数组形式，如果不是数组形式就转换成数组形式就可以
        });
      },
      // ---------------------------
      getInfo() {
        uni.showLoading({
          mask: true,
          title: "加载中",
        });
        let postData = {
          deptId: this.selectDeptId == "undefined" ?
            this.msg.startDept : this.selectDeptId,
          gdId: this.msg.uuid,
        };
        post(`/api/getStartDeptSpecimensNum`, postData).then((res) => {
          uni.hideLoading();
          if (res.status == 200) {
            this.speNum = res.data[0].deptSpecimensNum;
            this.modifyReason = res.data[0].modifyReason;
            get(
              `/common/common/listAttachment/specimenPhotos/${res.data[0].bindId}`
            ).then((result) => {
              if (result.status == 200) {
                this.imgs = result.data.map((v) => v.previewUrl);
              } else {
                this.imgs = [];
              }
            });
          } else {
            this.speNum = "";
            this.modifyReason = "";
          }
        });
      },
      getList() {
        uni.showLoading({
          mask: true,
          title: "加载中",
        });
        let postData = {
          checkDept: this.options.endDepts, //终点科室
          transDept: Number(this.msg.startDept), //起点科室id
          gdId: this.msg.uuid, //工单id或uuid
        };
        if (this.selectDeptId != "undefined") {
          if (Number(this.msg.startDept) != Number(this.selectDeptId)) {
            postData.checkDept = Number(this.selectDeptId); //签到的科室或者选择的科室
            if (this.options.t) {
              postData.sign = true; //待送达
            }
          }
        }
        post(`/api/getTransDeptSpecimens`, postData).then((res) => {
          uni.hideLoading();
          uni.stopPullDownRefresh();
          if (res.status == 200) {
            this.list = res.data;
            this.getInfo();
          } else {
            uni.showToast({
              icon: "none",
              title: "请求失败！",
            });
          }
        });
      },
      // 返回
      goto() {
        if (this.options.t == "big") {
          uni.navigateBack();
        } else if (this.options.t == "small") {
          uni.navigateBack();
        } else {
          uni.navigateTo({
            url: `../../pages/specimenChecking/specimenChecking?infoDATA=${encodeURIComponent(
            JSON.stringify(this.msg)
          )}`,
          });
        }
      },
      // 修改标本数量-确认
      speOk(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.options.endDepts, //终点科室
          transDeptId: this.msg.startDept,
          gdId: this.msg.uuid,
          deptId: this.selectDeptId == "undefined" ?
            this.msg.startDept : this.selectDeptId,
          specimensNum: speNum,
          modifyReason: reason,
        };
        post("/api/updateCheckDeptSpecimensNum", postData).then((res) => {
          if (res.status == 200) {
            console.log(imageValue);
            if (!imageValue.length) {
              uni.hideLoading();
              if (this.options.t == "big") {
                if (this.options.gdState == 4) {
                  // 待到达
                  uni.navigateTo({
                    url: `../../pages/receiptpage/receiptpage`,
                  });
                } else if (this.options.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.options.t == "small") {
                if (this.selectDeptId == "undefined") {
                  //快捷建单建单进入
                  uni.navigateTo({
                    url: `../../pages/receiptpage/receiptpage`,
                  });
                } else {
                  if (this.options.gdState == 4) {
                    // 待到达
                    uni.navigateTo({
                      url: `../../pages/receiptpage/receiptpage`,
                    });
                  } else if (this.options.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.msg)
                )}`,
                });
              }
              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.cloudPath,
                    },
                    success: (uploadFileRes) => {
                      console.log(uploadFileRes);
                      if (--n === 0) {
                        uni.hideLoading();
                        uni.showModal({
                          title: "提示",
                          content: "修改成功！",
                          showCancel: false,
                          success: (result) => {
                            if (result.confirm) {
                              console.log("用户点击确定", this.options.t);
                              if (this.options.t == "big") {
                                if (this.options.gdState == 4) {
                                  // 待到达
                                  uni.navigateTo({
                                    url: `../../pages/receiptpage/receiptpage`,
                                  });
                                } else if (this.options.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.options.t == "small") {
                                if (this.selectDeptId == "undefined") {
                                  //快捷建单建单进入
                                  uni.navigateTo({
                                    url: `../../pages/receiptpage/receiptpage`,
                                  });
                                } else {
                                  if (this.options.gdState == 4) {
                                    // 待到达
                                    uni.navigateTo({
                                      url: `../../pages/receiptpage/receiptpage`,
                                    });
                                  } else if (this.options.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.msg)
                                )}`,
                                });
                              }
                            } 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: "请求失败！",
            });
          }
        });
      },
      // 修改标本数量-取消
      speCancel() {
        this.changeSpeModels.disjunctor = false;
      },
      // 修改标本数量弹窗
      showChangeSpe() {
        this.changeSpeModels = {
          title: "修改标本数量",
          disjunctor: true,
        };
      },
    },
    onLoad(options) {
      console.log(options, "快捷建单");
      this.options = options;
      this.msg = JSON.parse(options.infoDATA);
      this.selectDeptId = options.id;
      // this.msg = JSON.parse(options.infoDATA);
      // this.targetDeptShow = this.msg.targetDeptShow.split(",");
      this.getList();
      // #ifdef APP-PLUS
      webHandle("no", "app");
      // #endif
      // #ifdef H5
      webHandle("no", "wx");
      // #endif
    },
    onPullDownRefresh() {
      this.getList();
    },
  };
</script>
<style lang="less" scoped>
  .specimenCheckingDetail {
    padding-bottom: 100rpx;

    .page_header {
      margin: 20rpx;
      padding: 16rpx;
      border: 2rpx solid #e5e9ed;
      background: #fff;
      border-radius: 8rpx;

      .page_header_item {
        margin-bottom: 16rpx;

        .page_header_title {
          margin-bottom: 8rpx;
          font-weight: bold;
        }

        .page_header_content {
          display: flex;

          image {
            height: 100rpx;
            width: 30%;
            margin: 0 8rpx;
          }
        }
      }
    }

    .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: 0 16rpx;

          .page_item_top-inner {
            display: flex;
            justify-content: space-between;
            align-items: center;
            height: 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;

              .back {
                color: rgb(7, 134, 60);
                background-color: #49b856;
                margin-left: 16rpx;
              }

              .L_iocn {
                display: flex;
                justify-content: space-between;
                align-items: center;
                font-size: 36rpx;
                font-weight: 700;
              }
            }
          }
        }

        .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;
            padding-bottom: 28rpx;
            font-size: 28rpx;

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

          .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>
