<template>
  <view class="container">
    <!-- 头部导航 -->
    <uni-nav-bar
      left-icon="left"
      title="病情记录"
      @clickLeft="goBack"
      fixed
      color="#8B2316"
      height="140rpx"
      :border="false"
      backgroundColor="#eee"
    >
      <template #right>
        <view class="nav-right">
          <text class="modify-btn" @click="saveRecord" v-if="recordUuid"
            >修改</text
          >
          <text class="save-btn" @click="saveRecord" v-else>保存</text>
        </view>
      </template>
    </uni-nav-bar>

    <!-- 主要内容区域 -->
    <view class="main-content">
      <!-- 日期选择区域 -->
      <view class="form-item row">
        <view class="form-label">日期</view>
        <view class="form-value" @click="openDateTime">
          <text class="date-text">{{ dateTime }}</text>
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>
      <view class="divider"></view>

      <view class="form-item">
        <view class="form-label">描述</view>
        <view class="form-value">
          <textarea
            class="description-input"
            v-model="des"
            placeholder="请输入患者病情"
          ></textarea>
        </view>
      </view>
      <view class="divider"></view>

      <!-- 图片上传区域 -->
      <view class="form-item">
        <view class="form-label">图片</view>
        <view class="image-upload-area">
          <!-- 已上传的图片 -->
          <view
            class="image-item"
            v-for="(image, index) in tempImageList"
            :key="index"
          >
            <image
              :src="image"
              class="uploaded-image"
              mode="aspectFill"
              @click="previewImage(index)"
            />
            <view class="delete-btn" @click="deleteImage(index)">
              <uni-icons type="closeempty" size="15" color="#fff"></uni-icons>
            </view>
          </view>

          <!-- 添加图片按钮 -->
          <view
            class="add-image-btn"
            v-if="imageList.length < 9"
            @click="chooseImage"
          >
            <uni-icons type="plus" size="24" color="#999"></uni-icons>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部删除按钮 -->
    <view class="bottom-actions" v-if="recordUuid">
      <button class="delete-btn" @click="deleteRecord">删除该条记录</button>
    </view>

    <up-datetime-picker
      :show="showDate"
      v-model="selectedDate"
      @cancel="showDate = false"
      @confirm="confirmDate"
      mode="date"
    ></up-datetime-picker>
  </view>
</template>

<script setup>
// Vue3 Composition API
import { ref, reactive, onMounted, computed } from "vue";
import { onShow, onLoad } from "@dcloudio/uni-app";
import api from "@/api/api.js";
import docUrl from "@/utils/docUrl.js";
import dayjs from "dayjs";
import { pathToBase64} from "image-tools";

// 响应式数据
const des = ref("");
const showDate = ref(false);
const recordUuid = ref("");
const patientUuid = ref("");
const dateTime = ref(dayjs().format("YYYY年MM月DD日"));
const selectedDate = ref(dayjs());
const description = ref("");
const imageList = ref([]);
const tempImageList = ref([]);
const originalData = ref({});

// 方法
const goBack = () => {
  uni.navigateBack({
    delta: 1,
    fail() {
      uni.redirectTo({
        url: "/pages/index/index",
      });
    },
  });
};

const confirmDate = ({ value, mode }) => {
  console.log(value);
  dateTime.value = dayjs(value).format("YYYY年MM月DD日");
  selectedDate.value = dayjs(value).format("YYYY-MM-DD");
  showDate.value = false;
};
const openDateTime = () => {
  console.log("openDateTime");
  showDate.value = true;
};

const chooseImage = () => {
  uni.chooseImage({
    count: 8 - imageList.value.length,
    sizeType: ["original", "compressed"],
    sourceType: ["album", "camera"],
    success: (res) => {
      // 这里应该上传图片到服务器
      // imageList.value = [...imageList.value, ...res.tempFilePaths]
      tempImageList.value = [...tempImageList.value, ...res.tempFilePaths];
      for (let i = 0; i < res.tempFilePaths.length; i++) {
        pathToBase64(res.tempFilePaths[i])
          .then((base64) => {
            imageList.value.push(base64.split(',')[1]);
          })
          .catch((error) => {
            console.error(error);
          });
      }
    },
  });
};

const deleteImage = (index) => {
  // 显示模态框
  uni.showModal({
    title: "确认删除",
    content: "确定要删除这张图片吗？",
    // 设置模态框点击确定按钮后的回调函数
    success: (res) => {
      // 如果用户点击了确认按钮
      if (res.confirm) {
        // 从imageList数组中删除指定索引的图片
        imageList.value.splice(index, 1);
        tempImageList.value.splice(index, 1);
      }
    },
  });
};

