import { get, post } from '../http/http.js'
import { pathUrl } from "../tools/photograph.js";

// 如果不是静配,药配,标本配送,标本轮巡
// 科室签到(小扫描)-拍照
export function nextDeptOrder_ss(_this, data, accountObj) {
  uni.showLoading({
    title: "加载中",
    mask: true,
  });
  _this.actions = _this.actions || [];
  console.log(_this.currentCode);
  if (_this.currentCode) {
    // 动作
    let actions = _this.actions.filter(v => v.checked);
    let actionRemarks = actions.map(v => v.name).toString();
    if(actionRemarks){
      let postData = {
        orderId: data.id,
      };
      if(data.gdState.value == 4){
        postData.actionStartRemarks = actionRemarks;
      }else if(data.gdState.value == 5){
        postData.actionRemarks = actionRemarks;
      }
      post("/workerOrder/addOtherRemarks", postData).then((result1) => {
        if(result1.state == 200){
          postWorkerOrder(_this, data, accountObj);
        }else{
          uni.hideLoading();
          uni.showToast({
            icon: "none",
            title: result1.msg || "接口获取数据失败!",
          });
        }
      });
    }else{
      postWorkerOrder(_this, data, accountObj);
    }
  }else{
    uni.hideLoading();
  }
}

// 完成工单
export function uploadToOther(_this, data, accountObj){
  uni.showLoading({
    mask: true,
    title: '加载中'
  });
  _this.imageValue = _this.imageValue || [];
  let imageValue = _this.imageValue;
  let gdOperate;
  let uploadType;
  if(data.gdState.value == 4){
    gdOperate = 27;
    uploadType = 'orderStartPhoto';
  }else if(data.gdState.value == 5){
    gdOperate = 22;
    uploadType = 'orderEndPhoto';
  }
  // 完成工单
  post('/workerOrder/findRecordInfoByOrderId', {
    orderId: data.id,
    gdOperate,
  }).then(result => {
    if (result.state == 200) {
      let n = 0;
      //#ifdef H5
      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/"+ uploadType +"/" +
                data.id +
                "/" + result.recordId,
              filePath: tp,
              name: "file",
              formData: {
                filename: v.name,
              },
              success: (uploadFileRes) => {
                console.log(uploadFileRes);
                if (--n === 0) {
                  nextDeptOrder_ss(_this, data, accountObj);
                }
              },
              fail: (err) => {
                n--;
                console.error(err);
                uni.showToast({
                  icon: "none",
                  title: "上传失败",
                  duration: 2000,
                });
              },
            });
          },
          "image/jpeg",
          0.1
        );
        // 图片上传 end
      });
      //#endif
      //#ifdef APP-PLUS
      imageValue.forEach((v) => {
        // 图片上传 start
        uni.compressImage({
          src: v.path,
          quality: 30,
          success: (res) => {
            console.log('压缩前', res)
            let tp = res.tempFilePath;
            console.log("压缩后");
            n++;
            uni.uploadFile({
              url: pathUrl +
                "/common/common/uploadAttachment/"+ uploadType +"/" +
                data.id +
                "/" + result.recordId,
              filePath: tp,
              name: "file",
              formData: {
                filename: v.name,
              },
              success: (uploadFileRes) => {
                console.log(uploadFileRes);
                if (--n === 0) {
                  nextDeptOrder_ss(_this, data, accountObj);
                }
              },
              fail: (err) => {
                n--;
                console.error(err);
                uni.showToast({
                  icon: "none",
                  title: "上传失败",
                  duration: 2000,
                });
              },
            });
          },
          fail: function () {
            uni.hideLoading();
            uni.showToast({
              icon: 'none',
              title: '上传失败',
              duration: 2000
            });
          }
        })
        // 图片上传 end
      });
      //#endif
    }else{
      uni.hideLoading();
    }
  })
}

// 完成工单
export function postWorkerOrder(_this, data, accountObj){
  uni.showLoading({
    title: "加载中",
    mask: true,
  });
  let isKs = 0;
  let ids = [];
  let id = data.id;
  ids.push(id);
  let list = {
    code: "",
    ids: ids,
  };
  let code = "";
  let type = "";
  let gdStateValue = data.gdState.value; //工单状态value
  let associationTypeValue = data.taskType.associationType.value; //关联类型value
  
  // 其他临床服务,并且工单状态是待到达||工单状态待送达
  if (
    (associationTypeValue == "other" &&
      gdStateValue == "4") ||
    gdStateValue == "5"
  ) {
    code = _this.currentCode;
    type = "orderSign/" + code;
    list = {
      ids
    };
    if (accountObj) {
      list.handover = [accountObj.accountId];
    }
    if (_this.logRemarks) {
      list.logRemarks = _this.logRemarks;
    }
    isKs = 1;
  }
  post("/workerOrder/" + type, list).then((res) => {
    console.log(res);
    uni.hideLoading();
    if (res) {
      if (res.status == 200) {
        if (
          gdStateValue == "4" &&
          associationTypeValue == "other"
        ) {
          uni.navigateTo({
            url: `../../pages/scanning_code/scanning_code?type=${associationTypeValue}&type1=${res.type}&id=${data.id}&deptCode=${code}&dept=${res.dept}&accountObj=${encodeURIComponent(JSON.stringify(accountObj))}`,
          });
        }
        if (gdStateValue == "5") {
          uni.navigateTo({
            url: `../../pages/scanning_code/scanning_code?type=${associationTypeValue}&type1=${res.type}&id=${data.id}&deptCode=${code}&dept=${res.dept}&accountObj=${encodeURIComponent(JSON.stringify(accountObj))}`,
          });
        }
      } else {
        uni.navigateTo({
          url: `../../pages/scanning_Result/scanning_Result?type=${
          associationTypeValue
        }&type1=${res.type}&id=${data.id}&status=600&msg=${
          res.msg
        }&isKs=${isKs}&model=${encodeURIComponent(
          JSON.stringify(res)
        )}&qrcode=${_this.currentCode}`,
        });
      }
    } else {
      uni.navigateTo({
        url: `../../pages/scanning_Result/scanning_Result?id=${data.id}&status=600&msg=扫码失败!请扫描正确的二维码!&isKs=${isKs}&qrcode=${_this.currentCode}`,
      });
    }
  });
}