<template>
   <navBar title="问题详情" />
  <view class="consult-detail-page">
    <!-- 导航栏 -->
   

    <!-- 内容区域 -->
    <scroll-view scroll-y class="content-scroll">
      <!-- 用户信息区域 -->
      <view class="user-section">
        <view class="user-info">
          <view class="user-name">
            <text class="name">{{ maskName(userInfo.name) }}</text>
            <text class="gender-age"
              >（{{ userInfo.gender }} {{ userInfo.age }}岁）</text
            >
          </view>
          <view class="detail-btn" @click="goInfo">
            <up-image :src="detailImg" width="183rpx" height="34rpx"></up-image>
          </view>
        </view>
      </view>

      <!-- 疾病标签和日期 -->
      <view class="tag-date-row">
        <view class="disease-tag">
          <text class="tag-text">{{ questionInfo.diseaseTag }}</text>
        </view>
        <view class="date">{{ questionInfo.date }}</view>
      </view>

      <!-- 问题内容 -->
      <view class="question-content">
        <view class="content-text">
          {{ questionInfo.diseaseDescribe }}
        </view>
        <view class="content-text">
          {{ questionInfo.your_question }}
        </view>
      </view>

      <!-- 疾病描述 -->
      <!-- <view v-if="questionInfo.diseaseDescribe" class="disease-describe">
				<view class="describe-title">疾病描述：</view>
				<text class="describe-text">{{ questionInfo.diseaseDescribe }}</text>
			</view> -->

      <!-- 图片网格 -->
      <view class="image-grid" v-if="questionInfo.images">
        <image
          v-for="(img, index) in questionInfo.images.split(',')"
          :key="index"
          :src="docUrl + img"
          class="grid-image"
          mode="aspectFill"
          @click="previewImageInfo(questionInfo.images,docUrl + img, index)"
        />
      </view>
     
      <view
        class="lookmore"
        v-if="
          questionInfo.SupplementList &&
          questionInfo.SupplementList.length > 1 && questionInfo.AnswerList.length > 0
        "
        @click="supplementShowAll = !supplementShowAll"
      >
        <view class="lookmore-text">
          {{ supplementShowAll ? "收起" : "查看更多" }}

        </view>
        <uni-icons :type="supplementShowAll?'up':'down'" size="34rpx" color="#8B2316"></uni-icons>
      </view>
      <view
        class="doctor-reply-section"
        style="margin-bottom: 10rpx;"
        v-for="(item,index) in displaySupplementList"
        :key="index"
        v-if="questionInfo.SupplementList && questionInfo.SupplementList.length > 0"
      >
        <view class="addbox">
          <view class="addwrap">
            <image :src="bgImg" class="addimg"></image>
            <view class="addtext">信息补充</view>
          </view>
          <view class="date" > {{formatDate(item.create_date) }} </view>
        </view>
        <view class="question-content" style="margin-top:25rpx;" >
              <text class="content-text" >
                {{item.disease_describe }}
              </text>
            
            </view>
      <!-- 图片网格 -->
      <view class="image-grid" v-if="item.imgs">
        <image
          v-for="(img, index) in item.imgs.split(',')"
          :key="index"
          :src="docUrl + img"
          class="grid-image"
          mode="aspectFill"
          @click="previewImageSupplement(item.imgs,docUrl + img, index)"
        />
      </view>
      </view>
      <!-- 补充信息：查看更多 / 收起 -->
     
      <view class="topbar"></view>

      <!-- 医生回答区域 -->
      
      <view
        class="doctor-reply-section"
        v-if="questionInfo.AnswerList.length > 0"
      >
        <view class="section-title">医生回答</view>

        <view
          class="doctor-cell"
          v-for="item in questionInfo.AnswerList"
          :key="item.answer_uuid"
        >
          <view class="doctor-card">
            <view class="doctor-info">
              <up-image
                :src="docUrl + item.photo"
                mode="aspectFill"
                :loadingIcon="lazyImg"
                :errorIcon="lazyImg"
                :lazy-load="true"
                class="doctor-avatar"
                width="90rpx"
                height="90rpx"
                radius="10rpx"
              >
                <template #error>
                  <image
                    :src="lazyImg"
                    mode="widthFix"
                    height="90rpx"
                    width="90rpx"
                    radius="10rpx"
                  ></image>
                </template>
                <template v-slot:loading>
                  <image
                    :src="lazyImg"
                    mode="widthFix"
                    height="90rpx"
                    width="90rpx"
                    radius="10rpx"
                  ></image>
                </template>
              </up-image>
              <view class="doctor-details">
                <view class="namebox">
                  <view class="namecontet">
                    <view class="doctor-name">{{ item.realname }}</view>
                    <view class="bar" v-if="item.realname!='账号已注销'"></view>
                    <view class="doctor-hospital"  v-if="item.realname!='账号已注销'" style="margin-left: 0rpx;color:#999">{{ item.name }}</view>
                  </view>
                 
                </view>
                <view class="hospital-time-row">
                  <view class="doctor-hospital">{{ item.hospital_name }}</view>
                  <view class="reply-time">{{ item.create_date }}</view>
                </view>
              </view>
            </view>

            <view class="reply-content">
              <text class="reply-text">{{ item.note }}</text>
            </view>
            <view class="reply-content" style="background: none; padding: 0">
              <view v-if="item.imgs" class="reply-images">
                <image
                  v-for="(img, idx) in item.imgs.split(',')"
                  :key="idx"
                  :src="docUrl + img"
                  class="reply-image"
                  @click="previewReplyImages(item, idx)"
                />
              </view>
            </view>
          </view>
          <view class="smallbar"></view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部固定区域 -->
    <view class="bottom-fixed">
      <!-- 特别声明 -->
      <view class="disclaimer">
        <text class="disclaimer-title">特别声明：</text>
        <text class="disclaimer-text"
          >答案仅为医生个人经验或建议分享，不能视为诊断依据，如有诊疗需求，请务必前往正规医院就诊。</text
        >
      </view>

      <!-- 编辑按钮 -->
      <view class="edit-btn" @click="editQuestion(status)">
        {{ status == 1 ? "我要编辑" : "我要回答" }}
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from "vue";
import navBar from "@/components/navBar/navBar.vue";
import detailImg from "@/static/iv_jiwangshi.png";
import navTo from "@/utils/navTo.js";
import { onLoad, onShow,onUnload } from "@dcloudio/uni-app";
import docUrl from "@/utils/docUrl";
import api from "@/api/api.js";
import lazyImg from "@/static/avastar.png";
import bgImg from "@/static/complete_question.png";
const uuid = ref("");
const step1_uuid = ref("");
const answer_uuid = ref("");
const status = ref(0);
onLoad((options) => {
  uuid.value = options.uuid;
  status.value = options.status || 0;
  console.log(uuid.value);
});
const goInfo = () => {
  navTo({
    url: "/pages_app/patientInfo/patientInfo?step1_uuid=" + step1_uuid.value,
  });
};
const getInterrogation = () => {
  api
    .getInterrogation({
      uuid: uuid.value,
    })
    .then((res) => {
      console.log(res);
      if (res.code === "200" && res.data) {
        step1_uuid.value = res.data.step1_uuid || "";
        // 更新用户信息
        userInfo.value = {
          name: res.data.name || "提**",
          gender: res.data.sex === 1 ? "女" : "男",
          age: res.data.birthday ? calculateAge(res.data.birthday) : "未知",
        };

        // 更新问题信息
        questionInfo.value = {
          date: res.data.create_date
            ? formatDate(res.data.create_date)
            : "未知",
          diseaseTag: res.data.disease_name || "未知疾病",
          content: res.data.your_question || "暂无问题描述",
          images: res.data.imgs || "",
          AnswerList: res.data.AnswerList || [],
          SupplementList: res.data.SupplementList || [],
          your_question: res.data.your_question || "",
        };
        if(res.data.AnswerList.length == 0 && res.data.SupplementList.length > 0){
          supplementShowAll.value = true;
        }else{
          supplementShowAll.value = false;
        }

        // 更新疾病描述
        if (res.data.disease_describe) {
          questionInfo.value.diseaseDescribe = res.data.disease_describe;
        }
        let user = uni.getStorageSync("userInfo");
        let arr = res.data.AnswerList.filter((item) => {
          return user.uuid == item.expert_uuid;
        });
        if (arr.length > 0) {
          status.value = 1;
          answer_uuid.value = arr[0].answer_uuid;
        }
      }
    });
};
onUnload(() => {
  uni.$off('updateStatus');
})
onShow(() => {
  getInterrogation();
  uni.$on('updateStatus',() => {
    status.value = 1;
  })
});
const maskName = (name) => {
  if (!name) return "**";
  const first = name.slice(0, 1);
  return `${first}**`;
};
// 计算年龄
function calculateAge(birthday) {
  const birthDate = new Date(birthday);
  const today = new Date();
  let age = today.getFullYear() - birthDate.getFullYear();
  const monthDiff = today.getMonth() - birthDate.getMonth();
  if (
    monthDiff < 0 ||
    (monthDiff === 0 && today.getDate() < birthDate.getDate())
  ) {
    age--;
  }
  return age.toString();
}

