<template>
  <div class="quicl-review" @scroll="handleScroll">
    <div class="card-container">
      <p>
        <el-button type="primary" @click="backPage" style="width: 80px">返回</el-button>
      </p>
    </div>
    <div class="card-container">
      <div class="search-content">
        <el-form :model="searchFrom" label-width="140px">
          <el-row>
            <el-col :span="6">
              <el-form-item label="执行包年度">
                <el-date-picker clearable class="w100" v-model="searchFrom.year" type="year" placeholder="请选择执行包年度" format="yyyy" value-format="yyyy"> </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="执行包季度">
                <el-select v-model="searchFrom.quarter" placeholder="请选择服务季度" class="w100" clearable>
                  <el-option label="第一季度" :value="1"></el-option>
                  <el-option label="第二季度" :value="2"></el-option>
                  <el-option label="第三季度" :value="3"></el-option>
                  <el-option label="第四季度" :value="4"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="服务提交时间">
                <el-date-picker class="w100" clearable v-model="searchFrom.createTime" type="date" placeholder="选择日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="服务类型">
                <el-select v-model="searchFrom.taskTypeId" placeholder="请选择服务类型" class="w100" clearable>
                  <el-option :label="item.name" :value="item.id" v-for="item in taskTypeAvailArr" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="服务提供商">
                <el-select v-model="searchFrom.vendorId" placeholder="请选择服务提供商" class="w100" clearable filterable>
                  <el-option v-for="item in deptListArr" :key="item.entId" :label="item.name" :value="item.entId" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="推广员姓名">
                <el-select v-model="searchFrom.salesId" placeholder="请选择推广员姓名" class="w100" clearable filterable>
                  <el-option v-for="item in userListArr" :key="item.userId" :label="item.realName" :value="item.userId" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="产品所属生产企业">
                <el-select v-model="searchFrom.mahName" @change="mahNameChange" placeholder="请选择产品所属生产企业" class="w100" clearable>
                  <el-option v-for="item in mahNameArr" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="关联产品名称">
                <el-select v-model="searchFrom.skuId" placeholder="请选择关联产品名称" class="w100" :disabled="drugDisabled" clearable filterable>
                  <el-option v-for="item in currDrugList" :key="item.id" :label="item.drugName" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="执行包所属省份">
                <el-select v-model="searchFrom.provAbbr" placeholder="请选择省份" class="w100" clearable>
                  <el-option v-for="province in abbreviationsProvincesList" :key="province" :label="province" :value="province" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="上游服务包名称">
                <el-select v-model="searchFrom.pkgIds" placeholder="请选择上游服务包名称" class="w100" clearable filterable>
                  <el-option v-for="(item, index) in relPkgNameArr" :key="index" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <div class="search-btns">
                <el-button type="success" @click="clickBtn">搜索</el-button>
                <el-button @click="clearSearch">清空</el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <div class="card-container" v-if="false">
      <div class="card-all-review">
        <div class="btns">
          <el-button type="primary" @click="allClickBtn">批量审核</el-button>
        </div>
        <div class="check-info">
          <el-checkbox v-model="allCheck" @change="allClick">全选</el-checkbox>
          <p>当前已选择{{ checkAllLength }}项，总积分：{{ checkAllTaskScore }}</p>
        </div>
      </div>
    </div>

    <div class="card-list card-container" v-loading="getPageLoading">
      <template v-if="list.length === 0">
        <div class="no-data">
          <el-empty description="暂无数据"></el-empty>
        </div>
      </template>
      <div class="cards" v-masonry :cols="2" :gutter="20" style="width: 100%" v-else>
        <template v-for="(curr, currIndex) in list">
          <div class="card" v-masonry-tile :key="curr.info.taskId" v-if="curr.reviewInfo.show">
            <div class="task-info">
              <div class="task-type-info">
                <el-checkbox
                  v-if="false"
                  v-model="curr.reviewInfo.checked"
                  @change="
                    (val) => {
                      itemChecked(val, curr);
                    }
                  "
                ></el-checkbox>
                服务类型： {{ getName(curr?.info.taskTypeId) }}
              </div>
              <div class="info">
                <p>任务ID：{{ curr?.info.taskId }}</p>
                <p>任务编号：{{ curr?.info.taskNumber }}</p>
              </div>
              <div class="info">
                <p>服务积分：{{ curr?.info.taskScore }}</p>
                <p>代表姓名：{{ curr?.info.salesName }}</p>
              </div>
              <div class="info">
                <p>产品名称：{{ curr?.info.skuName }}</p>
                <p>生产企业：{{ curr?.info.mahName }}</p>
              </div>
              <div class="info">
                <p>执行包名称：{{ curr?.info.pkgName }}</p>
                <p>起止时间：{{ curr?.info.pkgStartTime }} ~ {{ curr?.info.pkgEndTime }}</p>
              </div>
            </div>
            <div class="detail">服务详情</div>
            <template v-if="curr?.info?.configs">
              <div v-for="(item, index) in curr?.info?.configs" :key="index" class="field-box">
                <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(curr.info, item) }}
                  </div>
                </template>

                <!-- * 文本类型 -->
                <template v-if="typeArr.includes(item.taskFiledType)">
                  <div class="title-value">{{ item.taskFiledValue }}：</div>
                  <div class="desc-value">
                    {{ curr.info.taskContent[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
                          class="img-item"
                          :src="iItem.url"
                          :preview-src-list="getPreviewList(item.previewList, index)"
                          @error="(err) => imgeError(err, item, index, iItem.url)"
                        >
                          <div slot="error" class="image-slot">
                            <i class="el-icon-loading"></i>
                          </div>
                        </el-image>
                      </div>
                    </div>
                  </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="curr.info.taskContent[item.taskFiledKey] || '--'" :maxlength="item.taskFiledMaxsize" />
                  </div>
                </template>
              </div>
            </template>
            <div class="divline" style="width: 100%; height: 15px; background-color: #e9e9e9; margin-bottom: 5px"></div>
            <div class="longtext-box review-textarea">
              <div class="field-text">意见说明</div>
              <el-input type="textarea" class="textarea-box" resize="none" v-model="curr.reviewInfo.checkMessage" />
            </div>

            <div class="btns">
              <el-button class="btn" type="danger" @click="passClick(curr, false)">不通过</el-button>
              <el-button class="btn" type="primary" @click="passClick(curr, true)">通过</el-button>
            </div>
          </div>
        </template>
      </div>
    </div>

    <!-- 审核弹窗 -->
    <el-dialog title="审核" :close-on-click-modal="false" :visible.sync="reviewDialog" top="12vh" width="50%" :before-close="handleClose" center>
      <div class="reviewContent" v-loading="loading">
        <div class="check-tips">审核令牌有效期为3分钟，请在【{{ expireTime }}】前完成审核操作，如果失效，请重新打开弹窗。</div>

        <div class="teskDetailsty">审批意见</div>
        <el-form :model="taskForm" :rules="rules" ref="taskForm" label-width="100px">
          <el-form-item label="审批意见:" prop="checkResult" class="formitem-box">
            <el-radio-group v-model="taskForm.checkResult">
              <el-radio :label="true">通过</el-radio>
              <el-radio :label="false">拒绝</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            label="意见说明:"
            prop="checkMessage"
            class="formitem-box"
            :rules="[
              {
                required: !taskForm.checkResult,
                message: '请输入审批说明',
                trigger: 'blur'
              }
            ]"
          >
            <el-input type="textarea" v-model="taskForm.checkMessage"></el-input>
          </el-form-item>
          <refuseReason @selectRefuseReason="selectRefuseReason" />
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="checkForm" v-loading="loading">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="批量审核预处理结果" :visible.sync="lockedDialog" top="12vh" width="50%" :before-close="lockedDialogClose" center :show-close="false">
      <div>
        <div class="check-tips">
          本次批量审核，拟处理服务 【{{ pretreatmentInfo?.total?.length }}】 个, 成功预留【{{ pretreatmentInfo?.available?.length }}】个，忽略【{{
            pretreatmentInfo?.locked?.length
          }}】个, 继续审核请点击“确定”，放弃请点击“取消”（有效期三分钟）。
        </div>
        <el-table
          :data="pretreatmentInfo?.total"
          border
          style="width: 100%"
          max-height="500"
          :header-cell-style="{ 'text-align': 'center' }"
          :cell-style="{ 'text-align': 'center' }"
        >
          <el-table-column prop="taskId" label="任务ID"> </el-table-column>
          <el-table-column prop="status" label="预留结果">
            <template slot-scope="scope">
              <span :class="scope.row.status === '成功' ? 'status-success' : 'status-fail'">{{ scope.row.status }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="lockInfo" label="结果说明"> </el-table-column>
          <el-table-column prop="expireAt" label="锁定至"> </el-table-column>
        </el-table>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="lockedDialogClose">取 消</el-button>
        <el-button type="primary" @click="lockedBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getTaskTypeAvailApi,
  getDeptv2Avail,
  getDrug2Avail,
  getUserV2Avail,
  getTaskV2TokenApi,
  taskV2CheckBatchApi,
  checkSingleApi,
  getTaskV2PageTileApi,
  getPkgV2Api,
  getPretreatmentApi,
  pretreatmentClearApi
} from '@/api/serviceManagement/servicesToBeReviewed/index.js';
import refuseReason from '@/components/refuseReason';
import { getDictType } from '@/api/common';
import abbreviationsProvinces from '@/const/abbreviationsProvinces.js';
import dayjs from 'dayjs';
import { mapGetters } from 'vuex';
import heic2any from 'heic2any';

export default {
  components: { refuseReason },
  data() {
    return {
      typeArr: ['area', 'text', 'inputautoselect', 'map', 'mapwithimg', 'datetime', 'datatimerange', 'money', 'number', ''],
      taskStatusArr: [],
      taskTypeAvailArr: [],
      mahNameArr: [],
      deptListArr: [],
      drugListArr: [],
      userListArr: [],
      currDrugList: [],
      relPkgNameArr: [],
      drugDisabled: true,
      abbreviationsProvincesList: abbreviationsProvinces,
      nodeId: '',
      getPageLoading: false,
      searchFrom: {
        year: '',
        taskTypeId: '',
        quarter: '',
        createTime: '',
        provAbbr: '',
        mahName: '',
        vendorId: '',
        salesId: '',
        skuId: '',
        pkgIds: '',
        taskStatus: 3
      },
      page: {
        total: 0,
        currentPage: 1,
        pageSize: 10
      },
      nodeId: '',
      list: [],
      allCheck: false,
      checkAllLength: 0,
      checkAllTaskScore: 0,
      checkIds: [],
      reviewToken: '',
      expireTime: '',
      reviewDialog: false,
      taskForm: {
        checkResult: '',
        checkMessage: ''
      },
      rules: {
        checkResult: [{ required: true, message: '请选择审批意见', trigger: 'change' }]
      },
      loading: false,
      pretreatmentInfo: {},
      lockedInfo: [],
      lockedDialog: false,
      checkNodeId: ''
    };
  },
  async created() {
    let nodeId = '';
    const roles = this.userInfo.roles;

    switch (true) {
      // 43	地市管理员
      case roles.includes(43):
        nodeId = 2;
        break;
      // 4	区域管理员
      case roles.includes(4):
        nodeId = 3;
        break;
      // 42	市场管理员
      case roles.includes(42):
        nodeId = 8;
        break;
      // 40	商务管理员
      case roles.includes(40):
        nodeId = 9;
        break;
      // 39	事业部总经理
      case roles.includes(39):
        nodeId = 6;
        break;
      // 41	事业部分管领导
      case roles.includes(41):
        nodeId = 5;
        break;
      default:
        nodeId = 1;
    }
    this.checkNodeId = nodeId;

    await this.getDict();
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll);

    const roles = this.userInfo.roles;

    let nodeId = '';
    switch (true) {
      // 43	地市管理员
      case roles.includes(43):
        nodeId = 1;
        break;
      // 4	区域管理员
      case roles.includes(4):
        nodeId = 2;
        break;
      // 42	市场管理员： 获取审核节点为3和9   nodeid为12
      case roles.includes(42):
        nodeId = 12;
        break;
      // 40	商务管理员： 获取审核节点为3和8   nodeid为11
      case roles.includes(40):
        nodeId = 11;
        break;
      // 41	事业部分管领导
      case roles.includes(41):
        nodeId = 9;
        break;
      // 39	事业部总经理
      case roles.includes(39):
        nodeId = 15;
        break;
      default:
        nodeId = 1;
    }

    const lastYear = dayjs().subtract(1, 'year').format('YYYY');
    this.searchFrom.year = lastYear;
    this.nodeId = nodeId;
    this.searchFrom.nodeId = nodeId;
    this.getList();
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll);
  },
  methods: {
    imgeError(err, item, index, url) {
      this.handleImage(url, item, index);
    },
    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();
        });
      }
    },
    handleScroll(event) {
      const scrollHeight = event.target.scrollHeight; // 获取滚动元素的总高度
      const scrollTop = event.target.scrollTop; // 获取滚动元素的当前滚动高度
      const windowHeight = event.target.clientHeight; // 获取滚动元素的可视区域高度
      if (scrollTop + windowHeight >= scrollHeight - 10) {
        if (!this.getPageLoading && this.page.total > this.page.currentPage * this.page.pageSize) {
          this.page.currentPage += 1;
          this.getList();
        }
      }
    },

    getDict() {
      getDictType({ type: 'task_status' }).then((res) => {
        this.taskStatusArr = res.data.data;
      });
      getDictType({ type: 'mah_name' }).then((res) => {
        this.mahNameArr = res.data.data;
      });
      getTaskTypeAvailApi().then((res) => {
        this.taskTypeAvailArr = res.data.data;
      });
      getDeptv2Avail().then((res) => {
        this.deptListArr = res.data.data;
      });
      getUserV2Avail().then((res) => {
        this.userListArr = res.data.data;
      });

      getDrug2Avail().then((res) => {
        this.drugListArr = res.data.data;
      });
      getPkgV2Api().then((res) => {
        let arr = [];
        let data = res.data.data;
        for (let key in data) {
          let obj = {
            label: key,
            value: data[key]
          };
          arr.push(obj);
        }

        this.relPkgNameArr = arr;
      });
    },
    mahNameChange(e) {
      if (e) {
        const curr = this.drugListArr[e];
        this.currDrugList = curr;

        this.drugDisabled = false;
      } else {
        this.searchFrom.skuId = '';
        this.currDrugList = [];
        this.drugDisabled = true;
      }
    },
    async getList() {
      this.getPageLoading = true;
      const obj = Object.assign(
        {
          current: this.page.currentPage,
          size: this.page.pageSize
        },
        this.searchFrom
      );

      try {
        const res = await getTaskV2PageTileApi(obj);
        if (res.data.code === 0) {
          let list = res.data.data.records;
          // this.list.push(...res.data.data.records);
          this.page.total = res.data.data.total;
          list.forEach((item) => {
            let reviewInfo = {
              checked: false,
              checkMessage: '',
              show: true
            };
            item.reviewInfo = reviewInfo;
            item?.info?.configs?.forEach((iten) => {
              iten.taskFiledType = iten.taskFiledType.trim();
              if (iten.taskFiledType == 'img') {
                this.getImgList(item.info.taskContent[iten.taskFiledKey], iten);
              }
            });
          });
          this.list.push(...list);
          this.$forceUpdate();
          this.getPageLoading = false;
        }
      } catch (err) {
        this.getPageLoading = false;
      }
    },

    allClick(val) {
      if (val) {
        this.list.forEach((item) => (item.reviewInfo.checked = true));
        this.$forceUpdate();
        this.calcInfo();
      } else {
        this.list.forEach((item) => (item.reviewInfo.checked = false));
        this.checkAllLength = 0;
        this.checkAllTaskScore = 0;
        this.$forceUpdate();
      }
    },
    calcInfo() {
      let checkAllLength = 0;
      let checkAllTaskScore = 0;
      let ids = [];
      this.list.forEach((item) => {
        if (item.reviewInfo.checked) {
          checkAllLength++;
          checkAllTaskScore += Number(item.info.taskScore);
          ids.push(item.info.taskId);
        }
      });
      this.checkAllLength = checkAllLength;
      this.checkAllTaskScore = checkAllTaskScore;
      this.checkIds = ids;
    },
    itemChecked(val, item) {
      this.$forceUpdate();

      if (val) {
        this.checkAllLength++;
        this.checkIds.push(item.info.taskId);
        this.checkAllTaskScore += Number(item.info.taskScore);
      } else {
        this.checkAllLength--;
        let index = this.checkIds.findIndex((curr) => curr === item.info.taskId);
        this.checkIds.splice(index, 1);
        this.checkAllTaskScore -= Number(item.info.taskScore);
      }
    },
    async allClickBtn() {
      if (!this.checkIds.length) {
        return this.$message.error('请选择待审核数据');
      }

      this.getPretreatment();
    },
    async getPretreatment() {
      const res = await getPretreatmentApi({ taskIds: this.checkIds, nodeId: this.checkNodeId });
      if (res.data.code === 0) {
        this.pretreatmentInfo = res.data.data;
        this.lockedInfo = res.data.data.locked;
        this.lockedDialog = true;
      }
    },
    async lockedBtn() {
      if (this.pretreatmentInfo.available.length) {
        this.lockedDialog = false;
        this.lockedInfo = [];
        this.reviewDialog = true;
        // await this.getToken(this.checkIds);
      } else {
        this.$message.info('当前无可审核数据！');
        this.list.forEach((item) => {
          if (item.reviewInfo.checked) {
            this.checkAllLength = 0;
            this.checkAllTaskScore;
            item.reviewInfo.checked = false;
            item.reviewInfo.show = false;
          }
        });
        this.lockedDialogClose();
      }
    },
    async lockedDialogClose() {
      const taskIds = this.pretreatmentInfo.available.map((item) => item.taskId);
      if (this.pretreatmentInfo?.token?.token) {
        const obj = {
          taskIds: taskIds,
          token: this.pretreatmentInfo.token.token,
          nodeId: this.checkNodeId
        };
        await pretreatmentClearApi(obj);
      }
      this.list.forEach((item) => {
        item.reviewInfo.checked = false;
      });
      this.checkIds = [];
      this.lockedDialog = false;
      this.lockedInfo = [];
    },
    async getToken(taskIds) {
      const tokenRes = await getTaskV2TokenApi({ taskIds: taskIds });
      if (tokenRes.data.code !== 0 || !tokenRes.data.data?.token) {
        return this.$message.error('获取token失败');
      }
      this.reviewToken = tokenRes.data.data.token;
      this.expireTime = tokenRes.data.data.expireTime;
    },

    closeDialog() {
      this.reviewDialog = false;
      this.taskForm = {
        checkResult: '',
        checkMessage: ''
      };
    },
    async handleClose() {
      const taskIds = this.pretreatmentInfo.available.map((item) => item.taskId);
      if (this.pretreatmentInfo?.token?.token) {
        const obj = {
          taskIds: taskIds,
          token: this.pretreatmentInfo.token.token,
          nodeId: this.checkNodeId
        };
        await pretreatmentClearApi(obj);
      }
      this.list.forEach((item) => {
        item.reviewInfo.checked = false;
      });
      this.checkIds = [];
      this.closeDialog();
    },
    clickBtn() {
      this.list = [];
      this.page.currentPage = 1;
      this.checkIds = [];
      this.allCheck = false;
      this.checkAllLength = 0;
      this.checkAllTaskScore = 0;
      this.getList();
    },
    clearSearch() {
      this.searchFrom = {
        year: '',
        taskTypeId: '',
        quarter: '',
        createTime: '',
        provAbbr: '',
        mahName: '',
        vendorId: '',
        salesId: '',
        skuId: '',
        pkgIds: '',
        taskStatus: 3
      };
      this.searchFrom.nodeId = this.nodeId;
    },
    getName(taskType) {
      let curr = this.taskTypeAvailArr.find((item) => item.id == taskType);
      return curr.name;
    },

    getPreviewList(imgList, index) {
      // 解决el-image大图预览定位图片不准确的问题
      return imgList.slice(index).concat(imgList.slice(0, index));
    },
    getImgList(urlStr, item) {
      // 如果类型不匹配或者 urlStr 为空，直接返回
      if (item.taskFiledType !== 'img' || !urlStr) return '';

      // 缓存环境变量中的基础 URL
      const { VUE_APP_URL } = process.env;

      // 以逗号分割，并过滤掉空字符串
      const imgArray = urlStr.split(',').filter(Boolean);
      if (!imgArray.length) return '';

      // 生成包含 type 和 url 的数组
      const imgList = imgArray.map((originalUrl) => {
        let type = '无';
        let url = originalUrl;

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

        return {
          type,
          url: VUE_APP_URL + url
        };
      });

      // 提取预览图片的 URL 列表
      const previewList = imgList.map((item) => item.url);

      // 将处理结果赋值给对应字段
      item.imgList = imgList;

      item.previewList = previewList;

      // 函数约定返回空字符串
      return '';
    },

    getDesc(curr, item) {
      // 拜访类任务
      const arr = ['51', '52', '53'];
      if (arr.includes(item.taskTypeId) && item.taskFiledKey === 'temp24') {
        return curr.taskContent['temp24label'];
      }
      // 获取需要转换的字符串（例如 '1,2,3'）
      const contentValue = curr.taskContent[item.taskFiledKey];
      if (!contentValue) return '--';
      // 获取字典表对应数组
      const itemList = curr.dict[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(',');
    },
    async passClick(item, flag) {
      if (!flag && !item.reviewInfo.checkMessage) {
        return this.$message.error('请填写审核意见');
      }

      //
      let nodeId = '';
      const roles = this.userInfo.roles;
      switch (true) {
        // 43	地市管理员
        case roles.includes(43):
          nodeId = 2;
          break;
        // 4	区域管理员
        case roles.includes(4):
          nodeId = 3;
          break;
        // 42	市场管理员
        case roles.includes(42):
          nodeId = 8;
          break;
        // 40	商务管理员
        case roles.includes(40):
          nodeId = 9;
          break;
        // 39	事业部总经理
        case roles.includes(39):
          nodeId = 6;
          break;
        // 41	事业部分管领导
        case roles.includes(41):
          nodeId = 5;
          break;
        default:
          nodeId = 1;
      }
      let obj = {
        token: item.token.token,
        taskId: item.token.value,
        checkResult: flag,
        checkMessage: item.reviewInfo.checkMessage,
        nodeId: nodeId
      };
      try {
        const res = await checkSingleApi(obj);
        if (res.data.code === 0) {
          item.reviewInfo.checked = flag;
          item.reviewInfo.show = false;
          this.$forceUpdate();
        }
      } catch (err) {
        // this.$message.error(err);
        item.reviewInfo.checked = flag;
        item.reviewInfo.show = false;
        this.$forceUpdate();
      }
    },

    checkForm() {
      let nodeId = '';
      const roles = this.userInfo.roles;
      switch (true) {
        // 43	地市管理员
        case roles.includes(43):
          nodeId = 2;
          break;
        // 4	区域管理员
        case roles.includes(4):
          nodeId = 3;
          break;
        // 42	市场管理员
        case roles.includes(42):
          nodeId = 8;
          break;
        // 40	商务管理员
        case roles.includes(40):
          nodeId = 9;
          break;
        // 39	事业部总经理
        case roles.includes(39):
          nodeId = 6;
          break;
        // 41	事业部分管领导
        case roles.includes(41):
          nodeId = 5;
          break;
        default:
          nodeId = 1;
      }

      const taskIds = this.pretreatmentInfo.available.map((item) => item.taskId);
      this.$refs.taskForm.validate(async (valid) => {
        if (valid) {
          let obj = {
            token: this.pretreatmentInfo.token.token,
            taskIds: taskIds,
            checkResult: this.taskForm.checkResult,
            checkMessage: this.taskForm.checkMessage,
            nodeId: nodeId
          };
          try {
            const res = await taskV2CheckBatchApi(obj);
            if (res.data.code === 0 && res.data.data) {
              this.$message.success('审核成功！');
              this.checkIds = [];

              this.closeDialog();
              this.list.forEach((item) => {
                if (item.reviewInfo.checked) {
                  this.checkAllLength = 0;
                  this.checkAllTaskScore;
                  item.reviewInfo.checked = false;
                  item.reviewInfo.show = false;
                }
              });
            }
            this.loading = false;
          } catch (err) {
            this.loading = false;
          }
        }
      });
    },
    selectRefuseReason(refuseReason) {
      let info;
      if (this.taskForm.checkMessage) {
        info = this.taskForm.checkMessage + refuseReason + '；';
      } else {
        info = refuseReason + '；';
      }

      this.$set(this.taskForm, 'checkMessage', info);
    },
    backPage() {
      this.$router.$avueRouter.closeTag();
      this.$router.back();
    }
  }
};
</script>

