<template>
  <view class="Scanning_Result">
    <view class="Scanning_top">
      <view class="Scanning_top_icon">
        您需要上传图片留存，请拍摄照片上传！
      </view>
    </view>

    <view class="Scanning_cont">
      <scroll-view scroll-y class="scrollContent">
        <view class="content">
          <view class="dept">
            {{workOrder.startDept ? workOrder.startDept.dept : ''}}<text class="newicon newicon-arrow-right-full"></text>{{workOrder.endDeptNames || ''}}
          </view>
          <view class="column">
            <view class="name">工单单号：</view>
            <view class="value">{{workOrder.gdcode}}</view>
          </view>
          <view class="column">
            <view class="name">任务类型：</view>
            <view class="value">{{workOrder.taskType ? workOrder.taskType.taskName : ''}}</view>
          </view>
          <view class="column">
            <view class="name">签到科室：</view>
            <view class="value">{{queryObj.accountDeptName}}</view>
          </view>
          <view class="column" v-if="queryObj.accountName">
            <view class="name">交接人：</view>
            <view class="value">{{queryObj.accountName}}</view>
          </view>
          <template v-if="config.drugsModel === 1">
            <view class="column">
              <view class="name">药品数：</view>
              <view class="value">{{drugsBagList.length ? drugsBagList[0].drugsCount : ''}}</view>
            </view>
            <view class="column">
              <view class="name">药品单号：</view>
              <view class="value">{{drugsBagList.length ? drugsBagList[0].batchNo : ''}}</view>
            </view>
          </template>
          <template v-if="config.drugsModel === 2">
            <view class="column">
              <view class="name">药单数：</view>
              <view class="value">{{drugsBagList.length}}</view>
            </view>
          </template>
          <view class="column top">
            <view class="name">留存照片：</view>
            <view class="value flex1">
              <uni-file-picker ref="handlerImgRef" v-model="imgList" limit="1" @success="handlerImgSuccess" @fail="handlerImgFail" @select="handlerImgSelect" @delete="handlerImgDelete"></uni-file-picker>
              <text class="imgTips">(支持JPG/PNG格式图片，单张大小10M以内)</text>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <view class="foot_btn_spe">
      <view class="column">
        <view class="btn" @click="goBack()">返回</view>
        <view class="btn" @click="completeOrder()">提交</view>
      </view>
    </view>
  </view>
