<template>
  <basic-container class="basic">
    <el-image-viewer v-if="showViewer" :on-close="closeViewer" :url-list="viewerList" />
    <Card class="cardTitle">
      <p>
        <el-button type="primary" @click="backPage" style="width: 80px">返回</el-button>
      </p>
    </Card>
    <div class="search">
      <el-form :model="form" label-width="100px" ref="formRef">
        <el-row>
          <el-col :span="8">
            <el-form-item label="任务ID" prop="taskId">
              <el-input v-model="form.taskId" placeholder="执行任务" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="任务编号" prop="taskNumber">
              <el-input v-model="form.taskNumber" placeholder="任务编号" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="服务类型" prop="taskTypeId">
              <el-select v-model="form.taskTypeId" placeholder="服务类型" class="w100" clearable>
                <el-option :label="item.taskTypeName" :value="item.id" v-for="item in taskList" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="起止时间">
              <ElQuarterPicker placeholder="请选择" v-model="monthrange" @change="monthrangeChange" class="w100" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="执行包名称" prop="pkgName">
              <el-input v-model="form.pkgName" placeholder="执行包名称" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生产企业" prop="mahName">
              <el-select v-model="form.mahName" placeholder="生产企业" clearable class="w100">
                <el-option :label="item.label" :value="item.value" v-for="item in mahNameList" :key="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="代表名字" prop="memberName">
              <el-input v-model="form.memberName" placeholder="代表名字" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <div class="search-btns">
              <el-form-item>
                <el-button type="primary" @click="onSubmit">查询</el-button>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="restFn">重置</el-button>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <div class="content" v-if="!IS_FWS && type">
        <el-button type="primary" class="all-btn" @click="allPassClick">批量审核</el-button>
        <el-checkbox v-model="allCheck" @change="allClick">全选</el-checkbox>
      </div>
    </div>
    <div class="content">
      <div class="list" v-if="list.length">
        <el-card
          shadow="always"
          class="item"
          v-for="(item, index) in list"
          :key="index"
          v-show="item.show"
          :class="'cls' + item.id"
          :style="{
            left: item.left,
            top: item.top
          }"
        >
          <div class="task-type-name">
            <el-checkbox
              v-if="!IS_FWS && type"
              v-model="item.checked"
              @change="
                val => {
                  itemChecked(val, item.id, item.score);
                }
              "
            ></el-checkbox>
            服务类型： {{ getName(item.taskType) }}
          </div>
          <div class="info">
            <p>任务ID：{{ item.id }}</p>
            <p>任务编号：{{ item.taskInfo.taskNumber }}</p>
          </div>
          <div class="info">
            <p>服务积分：{{ item.score }}</p>
            <p>代表姓名：{{ item.taskUserName }}</p>
          </div>
          <div class="info">
            <p>产品名称：{{ item.drugName }}</p>
            <p>生产企业：{{ item.mah }}</p>
          </div>
          <div class="info">
            <p>执行包名称：{{ item.pkgName }}</p>
            <p>起止时间：{{ item.period }}</p>
          </div>
          <div class="detail">
            服务详情
          </div>
          <el-image v-if="item.taskInfo.shareImgUrl" :src="item.taskInfo.shareImgUrl" :preview-src-list="[item.taskInfo.shareImgUrl]"> </el-image>
          <template v-if="['8', '9', '10', '11'].includes(item.taskType)">
            <div v-if="item.taskInfo">
              <div>转发时间： {{ item.taskInfo.createTime || '' }}</div>
              <div>文章标题：{{ item.title }}</div>
              <div>获得积分：+{{ item.score }}</div>
              <div>备注：{{ item.remark }}</div>
              <div class="tc" v-if="item.ercodeUrl" :style="{height: '150px'}">
                <img class="ercode-icon" :src="item.ercodeUrl" />
              </div>
            </div>
          </template>
          <template v-if="['5', '6', '33'].includes(item.taskType)">
            <div v-for="(iten, index) in item.wmUserSignList" :key="index" class="visit-list">
              <div class="visit-title">
                拜访记录：
              </div>
              <div>{{ iten.signEntName }} {{ iten.signDate }} 打卡</div>
              <template v-if="iten.userSignDetail">
                <div class="visit-title">
                  拜访明细：
                </div>
                <div class="detail-info">
                  <ul>
                    <li v-if="iten.userSignDetail.drug.length > 0">
                      <span>推广产品：</span>
                      <p>
                        {{ iten.userSignDetail.drug && iten.userSignDetail.drug.join('，') }}
                      </p>
                    </li>
                    <li
                      v-if="
                        iten.signEntType == '1' &&
                          iten.userSignDetail &&
                          iten.userSignDetail.templateType !== 'TEMPLATE2' &&
                          iten.userSignDetail.detail &&
                          iten.userSignDetail.detail.length > 0
                      "
                    >
                      <span>拜访科室：</span>
                      <div>
                        <div v-for="(iteo, indey) in iten.userSignDetail.detail" :key="indey">
                          <div>{{ iteo.departmentName }}</div>
                          <el-image v-if="iteo.fileUrl.length" :preview-src-list="iteo.fileUrl" style="width: 100px; height: 100px" :src="getUrl(iteo.fileUrl[0])"></el-image>
                        </div>
                      </div>
                    </li>
                    <li v-if="iten.signEntType == '1' && iten.userSignDetail && iten.userSignDetail.department">
                      <span>拜访科室：</span>
                      <p>{{ iten.userSignDetail.department }}</p>
                    </li>
                    <li v-if="iten.userSignDetail && iten.userSignDetail.visitor">
                      <span>拜访人员：</span>
                      <p>{{ iten.userSignDetail.visitor }}</p>
                    </li>
                    <li>
                      <span>拜访目的：</span>
                      <p>
                        {{ iten.userSignDetail.purposeName && iten.userSignDetail.purposeName.join('，') }}
                      </p>
                    </li>
                    <li>
                      <span>拜访结果：</span>
                      <p>{{ iten.userSignDetail.resultName }}</p>
                    </li>
                    <template v-if="iten.userSignDetail.templateType === 'TEMPLATE2'">
                      <li>
                        <span>是否针对了正确的HCP：</span>
                        <p>
                          {{ iten.userSignDetail.detail[0].rightHcp ? '是' : '否' }}
                        </p>
                      </li>
                      <li>
                        <span>是否传递了正确的信息：</span>
                        <p>
                          {{ iten.userSignDetail.detail[0].rightInfo ? '是' : '否' }}
                        </p>
                      </li>
                      <li>
                        <span>是否采取了正确的活动形式和频率：</span>
                        <p>
                          {{ iten.userSignDetail.detail[0].rightActivity ? '是' : '否' }}
                        </p>
                      </li>
                    </template>
                    <li>
                      <span>备注：</span>
                      <p>{{ iten.userSignDetail.remark }}</p>
                    </li>
                  </ul>
                </div>
              </template>
            </div>
          </template>
          <template v-if="item.config && item.config.length != 0">
            <div>
              <div v-for="iten in item.config" :key="iten.id" class="field-box">
                <template v-if="iten.taskFiledType == 'domain' || iten.taskFiledType == 'select'">
                  <div class="title-value">{{ iten.taskFiledValue }}：</div>
                  <div class="desc-value" v-show="!(iten.taskTypeId == '19' && iten.taskFiledKey == 'temp3')">
                    {{ getDesc(iten, item) }}
                  </div>
                </template>
                <!-- 城市选择 -->
                <template v-if="iten.taskFiledType === 'area'">
                  <div class="title-value">{{ iten.taskFiledValue }}：</div>
                  <div class="desc-value">
                    {{ getAddress(iten, item) }}
                  </div>
                </template>
                <!-- 文字输入 -->
                <template v-if="iten.taskFiledType == 'text' || iten.taskFiledType == 'inputautoselect' || iten.taskFiledType == 'map'">
                  <div class="title-value">{{ iten.taskFiledValue }}：</div>
                  <div class="desc-value">
                    {{ item.wmTaskContent[iten.taskFiledKey] || '--' }}
                  </div>
                  <!-- 地图 -->
                  <template v-if="getMapShow(iten) && mapShow">
                    <div :id="item.id" style="width:100%; height:300px">
                      <!-- {{ iten.id && initMap(iten.id, item)}} -->
                    </div>
                  </template>
                </template>
                <!-- 时间 -->
                <template v-if="iten.taskFiledType == 'datetime'">
                  <div class="title-value">{{ iten.taskFiledValue }}：</div>
                  <div class="desc-value">
                    {{ item.wmTaskContent[iten.taskFiledKey] || '--' }}
                  </div>
                </template>
                <!-- 日期范围 -->
                <template v-if="iten.taskFiledType == 'datatimerange'">
                  <div class="title-value">{{ iten.taskFiledValue }}：</div>
                  <div class="desc-value">
                    {{ item.wmTaskContent[iten.taskFiledKey] }}
                  </div>
                </template>
                <!-- 签名 -->
                <div v-if="item.taskFiledType == 'sign'" class="divline" />
                <template v-if="iten.taskFiledType == 'sign'">
                  <div class="upload-field">
                    <div class="field-text" :class="{required: iten.isMustfill == '1'}">{{ iten.taskFiledValue }}：</div>
                    <!-- 上传组件 -->
                    <div class="img-box">
                      <el-image
                        :key="index"
                        class="img-iten"
                        fit="fill"
                        :src="baseUrl + item.wmTaskContent[iten.taskFiledKey]"
                        :preview-src-list="getPreviewList([baseUrl + item.wmTaskContent[iten.taskFiledKey]], 0)"
                      >
                      </el-image>
                    </div>
                  </div>
                </template>
                <!-- 图片上传 -->
                <div v-if="iten.taskFiledType == 'img'" class="divline"></div>
                <template v-if="iten.taskFiledType == 'img'">
                  <div class="upload-field">
                    <div class="field-text" :class="{required: iten.isMustfill == '1'}">
                      {{ iten.taskFiledValue }}：
                      <!-- {{ getImgList(item.wmTaskContent[iten.taskFiledKey], iten) }} -->
                    </div>
                    <!-- 上传组件 -->
                    <div class="img-box" v-if="iten.imgList">
                      <div v-for="(iiten, index) in iten.imgList" :key="index" class="img-box-content">
                        <span class="type">{{ iiten.type }}</span>
                        <img :src="iiten.url" @click="viewImgFn(iiten.url)" class="img-iten" alt="" />
                      </div>
                    </div>
                  </div>
                </template>
                <!-- 文件类型 -->
                <template v-if="iten.taskFiledType === 'fileurl'">
                  <div class="upload-field">
                    <div class="field-text" :class="{required: iten.isMustfill == '1'}">
                      {{ iten.taskFiledValue }}：
                      {{ getFileList(item.wmTaskContent[iten.taskFiledKey], iten) }}
                    </div>
                    <div v-if="iten.fileList" class="pl60 pr60">
                      <!-- 图片文件 -->
                      <div class="img-box">
                        <template v-for="(iItem, index) in iten.fileList">
                          <el-image
                            v-if="imgTypeList.includes(iItem.url.split('.')[1])"
                            :key="index"
                            class="img-item"
                            :src="iItem.url"
                            :preview-src-list="getPreviewList(iten.fileList.map(ele => ele.url), index)"
                          >
                          </el-image>
                        </template>
                      </div>
                      <!-- 其他文件 -->
                      <div class="file-box">
                        <template v-for="(iItem, index) in iten.fileList">
                          <div v-if="!imgTypeList.includes(iItem.url.split('.')[1])" :key="index" class="df_sb file-item">
                            <span>{{ iItem.fileName }}</span>
                            <span @click="downloadFn(iItem)">下载</span>
                          </div>
                        </template>
                      </div>
                    </div>
                  </div>
                </template>
                <!-- 金额 -->
                <template v-if="iten.taskFiledType == 'money'">
                  <div class="title-value">{{ iten.taskFiledValue }}：</div>
                  <div class="desc-value">
                    {{ item.wmTaskContent[iten.taskFiledKey] || '--' }}
                  </div>
                </template>
                <!-- 数字 -->
                <template v-if="iten.taskFiledType == 'number'">
                  <div class="title-value">{{ iten.taskFiledValue }}：</div>
                  <div class="desc-value">
                    {{ item.wmTaskContent[iten.taskFiledKey] || '--' }}
                  </div>
                </template>
                <!-- 长文本 -->
                <template v-if="iten.taskFiledType == 'longtext'">
                  <div class="longtext-box">
                    <div class="field-text" :class="{required: iten.isMustfill == '1'}">{{ iten.taskFiledValue }}：</div>
                    <textarea class="textarea-box" :disabled="true" :value="item.wmTaskContent[iten.taskFiledKey] || '--'" :maxlength="iten.taskFiledMaxsize" />
                  </div>
                </template>
              </div>
            </div>
          </template>
          <template>
            <div class="reason" v-if="item.supervisionMessage">
              <div class="reason-list">
                <span>监督员监督结果</span>
                <div class="text">{{ item.supervisionMessage }}</div>
              </div>
            </div>
          </template>
          <template>
            <div class="reason" v-if="item.adviceMessages && item.adviceMessages.length">
              <div class="reason-list" v-for="(iten, indey) in item.adviceMessages" :key="indey">
                <div class="text">{{ iten }}</div>
              </div>
            </div>
          </template>

          <template v-if="!IS_FWS && type">
            <div class="reason">
              <div class="field-text">监督结果</div>
              <el-input type="textarea" v-model="item.submitRemark"></el-input>
            </div>
          </template>

          <div class="btns" v-if="!IS_FWS && type">
            <el-button class="btn" type="danger" @click="passClick(index, false, item.id, item)">不通过</el-button>
            <el-button class="btn" type="primary" @click="passClick(index, true, item.id, item)">通过</el-button>
          </div>
        </el-card>
      </div>
      <template v-else>
        <div class="empty">
          <el-empty description="无查找结果数据"></el-empty>
        </div>
      </template>
    </div>
    <!-- 批量审核弹窗 -->
    <el-dialog title="批量审核" :visible.sync="dialogVisible" width="45%" center :before-close="handleClose">
      <el-form ref="allFormRef" :model="taskForm" label-width="120px" :rules="rules">
        <el-form-item label="审批意见:" prop="supervision" class="formitem-box">
          <el-radio-group v-model="taskForm.supervision">
            <el-radio :label="true">通过</el-radio>
            <el-radio :label="false">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="意见说明:"
          prop="remarks"
          class="formitem-box"
          :rules="[
            {
              required: taskForm.supervision == false,
              message: '请输入审批说明',
              trigger: 'blur'
            }
          ]"
        >
          <el-input type="textarea" v-model="taskForm.remarks"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="sureBtn">确 定</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