<style lang="scss" scoped>
.quicl-review {
  overflow: auto;
  height: 100%;
  padding-bottom: 30px;
  .card-container {
    margin: 0 10px;
    margin-bottom: 10px;
    padding: 20px;
    border-radius: 10px;
    background: #fff;
    box-sizing: border-box;
  }
}

.search-btns {
  margin-left: 50px;
  display: flex;
  justify-content: space-between;
}

.card-list {
  overflow: auto;
  min-height: 200px;
  box-sizing: border-box;
  .cards {
    box-sizing: border-box;
    width: 100%;
    padding: 10px;
  }

  .card {
    box-sizing: border-box;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
    border: 1px solid #ebeef5;
    background-color: #fff;
    color: #303133;
    transition: 0.3s;
    min-height: 300px;
    width: 48%;
    // min-width: 500px;
    margin-bottom: 10px;
    padding: 10px;
  }

  .task-type-info {
    font-size: 16px;
    color: #333;
    font-weight: 600;
    margin-bottom: 5px;
  }
  .info {
    display: flex;
    font-size: 12px;
    color: #7f7f7f;
    margin-bottom: 5px;

    p {
      flex: 1;
      margin-right: 30px;
    }
  }

  .detail {
    font-size: 14px;
    font-weight: 500;
    color: #333333;
    border-bottom: 2px solid #d7d6d5;
    line-height: 30px;
    margin: 5px 0;
  }
}

