<template>
  <div class="diagnosis flex-plane-center-top">
    <div class="pre-left">
      <!-- 标题信息 -->
      <div class="pre-title" v-if="false">
        <div class="flex-vertical-center-l title-container">
          <span></span>
          <div>患者信息</div>
        </div>
      </div>
      <div class="patiens-msg" v-if="false">
        <p v-if="patiensMsg.sex">患者性别：{{patiensMsg.sex}}</p>
        <p v-if="patiensMsg.age">患者年龄：{{patiensMsg.age}}</p>
        <p
          v-if="patiensMsg.isGravidity && patiensMsg.isGravidity=='2'"
        >是否怀孕：{{patiensMsg.isGravidity=='1'?'否':patiensMsg.isGravidity=='2'?'是':'无'}}</p>
        <p
          v-if="patiensMsg.isBreastFeeding && patiensMsg.isBreastFeeding==1"
        >是否哺乳：{{patiensMsg.isBreastFeeding==1?'是':patiensMsg.isBreastFeeding==2?'否':'无'}}</p>
      </div>
      <!-- mr-t30 -->
      <div class="pre-title">
        <div class="flex-vertical-center-l title-container">
          <span></span>
          <div>中医电子病历</div>
        </div>
      </div>
      <div class="patiens-msg" v-if="patiensMsg.outpatientElectronicmedicalrecord">
        <p v-if="patiensMsg.outpatientElectronicmedicalrecord.chiefcomplaint">
          <span>主诉：</span>
          {{patiensMsg.outpatientElectronicmedicalrecord.chiefcomplaint}}
        </p>
        <p v-if="patiensMsg.outpatientElectronicmedicalrecord.historypresent">
          <span>现病史：</span>
          {{patiensMsg.outpatientElectronicmedicalrecord.historypresent}}
        </p>
        <p v-if="patiensMsg.outpatientElectronicmedicalrecord.pasthistory">
          <span>既往史：</span>
          {{patiensMsg.outpatientElectronicmedicalrecord.pasthistory}}
        </p>
        <p v-if="patiensMsg.outpatientElectronicmedicalrecord.fourmedicine">
          <span>中医四诊：</span>
          {{patiensMsg.outpatientElectronicmedicalrecord.fourmedicine}}
        </p>
        <p v-if="patiensMsg.outpatientElectronicmedicalrecord.physicalexamination">
          <span>体格检查：</span>
          {{patiensMsg.outpatientElectronicmedicalrecord.physicalexamination}}
        </p>
        <p v-if="patiensMsg.outpatientElectronicmedicalrecord.supplementaryexamination">
          <span>辅助检查：</span>
          {{patiensMsg.outpatientElectronicmedicalrecord.supplementaryexamination}}
        </p>
        <div v-if="patiensMsg.outpatientElectronicmedicalrecord.image1.length>0">
          <div style="margin: 4px 0 8px;">报告上传：</div>
          <el-image
            :preview-src-list="patiensMsg.outpatientElectronicmedicalrecord.image1"
            :src="item"
            :key="index"
            style="width:64px;height: 64px;margin-right: 10px;"
            alt
            v-for="(item,index) in patiensMsg.outpatientElectronicmedicalrecord.image1"
          />
        </div>
      </div>
    </div>
    <div class="diagnosis-container">
      <div class="title">主诊断</div>

      <div class="form flex-vertical-center-l">
        <div class="flex-vertical-center-l item">
          <span>诊断类型：</span>
          <!-- <div class="form-msg">
                        <el-select v-model="type" placeholder="请选择" @change="typeChange()" disabled>
                            <el-option label="中医诊断" value="zyzd"></el-option>
                            <el-option label="西医诊断" value="xyzd"></el-option>
                        </el-select>
          </div>-->
          <div class="form-msg">中医诊断</div>
        </div>
        <!-- <div class="bianzheng flex-center" v-if="type=='zyzd'"
        @click="$router.push({path:'/index/dialectical'})">智能辨证</div>-->
        <el-button
          type="danger"
          size="small"
          v-if="type=='zyzd'"
          @click="$router.push({path:'/index/dialectical'})"
        >智能辨证</el-button>
      </div>
      <div class="form flex-vertical-center-l" v-if="false">
        <div class="flex-vertical-center-l item">
          <span>{{type=='zyzd'?'中医':'西医'}}病名：</span>

          <!-- z中医  -->
          <div class="form-msg" v-if="type=='zyzd'">
            <el-select
              size="small"
              v-model="dise_name"
              @change="cNameChange()"
              filterable
              remote
              clearable
              :placeholder="type=='zyzd'?'请输入中医病名':'请输入西医病名'"
              :filter-method="filterMethod"
            >
              <el-option
                :label="item.disname"
                :value="item.disname"
                v-for="(item,index) in cDiseaseNameL"
                :key="index"
              ></el-option>
            </el-select>
            <!-- <el-autocomplete class="inline-input" v-model="form.departName" :fetch-suggestions="querySearch"
            :placeholder="type=='zyzd'?'请输入中医病名':'请输入西医病名'" @select="handleSelect"></el-autocomplete>-->
          </div>
          <!-- 西医  -->
          <div class="form-msg" v-else>
            <el-select
              size="small"
              v-model="dise_name"
              filterable
              :placeholder="type=='zyzd'?'请输入中医病名':'请输入西医病名'"
            >
              <el-option
                :label="item.westname"
                :value="item.westcode"
                v-for="(item,index) in xDiseaseNameL"
                :key="index"
              ></el-option>
            </el-select>
          </div>
        </div>
        <div class="flex-vertical-center-l item mr-l20" v-if="type=='zyzd'">
          <span>中医证型：</span>
          <div class="form-msg">
            <!-- <el-select v-model="zhengxing" filterable placeholder="请输入" id='zhengxing' ref='zhengxing'
                            @change="cardTypeChange()" no-data-text='无匹配数据,请修改病名' remote :filter-method='filterMethod1'>
                            <el-option :label="item.symname" :value="item.symname" v-for="(item,index) in cCardTypeL"
                                :key="index">
                            </el-option>

            </el-select>-->
            <el-autocomplete
              size="small"
              v-model="zhengxing"
              :fetch-suggestions="searchZhengxing"
              :trigger-on-focus="true"
              @select="selectZX($event)"
              ref="zhengxing"
              :id="'zhengxing'"
              placeholder="请输入"
            ></el-autocomplete>
          </div>
        </div>
        <div class="flex-vertical-center-l item mr-l20" v-if="type=='zyzd'">
          <span>中医治法：</span>
          <div class="form-msg">
            <!-- <el-input v-model="zhifa" placeholder="请输入"></el-input> -->
            <el-select
              size="small"
              v-model="zhifa"
              ref="zhifa"
              filterable
              placeholder="请输入"
              no-data-text="无匹配数据,请修改证型"
            >
              <el-option :label="item" :value="item" v-for="(item,index) in therapy" :key="index"></el-option>
            </el-select>
          </div>
        </div>
      </div>
      <div class="form">
        <TCMDiagnosis size="small" title="中医" ref="TCM"></TCMDiagnosis>
      </div>

      <div class="title">次诊断</div>
      <div class="table">
        <el-table :data="tableData" style="width: 100%" border height="100%">
          <el-table-column prop="id" label="序号" width="50"></el-table-column>
          <el-table-column prop="type" label="诊断类型" width="150">
            <template slot-scope="scope">
              <el-select
                size="small"
                v-model="scope.row.type"
                placeholder="请选择"
                @change="sTypeChange($event,scope)"
              >
                <el-option label="中医诊断" value="zyzd"></el-option>
                <el-option label="西医诊断" value="xyzd"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="诊断内容">
            <template slot-scope="scope">
              <div class="flex-vertical-around">
                <!-- 西医诊断 -->
                <div class="table-item flex-vertical-center-l" v-if="scope.row.type!='zyzd'">
                  <span>{{scope.row.type=='zyzd'?'中医':'西医'}}病名：</span>
                  <div class="input" style="width: auto;">
                    <!-- <el-select size='small' v-model="scope.row.xname" filterable
                                            :placeholder="type=='zyzd'?'请输入':'请输入'">
                                            <el-option :label="item.westname" :value="item.westcode"
                                                v-for="(item,index) in sxDiseaseNameL" :key="index">
                                            </el-option>
                    </el-select>-->
                    <el-autocomplete
                      :fetch-suggestions="querySearch1"
                      :trigger-on-focus="false"
                      @select="handleSelect($event,scope)"
                      v-model="scope.row.xname"
                      placeholder="请输入"
                      size="small"
                      :id="'xyzd'+scope.row.id"
                    ></el-autocomplete>
                  </div>
                </div>
                <!-- 中医诊断 -->
                <template v-else>
                  <TCMDiagnosis size="small" title="中医" :ref="'TCM'+scope.row.id"></TCMDiagnosis>
                </template>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <div class="flex-vertical-around operation">
                <img src="../../assets/zhen_add.png" alt @click="addData(scope)" />
                <img src="../../assets/zhen_reduce.png" alt @click="removeData(scope)" />
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- <div class="submit flex-center" @click="submit()">保存并推导</div> -->
      <el-button @click="submit()" size="small" type="primary">保存并推导</el-button>
    </div>
  </div>
