<template>
  <!-- <div style="left: 0"> -->
  <!-- <van-nav-bar>
      <template #title>
        安全检查项目
      </template>
    </van-nav-bar> -->
  <van-sticky>
    <van-nav-bar title="安全检查详情" />
  </van-sticky>
  <!-- 检查项详情 -->
  <!-- <div style="margin-bottom: 130px"> -->
  <div class="empty" style="margin: 5px 20px 130px">
    <van-field
      label="所属任务"
      colon
      label-width="4.6em"
      v-model="detail.checkReason"
      readonly
    />
    <!-- </div>
    <div class="empty"> -->
    <van-field
      label="项目"
      colon
      label-width="4.6em"
      v-model="detail.itemName"
      :readonly="isfinish"
    />
    <!-- </div> -->
    <!-- 此处需要有类别字典 -->
    <!-- <div class="empty"> -->
    <van-field
      label="类别"
      colon
      label-width="4.6em"
      v-model="categoryText"
      readonly
      @click="!isfinish && (showCategory = true)"
    />
    <van-popup v-model:show="showCategory" round position="bottom">
      <van-picker
        show-toolbar
        v-model="selectedCategory"
        :columns="CategoryOptions"
        @confirm="onCategoryConfirm"
        @cancel="showCategory = false"
      />
    </van-popup>
    <!-- </div>
    <div class="empty"> -->
    <van-field
      label="内容"
      colon
      label-width="4.6em"
      v-model="detail.itemBody"
      :readonly="isfinish"
    />
    <!-- </div>
    <div class="empty"> -->
    <van-field
      label="工作标准"
      colon
      label-width="4.6em"
      autosize
      type="textarea"
      v-model="detail.workStandards"
      rows="1"
      :readonly="isfinish"
    />
    <!-- </div>
    <div class="empty"> -->
    <van-field
      label="扣分标准"
      colon
      label-width="4.6em"
      v-model="detail.scoringCriteria"
      autosize
      type="textarea"
      rows="1"
      :readonly="isfinish"
    />
    <!-- </div>
    <div class="empty"> -->
    <van-field
      label="备注"
      colon
      label-width="4.6em"
      v-model="detail.note"
      autosize
      type="textarea"
      rows="1"
      :readonly="isfinish"
    />
    <!-- </div>
    <div class="empty"> -->
    <van-field
      label="检查结果"
      colon
      label-width="4.6em"
      v-model="detail.checkResult"
      autosize
      type="textarea"
      rows="1"
      :readonly="isfinish"
    />
    <!-- </div>
    <div class="empty"> -->
    <van-field label="是否符合" colon label-width="4.6em" readonly>
      <template #input>
        <van-radio-group
          v-model="detail.correspond"
          @change="radioChange"
          direction="horizontal"
        >
          <van-radio :name="1" :disabled="isfinish">是</van-radio>
          <van-radio :name="0" :disabled="isfinish">否</van-radio>
        </van-radio-group>
      </template>
    </van-field>
    <!-- </div>
    <div class="empty"> -->
    <van-field
      label="隐患编号"
      colon
      label-width="4.6em"
      v-model="detail.hiddenTrouble"
      readonly
      :disabled="ishidden"
    />
    <!-- </div>
    <div class="empty"> -->
    <van-field
      label="隐患下发时间"
      colon
      center
      label-width="4.6em"
      v-model="detail.hiddenTroubleTime"
      readonly
      :disabled="ishidden"
    />
    <!-- </div> -->
    <!-- <div class="empty"> -->
    <van-field label="隐患图片" colon label-width="4.6em">
      <template #input>
        <van-uploader
          :key="uploaderKey"
          v-model="fileList"
          multiple
          accept="image/*"
          :after-read="afterRead"
          :before-read="beforeRead"
          :max-size="5 * 1024 * 1024"
          @oversize="onOversize"
          :before-delete="beforeDel"
          :deletable="!isfinish"
          :disabled="isfinish"
        />
      </template>
    </van-field>
  </div>
  <!-- </div> -->
  <div v-if="!isfinish" class="submitBottom">
    <van-row
      justify="space-around"
      style="height: 60px; display: flex; align-items: center"
    >
      <van-col span="11">
        <van-button round block type="primary" @click="save"> 保存 </van-button>
      </van-col>
      <van-col span="11">
        <van-button round block type="default" @click="router.go(-1)">
          关闭
        </van-button>
      </van-col>
    </van-row>
    <!-- <div style="height: 10px"></div> -->
  </div>
  <!-- 关闭按钮遮罩，防止点击/输入 -->
  <van-overlay v-if="isinit" :show="isinit" lock-scroll class="custom-overlay">
    <div class="loading-popup">
      <van-loading size="24px" color="white" />
      <p>加载中...</p>
    </div>
  </van-overlay>
  <van-overlay
    v-if="isLoading"
    :show="isLoading"
    lock-scroll
    class="custom-overlay"
  >
    <div class="loading-popup">
      <van-loading size="24px" color="white" />
      <p>保存中...</p>
    </div>
  </van-overlay>
  <!-- </div> -->
