<template>
  <div class="task-box">
    <!-- 分享的图片展示 -->

    <el-image v-if="showImg" style="width: 100px; height: 100px" :src="taskInfo.shareImgUrl" :preview-src-list="[taskInfo.shareImgUrl]"> </el-image>
    <template v-if="configList && configList.length > 0">
      <div style="max-height: 270px; overflow: auto">
        <div v-for="item in configList" :key="item.id" class="field-box">
          <!-- 城市选择 -->
          <template v-if="item.taskFiledType === 'tree'">
            <div class="title-value">{{ item.taskFiledValue }}：</div>
            <div class="desc-value">
              {{ wmTaskContent[item.taskFiledKey] || '--' }}
            </div>
          </template>

          <template v-if="item.taskFiledType == 'domain' || item.taskFiledType == 'select'">
            <div class="title-value">{{ item.taskFiledValue }}：</div>
            <div class="desc-value" v-show="!(item.taskTypeId == '19' && item.taskFiledKey == 'temp3')">
              {{ getDesc(item) }}
            </div>
          </template>
          <!-- 城市选择 -->
          <template v-if="item.taskFiledType === 'area'">
            <div class="title-value">{{ item.taskFiledValue }}：</div>
            <div class="desc-value">
              {{ wmTaskContent[item.taskFiledKey] || '--' }}
            </div>
          </template>
          <!-- 文字输入 -->
          <template v-if="item.taskFiledType == 'text' || item.taskFiledType == 'inputautoselect' || item.taskFiledType == 'map' || item.taskFiledType == 'mapwithimg'">
            <div class="title-value">{{ item.taskFiledValue }}：</div>
            <div class="desc-value">
              {{ wmTaskContent[item.taskFiledKey] || '--' }}
            </div>
          </template>
          <!-- 时间 -->
          <template v-if="item.taskFiledType == 'datetime'">
            <div class="title-value">{{ item.taskFiledValue }}：</div>
            <div class="desc-value">
              {{ wmTaskContent[item.taskFiledKey] || '--' }}
            </div>
          </template>
          <!-- 日期范围 -->
          <template v-if="item.taskFiledType == 'datatimerange'">
            <div class="title-value">{{ item.taskFiledValue }}：</div>
            <div class="desc-value">
              {{ wmTaskContent[item.taskFiledKey] }}
            </div>
          </template>
          <!-- 图片上传 -->
          <div v-if="item.taskFiledType == 'img'" class="divline" style="width: 100%; height: 15px; background-color: #e9e9e9; margin-bottom: 5px"></div>
          <template v-if="item.taskFiledType == 'img'">
            <div class="upload-field">
              <div class="field-text" :class="{ required: item.isMustfill == '1' }">{{ item.taskFiledValue }}：</div>
              <!-- 上传组件 -->
              <div class="img-box" v-if="item.imgList">
                <div v-for="(iItem, index) in item.imgList" :key="index" class="img-box-content">
                  <span class="type">{{ iItem.type }}</span>
                  <el-image
                    v-loading="imgErrorLoading"
                    class="img-item"
                    @error="(err) => imgeError(err, item, index, iItem.url)"
                    lazy
                    :src="iItem.url"
                    :preview-src-list="getPreviewList(item.previewList, index)"
                  />
                </div>
              </div>
            </div>
          </template>
          <!-- 金额 -->
          <template v-if="item.taskFiledType == 'money'">
            <div class="title-value">{{ item.taskFiledValue }}：</div>
            <div class="desc-value">
              {{ wmTaskContent[item.taskFiledKey] || '--' }}
            </div>
          </template>
          <!-- 数字 -->
          <template v-if="item.taskFiledType == 'number'">
            <div class="title-value">{{ item.taskFiledValue }}：</div>
            <div class="desc-value">
              {{ wmTaskContent[item.taskFiledKey] || '--' }}
            </div>
          </template>
          <!-- 长文本 -->
          <template v-if="item.taskFiledType == 'longtext'">
            <div class="longtext-box">
              <div class="field-text" :class="{ required: item.isMustfill == '1' }">{{ item.taskFiledValue }}：</div>
              <textarea class="textarea-box" :disabled="true" :value="wmTaskContent[item.taskFiledKey] || '--'" :maxlength="item.taskFiledMaxsize" />
            </div>
          </template>
        </div>
      </div>
    </template>
  </div>
