<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 && (!diseaseCode || invalid_disease)}"
            :size="size"
            slot="reference"
            :placeholder="key1?key1:'中医病名'"
            v-model="key1"
            ref="zybm"
            @input="getDiseaseList(key1)"
            @focus="handleFocus('bm')"
            @keydown.enter.native="handleEnter('bm')"
          >
            <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 in diseaseList"
              :key="item.$uid"
              :class="{
                active: name === item.$name
              }"
              @click="handleBm(item)"
            >{{ item.$name }}</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" :class="{invalid: syndrome && invalid_symptom}"
            slot="reference"
            :placeholder="key2?key2:'中医证型'"
            v-model="key2"
            ref="zhengxing"
            @input="getSymptomList(key2)"
            @focus="handleFocus('zx')"
            @keydown.enter.native="handleEnter('zx')"
          >
            <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 in symptomList"
              :key="item.$uid"
              :class="{
                active: syndrome === item.$name,
                matched: item.isMatched
              }"
              @click="handleZx(item)"
            >{{ item.$name }}</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" v-model="popoverZF">
          <el-input
              :size="size" :class="{invalid: therapy && invalid_therapy}"
              slot="reference"
              :placeholder="key3?key3:'中医治法'"
              v-model="key3"
              ref="zhifa"
              @input="getTherapyList(key3)"
              @focus="handleFocus('zf')"
              @keydown.enter.native="handleEnter('zf')"
          >
            <div slot="suffix" class="suffix">
              <i class="el-icon-arrow-down" v-if="!key3"></i>
              <i class="el-icon-circle-close" v-else @click="clearZf"></i>
            </div>
          </el-input>
          <ul class="option-list">
            <li
              v-for="item in therapyList"
              :key="item.$uid"
              :class="{
                active: therapy === item.$name,
                matched: item.isMatched
              }"
              @click="handleZf(item)"
            >{{ item.$name }}</li>
          </ul>
        </el-popover>
      </div>
    </div>
  </div>
</template>
<script>
import {getDiseaseListMethod, getSymptomListMethod, getTherapyListMethod} from '@/request/api';
import {addDiagnosisData2} from '@/api/diagnosis.js';
import { addRecipeFrom } from "@/api/dataAnalysis.js";
import { mapGetters } from "vuex";
import {findArray} from '@/tool';

