<template>
  <view class="my-answer-page">
    <navBar title="我的意见" />

    <scroll-view scroll-y class="content-scroll">
      <!-- 文本输入 -->
      <view class="card">
        <view class="card-title">我的意见 <text class="required">*</text></view>
        <view class="textarea-wrap">
          <textarea
            v-model="note"
            class="textarea"
            :maxlength="300"
            placeholder="请依据患者的个人信息、疾病资料及患者所咨询的问题详细解答患者的问题（信息仅提问患者及医生可见，最多输入300个字）"
            placeholder-class="ph"
            auto-height
          />
        </view>
      </view>

      <!-- 图片上传 -->
      <view class="card">
        <view class="card-title">相关图片</view>
        <view class="sub-tip">可以用部分科普或文献来协助回答问题，最多6张</view>
        <!-- <view class="imgbox">
					<uni-file-picker limit="6" v-model="tempImageList"  file-mediatype="image" :auto-upload="false" @select="selectImages" @delete="deleteImages" ></uni-file-picker>
				</view> -->
        <view class="img-grid">
          <view
            v-if="tempImageList.length > 0"
            v-for="(img, index) in tempImageList"
            :key="index"
            class="img-item"
            @click="preview(index)"
          >
            <image :src="img" mode="aspectFill" class="img" />
            <view class="del" @click.stop="remove(index)">×</view>
          </view>
          <view
            v-if="tempImageList.length < maxImages"
            class="img-item add"
            @click="beforeAddImages"
          >
            <view class="plus">＋</view>
          </view>
        </view>
      </view>
    </scroll-view>
    <!-- <button style="position: fixed;bottom: 200rpx;left: 50%;transform: translateX(-50%);z-index: 99999999999;" @click="test" >测试</button> -->
    <!-- 底部提交 -->
    <view class="bottom-fixed">
      <view class="submit-btn" @click="submit">提交</view>
    </view>
  </view>
</template>

<script setup>
import { ref } from "vue";
import navBar from "@/components/navBar/navBar.vue";
import api from "@/api/api";
import docUrl from "@/utils/docUrl";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { pathToBase64 } from "image-tools";
import { getCameraPermission } from "@/utils/permission.js";
import isAndroid from "@/utils/platform.js";
const uuid = ref("");
const answer_uuid = ref("");
const maxImages = 6;
const imgList = ref([]);
const isLock = ref(false);
const tempImageList = ref([]);
const note = ref("");
onLoad((options) => {
  uuid.value = options.uuid || "";
  answer_uuid.value = options.answer_uuid || "";
  getInterrogation();
});
const beforeAddImages = () => {
  if (isAndroid) {
    getCameraPermission(addImages);
  } else {
    addImages();
  }
};
const getInterrogation = () => {
  api
    .getInterrogation({
      uuid: uuid.value,
    })
    .then((res) => {
      console.log(res);
      if (res.code === "200" && res.data) {
        let user = uni.getStorageSync("userInfo");
        let arr = res.data.AnswerList.filter((item) => {
          return user.uuid == item.expert_uuid;
        });
        imgList.value = [];
        if (arr && arr.length > 0) {
          note.value = arr[0].note || "";
          let imgs = arr[0].imgs ? arr[0].imgs.split(",") : [];
          tempImageList.value = imgs.map((item, index) => {
            return {
              name: "图片" + index + 1,
              url: docUrl + item,
            };
          });
          tempImageList.value = imgs.map((item) => docUrl + item);
          for (let i = 0; i < imgs.length; i++) {
            uni.request({
              url: docUrl + imgs[i],
              method: "GET",
              responseType: "arraybuffer",
              success: (res) => {
                const base64 = `${uni.arrayBufferToBase64(res.data)}`;
                imgList.value.push(base64);
              },
              fail: (err) => {
                reject(err);
              },
            });
          }
        }
      }
    });
};
const updateInterrogationAnswer = () => {
  if (note.value.trim().length < 5) {
    uni.showToast({ title: "输入意见至少5个字", icon: "none" });
    return;
  }
  if (isLock.value) {
    return;
  }
  isLock.value = true;
  let imgobj = {};
  if (imgList.value.length > 0) {
    let count = 0;
    imgList.value.forEach((item, index) => {
      imgobj["img" + (index + 1)] = item;
    });
  }
  api
    .updateInterrogationAnswer({
      uuid: answer_uuid.value,
      note: note.value,
      imgsBean: imgobj,
    })
    .then((res) => {
      isLock.value = false;
      if (res.code == 200) {
        uni.showToast({ title: "提交成功", icon: "none" });
        uni.$emit("updateStatus", 1);
        uni.navigateBack();
      }
    });
};
const test = () => {
  uni.navigateTo({
    url: "/pages/upload/upload",
  });
};
const addInterrogationAnswer = () => {
  if (note.value.trim().length < 5) {
    uni.showToast({ title: "输入意见至少5个字", icon: "none" });
    return;
  }
  if (isLock.value) {
    return;
  }
  isLock.value = true;
  let imgobj = {};
  if (imgList.value.length > 0) {
    imgList.value.forEach((item, index) => {
      imgobj["img" + (index + 1)] = item;
    });
  }
  api
    .addInterrogationAnswer({
      step1_uuid: uuid.value,
      note: note.value,
      imgsBean: imgobj,
    })
    .then((res) => {
      isLock.value = false;
      if (res.code == 200) {
        uni.$emit("updateStatus", 1);
        uni.showToast({ title: "提交成功", icon: "none" });
        uni.navigateBack();
      }
    });
};
const selectImages = (e) => {
  let tempFilePaths = e.tempFiles;
  console.log(e);
  tempImageList.value = [...tempImageList.value, ...tempFilePaths];
  for (let i = 0; i < tempFilePaths.length; i++) {
    pathToBase64(tempFilePaths[i].url)
      .then((base64) => {
        console.log("转base64成功");
        imgList.value.push(base64.split(",")[1]);
      })
      .catch((error) => {
        console.log("转base64成功");
        console.error(error);
      });
  }
  console.log(tempImageList.value);
  console.log(imgList.value);
};
const addImages = () => {
  const remain = maxImages - imgList.value.length;
  if (remain <= 0) {
    uni.showToast({ title: "最多6张", icon: "none" });
    return;
  }
  console.log("执行选择图片");
 console.log('isAndroid:'+isAndroid)	
  if (isAndroid) {
    uni.chooseImage({
      count: remain,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
      success: (res) => {
        console.log("获取到照片");
        console.log(res.tempFilePaths);
        tempImageList.value = [...tempImageList.value, ...res.tempFilePaths];
        for (let i = 0; i < res.tempFilePaths.length; i++) {
             uni.saveFile({
              tempFilePath: res.tempFilePaths[i],
              success: (res1) => {
                pathToBase64(res1.savedFilePath)
            .then((base64) => {
              console.log("转base64成功");
              imgList.value.push(base64.split(",")[1]);
            })
            .catch((error) => {
              console.log("转base64失败");
              console.error(error);
            });
              }
             })
          
        }
      },
    });
  } else {
    uni.chooseImage({
      count: remain,
      sourceType: ["album", "camera"],
      crop: {
        width: 375,
        height: 500,
        resize: true,
        quality:100,
      },
      success: (res) => {
        console.log("获取到照片");
        console.log(res.tempFilePaths);
        tempImageList.value = [...tempImageList.value, ...res.tempFilePaths];
        for (let i = 0; i < res.tempFilePaths.length; i++) {
          uni.getImageInfo({
            src: res.tempFilePaths[i],
            success: (result) => {
              console.log(result);
              if (result.width > 1000) {
                uni.compressImage({
                  quality:100,
                  src: res.tempFilePaths[i],
                  success: (result2) => {
                    console.log("压缩成功");
                    console.log(result2.tempFilePath);
                    pathToBase64(result2.tempFilePath)
                      .then((base64) => {
                        console.log("转base64成功");
                        imgList.value.push(base64.split(",")[1]);
                      })
                      .catch((error) => {
                        console.log("转base64失败");
                        console.error(error);
                      });
                  },
                  fail: (err) => {
                    console.log("压缩失败:" + err.errMsg);
                  },
                });
              } else {
                pathToBase64(res.tempFilePaths[i])
                  .then((base64) => {
                    console.log("转base64成功");
                    imgList.value.push(base64.split(",")[1]);
                  })
                  .catch((error) => {
                    console.log("转base64失败");
                    console.error(error);
                  });
              }
            },
            
          });
        }
      },
      fail: (err) => {
              console.log("获取图片信息失败:");
              console.error(err.errMsg);
            },
    });
  }
  
};

