<template>
  <div class="tcm-dia">
    <!-- 病名 -->
    <div :class="['tcm-item',size,className]">
      <div class="name">
        <span>{{ title }}</span>
        <span>病名：</span>
      </div>
      <div class="value">
        <el-popover placement="bottom" width="180" trigger="focus" :close-delay="100">
          <el-input
            :class="{invalid: name && !zy_dise_id}"
            :size="size"
            slot="reference"
            :placeholder="key1?key1:'中医病名'"
            v-model="key1"
            ref="zybm"
            id="zybm"
            @input="getOriginNameData(key1)"
          >
            <div slot="suffix" class="suffix">
              <i class="el-icon-arrow-down" v-if="!key1"></i>
              <i class="el-icon-circle-close" v-else @click="clearBm"></i>
            </div>
          </el-input>
          <ul class="option-list">
            <li
              v-for="(item,index) in cDiseaseNameL"
              :key="index"
              :class="[zy_dise_id==item.disid?'active':'']"
              @click="handleBm(item)"
            >{{ item.disname }}</li>
          </ul>
        </el-popover>
      </div>
    </div>
    <!-- 证型 -->
    <div :class="['tcm-item',size,className]">
      <div class="name">
        <span>{{ title }}</span>
        <span>证型：</span>
      </div>
      <div class="value">
        <el-popover placement="bottom" width="180" trigger="focus" :close-delay="100">
          <el-input
            :size="size"
            slot="reference"
            :placeholder="key2?key2:'中医证型'"
            v-model="key2"
            ref="zhengxing"
            id="zyzx"
            @input="getOriginZxData(key2)"
          >
            <div slot="suffix" class="suffix">
              <i class="el-icon-arrow-down" v-if="!key2"></i>
              <i class="el-icon-circle-close" v-else @click="clearZx"></i>
            </div>
          </el-input>
          <ul class="option-list">
            <li
              v-for="(item,index) in cCardTypeL"
              :key="index"
              :class="[zhengxingid==item.symid?'active':'',item.isMatched?'matched':'']"
              @click="handleZx(item)"
            >{{ item.symname }}</li>
          </ul>
        </el-popover>
      </div>
    </div>
    <!-- 治法 -->
    <div :class="['tcm-item',size,className]">
      <div class="name">
        <span>{{ title }}</span>
        <span>治法：</span>
      </div>
      <div class="value">
        <el-select :size="size" v-model="therapy" ref="zhifa" :automatic-dropdown="true">
          <el-option v-for="(item,index) in therapyList" :key="index" :value="item"></el-option>
        </el-select>
      </div>
    </div>
  </div>