.field-box {
  padding: 0 10px 5px;
  overflow: hidden;
  .title-value {
    //width: 50%;
    float: left;
  }
  .desc-value {
    float: left;
  }
  .upload-field {
    .img-box {
      padding-top: 5px;
      display: flex;
    }
    .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: 0;
    }
  }
  .img-item {
    width: 100px;
    height: 100px;
    margin-right: 5px;
  }

  .divline {
    width: 100%;
    height: 5px;
    background-color: #e9e9e9;
    margin-bottom: 5px;
  }
  .img-iten {
    height: 60px;
    margin-right: 5px;
    width: 50px;
    cursor: pointer;
  }
}

.longtext-box {
  .textarea-box {
    margin-top: 5px !important;
    width: 100%;
    padding: 3px;
  }
}

.no-data {
  margin: 0 auto;
}

.btns {
  padding: 0 20px;
  padding-top: 5px;
  display: flex;
  justify-content: space-between;
  .btn {
    width: 48%;
  }
}

.card-all-review {
  width: 350px;
}
.check-info {
  padding-left: 20px;
  margin-top: 10px;
  display: flex;
  height: 30px;
  align-items: center;
  p {
    color: #85ce61;
    border-radius: 3px;
    line-height: 14px;
    font-size: 14px;
  }
}

.teskDetailsty {
  width: 100%;
  height: 30px;
  line-height: 30px;
  font-size: 16px;
  font-weight: 600;
  color: #333333;
  border-bottom: 1px solid #d7d6d5;
  margin: 0 0 10px 0;
}
.check-btns {
  width: 150px;
  display: flex;
  justify-content: space-between;
}

.check-tips {
  margin-bottom: 5px;
  font-size: 16px;
  color: rgb(233 77 77);
  text-align: center;
  font-weight: 600;
}
::v-deep .image-slot {
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
}
</style>