// 格式化日期
function formatDate(dateString) {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}
// 用户信息
const userInfo = ref({
  name: "提**",
  gender: "男",
  age: "15",
});

// 问题信息
const questionInfo = ref({
  date: "2022-11-09",
  diseaseTag: "甲型肝炎",
  content:
    "为什么程序员总是分不清万圣节和圣诞节？因为Oct31==Dec25。\n任何我写的代码，超过6个月不去看它，当我再看时，都像是别人写的。",
  diseaseDescribe: "", // 疾病描述
  images: "",
  SupplementList: [],
  AnswerList: [],
  your_question: "",
});
// 补充信息：查看更多 / 收起
const supplementShowAll = ref(false);
const displaySupplementList = computed(() => {
  if (
    !questionInfo.value.SupplementList ||
    questionInfo.value.SupplementList.length === 0
  ) {
    return [];
  }else if(!questionInfo.value.SupplementList || questionInfo.value.SupplementList.length == 1){
    return questionInfo.value.SupplementList;
  }
  return supplementShowAll.value
    ? questionInfo.value.SupplementList
    : [];
});

// 医生回答
const doctorReply = ref({
  avatar: "/static/images/doctor-avatar.jpg",
  name: "los测试",
  hospital: "隆福医院",
  time: "28天前",
  content:
    "徐徐，喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵喵",
  image: "/static/images/reply-image.jpg",
});

