<template>
  <div class="d-box">
    <page-model
      v-if="picaWechat != 'wechat'"
      ref="PageModel"
      :header-info="headerInfo"
    />
    <div class="title" />
    <div class="detail-box">
      <div class="status">
        <img
          v-if="dataDetail.status == 5"
          src="https://files.yunqueyi.com/image/png/common/20220817141150961.png"
          alt="success"
        >
        <img
          v-else
          src="https://files.yunqueyi.com/image/png/common/20220816135250298.png"
          alt="success"
        >
        <div>{{ dataDetail.status | statusFilter }}</div>
      </div>
      <div
        class="content"
      >
        <div
          v-if="![0,1,3,5].includes(dataDetail.status)"
          class="p30"
        >
          <div
            v-if="[2, 21, 22, 25, 27].includes(Number(dataDetail.status|| 0))"
            class="flex-wrap"
          >
            <div>
              预期报告生成时间:
            </div>
            <div class=" fc-blue">
              {{
                dataDetail.detectChargeType == 10
                  ? dataDetail.reportExpectDate
                  : dataDetail.reportExpectDateHigh
              }}
            </div>
          </div>
          <div
            v-if="dataDetail.status == 3"
            class="flex-wrap"
          >
            <div>
              报告生成时间
            </div>
            <div class="fc-blue">
              {{ dataDetail.reportDate }}
            </div>
          </div>
        </div>
        <div class="flow">
          <div class="f-list">
            <div
              v-for="(item, index) in dataList"
              :key="index"
              class="express-step"
              :class="{
                hideCircle: item.completed,
                last: index == dataList.length - 1,
              }"
            >
              <div
                v-if="item.completed"
                class="express-step-icon"
              >
                <img
                  class="step-pg"
                  :src="item.status == 5 ? 'https://files.yunqueyi.com/image/png/common/20220817141140460.png' : 'https://files.yunqueyi.com/image/png/common/2022081612011851.png'"
                >
              </div>
              <div
                v-else
                class="express-step-icon"
              />
              <div
                class="express-step-msg"
              >
                <div class="step-title">
                  <p>
                    {{ item.nodeName }}
                  </p>
                </div>
                <div
                  class="step-time"
                >
                  {{ item.nodeTime ? item.nodeTime : item.completed ? '暂无数据' : '未开始' }}
                </div>
              </div>
            </div>
          </div>
          <p
            v-if="dataDetail.status == 5"
            class="tips"
          >
            温馨提示:可联系医生重新采样
          </p>
        </div>
      </div>
    </div>
    <div class="detail-box pb60">
      <div class="content">
        <div class="info">
          <div class="list">
            <p class="l-left">
              受检人:
            </p>
            <p class="l-right">
              <span>{{ dataDetail.patientName || '--' }}</span><span>{{ dataDetail.sex | sexFilter }}</span><span class="font">{{
                dataDetail.ageMonth
                  ? dataDetail.ageMonth + '月'
                  : dataDetail.patientAge + '岁'
              }}</span>
            </p>
          </div>
          <div class="list">
            <p class="l-left">
              检测项目:
            </p>
            <p class="l-right">
              {{ dataDetail.checkName || '--' }}
            </p>
          </div>
          <div class="list">
            <p class="l-left">
              检测编号:
            </p>
            <p class="l-right">
              {{ dataDetail.recordNo || '--' }}
            </p>
          </div>
          <div class="list">
            <div class="l-left">
              条形码:
            </div>
            <div class="l-right">
              {{ dataDetail.sampleCode || '--' }}
              <div
                class="l-copy"
                @click="copyText(dataDetail.sampleCode)"
              >
                复制
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div
      v-if="[3].includes(dataDetail.status)"
      class="submit-container multi-sub-wrap"
    >
      <div
        class="submit-button submit-button-empty"
        @click="bottomBtnFun(dataDetail.reportUrl)"
      >
        查看报告
      </div>
      <div
        v-if="picaWechat == 'wechat' && (Number(dataDetail.reportExplain) == 0)"
        class="submit-button submit-button-empty"
      >
        <wx-open-launch-weapp
          style="position: absolute; top: 0; left: 0; width: 100%; height: 100%"
          :username="openWebAppConfig.username"
          :path="openWebAppConfig.path"
          :extra-data="openWebAppConfig.extraData"
          :env-version="envVersion"
        >
          <script type="text/wxtag-template">
            <style>.btn {position:absolute; top: 0; color: #ffffff;text-align: center;line-height: 40px; left: 0; width:100%; height: 100%;}</style> <div class="btn">{{ openWebAppBtnName }}</div>
          </script>
        </wx-open-launch-weapp>
      </div>
      <div
        v-else
        class="submit-button submit-button-empty"
        @click="getJumpToWebapp"
      >
        {{ openWebAppBtnName }}
      </div>

      <div
        v-if="picaWechat == 'wechat' && dataDetail.reimburseFlag"
        class="submit-button submit-button-empty"
      >
        <div
          class="btn-label"
          :style="{ background: mapColor(dataDetail.reimburseStatus) }"
        >
          {{ dataDetail.reimburseStatusStr }}
        </div>
        <wx-open-launch-weapp
          style="position: absolute; top: 0; left: 0; width: 100%; height: 100%"
          :username="openWebAppConfigPositive.username"
          :path="openWebAppConfigPositive.path"
          :env-version="envVersion"
        >
          <script type="text/wxtag-template">
            <style>.btn {position:absolute; top: 0; color: #ffffff;text-align: center;line-height: 40px; left: 0; width:100%; height: 100%;}</style> <div class="btn">阳性报销</div>
          </script>
        </wx-open-launch-weapp>
      </div>
      <div
        v-if="picaWechat != 'wechat' && dataDetail.reimburseFlag"
        class="submit-button submit-button-empty"
        @click="getJumpToWebapp2"
      >
        <div
          class="btn-label"
          :style="{ background: mapColor(dataDetail.reimburseStatus) }"
        >
          {{ dataDetail.reimburseStatusStr }}
        </div>
        阳性报销
      </div>
    </div>
    <div v-else class="submit-container multi-sub-wrap">
      <div
        class="submit-button2"
        @click="getReport()"
      >
        获取报告
      </div>
    </div>
  </div>
</template>
<script>
import { getDetectionDetailProces, getJumpToWebapp, detectionRecordInfo } from '@/api/detection';
const { VUE_APP_ENV } = process.env;
import axios from 'axios';
import {getDetailByYunOrderNo} from '@/api/appoint';
// 0待完善信息、1待采样、2已采样、21已送检、22快递已签收、 25实验室已收样、 27已上机、 3已完成、5样本失效、 6待支付
export default {
  filters: {
    sexFilter(val) {
      const str = val == 2 ? '女' : '男';
      return str;
    },
    statusFilter(type) {
      const obj = {
        0: '待完善信息',
        1: '待采样',
        2: '已采样',
        21: '已送检',
        25: '已接收',
        27: '已上机',
        22: '已签收',
        3: '已完成',
        5: '样本异常',
        6: '待支付',

      };
      return obj[type];
    },
    showBtnTextFilter(status) {
      const obj = {
        1: '绑定条形码',
        3: '查看报告',
      };
      return obj[status] || '';
    },
  },
  data() {
    return {
      envVersion: VUE_APP_ENV == 'production' ? 'release' : 'trial',
      picaWechat:window._picaWechat,
      status: '',
      headerInfo: {
        title: '检测详情',
        isBlack: true,
        backMethod: 'web',
        style: 'backgroundColor:#ffffff;zIndex:100;',
        background: '',
      },
      detectionRecordId: '',
      dataDetail: {},
      dataList: [],
      openWebAppConfig:{
        username:'gh_e92f58174364', // 小程序唯一username  1.gh_80d54796f2d5 云鹊助手 2. gh_e92f58174364 云鹊健康
        path:'pagesInsurance/all-entrance/index', // 打开页面
        extraData: JSON.stringify({})
      },
      openWebAppConfigPositive:{
        username:'gh_e92f58174364', // 小程序唯一username  1.gh_80d54796f2d5 云鹊助手 2. gh_e92f58174364 云鹊健康
        path:'pagesInsurance/all-entrance/index', // 打开页面
        extraData: JSON.stringify({})
      },
      openWebAppBtnName: '报告解读',
      yunOrderNo: '',
      action_code: ''
    };
  },
  created() {
    const {detectionRecordId, yunOrderNo} = this.$route.query;
    this.detectionRecordId = detectionRecordId;
    this.yunOrderNo = yunOrderNo;
    this.init();
  },
  mounted() {
    console.log('--VUE_APP_ENV', VUE_APP_ENV);
    this.$sendBuriedData({
      action: 'ACTION_WEB_AFTER',
      component_tag: '7802848#0#0#检测详情页面',
      web_data:{yunOrderNo: this.yunOrderNo},
    });
  },
  methods: {
    init() {
      const that = this;
      const ed = {
        channelSource: 'insurance_channel',
        targetPath: 'pagesInsurance/all-entrance/index',
        query: {yunOrderNo: this.yunOrderNo},
      };
      const o = {
        detectionRecordId: this.detectionRecordId,
        detectionKind: 0
      };
      console.log('----detectionRecordInfo', o);
      let jump_path = `pagesInsurance/all-entrance/index?yunOrderNo=${this.yunOrderNo}&channelSource=channelSource`;
      detectionRecordInfo(o, 0).then((res) => {
        if (res.code === '000000') {
          this.dataDetail = res.data;
          this.getDetailProces();
          const {inquiryStatus} = res.data;
          let n = '';
          if(inquiryStatus == 0) {
            this.action_code = 'bottomBtnFun2';
            jump_path = jump_path + '&action_code=bottomBtnFun2';
            n = '报告解读';
          }else if([4, 6].includes(inquiryStatus)) {
            n = '查看专家建议';
            this.action_code = 'getAdvice';
            jump_path = jump_path + '&action_code=getAdvice';
            // ed.targetPath = '/pages/health/detection-detail/index';
          }else {
            n = '已预约待咨询';
            this.action_code = 'goIm';
            jump_path = jump_path + '&action_code=goIm';
            // ed.targetPath = '/pages/consultation-im/index?initTRTC=false';
          }
          that.openWebAppConfig.extraData = JSON.stringify(ed);
          that.openWebAppBtnName = n;
          that.openWebAppConfig.path = jump_path;
          this.openWebAppConfigPositive.path = `pagesInsurance/all-entrance/index?detectionKind=0&tradeDetectionServiceRecordId=${this.dataDetail.detectionRecordId}`;
          console.log('-that.openWebAppConfig.', that.openWebAppConfig, that.openWebAppConfigPositive, that.openWebAppBtnName);
        } else {
          that.$toast(res.message);
        }
        this.$loading.hide();
      });
    },
    copyText(val) {
      const input = document.createElement('input');
      input.value = val;
      document.body.appendChild(input);
      input.select();
      input.setSelectionRange(0, input.value.length);
      document.execCommand('Copy');
      document.body.removeChild(input);
      this.$toast('已复制');
      console.log('已复制的内容：', val);
    },
    // 检测详情
    getDetailProces() {
      getDetectionDetailProces({id:this.detectionRecordId, channel: 4} ).then((res) => {
        if (res.code === '000000') {
          this.dataList = res.data || [];
        } else {
          this.$toast(res.message);
        }
      });
    },
    bottomBtnFun(u) {
      if(!u) {
        this.$toast('reportUrl--为空', u);
        return false;
      }
      const p = '/pdf-preview';
      this.$router.push(
        {
          path:  p,
          query: {
            url: u,
          },
        }
      );
    },
    getJumpToWebapp() {
      if(this.picaWechat == 'wechat') {
        return false;
      }
      const query = `channelSource=insurance_channel&yunOrderNo=${this.yunOrderNo}&action_code=${this.action_code}`;
      const p = {params:{path:'pagesInsurance/all-entrance/index', query:query}, type: 2};
      getJumpToWebapp(p).then(res => {
        console.log('--res', res);
        if(res.data) {
          window.location.href = res.data;
        }else{
          this.$toast(res.message);
        }

      });
    },
    mapStatus(inquiryStatus) {
      console.log('--mapStatus', inquiryStatus);
      const s = String(inquiryStatus);
      let m = '报告解读';
      if(s == '0') {
        m = '报告解读';
      }else if(['4', '6'].includes(s)) {
        m = '查看专家建议';
      }else{
        m = '已预约待咨询';
      }
      console.log('--mapStatus', m);
      return m;
    },
    getJumpToWebapp2() {
      if(this.picaWechat == 'wechat') {
        return false;
      }
      const query = `detectionKind=0&tradeDetectionServiceRecordId=${this.dataDetail.detectionRecordId}`;
      const p = {params:{path:'pagesInsurance/all-entrance/index', query:query}, type: 2};
      getJumpToWebapp(p).then(res => {
        console.log('--res', res);
        if(res.data) {
          window.location.href = res.data;
        }else{
          this.$toast(res.message);
        }

      });
    },
    mapColor(s) {
      // 申请状态 1：待审核，2：审核通过（待打款），3：审核驳回，4：已撤销，5：已打款
      let t = '#FF720C';
      switch (Number(s)) {
        case 1:
          t = '#00BDA5';
          break;
        case 2:
          t = '#00BDA5';
          break;
        case 3:
          t = '#FF4B33';
          break;
        case 4:
          t = '#AAAAAA';
          break;
        case 5:
          t = '#AAAAAA';
          break;
        default:
          break;
      }
      return t;
    },
    getReport() {
      this.$loading.show('报告生成中,请稍等...');
      getDetailByYunOrderNo(this.yunOrderNo).then(res => {
        console.log(res);
        const {showFlagForReport} = res.data;
        if(showFlagForReport == 1) {
          const p = {
            env: VUE_APP_ENV == 'production' ? 'prod' : 'test1',
            sample_code: this.dataDetail.sampleCode,
            res_type: 1
          };
          //
          axios.post('https://project.picahealth.com/auto_set_detection_report', p)
            .then(res => {
              console.error('请求menu接口失败error', res);
              const {errorMessage} = res.data.data;
              this.$toast(errorMessage);
              this.init();
            }).catch(error => {
            console.error('请求menu接口失败error', error);
            const {errorMessage} = error.data.data;
            this.$toast(errorMessage);
            this.init();
          });
        }else {
          this.$loading.hide();
        }
        console.log('--showFlagForReport', showFlagForReport);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