</template>

<script setup>
import { onMounted, ref, computed, reactive } from "vue";
import { useRouter, useRoute } from "vue-router";
import { CheckItemDetail, SaveCheckItem, getDictionary } from "@/api/check";
import { uploadData } from "@/api/index.js";
import { fileToMD5 } from "@/utils/fileToMD5";
const route = useRoute();
const router = useRouter();
const itemId = route.query.itemid;
const isfinish = route.query.band === "true";
const categoryText = ref("");
const showCategory = ref(false);
const detail = reactive({});
const isLoading = ref(false);
const uploaderKey = ref(0);
const CategoryOptions = reactive([]);
const ishidden = ref(false);
const selectedCategory = ref([]);
let labels = [];
// const fileList = reactive([]);
const fileList = ref([]);
const uploadfiles = ref([]);
const uploadfiles_del = ref([]);
const isinit = ref(false);
let dictstatus = [];
async function onCategoryConfirm(selectedItems) {
  detail.itemCategory = selectedItems.selectedOptions[0].value;
  selectedCategory.value = [detail.itemCategory];
  // console.log("selectedCategory.value", selectedCategory.value)
  // console.log("detail被选择：", detail);
  categoryText.value = getCategoryText();
  showCategory.value = false; // 关闭 popup
}
function getCategoryText() {
  const option = CategoryOptions.find(
    (item) => item.value == detail.itemCategory
  );
  return option ? option.text : "未找到对应类别";
}
const onOversize = (file) => {
  showToast("图片大小不能超过 5MB");
};
const beforeRead = (file) => {
  if (file instanceof Array) {
    // 多张图片
    file.forEach((f) => {
      // console.log("多张图片", f);
      if (f.type.indexOf("image/") == -1) {
        showToast("请上传 jpg 格式图片");
        return false;
      }
    });
  } else {
    // console.log("单张图片", file);
    if (file.type.indexOf("image/") == -1) {
      showToast("请上传 jpg 格式图片");
      return false;
    }
  }
  return true;
};
const afterRead = (file) => {
  file.status = "uploading";
  file.message = "上传中...";
  if (file instanceof Array) {
    // 多张图片
    file.forEach((f) => {
      // file.status = "done";
      uploadImg(f);
    });
  } else {
    // 单张图片
    uploadImg(file);
  }
};
const beforeDel = (file, cb) => {
  uploadfiles.value.splice(cb.index, 1);
  uploadfiles_del.value.push(file.id);
  // console.log("删除图片后的列表", uploadfiles.value);
  // console.log("删除图片后的删除列表", uploadfiles_del.value);
  return true;
};
async function uploadImg(file) {
  const fileMd5 = await fileToMD5(file.file);
  const fileData = new FormData();
  fileData.append("file", file.file);
  fileData.append("fileMd5", fileMd5);
  fileData.append("fileName", file.file.name);
  fileData.append("__ajax", "json");
  try {
    const res = await uploadData(fileData);
    // console.log("upload res", res);
    if (res.result == "true") {
      let fileid = res.fileUpload.id;
      uploadfiles.value.push(fileid);
      showSuccessToast("上传成功");
      file.status = "done";
    } else {
      showFailToast("上传失败");
      file.status = "failed";
      file.message = "上传失败";
      console.log("upload error", res);
    }
  } catch (error) {
    console.error("Upload failed with error:", error);
    showFailToast("上传失败，请重试");
    file.status = "failed";
    file.message = "上传失败";
  }
  // console.log("上传后，uploadfiles.value", uploadfiles.value);
}
function radioChange(value) {
  if (value == 0) {
    detail.correspond = 0;
  } else if (value == 1) {
    detail.correspond = 1;
  }
  // console.log("detail.correspond", detail.correspond);
}
async function statusDict(param) {
  try {
    const res = await getDictionary(param);
    if (res) {
      const options = res
        .sort((a, b) => a.dictValue - b.dictValue)
        .map((item) => {
          labels.push(item.dictLabel);
          return {
            text: item.dictLabel,
            value: item.dictValue,
          };
        });
      CategoryOptions.push(...options);
    }
  } catch (error) {
    console.error("获取字典失败:", error);
  }
}
async function getDetail() {
  try {
    isinit.value = true;
    const res = await CheckItemDetail(itemId);
    // console.log("res-----", res);
    if (res.code && res.code == 200) {
      isinit.value = false;
      await statusDict("check_item_category");
      Object.assign(detail, res.data);
      if (detail.correspond === 1) {
        ishidden.value = true;
      }
      selectedCategory.value = [detail.itemCategory];
      let files = detail.files;

      files.forEach((item) => {
        // console.log("item.fileUrl===", item.fileUrl);
        let fileUrl = item.fileUrl;
        let itemUrl = fileUrl.substring(fileUrl.indexOf(":8080/web/") + 9);
        // console.log("itemUrl===", itemUrl);
        fileList.value.push({
          id: item.id,
          url: process.env.VUE_APP_BASE_API + itemUrl,
        });
        // console.log("fileList===", fileList.value);
        uploadfiles.value.push(item.id);
      });
      // console.log("接口返回图片", files);
      // console.log("fileList===", fileList.value);
      // console.log("detail初始化：", detail);
      categoryText.value = getCategoryText();
    }
  } catch (error) {
    isinit.value = false;
    showToast("加载失败，请刷新重试");
    console.error("获取检查项详情失败", error);
  }
}
async function save() {
  isLoading.value = true;
  try {
    // detail是reactive对象，不直接删除details中的属性，避免响应式影响视图
    let tempo = Object.keys(detail)
      .filter(
        (key) =>
          ![
            "updateDate",
            "updateBy",
            "createBy",
            "files",
            "createDate",
            "isFinish",
            "isNewRecord",
          ].includes(key)
      )
      .reduce((obj, key) => {
        obj[key] = detail[key];
        return obj;
      }, {});
    // 调用保存接口

    tempo.checkTemplateTaskItem_image = uploadfiles.value + "";
    tempo.checkTemplateTaskItem_image_del = uploadfiles_del.value + "";
    // console.log("");
    // console.log("向接口发送的数据", tempo);
    const res = await SaveCheckItem(tempo);
    console.log("保存接口", res);
    if (res) {
      if (res.code === 200) {
        isLoading.value = false;
        showToast("保存成功");
        // await getDetail(); // 获取详情
        router.push({
          path: "/jcrw-jcx",
          query: { id: detail.taskId },
        });
      } else {
        isLoading.value = false;
        showToast("保存失败，请重试");
      }
    } else {
      isLoading.value = false;
      showToast("保存失败，请重试");
    }
  } catch (error) {
    isLoading.value = false;
    console.error("保存时发生错误:", error);
    showToast("保存失败，请重试");
  }
}
onMounted(async () => {
  await getDetail();
});
</script>

<style scoped>
.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  /* padding: 0 8px; */
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: white;
}
.buttons {
  display: flex;
  flex-direction: row;
  width: 95%;
}
.custom-overlay {
  --van-overlay-z-index: 1001;
  --van-overlay-background: rgba(0, 0, 0, 0);
}
.loading-popup {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: white;
  background-color: rgb(135, 134, 134);
  padding: 20px 20px 0 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  text-align: center;
  width: 80px;
  height: 80px;
}
.submitBottom {
  height: 60px;
  line-height: 60px;
  position: fixed;
  display: flex;
  flex-direction: column;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #f7f8fa;
}
.submitBottom ::v-deep .van-button {
  padding: 5px;
}
.van-button--round {
  border-radius: 12px;
}
</style>