// 返回上一页
function goBack() {
  uni.navigateBack();
}

// 预览图片
function previewImage(current, index) {
  let urls=questionInfo.value.images
      ? questionInfo.value.images.split(",").map((path) => docUrl + path)
      : [];
  uni.previewImage({
    showmenu:true,
    urls:urls,
    current: index,
    longPressActions: {
      itemList:['保存图片'],
      success:()=>{
        uni.closePreviewImage();
        uni.saveImageToPhotosAlbum({
          filePath: urls[index],
          success:()=>{
            uni.showToast({
              title: '图片保存成功',
              icon: 'none'
            })
          },
          fail:(err)=>{
            uni.showToast({
              title: '图片保存失败:'+err.errMsg,
              icon: 'none'
            })
          }
        })
    },
    
    },
  });
}
const previewImageSupplement = (imgsStr,current, index) => {
  let urls=imgsStr.split(",").map((path) => docUrl + path);
  uni.previewImage({
    showmenu:true,
    urls: urls,
    current: index,
    longPressActions: {
      itemList:['保存图片'],
      success:()=>{
        uni.closePreviewImage();
        uni.saveImageToPhotosAlbum({
          filePath: urls[index],
          success:()=>{
            uni.showToast({
              title: '图片保存成功',
              icon: 'none'
            })
          },
          fail:(err)=>{
            uni.showToast({
              title: '图片保存失败:'+err.errMsg,
              icon: 'none'
            })
          }
        })
    },
    
    },
   
  });
}
const previewImageInfo = (imgsStr,current, index) => {
  let urls=imgsStr.split(",").map((path) => docUrl + path);
  uni.previewImage({
    showmenu:true,
    urls: urls,
    current: index,
    longPressActions: {
      itemList:['保存图片'],
      success:()=>{
        uni.closePreviewImage();
        uni.saveImageToPhotosAlbum({
          filePath: urls[index],
          success:()=>{
            uni.showToast({
              title: '图片保存成功',
              icon: 'none'
            })
          },
          fail:(err)=>{
            uni.showToast({
              title: '图片保存失败:'+err.errMsg,
              icon: 'none'
            })
          }
        })
    },
    
    },
  });
}