</template>
<script>
  import { uploadFile } from '@/tools/uploadFile.js'
  import {
    get,
    post,
    SM,
    webHandle
  } from "@/http/http.js";
  export default {
    data() {
      return {
        imgList: [],//图片列表
        hosId: uni.getStorageSync('userData').user.currentHospital.id,
        queryObj: {}, //路由传递过来的数据
        drugsBagList: [], //药包列表
        drugsList: [], //药品列表
        workOrder: {}, //工单信息
        config: {}, //配置
      };
    },
    methods: {
      // 返回
      goBack(){
       uni.navigateBack();
      },
      // 工单完成
      completeOrder(){
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
        if(this.imgList.length){
          // 有图片
          this.$refs.handlerImgRef.upload();
        }else{
          // 没有图片
          let handlerOrder$ = this.handlerOrder();
          let requestList = [handlerOrder$];
          Promise.all(requestList).then(resList => {
            uni.hideLoading();
            console.log(resList);
            if(resList[0].state == 200){
              uni.showToast({
                icon: "none",
                title: this.workOrder.gdState.value == 4 ? "交接成功，请尽快送达科室！" : (this.workOrder.gdState.value == 5 ? "交接成功，完成配送！" : ""),
                duration: 60000,
                mask: true,
                complete(){
                  setTimeout(() => {
                    uni.hideToast();
                    uni.redirectTo({
                      url: `/pages/receiptpage/receiptpage`,
                    });
                  }, 2000)
                }
              });
            }else{
              uni.showToast({
                icon: 'none',
                title: resList[0].msg || '请求数据失败！'
              });
            }
          })
        }
      },
      // 工单完成接口
      handlerOrder(){
        let postData = {
          "type": this.queryObj.drugsBagType,
          "orderId": this.workOrder.id,
          "handover": this.queryObj.accountId ? +this.queryObj.accountId : undefined,
        };
        return post('/transflow/checkComplete', postData);
      },
      // 处理图片
      handlerOrderImg(imgObj){
        return uploadFile(imgObj, this.workOrder.gdState.value == 4 ? 'drugsBagStartCheck' : 'drugsBagEndCheck', this.workOrder.id)
      },
      // 上传报修图片成功
      handlerImgSuccess(e){
        this.imgList.forEach(v => {
          v.url = v.path;
        })
        console.log(this.imgList);
        
        let handlerOrder$ = this.handlerOrder();
        let requestList = [handlerOrder$];
        this.imgList.forEach(v => {
          let handlerOrderImg$ = this.handlerOrderImg(v);
          requestList.push(handlerOrderImg$);
        })
        
        Promise.all(requestList).then(resList => {
          uni.hideLoading();
          console.log(resList);
          if(resList[0].state == 200){
            uni.showToast({
              icon: "none",
              title: this.workOrder.gdState.value == 4 ? "交接成功，请尽快送达科室！" : (this.workOrder.gdState.value == 5 ? "交接成功，完成配送！" : ""),
              duration: 60000,
              mask: true,
              complete(){
                setTimeout(() => {
                  uni.hideToast();
                  uni.redirectTo({
                    url: `/pages/receiptpage/receiptpage`,
                  });
                }, 2000)
              }
            });
          }else{
            uni.showToast({
              icon: 'none',
              title: resList[0].msg || '请求数据失败！'
            });
          }
        })
      },
  
      // 上传报修图片失败
      handlerImgFail(e){
        this.imgList.forEach(v => {
          v.url = v.path;
        })
        console.log(this.imgList);
      },
      // 选择上传图片
      handlerImgSelect(e){
        this.imgList = this.imgList.concat(e.tempFiles);
        console.log(this.imgList);
      },
      // 删除上传图片
      handlerImgDelete(e){
        this.imgList = this.imgList.filter(v => e.tempFile.uuid != v.uuid);
        console.log(this.imgList);
      },
      // 初始化
      init(){
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
        
        let info$ = post(`/transflow/extra`, {type: this.queryObj.drugsBagType, extraType: 'orderInfo', orderId: +this.queryObj.orderId});
        let config$ = post(`/simple/data/fetchDataList/taskTypeConfig`, {
            "idx": 0,
            "sum": 1,
            "taskTypeConfig": {
                "taskTypeDTO": {
                    "hosId": {
                        "id": this.hosId
                    },
                    "ordinaryField": {
                        "key": "ordinary_field",
                        "value": this.queryObj.drugsBagType
                    }
                }
            }
        });
        
        Promise.all([info$, config$]).then(result => {
          uni.hideLoading();
          let [info, config] = result || [];
          
          if(info.state == 200){
            if(info.data){
              this.drugsBagList = info.data.drugsBagList || [];
              if(Array.isArray(info.data.workOrder.endDepts)){
                info.data.workOrder.endDeptNames = info.data.workOrder.endDepts.map(v => v.dept).join();
              }
              this.workOrder = info.data.workOrder || {};
            }
          }else{
            uni.showToast({
              icon: "none",
              title: info.msg || "接口获取数据失败！",
            });
          }
          
          if(config.status == 200){
            let list  = config.list || [];
            this.config = list.length ? list[0] : {};
          }else{
            uni.showToast({
              icon: "none",
              title: config.msg || "接口获取数据失败！",
            });
          }
        })
      },
    },
    onLoad(options) {
      console.log(options, "options");
      this.queryObj = options;
      this.init();
      // #ifdef APP-PLUS
      webHandle("no", "app");
      // #endif
      // #ifdef H5
      webHandle("no", "wx");
      // #endif
    },
  };
</script>
<style lang="less" scoped>
  .Scanning_Result {
    background: #FAFBFD;
    padding: 0 24rpx;
    display: flex;
    flex-direction: column;
    height: 100vh;

    .Scanning_top {
      margin: 32rpx auto;
      .Scanning_top_icon {
        font-size: 28rpx;
        font-weight: bold;
      }
    }

    .Scanning_cont {
      flex: 1;
      min-height: 0;
      display: flex;
      flex-direction: column;
      .scrollContent{
        flex: 1;
        min-height: 0;
      }
      .content{
        border: 1rpx solid #C5C5C5;
        background: #FFFFFF;
        padding: 32rpx;
        .dept{
          font-size: 30rpx;
          font-weight: bold;
          .newicon{
            margin: 0 32rpx;
          }
        }
        .column{
          display: flex;
          align-items: center;
          font-size: 30rpx;
          margin-top: 32rpx;
          &.top{
            align-items: flex-start;
          }
          .name{
            font-weight: bold;
            word-break: break-all;
            flex-shrink: 0;
          }
          .value{
            word-break: break-all;
            &.flex1{
              flex: 1;
              flex-shrink: 0;
            }
            .imgTips{
              font-size: 22rpx;
              color: #8E8E8E;
            }
          }
        }
      }
    }

    .foot_btn_spe {
      margin: 24rpx 0;
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 24rpx;
      font-weight: bold;
      
      .column{
        width: 100%;
        height: 78rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 24rpx;
        
        .btn {
          height: 100%;
          flex: 1;
          background: linear-gradient( 90deg, #6FC073 0%, #3DB197 100%);
          color: #fff;
          border-radius: 4rpx;
          font-size: 30rpx;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
    }
  }
</style>