const previewImage = (index) => {
  uni.previewImage({
    current: index,
    urls: imageList.value,
  });
};
const addRecord = async () => {
  if (!des.value) {
    uni.showToast({
      title: "请输入患者病情",
      icon: "none",
    });
    return;
  }
  let usrInfo = uni.getStorageSync("userInfo");
  const res = await api.addConditionRecord({
    patient_uuid: patientUuid.value,
    expert_uuid: usrInfo.uuid,
    des: des.value,
    create_date: dayjs(selectedDate.value).format("YYYY-MM-DD"),
    img1: imageList.value[0] || "",
    img2: imageList.value[1] || "",
    img3: imageList.value[2] || "",
    img4: imageList.value[3] || "",
    img5: imageList.value[4] || "",
    img6: imageList.value[5] || "",
    img7: imageList.value[6] || "",
    img8: imageList.value[7] || "",
  });
  if (res.code == 200) {
    uni.showToast({
      title: "添加成功",
      icon: "none",
    });
    goBack();
  }
};
const updateRecord = async () => {
  if (!des.value) {
    uni.showToast({
      title: "请输入患者病情",
      icon: "none",
    });
    return;
  }
  let usrInfo = uni.getStorageSync("userInfo");
  const res = await api.updateConditionRecord({
    uuid: recordUuid.value,
    patient_uuid: patientUuid.value,
    expert_uuid: usrInfo.uuid,
    des: des.value,
    create_date: dayjs(selectedDate.value).format("YYYY-MM-DD"),
    img1: imageList.value[0] || "",
    img2: imageList.value[1] || "",
    img3: imageList.value[2] || "",
    img4: imageList.value[3] || "",
    img5: imageList.value[4] || "",
    img6: imageList.value[5] || "",
    img7: imageList.value[6] || "",
    img8: imageList.value[7] || "",
  });
  if (res.code == 200) {
    uni.showToast({
      title: "修改成功",
      icon: "none",
    });
    uni.setStorageSync("caseRecord", null);
    goBack();
  }
};
const deleteConditionRecord = async () => {
  const res = await api.deleteConditionRecord({
    uuid: recordUuid.value,
  });
  if (res.code == 200) {
    uni.showToast({
      title: "删除成功",
      icon: "none",
    });
    goBack();
  }
};

const deleteRecord = () => {
  uni.showModal({
    title: "确认删除",
    content: "确定要删除这条记录吗？",
    success: (res) => {
      if (res.confirm) {
        deleteConditionRecord();
      }
    },
  });
};

// 生命周期
onLoad((options) => {
  console.log(options);
  recordUuid.value = options.uuid || "";
  patientUuid.value = options.patientUuid || "";
  if (recordUuid.value) {
    imageList.value = [];
    let record = uni.getStorageSync("caseRecord");
    des.value = record.des;
    tempImageList.value = record.photo.map((item) => docUrl + item);
    // imageList.value = record.photo.map(item=>docUrl+item);
    dateTime.value = dayjs(record.create_date).format("YYYY年MM月DD日");
    selectedDate.value = dayjs(record.create_date);
    for (let i = 0; i < record.photo.length; i++) {
      console.log("url", docUrl + record.photo[i]);
      uni.request({
        url: docUrl + record.photo[i],
        method: "GET",
        responseType: "arraybuffer",
        success: (res) => {
          const base64 = `${uni.arrayBufferToBase64(res.data)}`;
          console.log(base64);
          imageList.value.push(base64);
        },
        fail: (err) => {
          reject(err);
        },
      });
    }
  }
});

const saveRecord = () => {
  if (recordUuid.value) {
    updateRecord();
  } else {
    addRecord();
  }
};
</script>

<style scoped lang="scss">
.row {
  display: flex;
  align-items: center;
  flex-direction: row;
}
.container {
  background-color: #ffffff;
  min-height: 100vh;
}

/* 头部导航样式 */
.nav-right {
  padding-right: 30rpx;
}

.modify-btn,
.save-btn {
  font-size: 32rpx;
  color: #8b2316;
  font-weight: 500;
}

/* 主要内容区域 */
.main-content {
  padding: 0rpx 30rpx;
}

.form-item {
  padding: 30rpx 0;
}

.form-label {
  font-size: 32rpx;
  color: #333333;
  margin-bottom: 20rpx;
  font-weight: 500;
}

.form-value {
  display: flex;
  flex: 1;
  justify-content: flex-end;
  align-items: center;
  padding: 20rpx 0;
}

.date-text {
  font-size: 30rpx;
  color: #333333;
}

.description-input {
  width: 100%;
  min-height: 200rpx;
  font-size: 30rpx;
  color: #333333;
  line-height: 1.6;
  background-color: 2rpx solid #f5f5f5;
  border: none;
  padding: 20rpx 0;
}

.description-input:disabled {
  color: #999999;
  background-color: #f5f5f5;
}

/* 图片上传区域 */
.image-upload-area {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin-top: 20rpx;
}

.image-item {
  position: relative;
  width: 160rpx;
  height: 160rpx;
  border-radius: 12rpx;
  overflow: hidden;
}

.uploaded-image {
  width: 100%;
  height: 100%;
}

.image-item .delete-btn {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.add-image-btn {
  width: 160rpx;
  height: 160rpx;
  border: 2rpx dashed #cccccc;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f9f9f9;
}

.divider {
  height: 1rpx;
  background-color: #f0f0f0;
  margin: 0 -30rpx;
}

/* 底部操作区域 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 30rpx;
  background-color: #ffffff;
  border-top: 1rpx solid #f0f0f0;
}

.bottom-actions .delete-btn {
  width: 100%;
  height: 88rpx;
  background-color: #8b2316;
  color: white;
  border: none;
  border-radius: 12rpx;
  font-size: 32rpx;
  font-weight: 500;
}
</style>