import {supervisionTaskListApi, supervisionTaskCreateApi, supervisionCreateBatchApi} from '@/api/monitor.js';
import {getTaskList} from '@/api/assignPoints/currency/taskAudit';
import provinces from '@/util/lib/province';
import citys from '@/util/lib/city';
import areas from '@/util/lib/area';
import QRCode from 'qrcode';
import request from '@/router/axios';
import ElImageViewer from 'element-ui/packages/image/src/image-viewer';
import {mapGetters} from 'vuex';
import ElQuarterPicker from '@/components/ElQuarterPicker/index';
import {getDictType} from '@/api/common';
export default {
  components: {ElImageViewer, ElQuarterPicker},
  data() {
    return {
      type: 0,
      hasMap: false,
      mapShow: true,
      taskList: [],
      baseUrl: process.env.VUE_APP_URL,
      list: [],
      mahNameList: [],
      checkedIds: [],
      mapIds: [],
      maps: {},
      column1Height: 400,
      column2Height: 400,
      imgTypeList: ['jpeg', 'jpg', 'png', 'git', 'bmp'], // 能查看的文件类型
      showViewer: false,
      viewerList: [],
      IS_FWS: false,
      page: {
        total: 0,
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      form: {
        taskId: '',
        taskNumber: '',
        taskTypeId: '',
        pkgName: '',
        pkgPeriod: [],
        mahName: '',
        memberName: ''
      },
      monthrange: '',
      allCheck: false,
      checkedIds: [],
      dialogVisible: false,
      taskForm: {
        supervision: null,
        remarks: ''
      },
      rules: {
        supervision: [{required: true, message: '请选择审批意见', trigger: 'change'}]
      }
    };
  },
  computed: {
    ...mapGetters(['userInfo', 'roles'])
  },
  async created() {
    this.type = this.$route.query.type == 0;

    await this.getTaskList();
    this.getList();
  },
  beforeDestroy() {
    this.mapShow = false;
  },
  mounted() {
    if (this.userInfo.roles.includes(37)) {
      this.IS_FWS = true;
    }
    document.querySelector('.basic').addEventListener('scroll', this.handleScroll);
    document.addEventListener('click', this.imgClose);
    let timer = setInterval(() => {
      if (this.mapIds.length) {
        clearInterval(timer);
        const maps = {};
        this.mapIds.forEach(info => {
          const observer = new IntersectionObserver(entries => {
            entries.forEach(entry => {
              const containerId = entry.target.id;
              if (entry.isIntersecting) {
                if (!maps[containerId]) {
                  maps[containerId] = this.init(info.id, info.item);
                }
              } else {
                if (maps[containerId]) {
                  maps[containerId].destroy && maps[containerId].destroy();
                  maps[containerId].setMap && maps[containerId].setMap(null);
                  delete maps[containerId];
                }
              }
            });
          });
          observer.observe(document.getElementById(info.id));
        });
      }
    }, 400);
    setTimeout(() => {
      if (timer && !this.mapIds.length) clearInterval(timer);
    }, 10000);
  },
  destroyed() {
    document.removeEventListener('click', this.imgClose);
    window.removeEventListener('scroll', this.handleScroll);
  },

  methods: {
    allClick(val) {
      this.checkedIds = [];
      if (val) {
        this.checkedIds = [];
        this.list.forEach(item => {
          item.checked = true;
          this.checkedIds.push(item.id);
        });
      } else {
        this.checkedIds = [];
        this.allCheck = false;
        this.list.forEach(item => {
          item.checked = false;
        });
      }
    },
    allPassClick() {
      if (!this.checkedIds.length) {
        return this.$message.info('请选择待审核数据');
      }
      this.dialogVisible = true;
    },
    itemChecked(val, id, score) {
      if (val) {
        this.checkedIds.push(id);
      } else {
        let index = this.checkedIds.findIndex(item => item === id);
        this.checkedIds.splice(index, 1);
      }
    },
    handleClose() {
      this.taskForm = {
        supervision: null,
        remarks: ''
      };
      this.dialogVisible = false;
    },
    sureBtn() {
      this.$refs.allFormRef.validate(valid => {
        if (valid) {
          let args = {
            supervisionIds: this.checkedIds,
            supervision: this.taskForm.supervision,
            remarks: this.taskForm.remarks
          };
          supervisionCreateBatchApi(args)
            .then(res => {
              console.log('res', res);
              if (res.data.code === 0) {
                this.$message.success('批量审核成功');
                this.list.forEach(item => {
                  if (item.checked) {
                    item.show = false;
                    this.column1Height = 400;
                    this.column2Height = 400;
                    this.calculateItemHeights();
                  }
                });
                this.handleClose();
              }
            })
            .catch(() => {
              this.tableLoading = false;
            });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    monthrangeChange(e) {
      if (e) {
        let arr = this.getQuarterRange(e);
        this.form.pkgPeriod = arr;
      } else {
        this.monthrange = '';
        this.form.pkgPeriod = [];
      }
    },
    getQuarterRange(dateString) {
      const [year, quarterCode] = dateString.split('-').map(Number);
      let startMonth, endMonth, endDay;
      switch (quarterCode) {
        case 1: // Q1
          startMonth = 1;
          endMonth = 3;
          endDay = 31;
          break;
        case 2: // Q2
          startMonth = 4;
          endMonth = 6;
          endDay = 30;
          break;
        case 3: // Q3
          startMonth = 7;
          endMonth = 9;
          endDay = 30;
          break;
        case 4: // Q4
          startMonth = 10;
          endMonth = 12;
          endDay = 31;
          break;
        default:
          throw new Error('Invalid quarter code');
      }
      const startDate = `${year}-${String(startMonth).padStart(2, '0')}-01`;
      const endDate = `${year}-${String(endMonth).padStart(2, '0')}-${endDay}`;
      return [startDate, endDate];
    },
    onSubmit() {
      this.page = {
        total: 0,
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      };
      this.list = [];
      this.getList();
    },
    closeViewer() {
      this.showViewer = false;
    },
    viewImgFn(url) {
      this.viewerList = [url];
      this.showViewer = true;
    },
    getUrl(url) {
      return `${process.env.VUE_APP_URL}${url}`;
    },
    imgClose(e) {
      if (e.target.className == 'el-image-viewer__mask') {
        let close = document.querySelector('.el-icon-circle-close');
        close.click();
      }
    },
    backPage() {
      this.$router.$avueRouter.closeTag();
      this.$router.back();
    },
    calculateItemHeights() {
      this.list.forEach(item => {
        if (item.show) {
          let className = '.cls' + item.id + ' .el-card__body';
          let element = document.querySelector(className);
          let top = 0;
          let left = 0;
          item.height = element.clientHeight;

          if (this.column1Height <= this.column2Height) {
            top = this.column1Height;
            this.column1Height += element.clientHeight + 20;
            left = '3%';
          } else {
            top = this.column2Height;
            this.column2Height += element.clientHeight + 20;
            left = '51%';
          }
          item.top = top + 'px';
          item.left = left;
        }
      });
      this.$forceUpdate();
    },
    async search() {
      await this.getList();
      if (this.list.length) {
        this.column1Height = 400;
        this.column2Height = 400;
        this.calculateItemHeights();
      }
    },
    resetClick() {
      this.form.taskTypeId = '';
    },

    async getTaskList() {
      let res;
      res = await getTaskList(this.$route.query.deptId, this.$route.query.taskStatus == '2' ? '2' : '');
      this.taskList = res.data.data;
      getDictType({type: 'mah_name'}).then(res => {
        this.mahNameList = res.data.data;
        console.log('res', res);
      });
    },

    getName(taskType) {
      let curr = this.taskList.find(item => item.id == taskType);
      return curr.taskTypeName;
    },
    handleScroll() {
      const basicElement = document.querySelector('.basic');
      const scrollTop = basicElement.scrollTop; // 获取滚动条高度（对于 .basic 元素）
      const clientHeight = basicElement.clientHeight; // 可视区域高度
      const scrollHeight = basicElement.scrollHeight; // 文档总高度
      // 判断是否滚动到底部
      if (scrollTop + clientHeight >= scrollHeight - 1) {
        this.onScrollToBottom(); // 调用滚动到底部的处理逻辑
      }
    },
    onScrollToBottom() {
      // 处理滚动到底部的业务逻辑
      if (this.list.length < this.page.total) {
        this.page.currentPage += 1;
        this.getList(); // 示例：加载更多数据
      }
    },
    restFn() {
      this.$refs.formRef.resetFields();
      this.monthrange = '';
      this.form.pkgPeriod = [];
    },
    async getList() {
      console.log(' this.from', this.form);

      let res;
      let obj = Object.assign(
        {
          deptId: this.$route.query.deptId,
          current: this.page.currentPage,
          size: this.page.pageSize,
          review: !this.type
        },
        this.form
      );

      res = await supervisionTaskListApi(obj);

      this.page.total = res.data.data.total;
      let list = this.list.concat(res.data.data.records);
      await list.forEach(async item => {
        if (item.config && item.config.length != 0) {
          item.config.forEach(iten => {
            iten.taskFiledType = iten.taskFiledType.trim();
            if (iten.taskFiledType == 'img') {
              this.getImgList(item.wmTaskContent[iten.taskFiledKey], iten);
            }
          });
        }
        item.submitRemark = '';
        item.checked = false;
        item.show = true;
        if (['7', '8', '9', '10', '11'].includes(item.taskType)) {
          let type = null;
          if (item.taskType == '9' || item.taskType == '10') {
            type = 'article';
          }
          let shareUrl = `${process.env.VUE_APP_URL}/h5/#/pages/artile/detail?type=${type}&id=${item.shareId}`;
          const canvas = document.createElement('canvas');
          QRCode.toDataURL(canvas, shareUrl, {
            width: 400, // 二维码宽度
            height: 400 // 二维码高度
          }).then(url => {
            item.ercodeUrl = url;
          });

          this.$forceUpdate();
        }
      });
      this.list = list;
      if (this.list.length) {
        this.column1Height = 400;
        this.column2Height = 400;
        this.$nextTick(() => {
          this.calculateItemHeights();
        });
      }
      this.checkedIds = [];
      this.allPoints = 0;
      this.allCheck = false;

      for (let val of this.list) {
        if (!val.config) continue;
        for (let item of val.config) {
          if (this.getMapShow(item)) {
            let obj = {
              id: val.id,
              item: val
            };
            this.mapIds.push(obj);
          }
        }
      }
    },
    getDesc(item, data) {
      const arr = ['51', '52', '53'];
      // 拜访类服务
      if (arr.includes(item.taskTypeId) && item.taskFiledKey === 'temp24') {
        return data.wmTaskContent['temp24label'];
      }
      let value = data.wmTaskContent[item.taskFiledKey];
      if (item.taskFiledKey === 'temp12') {
        // 推广产品
        return value;
      }
      if (item.taskFiledKey == 'temp32') {
        return value;
      }
      let itemList = data.dict[item.dictGroupName] || [];
      let resItem = {};
      // 如果是库存调查 && 调查类型字段
      if (data.taskType == 14 && item.taskFiledKey == 'temp3') {
        let resStr = '';
        if (!value) return '--';
        let dArr = value.split(',');
        let descName = '';
        let descObj = {};
        dArr.forEach(dItem => {
          // 查找对应医院
          if (data.dict.hospital_service && data.dict.hospital_service.length > 0) {
            descObj = data.dict.hospital_service.find(hItem => {
              return dItem == hItem.value;
            });
          }
          if (!descObj) {
            // 查找对应公司
            descObj = data.dict.distribution_service.find(hItem => {
              return dItem == hItem.value;
            });
          }
          if (descName) {
            descName += ',' + descObj.label;
          } else {
            descName = descObj.label;
          }
        });
        return descName;
      }
      if (item.taskFiledKey == 'temp1') {
        return this.getTemp1Desc(item);
      }
      //                            并且不是药店调查
      if (item.dictGroupName && item.dictGroupName != 'ent_pharmacy1') {
        let resStr = '';
        if (!value) return '--';
        let vArr = value.split(',');
        vArr.forEach(vItem => {
          resItem = itemList.find(lItem => {
            return lItem.value == value;
          });
          if (resItem) {
            if (resStr) {
              resStr += ',' + resItem.label;
            } else {
              resStr = resItem.label;
            }
          } else {
            resStr = '--';
          }
        });
        return resStr;
      } else {
        // 如果是药店调查  并  为 药店的名字 的 key
        if (item.taskTypeId == 18 && item.taskFiledKey == 'temp3') {
          return data.wmTaskContent[item.taskFiledKey];
        } else {
          return item;
        }
      }
    },
    getAddress(item, data) {
      if (item.taskFiledType == 'area') {
        let e = data.wmTaskContent[item.taskFiledKey];
        if (!e) return '--';
        let arr = e.split(',');
        let provincesName = '';
        let provincesIndex = '';
        let cityName = '';
        let cityIndex = '';
        let areasName = '';
        // 如果为数字，方形，不为数组则展示
        var n = parseInt(arr[0]);
        // 如果不为数字，则返回
        if (isNaN(n)) {
          return arr[0];
        }
        if (arr[0]) {
          provinces.map((v, k) => {
            if (v.value + '0000' == arr[0]) {
              provincesName = v.label;
              provincesIndex = k;
            }
          });
        }
        if (arr[1]) {
          citys[provincesIndex].map((v, k) => {
            if (v.value + '00' == arr[1]) {
              cityName = v.label;
              cityIndex = k;
            }
          });
        }
        if (arr[2]) {
          areas[provincesIndex][cityIndex].map((v, k) => {
            if (v.value == arr[2]) {
              areasName = v.label;
            }
          });
        }
        return `${provincesName}-${cityName}-${areasName}`;
      }
    },
    getMapShow(item) {
      if (item.taskTypeId == '16' && item.taskFiledKey == 'temp4') {
        return true;
      }
      if (item.taskTypeId == '18' && item.taskFiledKey == 'temp4') {
        return true;
      }
      if ((item.taskTypeId == '30' || item.taskTypeId == '15') && item.taskFiledKey == 'temp16') {
        return true;
      }
      return false;
    },
    getPreviewList(imgList, index) {
      // 解决el-image大图预览定位图片不准确的问题
      return imgList.slice(index).concat(imgList.slice(0, index));
    },
    getImgList(urlStr, item) {
      if (item.taskFiledType != 'img') return '';
      if (!urlStr) return '';
      let uArr = urlStr.split(',');
      if (!uArr) return '';
      let imgList = [];
      let previewList = [];
      uArr.forEach(uItem => {
        let type = '无 ';
        if (uItem.includes(';1')) {
          type = '拍照';
          uItem = uItem.replace(';1', '');
        }
        if (uItem.includes(';2')) {
          type = '相册';
          uItem = uItem.replace(';2', '');
        }
        imgList.push({
          type,
          url: process.env.VUE_APP_URL + uItem
        });
        previewList.push(process.env.VUE_APP_URL + uItem);
      });
      item.imgList = imgList;
      item.previewList = previewList;
      return '';
    },
    // 得出文件 jsonStr: temp字符串
    getFileList(jsonStr, item) {
      if (item.taskFiledType !== 'fileurl') return '';
      if (!jsonStr) return '';
      const parseFileList = JSON.parse(jsonStr);
      if (!parseFileList) return '';
      let fileList = [];
      parseFileList.forEach(fileItem => {
        fileList.push({
          fileName: fileItem.fileName,
          url: process.env.VUE_APP_URL + fileItem.url
        });
      });
      item.fileList = parseFileList;
      return '';
    },
    // 下载文件
    downloadFn(item) {
      request({
        url: item.url,
        method: 'get',
        responseType: 'blob'
      }).then(response => {
        // 处理返回的文件流
        const blob = response.data;
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = item.fileName;
        document.body.appendChild(link);
        link.click();
        window.setTimeout(function() {
          URL.revokeObjectURL(blob);
          document.body.removeChild(link);
        }, 0);
      });
    },
    init(id, item) {
      if (!document.getElementById(id)) return;
      //定义地图中心点坐标
      var center = new TMap.LatLng(22.547931568083015, 114.1306221485138);
      //定义map变量，调用 TMap.Map() 构造函数创建地图
      const map = new TMap.Map(document.getElementById(id), {
        center: center, //设置地图中心点坐标
        zoom: 16, //设置地图缩放级别
        viewMode: '2D' // 可选 2D 3D
      });
      // this.mapInstance.push(map)
      // 新建一个正逆地址解析类
      const geocoder = new TMap.service.Geocoder();
      //初始化marker图层
      const markerLayer = new TMap.MultiMarker({
        id: 'marker-layer',
        map: map
      });
      // this.map.on("click",this.clickHandler)
      this.getAddressKeyword(item, map, geocoder, markerLayer);
      this.maps[id] = map;
      return map;
    },
    removeMarker(markerLayer) {
      const markList = markerLayer.getGeometries();
      if (markerLayer && markList.length > 0) {
        markerLayer.remove(markList[0].id);
      }
    },
    getAddressKeyword(item, map, geocoder, markerLayer) {
      let address = this.getMapAddress(item);
      const convert = () => {
        // 将给定的地址转换为坐标位置
        geocoder.getLocation({address}).then(result => {
          this.removeMarker(markerLayer);
          this.$nextTick(() => {
            markerLayer.updateGeometries([
              {
                position: result.result.location // 将得到的坐标位置用点标记标注在地图上
              }
            ]);
          });
          map.setCenter(result.result.location);
        });
      };
      convert();
    },
    getMapAddress(item) {
      let address;
      // 商业公司信息收集
      if (item.taskType == '16') {
        address = item.wmTaskContent['temp4'] + item.wmTaskContent['temp3'];
      }
      // 药店调查
      if (item.taskType == '18') {
        let str = item.wmTaskContent['temp7'].replaceAll('-', '');
        address = str + item.wmTaskContent['temp4'] + item.wmTaskContent['temp3'];
      }
      // 医院信息收集
      if (item.taskType == '30' || item.taskType == '15') {
        let str = item.wmTaskContent['temp4'].replaceAll('-', '');
        address = str + item.wmTaskContent['temp16'] + item.wmTaskContent['temp3'];
      }
      return address;
    },
    async passClick(index, type, id, item) {
      let remarks;
      if (!type && !item.submitRemark) {
        return this.$message.info('请填写异常原因');
      }
      if (item.submitRemark) {
        remarks = item.submitRemark;
      }

      remarks = item.submitRemark ? item.submitRemark : '监督无异常';

      let obj = {
        taskId: id,
        pkgId: item.taskInfo.scorePackageId,
        supervision: type,
        remarks: remarks
      };
      const res = await supervisionTaskCreateApi(obj);
      this.list[index].show = false;
      this.column1Height = 400;
      this.column2Height = 400;
      this.calculateItemHeights();
      if (this.maps[id]) {
        this.maps[id].destroy && this.maps[id].destroy();
        this.maps[id].setMap && this.maps[id].setMap(null);
      }
      this.$forceUpdate();
    }
  }
};
</script>

<style lang="scss" scoped>
.basic {
  height: calc(100vh - 130px);
  padding-bottom: 30px;
  overflow: auto;
  position: relative;
  ::v-deep .el-card__body {
    background-color: #f7f7f7;
  }
}
.search {
  width: 100%;
  margin-top: 20px;
  .search-btns {
    display: flex;
    justify-content: space-between;
  }
}
.content {
  margin-top: 20px;
  .head {
    .clear {
      cursor: pointer;
    }
    .btn {
      margin: 0 20px;
    }
  }
  .list {
    margin-top: 20px;
    padding: 0 20px;

    .item {
      position: absolute;
      width: 45%;
      min-height: 50px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      ::v-deep .el-card__body {
        background-color: #fff;
      }

      .task-type-name {
        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: 1px solid #d7d6d5;
        line-height: 30px;
        margin-bottom: 5px;
      }
      .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;
        }
        .longtext-box {
          .textarea-box {
            margin-top: 5px !important;
            width: 100%;
            padding: 3px;
          }
        }
        .divline {
          width: 100%;
          height: 5px;
          background-color: #e9e9e9;
          margin-bottom: 5px;
        }
        .img-iten {
          height: 60px;
          margin-right: 5px;
          width: 50px;
          cursor: pointer;
        }
      }
      .visit-list {
        .visit-title {
          color: #2689ff;
          padding-bottom: 5px;
        }
        .detail-info {
          ul {
            list-style: none;
            li {
              span {
                min-width: 80px;
              }
              display: flex;
              margin-bottom: 5px;
            }
          }
        }
      }
      .btns {
        padding: 0 20px;
        padding-top: 5px;
        display: flex;
        justify-content: space-between;
        .btn {
          width: 48%;
        }
      }
    }
  }
}
.reason {
  padding: 0 10px 5px;
  .reason-list {
    margin-bottom: 6px;
    .text {
      margin: 5px 0;
      font-size: 14px;
      color: #e93d3d;
    }
  }
}
.empty {
  margin-top: 10px;
}
.form {
  margin-top: 10px;
}
.all-btn {
  margin-right: 10px;
}
</style>
