<template>
  <div class="task-box">
    <!-- 分享的图片展示 -->
    <!--    <img v-if="showImg" mode="widthFix" class="poster-img" :src="taskInfo.shareImgUrl" />-->
    <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 == 'domain' || item.taskFiledType == 'select' || item.taskFiledType == 'tree'">
            <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">
              {{ getAddress(item) }}
            </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 v-if="getMapShow(item)">
              <div id="container" style="width:100%; height:300px"></div>
            </template>
            <!-- 用temp17存储打卡图片 -->
            <div v-if="item.taskFiledType == 'mapwithimg' && !!wmTaskContent['temp17']" class="location-img">
              <div class="field-text">位置打卡图片</div>
              <div class="img-box">
                <el-image class="img-item" :src="baseUrl + wmTaskContent['temp17']" :preview-src-list="getPreviewList([baseUrl + wmTaskContent['temp17']], 0)"> </el-image>
              </div>
            </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 == 'sign'" class="divline" style="width:100%; height: 15px;background-color:#E9E9E9;margin-bottom: 5px;"></div>
          <template v-if="item.taskFiledType == 'sign'">
            <div class="upload-field">
              <div class="field-text" :class="{required: item.isMustfill == '1'}">{{ item.taskFiledValue }}：</div>
              <!-- 上传组件 -->
              <div class="img-box">
                <el-image
                  :key="index"
                  class="img-item"
                  :src="baseUrl + wmTaskContent[item.taskFiledKey]"
                  :preview-src-list="getPreviewList([baseUrl + wmTaskContent[item.taskFiledKey]], 0)"
                >
                </el-image>
              </div>
            </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 }}：
                <!-- {{ getImgList(wmTaskContent[item.taskFiledKey], item) }} -->
              </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" lazy :src="iItem.url" :preview-src-list="getPreviewList(item.previewList, index)" />
                </div>
              </div>
            </div>
          </template>
          <!-- 文件类型 -->
          <template v-if="item.taskFiledType === 'fileurl'">
            <div class="upload-field">
              <div class="field-text" :class="{required: item.isMustfill == '1'}">
                {{ item.taskFiledValue }}：
                {{ getFileList(wmTaskContent[item.taskFiledKey], item) }}
              </div>
              <div v-if="item.fileList" class="pl60 pr60">
                <!-- 图片文件 -->
                <div class="img-box">
                  <template v-for="(iItem, index) in item.fileList">
                    <el-image
                      v-if="imgTypeList.includes(iItem.url.split('.')[1])"
                      :key="index"
                      class="img-item"
                      :src="iItem.url"
                      :preview-src-list="getPreviewList(item.fileList.map(ele => ele.url), index)"
                    >
                    </el-image>
                  </template>
                </div>
                <!-- 其他文件 -->
                <div class="file-box">
                  <template v-for="(iItem, index) in item.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="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" @input="onInput" />
            </div>
          </template>
        </div>
      </div>
    </template>
    <div style="padding:10px;font-size: 20px" v-else-if="taskTypeId == 8 || taskTypeId == 9 || taskTypeId == 10 || taskTypeId == 11">
      <div v-if="taskInfo">转发时间： {{ taskInfo.createTime || '' }}</div>
      <div>文章标题：{{ title }}</div>
      <div>获得积分：+{{ score }}</div>
      <div>备注：{{ remark }}</div>
      <div class="tc">
        <img class="ercode-icon" :src="ercodeUrl" />
      </div>
    </div>
    <div class="sign-in-box" v-if="taskTypeId == 5 || taskTypeId == 6 || taskTypeId == 33">
      <div v-for="(item, index) in signInLog" :key="index">
        <div style="color: #2689ff;padding-bottom: 20px">
          拜访记录：
        </div>
        <div>{{ item.signEntName }} {{ item.signDate }} 打卡</div>
        <template v-if="item.userSignDetail">
          <div style="color: #2689ff;padding: 20px 0">
            拜访明细：
          </div>
          <div class="detail-info">
            <ul>
              <li v-if="item.userSignDetail.drug.length > 0">
                <span>推广产品：</span>
                <p>
                  {{ item.userSignDetail.drug && item.userSignDetail.drug.join('，') }}
                </p>
              </li>

              <li
                v-if="
                  item.signEntType == '1' &&
                    item.userSignDetail &&
                    item.userSignDetail.templateType !== 'TEMPLATE2' &&
                    item.userSignDetail.detail &&
                    item.userSignDetail.detail.length > 0
                "
              >
                <span>拜访科室：</span>
                <div>
                  <div v-for="(iten, indey) in item.userSignDetail.detail" :key="indey">
                    <div>{{ iten.departmentName }}</div>
                    <el-image v-if="iten.fileUrl.length" :preview-src-list="iten.fileUrl" style="width: 100px; height: 100px" :src="getUrl(iten.fileUrl[0])"></el-image>
                  </div>
                </div>
              </li>
              <li v-if="item.signEntType == '1' && item.userSignDetail.department">
                <span>拜访科室：</span>
                <p>{{ item.userSignDetail.department }}</p>
              </li>
              <li v-if="item.userSignDetail.visitor">
                <span>拜访人员：</span>
                <p>{{ item.userSignDetail.visitor }}</p>
              </li>
              <li>
                <span>拜访目的：</span>
                <p>
                  {{ item.userSignDetail.purposeName && item.userSignDetail.purposeName.join('，') }}
                </p>
              </li>
              <li>
                <span>拜访结果：</span>
                <p>{{ item.userSignDetail.resultName }}</p>
              </li>
              <template v-if="item.userSignDetail.templateType === 'TEMPLATE2'">
                <li>
                  <span>是否针对了正确的HCP：</span>
                  <p>
                    {{ item.userSignDetail.detail[0].rightHcp ? '是' : '否' }}
                  </p>
                </li>
                <li>
                  <span>是否传递了正确的信息：</span>
                  <p>
                    {{ item.userSignDetail.detail[0].rightInfo ? '是' : '否' }}
                  </p>
                </li>
                <li>
                  <span>是否采取了正确的活动形式和频率：</span>
                  <p>
                    {{ item.userSignDetail.detail[0].rightActivity ? '是' : '否' }}
                  </p>
                </li>
              </template>
              <li>
                <span>备注：</span>
                <p>{{ item.userSignDetail.remark }}</p>
              </li>
            </ul>
          </div>
        </template>
      </div>
    </div>
  </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 {handleDown} from '@/util/util';
