<template>
  <div class="symp-wrap symper btscroll">
    <div class="content">
      <div
        class="choose"
        v-if="chooseSymp.length>0"
      >
        <p class="quest">已选症状</p>
        <p
          class="choo-symp"
          v-for="(v,i) in chooseSymp"
        >
          <span @click="showChecked(v,i)">{{v.description || v.name}}</span>
          <span @click="deletSymp(v,i)"><img
              src="../images/del.png"
              alt=""
            ></span>
        </p>
      </div>
      <div class="label">
        <p class="quest" id="test">{{quesText}}<img
            @click="search(true)"
            class="searchImg"
            src="../images/search.png"
            alt=""
          ></p>
        <div class="showHide" ref="showHide">
          <span
            class="symp"
            v-for="(it,ind) in symp"
            :key="it.conceptId"
            @touchstart.prevent="touchstart(it,ind)"
            @touchend.prevent="touchend(it,ind)"
          >{{it.description || it.name}}</span>
        </div>
        <p class="tip" v-show="chooseSymp.length==0">长按症状按钮可显示症状解释说明 <span @click="slideToggle" v-show="slide">{{slideTxt}}</span></p>
      </div>
      <div
        class="result"
        v-if="checkText.length>0"
      >
        <p class="title"><span class="line"></span>{{nameStr}}</p>
        <div class="bgResult">
          <template v-for="(value,index) in checkText">
            <!-- 患者于时间单位前诱因出现症状，其余题目的内容； -->
            <span :key="index" v-if="index==0">{{(value.idx==1?'':'伴')+value.textP}}{{checkText.length==1?'':'，'}}</span>
            <span :key="index" v-if="index==1">{{(checkText[0].idx == 1?'伴':'')+value.textP}}{{checkText.length==2?'':'、'}}</span>
            <span :key="index" v-if="index>1">{{value.textP}}{{index == checkText.length-1?'':'、'}}</span>
          </template>
        </div>
      </div>
    </div>
    <div v-if="modluesLen>1"
      @click="toNext"
      class="footer"
    >
      <div class="nextBtn" :class="{'nofoot':chooseSymp.length==0}">下一步</div>
    </div>
    <div v-if="modluesLen==1"
      class="footer"
      @click="toNext"
    >
      <div class="nextBtn" :class="{'nofoot':chooseSymp.length==0}">预览并提交病历</div>    
    </div>
    <Toast
      :message="delText"
      :show="showToast"
      @comfirn="comfirnDel"
      @cancel="cancelDel"
    />
    <Search
      v-if="this.$store.state.searchShow"
      @search="search"
      @showDetil="showDetil"
      :age="age"
      :chooseSymp="chooseSymp"
      :sexType="sexType"
    ></Search>
    <Tiptoast :show="showExp" :data="message" @close="closeTip"/>
  </div>