function preview(index) {
  uni.previewImage({
    urls: tempImageList.value,
    current: index,
  });
}

function remove(index) {
  imgList.value.splice(index, 1);
  tempImageList.value.splice(index, 1);
}
const deleteImages = (e) => {
  let index = e.index;
  imgList.value.splice(index, 1);
  tempImageList.value.splice(index, 1);
};

function submit() {
  if (answer_uuid.value) {
    updateInterrogationAnswer();
  } else {
    addInterrogationAnswer();
  }
}
</script>

<style lang="scss" scoped>
.my-answer-page {
  background-color: #fff;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.content-scroll {
  flex: 1;
  position: fixed;
  top: calc(var(--status-bar-height) + 44px);
  left: 0;
  right: 0;
  bottom: 160rpx;
  padding: 24rpx 24rpx 0;
  box-sizing: border-box;
}

.card {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;
}
.card-title {
  font-size: 32rpx;
  color: #8b2316;
  font-weight: 500;
  margin-bottom: 16rpx;
}
.required {
  color: #ff4d4f;
}

.textarea-wrap {
  position: relative;
  background: #f7f7f7;
  border-radius: 12rpx;
  padding: 16rpx 16rpx 16rpx 16rpx;
}
.textarea {
  min-height: 180rpx;
  width: 100%;
  font-size: 28rpx;
  color: #333;
}
.ph {
  color: #999;
}
.voice-btn {
  position: absolute;
  right: 16rpx;
  bottom: 16rpx;
  width: 64rpx;
  height: 64rpx;
  border-radius: 32rpx;
  background: #b90f0f;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
}

.sub-tip {
  font-size: 26rpx;
  color: #999;
  margin-bottom: 16rpx;
}

.img-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16rpx;
}
.img-item {
  position: relative;
  width: 150rpx;
  height: 150rpx;
  border-radius: 12rpx;
  overflow: hidden;
  background: #f0f0f0;
}
.img {
  width: 100%;
  height: 100%;
}
.add {
  display: flex;
  align-items: center;
  justify-content: center;
}
.plus {
  font-size: 80rpx;
  color: #c0c0c0;
  line-height: 1;
}
.del {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  width: 44rpx;
  height: 44rpx;
  border-radius: 22rpx;
  background: rgba(0, 0, 0, 0.5);
  color: #fff;
  text-align: center;
  line-height: 44rpx;
  font-size: 28rpx;
}

.bottom-fixed {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  padding: 24rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.06);
}
.submit-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  background: #3cc7c0;
  color: #fff;
  font-size: 32rpx;
  border-radius: 16rpx;
}
</style>