// 预览医生回复图片
function previewReplyImages(item, index) {
  if (!item || !item.imgs) {
    return;
  }
  const urls = item.imgs.split(",").map((path) => docUrl + path);
  uni.previewImage({
    showmenu:true,
    urls,
    current: index,
    longPressActions: {
      itemList:['保存图片'],
      success:()=>{
        uni.closePreviewImage();
        uni.saveImageToPhotosAlbum({
          filePath: urls[index],
          success:()=>{
            uni.showToast({
              title: '图片保存成功',
              icon: 'none'
            })
          },
          fail:(err)=>{
            uni.showToast({
              title: '图片保存失败:'+err.errMsg,
              icon: 'none'
            })
          }
        })
    },
    
    },
  });
}

// 编辑问题
function editQuestion() {
  if (status.value == 1) {
    navTo({
      url:
        "/pages_app/myAnswer/myAnswer?answer_uuid=" +
        answer_uuid.value +
        "&uuid=" +
        uuid.value,
    });
  } else {
    navTo({
      url: "/pages_app/myAnswer/myAnswer?uuid=" + uuid.value,
    });
  }
}
</script>

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

.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  padding: 0 32rpx;
  background-color: #ffffff;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;

  .nav-left {
    width: 80rpx;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    .back-icon {
      font-size: 48rpx;
      color: #8b2316;
      font-weight: bold;
    }
  }

  .nav-title {
    font-size: 36rpx;
    font-weight: 500;
    color: #8b2316;
  }

  .nav-right {
    width: 80rpx;
  }
}
.topbar{
  width: 100%;
  height: 20rpx;
  background-color: #efefef;
}
.bar {
  width: 2rpx;
  height: 30rpx;
  margin:0 20rpx;
  background-color: #999;
}
.doctor-hospital{
  margin-left: 20rpx;
}
.namecontet{
  display: flex;
  margin-left: 20rpx;
  align-items: center;
}
.lookmore{
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 28rpx;
  margin: 20rpx 30rpx 20rpx;
  .lookmore-text{
    font-size: 28rpx;
    color: #8B2316;
  }
}
.addbox {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 20rpx 30rpx 0;
  .addwrap {
    display: flex;
    align-items: center;
    position: relative;
    .addimg {
      width: 110rpx;
      height: 60rpx;
    }
  }
  .addtext {
    position: absolute;
    top: 9rpx;
    left: 6rpx;
    font-size: 24rpx;
    color: #fff;
    font-weight: 500;
  }
  .date {
    font-size: 28rpx;
    color: #999;
  }
}

// .smallbar {
//   width: 100%;
//   height: 10rpx;
//   background-color: #efefef;
// }
.content-scroll {
  flex: 1;
  position: fixed;
  top: calc(var(--status-bar-height) + 44px);
  width: auto;
  box-sizing: border-box;
  width: 100%;
  padding: 30rpx 0;
  bottom: 313rpx;
}

.user-section {
  background-color: #ffffff;
  border-radius: 16rpx;
  margin-bottom: 24rpx;

  margin: 0 30rpx;
  .user-info {
    display: flex;
    align-items: center;

    margin-bottom: 16rpx;

    .user-name {
      display: flex;
      align-items: center;

      .name {
        font-size: 32rpx;
        color: #8b2316;
        font-weight: 500;
      }

      .gender-age {
        font-size: 28rpx;
        color: #666;
        margin-left: 8rpx;
      }
    }

    .detail-btn {
      display: flex;
      margin-left: 10rpx;

      .detail-text {
        color: #ffffff;
        font-size: 24rpx;
        margin-right: 8rpx;
      }

      .detail-icon {
        color: #ffffff;
        font-size: 24rpx;
      }
    }
  }
}