</template>
<script>
import {
  getCDiseaseName,
  getXDiseaseName,
  getCCardType
} from "@/api/knowledge.js";
import { addRecipeFrom } from "@/api/dataAnalysis.js";
import {
  getEmrShowMsg,
  addDiagnosisData,
  getDiagnosisShowData,
  editDiagnosisData,
  // getPatiiensMsg,
  getPatiensBasisM
} from "@/api/diagnosis.js";
import { mapState, mapGetters, mapActions, mapMutations } from "vuex";
import TCMDiagnosis from "../../components/TCMDiagnosis.vue";

import { setTimeout } from "timers";

import { formatPicture } from "@/utils/picture";

export default {
  components: {
    TCMDiagnosis
  },
  data() {
    return {
      type: "zyzd",
      dise_id: '',
      dise_name: "",
      zy_dise_id: "",
      zhengxing: "",
      zhengxingid: "",
      zhifa: "",
      patiensMsg: {}, // 病人信息

      // 中医病名列表
      cDiseaseNameL: [],
      scDiseaseNameL: [], // 次诊断
      // 西医病名列表数据
      xDiseaseNameL: [],
      sxDiseaseNameL: [], // 次诊断
      // 中医证型列表
      cCardTypeL: [],
      // 中医治法集
      therapy: [],
      tableData: [
        {
          id: 1,
          type: "zyzd",
          cname: "",
          cid: "",
          xid: "",
          xname: "",
          zhengxing: "",
          zhengxingid: "",
          zhifa: "",
          therapy: [],
          cCardTypeL: []
        }
      ],
      isEdit: "", // 诊断id 有就是修改
      sonIndex: 0, // 次诊断 下标
      hasEdit: false // 是否有对内容进行修改
    };
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.getPatiiensMsg();
    });
  },
  created() {
    // this.getCDiseaseName('', '', 'son')
    // this.getXDiseaseName('', '', 'son')

    this.getEmrShowMsg();
    if (this.$route.query.type == "trun") {
      let res = {
        Data: {
          mainDiagnosis: JSON.parse(this.getOutpatientDiagnosis)
        }
      };
      this.dealBackShow(res);
    } else {
      this.getDiagnosisShowData();
    }
  },
  beforeRouteLeave(to, from, next) {
    if (this.hasEdit) {
      this.$confirm("当前操作尚未保存,是否需要保存", "提示", {
        confirmButtonText: "保存",
        cancelButtonText: "不保存",
        type: "warning"
      })
        .then(() => {
          this.addDiagnosisData(2, next);
        })
        .catch(() => {
          next();
        });
    } else {
      next();
    }
  },
  watch: {
    getOutpatientDiagnosis: {
      deep: true,
      handler: function() {
        let res = {
          Data: {
            mainDiagnosis: JSON.parse(this.getOutpatientDiagnosis)
          }
        };
        this.dealBackShow(res);
      }
    },
    tableData: {
      deep: true,
      handler: function() {
        this.hasEdit = true;
      }
    },
    dise_name() {
      this.hasEdit = true;
    },
    zhengxing() {
      this.hasEdit = true;
    },
    zhifa() {
      this.hasEdit = true;
    }
  },
  methods: {
    // 次诊断 中医病名搜索
    async querySearch(key, cb) {
      let pinyin = /^[A-Za-z]+$/g;
      if (pinyin.test(key)) {
        await this.getCDiseaseName(key, "1", "son");
      } else {
        await this.getCDiseaseName(key, "", "son");
      }

      if (this.scDiseaseNameL.length > 0) {
        let resault = [];
        this.scDiseaseNameL.forEach(item => {
          let obj = {
            value: item.disname,
            id: item.disid
          };
          resault.push(obj);
        });
        cb(resault);
      } else {
        cb([
          {
            value: "搜索不到数据"
          }
        ]);
      }
    },
    async querySearch1(key, cb1) {
      let pinyin = /^[A-Za-z]+$/g;
      if (pinyin.test(key)) {
        await this.getXDiseaseName(key, "1", "son");
      } else {
        await this.getXDiseaseName(key, "", "son");
      }

      if (this.sxDiseaseNameL.length > 0) {
        let resault = [];
        this.sxDiseaseNameL.forEach(item => {
          let obj = {
            value: item.westname,
            id: item.westcode
          };
          resault.push(obj);
        });
        cb1(resault);
      } else {
        cb([
          {
            value: "搜索不到数据"
          }
        ]);
      }
    },
    // 次诊断证型搜索
    async queryZhengx(key, cb) {
      let pinyin = /^[A-Za-z]+$/g;
      if (pinyin.test(key)) {
        await this.getCCardType("", this.sonIndex, key, "1");
      } else {
        await this.getCCardType(
          this.tableData[this.sonIndex].cid,
          this.sonIndex,
          key,
          ""
        );
      }

      if (this.tableData[this.sonIndex].cCardTypeL.length > 0) {
        let resault = [];
        this.tableData[this.sonIndex].cCardTypeL.forEach(item => {
          let obj = {
            value: item.symname,
            id: item.symid,
            therapys: item.therapys
          };
          resault.push(obj);
        });
        cb(resault);
      } else {
        cb([
          {
            value: "搜索不到数据"
          }
        ]);
      }
    },
    // 主诊断证型搜索
    async searchZhengxing(key, cb) {
      let pinyin = /^[A-Za-z]+$/g;
      if (pinyin.test(key)) {
        await this.getCCardType(this.zy_dise_id, "", key, "1");
      } else {
        await this.getCCardType(this.zy_dise_id, "", key, "");
      }

      if (this.cCardTypeL.length > 0) {
        let resault = [];
        this.cCardTypeL.forEach(item => {
          let obj = {
            value: item.symname,
            id: item.symid,
            therapys: item.therapys
          };
          resault.push(obj);
        });
        cb(resault);
      } else {
        cb([
          {
            value: "搜索不到数据"
          }
        ]);
      }
    },
    selectZX(e) {
      this.zhengxing = e.value;
      this.zhengxingid = e.id;
      this.therapy = e.therapys;
      this.$refs.zhifa.focus();
    },
    handleSelectZX(e, scope) {
      this.tableData[scope.$index].zhengxing = e.value;
      this.tableData[scope.$index].zhengxingid = e.id;
      this.tableData[scope.$index].therapy = e.therapys;
      console.log(document.getElementById("zyzf" + scope.row.id), "址发");
      document.getElementById("zyzf" + scope.row.id).focus();
    },
    zxInput(e, scope) {
      this.sonIndex = scope.$index;
    },
    // 次诊断 类型改变
    sTypeChange(e, scope) {
      console.log(e);

      if (e == "zyzd") {
        this.tableData[scope.$index].sxDiseaseNameL = [];
        this.tableData[scope.$index].xname = "";
        this.tableData[scope.$index].xid = "";
        // document.querySelectorAll('#xyzd' + scope.row.id)[0].style.borderColor = 'red'
      } else {
        this.tableData[scope.$index].scDiseaseNameL = [];
        this.tableData[scope.$index].cname = "";
        this.tableData[scope.$index].cid = "";
      }
    },
    handleSelect(e, scope) {
      let type = this.tableData[scope.$index].type;
      if (type == "zyzd") {
        this.tableData[scope.$index].cname = e.value;
        this.tableData[scope.$index].cid = e.id;
        this.getCCardType(scope.row.cid, scope.$index);

        document.getElementById("zyzx" + scope.row.id).focus();
      } else {
        this.tableData[scope.$index].xname = e.value;
        this.tableData[scope.$index].xid = e.id;
      }
    },
    typeChange() {
      this.dise_name = "";
    },

    filterMethod1(e) {
      let pinyin = /^[A-Za-z]+$/g;
      if (pinyin.test(e)) {
        this.getCCardType(this.zy_dise_id, "", e, "1");
      } else {
        this.getCCardType(this.zy_dise_id, "", e, "");
      }
    },
    filterMethod(e) {
      let pinyin = /^[A-Za-z]+$/g;
      if (pinyin.test(e)) {
        if (this.type == "zyzd") {
          this.getCDiseaseName(e, "1");
        } else {
          this.getXDiseaseName(e, "1");
        }
      } else {
        if (this.type == "zyzd") {
          this.getCDiseaseName(e, "");
        } else {
          this.getXDiseaseName(e, "");
        }
      }
    },
    cNameChange() {
      // let id = ''
      this.cDiseaseNameL.forEach(item => {
        if (item.disname == this.dise_name) {
          // id = item.disid
          this.zy_dise_id = item.disid;
        }
      });
      this.zhengxing = "";
      this.zhengxingid = "";
      this.zhifa = "";
      this.getCCardType(this.zy_dise_id);
      if (this.dise_name === "") return;
      setTimeout(() => {
        this.$refs.zhengxing.focus();
      }, 200);
    },
    // 列表内部 中医病名改变
    iCnameChnage(scope) {
      this.getCCardType(scope.row.cname, scope.$index);
    },
    // 列表内部 中医证型改变
    iCardTypeChange(scope) {
      let list = scope.row.cCardTypeL.filter(item => {
        return scope.row.zhengxing == item.symid;
      });

      this.tableData[scope.$index].therapy = list[0].therapys;
    },
    cardTypeChange() {
      let list = this.cCardTypeL.filter(item => {
        if (item.symname == this.zhengxing) {
          this.zhengxingid = item.symid;
        }
        return item.symname == this.zhengxing;
      });
      this.zhifa = "";
      this.therapy = list[0].therapys;
      this.$refs.zhifa.focus();
    },
    addData(row) {
      // console.log(row, 'row')
      let index = row.$index;
      if (index == this.tableData.length - 1) {
        this.tableData.push({
          id: row.row.id + 1,

          type: "zyzd",
          cname: "",
          cid: "",
          xid: "",
          xname: "",
          zhengxing: "",
          zhifa: ""
        });
        this.tableData.filter((item, index) => {
          return (item.id = index + 1);
        });
      } else {
        let data = this.tableData;

        let data1 = data.splice(index + 1); // 被截取掉的 数组

        data.push({
          id: row.row.id + 1,

          type: "zyzd",
          cname: "",
          cid: "",
          xid: "",
          xname: "",
          zhengxing: "",
          zhifa: ""
        });

        data = data.concat(data1);
        data.filter((item, index) => {
          return (item.id = index + 1);
        });
        this.tableData = data;
      }
    },
    removeData(row) {
      if (row.$index == 0 && this.tableData.length == 1) return;
      this.tableData.splice(row.$index, 1);
      this.tableData.filter((item, index) => {
        return (item.id = index + 1);
      });
    },
    submit() {
      let TCMParams = this.$refs.TCM.getParams();
      if (TCMParams.disid == "") {
        this.$message.warning("中医诊断病名不能为空");
        return;
      }
      if (TCMParams.symptomid == "") {
        this.$message.warning("中医诊断证型不能为空");
        return;
      }
      let hasid = true;
      if (this.tableData.length > 2) {
        this.tableData.forEach(item => {
          if (item.type == "zyzd") {
            let TCMPITEM = this.$refs["TCM" + item.id].getParams();
            if (!TCMPITEM.disid || !TCMPITEM.symptomid) {
              hasid = false;
            }
          } else {
            if (!item.xid) {
              hasid = false;
            }
          }
        });
      }

      if (!hasid) {
        this.$message("请选择正确的病名或证型--次诊断");
        return;
      }
      // let second = true;
      // this.tableData.forEach(item => {
      //   if (item.xname || item.cname) {
      //     if (item.type == "zyzd") {
      //       if (!item.zhifa) {
      //         second = false;
      //       }
      //     }
      //   }
      // });
      // if (!second) {
      //   this.$message.error("请完善次诊断信息");
      //   return;
      // }
      if (this.isEdit) {
        // 更新诊断页 数据 (统一 掉新增接口 后台处理逻辑)
        // this.editDiagnosisData()
        this.addDiagnosisData();
      } else {
        this.addDiagnosisData();
      }
    },
    // 处理回显数据
    dealBackShow(res) {
      this.isEdit = res.Data.mainDiagnosis.pid;

      const diagnosis = res.Data.mainDiagnosis;

      this.type = diagnosis.maindiagnosis === '0' ? 'zyzd' : 'xyzd';

      if (this.type === 'zyzd') {
        this.$nextTick(() => {
          this.$refs.TCM.setParams({
            namemedicine: diagnosis.namemedicine,
            disid: diagnosis.disid,
            symptomid: diagnosis.symptomid,
            syndrometypes: diagnosis.syndrometypes,
            treatment: diagnosis.treatment,

            disCode: diagnosis.disCode,

            diseaseCode: diagnosis.disCode,
            symptomCode: diagnosis.symptomid,
            therapyCode: diagnosis.therapyCode,
          });
        })
      } else {
        this.dise_id = diagnosis.westcode;
        this.dise_name = diagnosis.diagnosis;
      }

      //更新次诊断信息
      const secondaryDiagnosis = this.$route.query.type === 'trun' ? res.Data.secondarydiagnosis : res.Data.secondaryDiagnosises;

      if (Array.isArray(secondaryDiagnosis)) {
        this.tableData = secondaryDiagnosis.map((item, index) => {
          const type = item.secondarydiagnosis === '0' ? 'zyzd' : 'xyzd';
          return { type, id: index, pid: item.pid, xid: item.westcode, xname: item.diagnosis, _rawData: item };
        });
        this.$nextTick(() => {
          for (const item of this.tableData) {
            if (item.type === "zyzd") {
              const diagnosis = item._rawData;
              this.$refs[`TCM${item.id}`].setParams({
                namemedicine: diagnosis.namemedicine,
                disid: diagnosis.disid,
                symptomid: diagnosis.symptomid,
                syndrometypes: diagnosis.syndrometypes,
                treatment: diagnosis.treatment,

                disCode: diagnosis.disCode,

                diseaseCode: diagnosis.disCode,
                symptomCode: diagnosis.symptomid,
                therapyCode: diagnosis.therapyCode,
              });
            }
          }
        });
      }
      this.hasEdit = false;
    },
    // 新增处方来源统计
    async addRecipeFrom() {
      let res = await addRecipeFrom({
        type: "1"
      });
    },

    //   获取就诊详细数据
    async getPatiiensMsg() {
      let res = await getPatiensBasisM({
        patientId: this.getPatiensInfo.pid
      });
      if (res.ResultCode == 0) {
        if (!res.Data.outpatientElectronicmedicalrecord.chiefcomplaint) {
          // this.$message({
          //     type: 'warning',
          //     showClose: false,
          //     message: '请先填写中医电子病历'
          // })
          // this.$router.replace({
          //     path: '/index/emr'
          // })
          // // this.$router.back()
          // return
        }
        res.Data.outpatientElectronicmedicalrecord.image1 = formatPicture(res.Data.outpatientElectronicmedicalrecord.image1);

        this.patiensMsg = res.Data;
      } else {
        this.$message.error(res.ResultInfo);
      }
    },
    // 获取中医电子病历回显数据
    async getEmrShowMsg() {
      let params = {
        recordsId: this.getPatiensInfo.pid
      };
      let res = await getEmrShowMsg(params);
    },
    // 获取中医病名数据
    async getCDiseaseName(key, serchtype = "", type = "father") {
      let params = {
        pageid: 1,
        pagesize: 9999,
        serchtype,
        keyword: key
      };
      let res = await getCDiseaseName(params);
      if (res.code == 0) {
        this.cDiseaseNameL = res.data.diseases;
        if (type == "son") {
          this.scDiseaseNameL = res.data.diseases;
        }
      }
    },
    // 获取西医病名数据
    async getXDiseaseName(key, serchtype = "", type = "father") {
      let params = {
        pageid: 1,
        serchtype,
        keyword: key,
        pagesize: 9999
      };
      let res = await getXDiseaseName(params);
      if (res.code == 0) {
        this.xDiseaseNameL = res.data.wests;
        if (type == "son") {
          this.sxDiseaseNameL = res.data.wests;
        }
      }
    },
    // 获取中医证型
    async getCCardType(id, index = "", key = "", serchtype = "") {
      let params = {
        pageid: 1,
        pagesize: 9999,
        disid: serchtype == 1 ? "" : id,
        serchtype,
        keyword: key
      };
      let res = await getCCardType(params);

      if (res.code == 0) {
        if (index === "") {
          // let cardlist = res.data.sysptoms.filter(item => {
          //     return item.symname == this.zhengxing
          // })

          // this.zhengxing = cardlist[0].symid
          // console.log(res.data.sysptoms, 'sys')
          // let a = JSON.stringify(res.data.sysptoms)
          // console.log('啊啊啊啊啊啊', a);
          // this.cCardTypeL = JSON.parse(a)
          this.cCardTypeL = res.data.sysptoms;
          // console.log(this.cCardTypeL, 'cc');
        } else {
          this.tableData[index].cCardTypeL = res.data.sysptoms;
          this.$set(this.tableData[index].cCardTypeL, res.data.sysptoms);
          this.$set(this.tableData, index, this.tableData[index]);
        }
      }
    },

    // 提交中医诊断
    async addDiagnosisData(type = 1, next) {
      const loading = this.$loading({
        lock: true,
        text: "正在提交",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });

      const get = (item) => {
        switch (item.type) {
            /* 中医次诊断 */
          case 'zyzd': {
            const seqn = item.id || '';
            try {
              const TCMITEM = this.$refs[`TCM${seqn}`].getParams();
              return TCMITEM.namemedicine ? {
                seqn,
                maindiagnosis: '0',
                recordsid: this.getPatiensInfo.pid,
                pid: item.pid || '',

                westcode: '', diagnosis: '',

                ...TCMITEM,
              } : null;
            } catch {
              return null;
            }
          }
            /* 西医次诊断 */
          case 'xyzd':
            return item.xname ? {
              seqn: item.id,
              maindiagnosis: '1',
              recordsid: this.getPatiensInfo.pid,
              pid: item.pid || '',

              westcode: item.xid, diagnosis: item.xname,

              disid: '', namemedicine: '',
              symptomid: '', syndrometypes: '',
              treatmentCode: '', treatment: '',
            } : null;
          default:
            return null;
        }
      }

      let params = {
        mainDiagnosis: get({
          id: '',
          type: this.type,
          pid: this.isEdit,
        }),
        secondaryDiagnosises:  this.tableData.map(get).filter(Boolean).map(item => {
          item['secondarydiagnosis'] = item.maindiagnosis;
          delete item['maindiagnosis'];
          return item;
        })
      };
      let res = await addDiagnosisData(params);
      if (res.ResultCode == 0) {
        loading.close();
        this.addRecipeFrom();

        if (type == 1) {
          this.hasEdit = false;
          this.$message.success("提交成功");
          setTimeout(() => {
            this.$router.push({
              // path: "/index/prescribing?infer=true"
              path: "/index/prescribing?type=tuidao"
            });
          }, 1500);
        }
        if (type == 2) {
          this.$message.success("保存成功");
          next();
        }
      } else {
        loading.close();
        this.$message.error(res.ResultInfo);
      }
    },
    // 修改诊断页 数据
    async editDiagnosisData() {
      const loading = this.$loading({
        lock: true,
        text: "正在提交",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });

      let namemedicine = this.cDiseaseNameL.filter(item => {
        return item.disid == this.dise_name;
      });
      let diagnosis = this.xDiseaseNameL.filter(item => {
        return item.westcode == this.dise_name;
      });
      let syndrometypes = this.cCardTypeL.filter(item => {
        return item.symid == this.zhengxing;
      });
      let secondaryDiagnosises = [];
      this.tableData.forEach(item => {
        if (item.xname || item.cname) {
          // 中医病名
          let inamemedicine = this.cDiseaseNameL.filter(item1 => {
            return item1.disid == item.cname;
          });
          let idiagnosis = this.xDiseaseNameL.filter(item1 => {
            return item1.westcode == item.xname;
          });
          let isyndrometypes = item.cCardTypeL.filter(item1 => {
            return item1.symid == item.zhengxing;
          });

          let obj = {
            disid: item.type == "zyzd" ? item.cid : "",
            symptomid: item.zhengxing,
            westcode: item.type == "xyzd" ? item.xid : "",
            seqn: item.id,
            secondarydiagnosis: item.type == "zyzd" ? "0" : "1",
            // namemedicine: item.type == 'zyzd' ? inamemedicine[0].disname : '',
            // syndrometypes: item.type == 'zyzd' ? isyndrometypes[0].symname : '',
            namemedicine: item.type == "zyzd" ? item.cname : "",
            syndrometypes: item.type == "zyzd" ? isyndrometypes[0].symname : "",
            treatment: item.type == "zyzd" ? item.zhifa : "",
            recordsid: this.getPatiensInfo.pid,
            pid: item.pid ? item.pid : "",
            // diagnosis: item.type == 'zyzd' ? '' : idiagnosis[0].westname
            diagnosis: item.type == "zyzd" ? "" : item.xname
          };

          secondaryDiagnosises.push(obj);
        }
      });

      // secondaryDiagnosises = JSON.stringify(secondaryDiagnosises)

      let params = {
        mainDiagnosis: {
          maindiagnosis: this.type == "zyzd" ? "0" : "1",
          namemedicine: this.type == "zyzd" ? namemedicine[0].disname : "",
          syndrometypes: this.type == "zyzd" ? syndrometypes[0].symname : "",
          treatment: this.type == "zyzd" ? this.zhifa : "",
          recordsid: this.getPatiensInfo.pid,
          pid: this.isEdit,
          diagnosis: this.type == "zyzd" ? "" : diagnosis[0].westname
        },
        secondaryDiagnosises
      };
      let res = await addDiagnosisData(params);
      if (res.ResultCode == 0) {
        loading.close();
        this.$message.success("提交成功");
        setTimeout(() => {
          this.$router.push({
            path: "/index/prescribing"
          });
        }, 3000);
      } else {
        this.$message.error(res.ResultInfo);
      }
    },
    // 获取病人回显数据
    async getDiagnosisShowData() {
      let params = {
        recordsId: this.getPatiensInfo ? this.getPatiensInfo.pid : ""
      };
      let res = await getDiagnosisShowData(params);
      if (res.ResultCode == 0) {
        if (res.Data.mainDiagnosis) {
          this.dealBackShow(res);
        }
      }
    }
  },
  computed: {
    ...mapGetters(["getPatiensInfo", "getOutpatientDiagnosis"])
  }
};
</script>
<style lang="scss" scoped>
@import "../../style/common.scss";