</template>
<script>
import {
  getCDiseaseName,
  getXDiseaseName,
  getCCardType
} from "@/api/knowledge.js";
import { addDiagnosisData } from "@/api/diagnosis.js";
import { addRecipeFrom } from "@/api/dataAnalysis.js";
import { mapGetters } from "vuex";
export default {
  props: {
    title: {
      type: String,
      default: ""
    },
    size: {
      type: String,
      default: "mini"
    },
    patiensMsg: {
      type: Object,
      default: () => {
        return {};
      }
    },
    className: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      name: "", // 病名
      zy_dise_id: "", // 病名id

      syndrome: "", // 证型
      zhengxingid: "", // 证型id

      therapy: "", // 治法

      cDiseaseNameL: [], // 病名列表
      cCardTypeL: [], // 证型列表
      therapyList: [], //治法列表

      isInit: false, // 是否根据传入的数据初始化过
      key1: "", // 病名搜索条件
      key2: "", // 证型

      isEnter1: false, // 是否进入病名输入框
      isEnter2: false // 是否进入证型输入宽
    };
  },
  mounted() {
    this.getNamemedData();
    this.getCardType();

    let _this = this;
    document.getElementById("zybm").addEventListener("keydown", function(e) {
      if (e.key === "Enter") {
        _this.handleBmEnter();
      }
    });
    document.getElementById("zyzx").addEventListener("keydown", function(e) {
      if (e.key === "Enter") {
        _this.handleZxEnter();
      }
    });
  },
  watch: {
    key1: {
      handler: function() {
        if (this.key1 == "") {
          this.zy_dise_id = "";
          this.name = "";
        }
      }
    },
    key2: {
      handler: function() {
        if (this.key2 == "") {
          this.syndrome = "";
          this.zhengxingid = "";
        }
      }
    },
    patiensMsg: {
      immediate: true,
      deep: true,
      handler: function() {
        if (this.isInit) return;
        if (!this.patiensMsg) return;
        if (Object.keys(this.patiensMsg).length === 0) return;
        // 中医诊断
        this.name = this.patiensMsg.maindiagnosis.namemedicine || "";
        this.zy_dise_id = this.patiensMsg.maindiagnosis.disid || "";
        // 证形
        this.syndrome = this.patiensMsg.maindiagnosis.syndrometypes || "";
        this.zhengxingid = this.patiensMsg.maindiagnosis.symptomid || "";
        // 治法
        this.therapy = this.patiensMsg.maindiagnosis.treatment || "";
        this.key1 = this.name || "";
        this.key2 = this.syndrome || "";
        this.getNamemedData(this.name, "");
        this.getCardType(this.syndrome, "");
        this.isInit = true;
      }
    }
  },
  computed: {
    ...mapGetters(["getPatiensInfo", "getOutpatientDiagnosis"])
  },
  methods: {
    // 病名enter事件
    handleBmEnter() {
      if (this.cDiseaseNameL.length == 0) return;
      this.handleBm(this.cDiseaseNameL[0]);
    },
    // 症行enter事件
    handleZxEnter() {
      if (this.cCardTypeL.length == 0) return;
      this.handleZx(this.cCardTypeL[0]);
    },
    // 获取中医诊断信息
    getDiamsg() {
      this.saveDiagnosisData();
      return {
        disid: this.zy_dise_id,
        symptomid: this.zhengxingid,
        treatment: this.therapy
      };
    },
    // 获取内容参数
    getParams() {
      return {
        // 病名及id
        namemedicine: this.name,
        disid: this.zy_dise_id,
        //   证型及id
        symptomid: this.zhengxingid,
        syndrometypes: this.syndrome,
        //   治法
        treatment: this.therapy
      };
    },
    // 赋值内容参数
    setParams(data) {
      this.name = data.namemedicine || "";
      this.zy_dise_id = data.disid || "";
      this.zhengxingid = data.symptomid || "";
      this.syndrome = data.syndrometypes || "";
      this.therapy = data.treatment || "";
      this.key1 = this.name || "";
      this.key2 = this.syndrome || "";
      this.getNamemedData(this.name, "");
      this.getCardType(this.syndrome, "");

      this.$forceUpdate();
    },
    // 远程搜索病名
    getOriginNameData(e) {
      let pinyin = /^[A-Za-z]+$/g;
      if (pinyin.test(e)) {
        // 拼音
        this.getNamemedData(e, "1");
      } else {
        // 中文
        this.getNamemedData(e, "");
      }
    },
    // 搜索证型
    getOriginZxData(e) {
      let pinyin = /^[A-Za-z]+$/g;
      if (pinyin.test(e)) {
        // 拼音
        this.getCardType(e, "1");
      } else {
        // 中文
        this.getCardType(e, "");
      }
    },
    // 病名选中
    handleBm(item) {
      this.zy_dise_id = item.disid;
      this.name = item.disname;
      this.key1 = item.disname;
      this.$refs.zybm.blur();

      this.key2 = '';
      this.syndrome = "";
      this.zhengxingid = "";
      this.therapy = "";

      if (this.name === "") return;
      // this.getCCardType(this.zy_dise_id);
      this.getCardType();
      setTimeout(() => {
        this.$refs.zhengxing.focus();
      }, 0);
    },
    // 清空病名
    clearBm() {
      this.name = "";
      this.zy_dise_id = "";
      this.syndrome = "";
      this.zhengxingid = "";
      this.therapy = "";
      this.key1 = "";
      this.key2 = "";
    },
    // 证型选中\
    handleZx(item) {
      this.syndrome = item.symname;
      this.key2 = item.symname;
      this.zhengxingid = item.symid;
      this.$refs.zhengxing.blur();

      this.therapy = "";
      this.therapyList = item.therapys;

      setTimeout(() => {
        this.$refs.zhifa.focus();
      }, 0);
    },
    // 清空证型
    clearZx() {
      this.syndrome = "";
      this.zhengxingid = "";
      this.therapy = "";

      this.key2 = "";
    },
    //获取病名数据
    async getNamemedData(key = "", serchtype = "") {
      /*
      serchtype:搜索类型，1为拼音码，2为五笔码，搜索中文时可传空
      */
      let params = {
        pageid: 1,
        pagesize: 9999,
        keyword: key,
        serchtype
      };
      let res = await getCDiseaseName(params);
      if (res.code == 0) {
        this.cDiseaseNameL = res.data.diseases;
      }
    },
    // 获取证型数据
    async getCardType(key = "", serchtype = "") {
      let params = {
        pageid: 1,
        pagesize: 20000,
        keyword: key,
        serchtype,
        disid: this.zy_dise_id
      };
      let res = await getCCardType(params);
      if (res.code == 0) {
        this.cCardTypeL = res.data.sysptoms;
        setTimeout(() => {
          this.cCardTypeL.map(item => {
            if (item.symid == this.zhengxingid) {
              // console.log(item, "dayin item");
              this.therapyList = item.therapys;
            }
          });
        }, 200);
      }
    },
    // 新增处方来源统计
    async addRecipeFrom() {
      let res = await addRecipeFrom({
        type: "1"
      });
    },
    // 保存中医诊断信息
    async saveDiagnosisData() {
      let params = {
        mainDiagnosis: {
          disid: this.zy_dise_id,
          symptomid: this.zhengxingid,
          treatment: this.therapy,
          maindiagnosis: "0",
          recordsid: this.getPatiensInfo.pid,
          pid: this.patiensMsg.maindiagnosis.pid,
          namemedicine: this.name,
          syndrometypes: this.syndrome,
          zhengxing: ""
        }
      };
      let res = await addDiagnosisData(params).catch(() => ({ResultCode: -1}));
      if (+res.ResultCode === 0) {
        if (!this.name) {
          res.ResultCode = -1;
          res.ResultInfo = `请选择${this.title}病名`;
        } else if (!this.zy_dise_id) {
          res.ResultCode = -1;
          res.ResultInfo = `当前疾病编码与医保不匹配，请更换中医病名等诊断信息!`;
        } else {
          this.addRecipeFrom().catch();
        }
      }
      if (+res.ResultCode !== 0 && res.ResultInfo) this.$message.error(res.ResultInfo)
      return +res.ResultCode === 0;
    }
  }
};
</script>
<style scoped lang="scss">
.el-input.invalid::v-deep {
  input {
    color: #ff0000;
  }
}
div {
  box-sizing: border-box;
}
.tcm-dia {
  display: flex;
  align-items: flex-start;
  justify-content: flex-start;

  .tcm-item {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    margin-right: 10px;

    .name {
      font-size: 14px;
    }

    .value {
      max-width: 200px;
      flex: 1;
    }

    select {
      height: 100%;
      width: 100%;
    }
  }

  .small {
    height: 32px;
  }

  .mini {
    height: 28px;
  }

  .tcm-item:last-child {
    margin-right: 0;
  }
}

.option-list {
  margin: -12px -12px;
  max-height: 300px;
  overflow: auto;
  .active {
    color: #5386f6;
  }

  .matched {
    background: rgba($color: #5386f6, $alpha: 0.4);
  }
  li {
    padding: 8px 12px;
    list-style: none;
    font-size: 14px;
    box-sizing: border-box;
    width: 100%;
    color: #606266;
    font-weight: 500;
    cursor: pointer;
  }

  li:hover {
    background: #f5f7fa;
  }
}

.suffix {
  height: 100%;
  padding-right: 5px;
  display: flex;
  align-items: center;
}

::v-deep .el-popover {
  padding: 0 !important;
}

::v-deep .el-popper {
  padding: 0 !important;
}

.tcm-dia {
  .prescr .value {
    width: 150px;
  }

  .prescr:nth-child(1) .value {
    width: 100px;
  }

  .prescr:nth-child(2) .value {
    width: 120px;
  }
}
@media screen and(max-width:800px) {
  .tcm-dia {
    .tcm-item .value {
      width: 150px;
    }

    .tcm-item:nth-child(1) .value {
      width: 100px;
    }

    .tcm-item:nth-child(2) .value {
      width: 120px;
    }
  }
}
</style>