</template>
<script type="text/javascript">
import api from '@utils/api.js';
import Toast from '../common/Toast.vue';
import Tiptoast from '../common/Tiptoast.vue';
import Search from './Search.vue';
import {moduleCP,setScroll,trimDots} from '@utils/tools'
import BScroll from 'better-scroll';
import $ from 'jquery';
export default {
  name: 'Symptom',
  props:['modluesLen','nameStr'],
  data() {
    let { datas, pathInfo,searchShow } = this.$store.state;
    const { choose, text } = this.$store.state.symptom;
    return {
      age: pathInfo.patientAge,
      sexType: pathInfo.patientSex == '男' ? 1 : (pathInfo.patientSex == '女' ? 2 : 3),
      deptName: pathInfo.selfDeptName,
      hosCode: pathInfo.hospitalCode,
      chooseSymp: choose, //已选症状
      symp: [], //症状
      labelDetail: {}, //明细
      checkText: text, //症状情况文字
      questId: null, //id
      delText: "是否删除该信息？<br/>（已填内容将清除）",
      delIndex: null,
      showToast: false,
      searchShow: searchShow,//显示搜索界面
      tmpItem:{},//检索的症状
      isSearch:false,
      scroll:null,
      quesText:"请问您这次哪里最不舒服？",
      startTime:'',
      timer:null,
      showExp:false,
      message:{
        title:'',
        text:''
      },
      start:{},
      end:{},
      slide:false,
      slideTxt:'展开',
      staticSymp:[]
    }
  },
  created() {
    if (this.chooseSymp.length > 0) {
      this.quesText = "请问您还有其他不适吗？";
      // 推送
      const sympText = this.getSympText();
      this.getPush(sympText);
    } else {
      this.getSympList(); //常见
    }
  },
  mounted(){
    this.$nextTick(()=>{
      let scroll = setScroll(BScroll,true,'.symper')
      this.scroll = scroll
      scroll.on('scroll', this.onScroll)
    })
  },
  watch:{
    checkText:{//更新推送
      handler(newVal,oldVal){
        const sympText = this.getSympText();
        if(sympText){
          if(this.chooseSymp.length>1){
            this.getPush(sympText);
          }
          this.quesText = "请问您还有其他不适吗？";
        }else{
          this.getSympList();
          this.quesText = "请问您这次哪里最不舒服？";
        } 
      },
      deep:true
    }
  },
  methods: {
    slideToggle(){
      let flg = this.slideTxt
      if(flg == '展开'){
        this.$refs.showHide.style.height = 'auto'
        this.slideTxt = '收起'
      }else{
        this.$refs.showHide.style.height = '3rem'
        this.slideTxt = '展开'
      }
    },  
    touchend(item,flg) {//症状点开详情
      clearTimeout(this.timer);
      this.end = this.$store.state.scroll
      if(JSON.stringify(this.start) != JSON.stringify(this.end)){
        return
      }
      let endTime = +new Date();
      if(endTime - this.startTime < 500){//点击事件
        if(this.chooseSymp.length == 0){
          item.idx = 1
        }
        this.common(item,flg);
        this.slideTxt = '展开'
      }
      this.startTime = "";
    },
    touchstart(it){
      this.start = this.$store.state.scroll
      this.startTime = +new Date();
      const that = this;
      this.timer = setTimeout(function(){
        // 长按事件
          that.showExp = true;
          if(it.explains){
            that.message.title = it.description || it.name;
            that.message.text = it.explains;
          }else{
            that.message.title = "";
            that.message.text = "暂无资料";
          }
        },600)
    },
    closeTip(){
      this.showExp = false,
      this.message.title = '';
      this.message.text = '';
    },
    onScroll(data) {
      this.$store.commit('setScroll', data);
      document.activeElement.scrollIntoViewIfNeeded(true);
    },
    search(flg) {
      this.$store.commit('setSearchShow', flg);
    },

    getSympList() {
      const param = {
        "age": this.age,
        "deptName": this.deptName,
        "sexType": this.sexType
      }
      api.getSymptom(param).then((res) => {
        const result = res.data;
        if (result.code == 0) {
          this.symp = result.data;
          if(result.data.length>9){
            this.slide = true
          }else{
            this.slide = false
          }
        }
      })
    },
    toNext() {
      // 把1切换成完成图标，且2高亮--判断有几个模块显示，1个--提交预览；1个以上--下一步
      if (this.chooseSymp.length == 0) { return }
      // 把症状情况的数据存起-已选
      this.$store.commit('setChoose', { choose: this.chooseSymp, type: moduleCP['symp'] });
      if(this.modluesLen==1){
        this.$emit('next','preview')
      }else{
        this.$emit('next');
      }
    },
    common(item,flg){
      if(this.chooseSymp.length>12){
        this.$store.commit('setSearchShow', false);
        return
      }
      this.questId = item.questionId || item.id || item.conceptId;
      const id = item.questionId || item.id; //常见症状questionId，推送id,两者均有可能没有
      //将选中的name存到store中的text
      if (id&&this.chooseSymp.length == 0) {//只有第一次
        const param = {
          "age": this.age,
          "id": id,
          "sexType": this.sexType
        }
        api.getById(param).then((res) => {
          const result = res.data;
          if (result.code == 0) {
            const mapping = result.data.questionMapping;
            this.labelDetail = result.data;
            if(this.chooseSymp.length == 0){
              result.data.idx = 1
              this.$store.commit('setText', { type: moduleCP['symp'], text: '患者出现'+item.name,textP: '患者出现'+(item.description||item.name), pId: this.questId,idx:flg });
            }else{
              this.$store.commit('setText', { type: moduleCP['symp'], text: item.name,textP: item.description||item.name, pId: this.questId,idx:flg });
            }
            this.$store.commit('setOrigin', { type: moduleCP['symp'], data: result.data });
            if (mapping && mapping.length > 0) {
              for(let i = 0;i < mapping.length;i++){
                if(mapping[i].flag == 3){
                  this.staticSymp = mapping[i].questionDetailList
                }
              }
              this.$store.commit('setDetail',{detail:result.data,ppId:null,moduleType:moduleCP['symp'],sign:1,idx:this.chooseSymp.length})
              this.$store.commit('setSearchShow', false);
              this.chooseSymp.push(item);
            } else { 
              this.chooseSymp.push(item);
              this.$store.commit('setSearchShow', false);
            }
            const sympText = this.getSympText();
            this.getPush(sympText);
          }
        }).catch(()=>{
          if(this.chooseSymp.length == 1){
            const sympText = this.getSympText();
            this.getPush(sympText);
          }
        })
      } else {//没有questionId或id 
        if(this.chooseSymp.length == 0){
          item.idx = 1
          this.$store.commit('setText', { type: moduleCP['symp'], text: '患者出现'+item.name,textP: '患者出现'+(item.description||item.name), pId: this.questId,idx:flg });
        }else{
          this.$store.commit('setText', { type: moduleCP['symp'], text: item.name,textP: item.description||item.name, pId: this.questId,idx:flg });
        }
        this.chooseSymp.push(item);
        const sympText = this.getSympText();
        this.getPush(sympText);
        // this.checkText = this.$store.state.symptom.text;
      }
    },
    showDetil(item,flg) {//搜索点开的详情
      this.tmpItem=item
      this.isSearch=flg||false
      this.common(item,flg,this.chooseSymp);
    },
    getSympText() {//推送使用医生端信息
      const text = this.$store.state.symptom.text;
      let msg = "";
      for (let i in text) {
        if(text[i] && text[i].text){
          msg += text[i].text;
        }
      }
      return trimDots(msg);
    },
    getPush(symptoms) {//推理
      const param = {
        "age": this.age,
        "hosCode": this.hosCode,
        "sex": this.sexType,
        "symptom": symptoms //症状+选择的明细,string
      }
      api.getPush(param).then((res) => {
        const result = res.data;
        if (result.code == 0) {
          let symp = result.data.symptom;
          let symped = JSON.parse(JSON.stringify(this.chooseSymp));//已选症状
          let sympStic = JSON.parse(JSON.stringify(this.staticSymp));//首次有无症状
          let sympAll = sympStic.concat(symp);
          var obj = {};
          sympAll = sympAll.reduce(function(item, next) {
            obj[next.name] ? '' : obj[next.name] = true && item.push(next);
            return item;
          }, []);
          // console.log(sympAll,symped)
          for(let i = 0;i < sympAll.length;i++){//去掉已选的已选症状
            for(let j = 0;j < symped.length;j++){//去掉
              if(symped[j].name == sympAll[i].name){
                sympAll.splice(i,1)
              }
            }
          }

          this.symp = sympAll.slice(0,12);
          // this.symp = symp;
          this.$refs.showHide.style.height = 'auto'
        }
      }).catch(()=>{

      })
    },
    deletSymp(item, index) {
      this.delIndex = index;
      this.questId = item.questionId || item.id || item.conceptId;
      if (this.chooseSymp.length == 1) {
        this.delText = "是否删除该信息？<br/>删除后将重新填写预问诊流程 <br/>（已填内容将清除）"
      }
      this.showToast = true;
      $(".btscroll").css({'position':'fixed'})
      $(".foot").css({'position':'fixed','bottom':'0'})
    },
    comfirnDel() {
      $(".btscroll").css({'position':'absolute','top':'0'})
      $(".foot").css({'position':'absolute','bottom':'0'})
      this.chooseSymp.splice(this.delIndex, 1);
      this.checkText.splice(this.delIndex, 1);
      this.$store.commit('delText', { type: moduleCP['symp'], pId: this.questId })
      // 删除setDatas数据,防止回读
      this.$store.commit('setDatas', { type: moduleCP['symp'], pId: this.questId ,data:''})
      // 删除完-常见；其他-推送
      if (this.chooseSymp.length > 0) {

      } else {
        // 全部删除完 重新走问诊流程
        // this.$router.push("/")
        // this.$router.replace({path:'/'})
        // 停留在当前页 8-19
        this.quesText = "请问您这次哪里最不舒服？";
        this.getSympList();
      }
      this.cancelDel();
    },
    cancelDel() {
      $(".btscroll").css({'position':'absolute','top':'0'})
      $(".foot").css({'position':'absolute','bottom':'0'})
      this.showToast = false;
      this.delIndex = null;
      this.questId = null;
      this.delText = "是否删除该信息？<br/>（已填内容将清除）";
    },
    showChecked(item,i) {
      const origin = this.$store.state.symptom.origin;
      const read = this.$store.state.symptom.datas;
      const data = read[(item.questionId||item.id)] || origin[(item.questionId||item.id)];
      if (data&&data.questionMapping && data.questionMapping.length > 0) {
        this.$store.commit('setDetail',{detail:data,ppId:null,moduleType:moduleCP['symp'],sign:1,idx:i})       
      }
    },
  },
  components: {
    Toast,
    Search,
    Tiptoast
  }
}
</script>
<style lang="less" scoped>
@import "../less/base.less";
.showHide {
  overflow: hidden;
  height: 3rem;
}
.tip span {
  color: #colors[theme];
  float: right;
  font-size: .28rem;
}
.symp-wrap {
  font-size: 0.3rem;
  .quest {
    color: #colors[quest];
    margin-bottom: 0.36rem;
    font-weight: 700;
    .searchImg {
      width: 0.44rem;
      height: 0.44rem;
      float: right;
    }
  }
}
.choose{
  padding-bottom: .2rem;
  .choo-symp{
      display: inline-block;
      min-width:2rem;
      height: .74rem;
      background: #colors[btn];
      border-radius: .08rem;
      white-space: nowrap;
      margin: 0 .25rem .3rem 0;
      span{
        display: inline-block;
        vertical-align: top;
      }
      span:first-child{
        min-width:1.42rem;
        height: .74rem;
        line-height: .74rem;
        text-align: center;
        color: #fff;
      }
      img{
        width:.48rem;
        height: .74rem;
      }
    }
    .choo-symp:last-child{
      margin-right: 0;
    }
  .label{
    .label;
  }
  .result{
    padding-right: .3rem;
    // .title{
    //   color: #colors[btn];
    //   padding-left: .1rem;
    //   margin-bottom: .19rem;
    //   font-weight: 700;
    // }
    p{
      color: #666;
      line-height: .44rem;
    }
  }
  .footer{
    .footer;
  }
}
.label{
  .label;
}
.result{
  .result;
}
.footer{
  .footer;
}
.nofoot{
  background:#CACCFF!important;
}
</style>