import request from '@/router/axios';

export default {
  name: 'index',
  data() {
    return {
      updated: false,
      address: '',
      map: null,
      markerLayer: null,
      geocoder: null,
      baseUrl: process.env.VUE_APP_URL,
      ercodeUrl: '',
      signInLog: [], // 拜访记录
      title: '',
      score: '',
      remark: '',
      showImg: false, // 是否显示只展示图片，分享用到
      taskInfo: {},
      wmTaskContent: {},
      drugObj: {}, // 选择的药企
      taskTypeId: 0, // 任务类型id
      inputLength: 0,
      cityKey: '', // 选择城市的 key
      customBtnStyle: {
        background: '#2689FF',
        color: '#ffffff'
      },
      accessToken: '',
      fileList: [], // 临时上传的url list
      timeParams: {
        year: true,
        month: true,
        day: true,
        hour: true,
        minute: true,
        second: false
      },
      showTimePicker: false, // 显示时间
      sendParams: {},
      actionFieldIndex: null, // 点击了第几个field
      actionItem: {},
      actionShow: false,
      actionList: [],
      actions: [
        {
          name: '选项'
        },
        {
          name: '选项'
        },
        {
          name: '选项',
          subname: '副文本',
          openType: 'share'
        }
      ],
      aaa: '',
      configList: [], // 配置列表
      dictList: [], //字典
      imgTypeList: ['jpeg', 'jpg', 'png', 'git', 'bmp'] // 能查看的文件类型
    };
  },
  props: {
    id: {
      type: String
    }
  },
  updated() {
    if (document.getElementById('container')) {
      if (!this.updated) {
        this.init();
      }
      this.updated = true;
    }
  },
  destroyed() {
    if (this.map) {
      this.map.destroy();
      this.map = null;
    }
  },
  methods: {
    getUrl(url) {
      return `${process.env.VUE_APP_URL}${url}`;
    },
    init() {
      //定义地图中心点坐标
      var center = new TMap.LatLng(22.547931568083015, 114.1306221485138);
      //定义map变量，调用 TMap.Map() 构造函数创建地图
      this.map = new TMap.Map(document.getElementById('container'), {
        center: center, //设置地图中心点坐标
        zoom: 16, //设置地图缩放级别
        viewMode: '2D' // 可选 2D 3D
      });
      // 新建一个正逆地址解析类
      this.geocoder = new TMap.service.Geocoder();
      //初始化marker图层
      this.markerLayer = new TMap.MultiMarker({
        id: 'marker-layer',
        map: this.map
      });
      // this.map.on("click",this.clickHandler)
      this.getAddressKeyword();
    },
    removeMarker() {
      const markList = this.markerLayer.getGeometries();
      if (this.markerLayer && markList.length > 0) {
        this.markerLayer.remove(markList[0].id);
      }
    },
    getAddressKeyword() {
      const convert = () => {
        // 将给定的地址转换为坐标位置
        const address = this.address;
        this.geocoder.getLocation({address}).then(result => {
          this.removeMarker();
          this.$nextTick(() => {
            this.markerLayer.updateGeometries([
              {
                position: result.result.location // 将得到的坐标位置用点标记标注在地图上
              }
            ]);
          });
          this.map.setCenter(result.result.location);
        });
      };
      if (this.address) {
        convert();
      }
    },

    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;
    },

    getMapAddress() {
      // 商业公司信息收集
      if (this.taskTypeId == '16') {
        let address = this.wmTaskContent['temp4'] + this.wmTaskContent['temp3'];
        this.address = address;
      }
      // 药店调查
      if (this.taskTypeId == '18') {
        let str = this.wmTaskContent['temp7'].replaceAll('-', '');
        let address = str + this.wmTaskContent['temp4'] + this.wmTaskContent['temp3'];
        this.address = address;
      }
      // 医院信息收集
      if (this.taskTypeId == '30' || this.taskTypeId == '15') {
        let str = this.wmTaskContent['temp4'].replaceAll('-', '');
        let address = str + this.wmTaskContent['temp16'] + this.wmTaskContent['temp3'];
        this.address = address;
      }
    },
    // 如果为拜访类型，那么获取拜访的列表
    async getSignInfoByTaskId(id) {
      const {data} = await taskApi.getSignInfoByTaskId({id});
      this.signInLog = data.data;
    },
    // 获取地址
    getAddress(item) {
      if (item.taskFiledType == 'area') {
        let e = this.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}`;
      }
    },
    // 获取详情
    getDesc(item) {
      const arr = ['51', '52', '53'];
      // 拜访类任务
      if (arr.includes(item.taskTypeId) && item.taskFiledKey === 'temp24') {
        return this.wmTaskContent['temp24label'];
      }

      let value = this.wmTaskContent[item.taskFiledKey];
      if (item.taskFiledKey === 'temp12') {
        // 推广产品
        return value;
      }
      if (item.taskFiledKey == 'temp32') {
        return value;
      }
      let itemList = this.dictList[item.dictGroupName] || [];
      let resItem = {};
      // 如果是库存调查 && 调查类型字段
      if (this.taskTypeId == 14 && item.taskFiledKey == 'temp3') {
        let resStr = '';
        if (!value) return '--';
        let dArr = value.split(',');
        let descName = '';
        let descObj = {};
        dArr.forEach(dItem => {
          // 查找对应医院
          if (this.dictList.hospital_service && this.dictList.hospital_service.length > 0) {
            descObj = this.dictList.hospital_service.find(hItem => {
              return dItem == hItem.value;
            });
          }
          if (!descObj) {
            // 查找对应公司
            descObj = this.dictList.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 this.wmTaskContent[item.taskFiledKey];
        } else {
          return item;
        }
      }
    },
    // temp1 特定为 服务药企
    getTemp1Desc(item) {
      let value = this.wmTaskContent[item.taskFiledKey];
      let itemList = this.dictList[item.dictGroupName];
      let resItem = {};
      let resStr = '';
      if (!value) return '--';
      let dArr = value.split(',');
      let descName = '';
      let descObj = {};
      dArr.forEach(dItem => {
        // 查找对药企
        if (this.dictList.ent_service && this.dictList.ent_service.length > 0) {
          descObj = this.dictList.ent_service.find(hItem => {
            return dItem == hItem.value;
          });
        }
        if (!descObj) {
          // 查找对应公司
          descObj = this.dictList.distribution_service.find(hItem => {
            return dItem == hItem.value;
          });
        }
        if (descName) {
          descName += ',' + descObj.label;
        } else {
          descName = descObj.label;
        }
      });
      return descName;
    },
    // 获取二维码
    async getErrCode(id, type) {
      let shareUrl = `${process.env.VUE_APP_URL}/h5/#/pages/artile/detail?type=${type}&id=${id}`;
      const res = await commonApi.getQrCodeByUrl(shareUrl);
      const data = res.data.data.data;
      this.ercodeUrl = process.env.VUE_APP_URL + data.url;
    },
    // 得出图片
    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 [imgList, previewList];
    },
    // 得出文件 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);
      });
    },
    // 获取任务详情
    async getTaskInfoById(id) {
      try {
        const res = await taskApi.getTaskInfoById(id);
        const {data} = res.data;
        this.wmTaskContent = data.wmTaskContent;
        this.taskInfo = data.taskInfo;
        this.title = data.title;
        this.score = data.score;
        this.remark = data.remark;
        this.taskTypeId = data.taskType;
        if (['15', '16', '18', '30'].includes(this.taskTypeId)) {
          // 这四种任务类型, 才调用'查询调查信息审核的任务详情接口'
          // 调用接口
          this.$emit('getSurveyTaskInfoById', id);
        }
        let shareTypeArr = this.$enum.getValueDescList('SHARE_TYPE_ENUM');
        let arr = shareTypeArr.map(item => {
          return item.value;
        });
        if (arr.includes(Number(data.taskType))) {
          if (data.taskInfo.shareImgUrl) {
            // 图片分享类型
            this.showImg = true;
          }
          // 组成文章详情，并生成二维码
          let type = null;
          if (data.taskType == 9 || data.taskType == 10) {
            // 文章
            type = 'article';
          }
          this.getErrCode(data.shareId, type); // 文章或者图片的 id
        } else {
          // 拜访类型
          // if (data.taskType == 5 || data.taskType == 6 || data.taskType == 33) {
          //   this.getSignInfoByTaskId(id);
          //   return;
          // }
          this.getTaskContentConfigByTaskTypeId(data.taskType);
        }
      } catch (e) {
        console.log(e);
      }
    },
    // 文字变化
    onInput(e) {
      this.inputLength = e.detail.cursor;
    },
    // 获取配置
    async getTaskContentConfigByTaskTypeId(value) {
      // uni.showLoading();
      this.taskTypeId = 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];
          }
        });
      } catch (e) {
        console.log(e);
      }
      this.getMapAddress();
      // uni.hideLoading();
    },
    getPreviewList(imgList, index) {
      // 解决el-image大图预览定位图片不准确的问题
      return imgList.slice(index).concat(imgList.slice(0, index));
    }
  },
  mounted() {
    this.getTaskInfoById(this.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>