</template>

<script>
import taskApi from '@/api/taskDetail/task';
import commonApi from '@/api/taskDetail/common';
import provinces from '@/util/lib/province';
import citys from '@/util/lib/city';
import areas from '@/util/lib/area';
import request from '@/router/axios';
import heic2any from 'heic2any';

export default {
  name: 'index',
  data() {
    return {
      baseUrl: process.env.VUE_APP_URL,
      showImg: false, // 是否显示只展示图片，分享用到
      taskInfo: {},
      wmTaskContent: {},
      taskTypeId: 0, // 任务类型id
      configList: [], // 配置列表
      dictList: [], //字典
      imgErrorLoading: false,
      imgTypeList: ['jpeg', 'jpg', 'png', 'git', 'bmp'] // 能查看的文件类型
    };
  },

  methods: {
    // 获取详情
    getDesc(item) {
      // 拜访类任务
      const arr = ['51', '52', '53'];
      if (arr.includes(item.taskTypeId) && item.taskFiledKey === 'temp24') {
        if (this.wmTaskContent['temp10']) {
          return this.wmTaskContent['temp10'];
        }

        return this.wmTaskContent['temp24label'];
      }
      // 获取需要转换的字符串（例如 '1,2,3'）
      const contentValue = this.wmTaskContent[item.taskFiledKey];
      if (!contentValue) return '--';
      // 获取字典表对应数组
      const itemList = this.dictList[item.dictGroupName] || [];
      // 按逗号拆分成数组
      const valueArray = contentValue.split(',');
      // 将每个拆分值找到对应的 label
      const result = valueArray.map((val) => {
        const foundItem = itemList.find((dictItem) => dictItem.value === val);
        return foundItem ? foundItem.label : null;
      });
      // 如果有任意一个值无法找到对应的 label，则直接返回 '--'
      if (result.some((label) => label === null)) {
        return '--';
      }
      // 否则，使用逗号拼接并返回
      return result.join(',');
    },

    // 得出图片
    imgeError(err, item, index, url) {
      this.imgErrorLoading = true;
      this.handleImage(url, item, index);
    },

    // 检查文件是否为 HEIC 格式
    isHeicFile(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onloadend = () => {
          const buffer = reader.result;
          // HEIC 文件的前几个字节为 "00 00 00 18 66 74 79 70 68 65 69 63" 或 "00 00 00 20 66 74 79 70 68 65 69 63" (小端字节序)
          const signature = new Uint8Array(buffer).subarray(0, 12);
          const heicSignature = [0x00, 0x00, 0x00, 0x18, 0x66, 0x74, 0x79, 0x70, 0x68, 0x65, 0x69, 0x63];

          const isHeic = signature.every((byte, index) => byte === heicSignature[index]);
          resolve(isHeic);
        };
        reader.onerror = reject;
        reader.readAsArrayBuffer(file);
      });
    },

    async handleImage(url, item, index) {
      const response = await fetch(url);
      const blob = await response.blob();

      if (await this.isHeicFile(blob)) {
        const heicImageBlob = await fetch(url).then((res) => res.blob());

        // 使用 heic2any 库将 HEIC 转换为 JPG
        heic2any({ blob: heicImageBlob, toType: 'image/jpeg' }).then((convertedBlob) => {
          const imgURL = URL.createObjectURL(convertedBlob);
          item.imgList[index].url = imgURL;
          item.previewList[index] = imgURL;
          this.$forceUpdate();
          this.imgErrorLoading = false;
        });
      } else {
        this.imgErrorLoading = false;
      }
    },

    // 得出图片
    getImgList(urlStr, item) {
      // 如果字段类型不是图片或没有 urlStr，则直接返回空数组
      if (item.taskFiledType !== 'img' || !urlStr) return [[], []];

      // 将字符串按逗号拆分为数组
      const urlArr = urlStr.split(',');
      // 如果拆分后为空，也返回空数组
      if (!urlArr.length) return [[], []];

      // 使用 reduce 一次性构建 imgList 和 previewList
      const [imgList, previewList] = urlArr.reduce(
        (acc, curUrl) => {
          let [imgListAcc, previewListAcc] = acc;
          let type = '无';
          let newUrl = curUrl;

          if (curUrl.includes(';1')) {
            type = '拍照';
            newUrl = curUrl.replace(';1', '');
          } else if (curUrl.includes(';2')) {
            type = '相册';
            newUrl = curUrl.replace(';2', '');
          }

          const fullUrl = process.env.VUE_APP_URL + newUrl;
          imgListAcc.push({ type, url: fullUrl });
          previewListAcc.push(fullUrl);

          return [imgListAcc, previewListAcc];
        },
        [[], []]
      );

      return [imgList, previewList];
    },

    // 获取任务详情
    async getTaskInfoById(id) {
      try {
        const res = await taskApi.getTaskInfoById(id);
        const { data } = res.data;
        this.wmTaskContent = data.wmTaskContent;
        this.taskInfo = data.taskInfo;
        this.taskTypeId = data.taskType;
        this.getTaskContentConfigByTaskTypeId(data.taskType);
      } catch (e) {
        console.log(e);
      }
    },
    // 获取配置
    async getTaskContentConfigByTaskTypeId(value) {
      try {
        let res = await commonApi.getTaskContentConfigByTaskTypeId(value);
        let { config, dict } = res.data.data;
        this.configList = config;
        this.dictList = dict;
        this.configList.forEach((item) => {
          item.taskFiledType = item.taskFiledType.trim();
          if (item.taskFiledType == 'img') {
            let imgArr = this.getImgList(this.wmTaskContent[item.taskFiledKey], item);
            item.imgList = imgArr[0];
            item.previewList = imgArr[1];
            this.$forceUpdate();

            console.log('item', item);
          }
        });
      } catch (e) {
        console.log(e);
      }
      // this.getMapAddress();
      // uni.hideLoading();
    },
    getPreviewList(imgList, index) {
      // 解决el-image大图预览定位图片不准确的问题
      return imgList.slice(index).concat(imgList.slice(0, index));
    },
    getInfo(id) {
      this.getTaskInfoById(id);
    }
  }
};
</script>

<style lang="scss" scoped>
.field-box {
  //display: flex;
  padding: 0 20px 10px;
  overflow: hidden;
  .title-value {
    //width: 50%;
    float: left;
  }
  .desc-value {
    float: left;
  }
  .upload-field {
    .img-box {
      padding-top: 10px;
      display: flex;
      flex-wrap: wrap;
    }
    .file-box {
      .file-item {
        padding: 2px 8px;
        cursor: pointer;
        &:hover {
          background-color: #f5f7fa;
          color: #2d8cf0;
        }
      }
    }
  }
  .img-box-content {
    padding-top: 15px;
    position: relative;

    .type {
      font-size: 12px;
      position: absolute;
      top: -3px;
    }
  }
  .img-item {
    width: 100px;
    height: 100px;
    margin-right: 10px;
  }
  .longtext-box {
    width: 50%;
    .textarea-box {
      margin-top: 10px !important;
      width: 100%;
    }
  }
}

.sign-in-box {
  padding: 10px 20px;
}

.detail-info {
  ul {
    list-style: none;
    li {
      span {
        min-width: 80px;
      }
      display: flex;
      margin-bottom: 5px;
    }
  }
}
</style>