export default {
  props: {
    title: {
      type: String,
      default: ""
    },
    size: {
      type: String,
      default: "mini"
    },
    patiensMsg: {
      type: Object,
      default: () => {
        return {};
      }
    },
    className: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      invalid_disease: false,
      invalid_symptom: false,
      invalid_therapy: false,

      popoverZF: false,

      name: "", // 病名
      zy_dise_id: "", // 病名id
      diseaseCode: '', // 病名code

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

      therapy: "", // 治法
      therapyCode: '', // 治法

      diseaseList: [], // 病名列表
      symptomList: [], // 证型列表
      therapyList: [], //治法列表

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

      isEnter1: false, // 是否进入病名输入框
      isEnter2: false // 是否进入证型输入宽
    };
  },
  mounted() {
    this.getDiseaseList();
    this.getSymptomList();
    this.getTherapyList();
  },
  watch: {
    key1: {
      handler: function(value, oldVal) {
        if (this.key1 == "") {
          this.invalid_disease = false;
          this.zy_dise_id = "";
          this.diseaseCode = '';
          this.name = "";
        }
        if (!value && oldVal) {
          this.getDiseaseList();
          this.getSymptomList();
          this.getTherapyList();
        }
      }
    },
    key2: {
      handler: function(value, oldVal) {
        if (this.key2 == "") {
          this.invalid_symptom = false;
          this.syndrome = "";
          this.zhengxingid = "";
        }
        if (!value && oldVal) {
          this.getSymptomList();
          this.getTherapyList();
        }
      }
    },
    key3: {
      handler: function(value, oldVal) {
        if (this.key3 == "") {
          this.invalid_therapy = false;
          this.therapy = "";
          this.therapyCode = "";
        }
        if (!value && oldVal) {
          this.getTherapyList();
        }
      }
    },
    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.diseaseCode = this.patiensMsg.maindiagnosis.disCode || '';
        // 证形
        this.syndrome = this.patiensMsg.maindiagnosis.syndrometypes || "";
        this.zhengxingid = this.patiensMsg.maindiagnosis.symptomid || "";
        // 治法
        this.therapy = this.patiensMsg.maindiagnosis.treatment || "";
        this.therapyCode = this.patiensMsg.maindiagnosis.therapyCode || '';
        this.key1 = this.name || "";
        this.key2 = this.syndrome || "";
        this.key3 = this.therapy || '';
        if (this.key1) this.getDiseaseList(this.key1);
        if (this.key2) this.getSymptomList(this.key2);
        if (this.key3) this.getTherapyList(this.key3);
        this.isInit = true;
      }
    }
  },
  computed: {
    ...mapGetters(["getPatiensInfo", "getOutpatientDiagnosis"])
  },
  methods: {
    /**
     * focus 事件
     * @param {'bm'|'zx'|'zf'} type
     */
    handleFocus(type) {
      console.log(type);
      if (type === 'bm' && this.diseaseList.length === 0) this.getDiseaseList(this.key1);
      else if (type === 'zx' && this.symptomList.length === 0) this.getSymptomList(this.key2);
      else if (type === 'zf' && this.therapyList.length === 0) this.getTherapyList(this.key3);
    },
    /**
     * enter事件
     * @param {'bm'|'zx'|'zf'} type
     */
    handleEnter(type) {
      if (type === 'bm' && this.diseaseList.length) this.handleBm(this.diseaseList[0]);
      else if (type === 'zx' && this.symptomList.length) this.handleZx(this.symptomList[0]);
      else if (type === 'zf' && this.therapyList.length) this.handleZf(this.therapyList[0]);
    },
    // 获取中医诊断信息
    getDiamsg() {
      this.saveDiagnosisData();
      return {
        disCode: this.diseaseCode,
        symptomCode: this.zhengxingid,
        therapyCode: this.therapyCode,
        disid: this.zy_dise_id,
        symptomid: this.zhengxingid,
        treatment: this.therapy
      };
    },
    getIllness() {
      return {
        disease: {code: this.diseaseCode, id: this.zy_dise_id, name: this.name},
        symptom: {code: this.zhengxingid, name: this.syndrome},
        therapy: {code: this.therapyCode, name: this.therapy},
      }
    },
    optimalTherapyCode() {
      if (this.therapy && !this.therapyCode) try {
        this.therapyCode = this.therapyList.find(item => [item.therapy, item['therapyName']].includes(this.therapy)).therapyCode;
      } catch (_) {}
    },
    // 获取内容参数
    getParams() {
      return {
        // 病名及id
        namemedicine: this.name,
        disid: this.zy_dise_id,
        disCode: this.diseaseCode,
        //   证型及id
        symptomCode: this.zhengxingid,
        symptomid: this.zhengxingid,
        syndrometypes: this.syndrome,
        //   治法
        therapyCode: this.therapyCode,
        treatment: this.therapy
      };
    },
    // 赋值内容参数
    setParams(data) {
      console.log('setParams==赋值内容参数', data);
      this.name = data.namemedicine || "";
      this.zy_dise_id = data.disid || "";
      this.diseaseCode = data.disCode || "";
      this.zhengxingid = data.symptomid || data.synCode || "";
      this.syndrome = data.syndrometypes || "";
      this.therapyCode = data.therapyCode || '';
      this.therapy = data.treatment || "";
      this.key1 = this.name || "";
      this.key2 = this.syndrome || "";
      this.key3 = this.therapy || '';
      if (this.key1) this.getDiseaseList(this.key1);
      if (this.key2) this.getSymptomList(this.key2);
      if (this.key3) this.getTherapyList(this.key3);

      this.$forceUpdate();
    },
    // 病名选中
    async handleBm(item) {
      this.invalid_disease = false;
      this.zy_dise_id = item.disid;
      this.diseaseCode = item.$code;
      this.name = item.$name;
      this.key1 = item.$name;
      this.$refs.zybm.blur();

      this.clearZx();

      if (this.name === "") return;
      this.$refs.zhengxing.focus();
      await this.getSymptomList();
    },
    // 清空病名
    clearBm() {
      this.name = "";
      this.zy_dise_id = "";
      this.diseaseCode = '';
      this.key1 = "";
      this.clearZx();
    },
    // 证型选中\
    async handleZx(item) {
      this.invalid_disease = false;
      this.syndrome = item.$name;
      this.key2 = item.$name;
      this.zhengxingid = item.$code;
      this.$refs.zhengxing.blur();

      this.clearZf();
      this.$refs.zhifa.focus();
      await this.getTherapyList();
    },
    handleZf(item) {
      this.invalid_therapy = false;
      this.therapy = item.$name;
      this.therapyCode = item.$code;
      this.key3 = this.therapy;
      this.$nextTick(() => {
        this.$refs.zhifa.blur();
        this.popoverZF = false;
      });
    },
    // 清空证型
    clearZx() {
      this.syndrome = "";
      this.zhengxingid = "";
      this.key2 = "";
      this.clearZf();
    },
    // 清空证型
    clearZf() {
      this.therapy = '';
      this.therapyCode = '';
      this.key3 = '';
    },
    //获取病名数据
    async getDiseaseList(keyword = '') {
      const {total, list} = await getDiseaseListMethod(1, 9999, {keyword});
      this.diseaseList = list;
    },
    // 获取证型数据
    async getSymptomList(keyword = '') {
      const {total, list} = await getSymptomListMethod(1, 9999, {
        keyword,
        disid: this.zy_dise_id,
        disCode: this.diseaseCode,
      })
      this.symptomList = list;
    },
    /**
     * 获取治法
     * @param keyword
     * @return {Promise<void>}
     */
    async getTherapyList(keyword) {
      const {total, list} = await getTherapyListMethod(1, 9999, {
        keyword,
        disCode: this.diseaseCode,
        symptomCode: this.zhengxingid,
        symid: this.zhengxingid,
      })
      this.therapyList = list;
    },
    // 新增处方来源统计
    async addRecipeFrom() {
      let res = await addRecipeFrom({
        type: "1"
      });
    },
    // 保存中医诊断信息
    async saveDiagnosisData() {
      this.optimalTherapyCode();
      let params = {
        mainDiagnosis: {
          disid: this.zy_dise_id,
          disCode: this.diseaseCode,
          symptomid: this.zhengxingid,
          symptomCode: this.zhengxingid,
          therapyCode: this.therapyCode,
          treatment: this.therapy,
          maindiagnosis: "0",
          recordsid: this.getPatiensInfo.pid,
          pid: this.patiensMsg.maindiagnosis.pid,
          namemedicine: this.name,
          syndrometypes: this.syndrome,
          zhengxing: ""
        }
      };
      try {
        if (!this.name) throw {message: `请选择${this.title}病名`};
        if (!this.zy_dise_id) throw {message: `当前疾病编码与医保不匹配，请更换中医病名等诊断信息!`};
        let {mainDiagnosis} = await addDiagnosisData2(params);

        this.invalid_disease = !mainDiagnosis.disCode;
        this.invalid_symptom = !mainDiagnosis.symptomid;
        this.invalid_therapy = !mainDiagnosis.therapyCode;
        const tips = [
          this.invalid_disease ? `${this.title}病名` : '',
          this.invalid_symptom ? `证型` : '',
          this.invalid_therapy ? `治法` : '',
        ].filter(Boolean).join('，');
        if (tips) throw {message: `当前${tips}与医保不匹配，请更换${tips}等诊断信息!`};

        this.addRecipeFrom().catch();
        return true
      } catch (e) {
        this.$message.error(e.message);
      }
      return false;
    }
  }
};
</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>