.tag-date-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24rpx;
  margin: 0 30rpx 30rpx;
  .disease-tag {
    margin-bottom: 0;

    .tag-text {
      display: inline-block;
      background-color: #ffffff;
      color: #8b2316;
      border: 2rpx solid #8b2316;
      border-radius: 40rpx;
      padding: 7rpx 22rpx;
      font-size: 24rpx;
    }
  }

  .date {
    font-size: 28rpx;
    color: #999;
  }
}

.question-content {
  background-color: #f0f0f0;
  border-radius: 16rpx;
  padding: 32rpx;
  margin: 0 30rpx;
  margin-bottom: 24rpx;

  .content-text {
    font-size: 28rpx;
    color: #333;
    line-height: 1.6;
    word-break: break-all;
  }
}

.disease-describe {
  background-color: #f8f9fa;
  border-radius: 16rpx;
  padding: 32rpx;
  margin: 0 30rpx 24rpx;
  border-left: 6rpx solid #8b2316;

  .describe-title {
    font-size: 30rpx;
    color: #8b2316;
    font-weight: 500;
    margin-bottom: 16rpx;
  }

  .describe-text {
    font-size: 28rpx;
    color: #333;
    line-height: 1.6;
  }
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 8rpx;
  margin: 0 30rpx 40rpx;

  .grid-image {
    width: 100%;
    height: 160rpx;
    border-radius: 8rpx;
  }
}

.doctor-reply-section {
  margin: 0 0rpx 40rpx;
  .section-title {
    font-size: 32rpx;
    padding: 24rpx 30rpx;
    border-bottom: 1rpx solid #efefef;
    color: #8b2316;
    font-weight: 500;
  }

  .doctor-card {
    margin: 20rpx 30rpx 0;
    background-color: #ffffff;
    border-radius: 16rpx;
    .doctor-info {
      display: flex;
      align-items: center;
      margin-bottom: 24rpx;

      .doctor-avatar {
        width: 90rpx;
        height: 90rpx;
        border-radius: 10rpx;
        margin-right: 24rpx;
      }

      .doctor-details {
        flex: 1;
       
        .doctor-name {
          font-size: 34rpx;
          color: #8B2316;
          font-weight: 500;
          max-width: 203rpx;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .hospital-time-row {
          margin-top: 20rpx;
          display: flex;
          align-items: center;
          justify-content: space-between;

          .doctor-hospital {
            font-size: 28rpx;
            color: #999;
          }

          .reply-time {
            font-size: 28rpx;
            color: #999;
          }
        }
      }
    }

    .reply-content {
      margin-bottom: 24rpx;
      background-color: #f0f0f0;
      border-radius: 16rpx;
      font-size: 28rpx;
      padding: 32rpx;
      .reply-text {
        font-size: 30rpx;
        color: #333;
        line-height: 1.6;
      }
      .reply-images {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 8rpx;
        margin-top: 16rpx;
      }
    }

    .reply-image {
      width: 100%;
      height: 150rpx;
      border-radius: 8rpx;
      object-fit: cover;
    }
  }
}

.bottom-fixed {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ffffff;
  padding: 24rpx 32rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.disclaimer {
  background-color: #f6f6f6;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;

  .disclaimer-title {
    font-size: 28rpx;
    color: #892b1b;
  }

  .disclaimer-text {
    font-size: 28rpx;
    color: #9c9492;
   
  }
}

.edit-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  background-color: #3cc7c0;
  color: #ffffff;
  font-size: 32rpx;
  font-weight: 500;
  border-radius: 16rpx;
}
.doctor-cell{
  border-bottom: 12rpx solid #efefef;
}
.doctor-cell:last-child{
  border-bottom: none;
}
</style>