.diagnosis {
  // height: 500px;
  // overflow-y: auto;
  height: 82vh;

  .pre-title {
    margin-bottom: 10px;

    .title-container {
      span {
        width: 3px;
        height: 14px;
        background: #5386f6;
        border-radius: 1px;
        display: inline-block;
      }

      div {
        font-size: 18px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #5386f6;
        margin-left: 9px;
      }
    }
  }

  .pre-left {
    width: 230px;
    padding: 10px 12px;
    background: #fff;
    box-sizing: border-box;
    margin-right: 10px;
    min-height: 470px;
    height: 100%;
    overflow-y: auto;

    .patiens-msg {
      font-size: 14px;
      font-family: PingFang SC;
      font-weight: 400;
      color: #333333;

      h4 {
        font-size: 16px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #333333;
        margin-bottom: 5px;
      }

      p {
        span {
          display: inline-block;
          width: 70px;
          text-align: right;
        }

        margin-bottom: 5px;
      }
    }
  }

  .diagnosis-container {
    padding: 10px 10px;
    background: #fff;
    border-radius: 5px;
    flex: 1;
    box-sizing: border-box;
    overflow-y: auto;
    min-height: 470px;
    height: 100%;

    .title {
      font-size: 18px;
      font-family: PingFang SC;
      font-weight: 400;
      color: #333333;
      margin-bottom: 10px;
    }

    .form {
      margin-bottom: 15px;

      .item {
        span {
          font-size: 14px;
          font-family: PingFang SC;
          font-weight: 400;
          color: #333333;
        }

        .form-msg {
          width: 200px;
        }
      }
    }

    .table {
      margin-bottom: 10px;
    }

    .table-item {
      .input {
        width: 128px;
      }
    }

    .operation {
      img {
        width: 26px;
      }
    }

    .submit {
      margin-top: 30px;
      width: 110px;
      height: 46px;
      background: #5386f6;
      border-radius: 4px;
      font-size: 16px;
      font-family: PingFang SC;
      font-weight: 400;
      color: #ffffff;
      cursor: pointer;
    }

    .bianzheng {
      width: 319px;
      height: 38px;
      background: #ff6245;
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFang SC;
      font-weight: 400;
      color: #ffffff;
      margin-left: 123px;
      cursor: pointer;
    }
  }
}

.form-msg::v-deep .el-select {
  width: 100%;
}

.table::v-deep .el-table .cell {
  text-align: center;
}
</style>
<style lang="scss" scoped>
@media screen and(min-width: 1681px) and(max-width: 1920px) {
  .diagnosis {
    height: 88vh;

    .table {
      height: 74%;
    }
  }
}

@media screen and(min-width: 1601px) and(max-width: 1680px) {
  .emr-main-body {
    height: 83vh;

    .table {
      height: 60%;
    }
  }
}

@media screen and(min-width: 1440px) and(max-width: 1600px) {
  .emr-main-body {
    height: 80vh;
  }
}

@media screen and(min-width: 1360px) and(max-width: 1439px) {
  .emr-main-body {
    height: 76vh;
  }
}
</style>