<template>
  <div class="modal-container">
    <div class="cover"></div>
    <div class="modal-box">
      <div class="modal-title">
        <span class="title-l">{{title}}{{tip}}</span>
        <a class="close" @click="closeModal()">×</a>
      </div>
      <div class="modal-body">
        <el-form
          :model="form"
          :rules="rules"
          label-position="right"
          label-width="145px"
          ref="relationForm"
        >
          <div class="AddChemicalAndCommonMappingBox clearfix">
            <div class="titleBox clearfix">
              <p class="title">医院术语</p>
              <p class="title">标准术语</p>
            </div>
            <!-- 左边框中的内容 -->
            <div class="leftBox clearfix">
              <el-row>
                <el-col :span="16">
                  <el-form-item :label="meal+'：'" prop="hisName">
                    <el-input
                      v-model.trim="form.hisName"
                      clearable
                      style="minWidth: 240px"
                      @input="onchange"
                      @blur="onblur"
                    ></el-input>
                  </el-form-item>
                  <el-form-item :label="meal+'预览：'">
                    <span class="previewInfo" style="minWidth: 240px">{{form.hisName}}</span>
                  </el-form-item>
                  <el-form-item label="科室编码：" prop="hisCode" v-if="type==7">
                    <el-input v-model.trim="form.hisCode" clearable style="minWidth: 240px"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="16" v-if="type == 2 || type == 1">
                  <el-form-item :label="detail+'：'" prop="hisDetailName">
                    <el-input
                      v-model.trim="form.hisDetailName"
                      clearable
                      style="minWidth: 240px"
                      @input="onchange"
                      @blur="onblur"
                      @clear="clear"
                    ></el-input>
                  </el-form-item>
                  <el-form-item :label="detail+'预览：'">
                    <span class="previewInfo" style="minWidth: 240px">{{form.hisDetailName}}</span>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <!-- 相互关联图标 -->
            <div class="midBox">
              <img class="midLogo" src="../../images/relation.png" alt />
              <p class="midTitle">相互关联</p>
            </div>
            <!-- 右边框中的内容 -->
            <div class="rightBox">
              <el-row>
                <el-col :span="16">
                  <el-form-item :label="standard+'：'" prop="searchText">
                    <el-select
                      style="width:100%;minWidth: 240px"
                      v-model="form.searchText"
                      filterable
                      remote
                      clearable
                      :loading="showDrop"
                      loading-text="加载中..."
                      @change="changeWord"
                      @focus="handleFocus"
                      @visible-change="handleVisible"
                      placeholder="搜索"
                      :remote-method="searchTerms"
                      reserve-keyword
                    >
                      <el-option
                        v-for="item in uniqueNameList"
                        :key="item.icd10Code"
                        :label="searchType == 2 ? `${item.uniqueName}(${item.name})` : item.name"
                        :value="searchType == 2 ? `${item.uniqueName}` : item"
                        :title="searchType == 2 ? `${item.uniqueName}(${item.name})` : item.name"
                        @click.native="handleChoose(searchType == 2 ? `${item.uniqueName}` : item.name,item.id)"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item v-if="tableData.length >0">
                    <el-table
                      :header-row-style="{height:'40px'}"
                      :header-cell-style="{height:'40px',padding:'0'}"
                      :row-class-name="tableRowClassName"
                      :row-style="selectedstyle"
                      :data="tableData"
                      @row-click="btn"
                      size="mini"
                      :class="{tabs:uniqueNameList}"
                      class="tab"
                    >
                      <el-table-column prop="name" :show-overflow-tooltip="true" label="词名"></el-table-column>
                      <el-table-column prop="address" :show-overflow-tooltip="true" label="来源">
                        <template slot-scope="scope">
                          <span>{{scope.row.source == 1?'标准词匹配':scope.row.source == 2?'同义词匹配':scope.row.source == 5?'相似词匹配':''}}</span>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-form-item>

                  <el-form-item :label="standard+'预览：'">
                    <!-- <span class="previewInfo">{{!isEdit ? form.searchText.name : form.searchText}}</span> -->
                    <span class="previewInfo" style="minWidth: 240px">{{form.searchText}}</span>
                  </el-form-item>
                  <el-form-item label="ICD编码：" v-if="type == 4">
                    <span class="previewInfo" style="minWidth: 240px">{{form.icdCode}}</span>
                  </el-form-item>
                  <el-form-item :label="detail+'：'" v-if="type == 12 || type == 13 || type == 6">
                    <span class="previewInfo" style="minWidth: 240px">{{form.icdCode}}</span>
                  </el-form-item>
                  <el-form-item label="药品剂型：" v-if="type == 5">
                    <el-select
                      style="width:100%;minWidth: 240px"
                      v-model="form.form"
                      filterable
                      remote
                      clearable
                      :loading="showDrop"
                      loading-text="加载中..."
                      @change="drugchangeWord"
                      @focus="handleFocus"
                      @visible-change="handleVisible"
                      placeholder="搜索"
                      :remote-method="searchDrug"
                      reserve-keyword
                    >
                      <el-option
                        v-for="item in drugList"
                        :key="item.icd10Code"
                        :label="item.name"
                        :value="item"
                        :title="item.name"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-form>
      </div>
      <div class="mapList">
        已关联标准术语:
        <span v-for="item in mapList" :key="item.id">
          <span v-if="item.uniqueName">{{item.uniqueName}}&nbsp;&nbsp;{{item.form}}{{item.hisCode}}；</span>
        </span>
      </div>
      <div class="modal-footer">
        <button class="confirm btns" :disabled="saveDisable" @click="submitForm">确定</button>
        <button class="cancel btns" @click="closeModal">取消</button>
      </div>
    </div>
  </div>
</template>
<script>
import api from '@api/icss.js';
import config from '@api/config.js';
import utils from '@api/utils.js';
export default {
  name: 'lt-modal',
  props: ['modalVisiable', 'meal', 'detail', 'standard', 'type', 'data', 'tip'],
  data() {
    return {
      form: {
        searchText: '', //搜索字段
        hisName: '',
        icdCode: '',
        hisDetailName: '',
        formConceptId: '',
        conceptId: '',
        form: '',
        hisCode: '',
        source: ''
      },
      showDrop: false, //下拉框显示文字
      saveDisable: false, //保存按钮禁止点击
      uniqueNameList: [],
      rules: {
        hisName: [
          { required: true, message: '请输入' + this.meal, trigger: 'change' },
          { max: 80, message: this.meal + '最多80字', trigger: 'change' }
        ],
        searchText: [
          { required: true, message: '请选择' + this.meal, trigger: 'change' }
        ]
      },
      isEdit: false,
      editId: '',
      drugList: [],
      tableData: [],
      mapList: [],
      getIndex: 6,
      ty: this.type,
      searchType: '',
      title: '添加'
    };
  },
  created() {
    if (this.type == 1) {
      this.ty = 2; // 1-化验大项、2-化验小项
    }
    //修改
    if (JSON.stringify(this.data) != '{}') {
      this.title = '修改';
      this.isEdit = true;
      this.editId = this.data.id;
      this.form.hisName = this.data.hisName;
      this.form.hisDetailName = this.data.hisDetailName;
      this.form.searchText = this.data.uniqueName;
      this.form.icdCode = this.data.code;
      this.form.conceptId = this.data.conceptId;
      this.form.formConceptId = this.data.formConceptId;
      this.form.form = this.data.form;
      this.form.source = this.data.source;
      this.form.hisCode = this.data.hisCode;
      let name;
      if (
        this.data.hisName !== '' &&
        this.data.hisDetailName === '' &&
        this.type == 1
      ) {
        this.ty = 1; // 1-化验大项、2-化验小项
        this.searchType = 1;
        name = this.data.hisName;
      } else if (
        this.data.hisName !== '' &&
        this.data.hisDetailName !== '' &&
        this.type == 1
      ) {
        this.ty = 2;
        this.searchType = 2;
        name = this.data.hisDetailName;
      }
      this.getTermMatching(this.ty, name);
      this.getRelatedMapping();
    }
  },
  methods: {
    selectedstyle({ row, rowIndex }) {
      if (this.getIndex === rowIndex) {
        return {
          'background-color': '#EBEEF5',
          color: '#48C5D7'
        };
      }
    },
    tableRowClassName({ row, rowIndex }) {
      row.index = rowIndex;
    },
    btn(row) {
      const { hisName, hisDetailName } = this.form;
      if (hisName !== '' && hisDetailName === '' && this.type == 1) {
        this.ty = 1;
      } else if (hisName !== '' && hisDetailName !== '' && this.type == 1) {
        this.ty = 2;
      }
      console.log(this.ty)
      this.searchType = this.ty;
      if (this.getIndex == row.index) {
        this.getIndex = 6;
        this.form.searchText = '';
        this.form.conceptId = '';
        this.form.icdCode = '';
        this.form.source = '';
      } else {
        this.getIndex = row.index;
        this.form.searchText = row.name;
        this.form.conceptId = row.id;
        this.form.icdCode = row.code;
        this.form.source = row.source;
      }
    },
    handleChoose(val, id) {
      this.form.conceptId = id;
      this.form.searchTextPre = val;
      this.form.searchText = val;
    },
    // 搜索列表
    searchTerms(query) {
      if (!query) {
        this.uniqueNameList = [];
        return;
      }
      const { hisName, hisDetailName } = this.form;
      if (hisName !== '' && hisDetailName === '' && this.type == 1) {
        this.ty = 1;
      } else if (hisName !== '' && hisDetailName !== '' && this.type == 1) {
        this.ty = 2;
      }
      this.searchType = this.ty;
      this.showDrop = true;
      let params = {
        type: this.ty ? this.ty : this.type,
        inputStr: query,
        sex: 3,
        age: 0
      };
      api.retrievalSearch(params).then(res => {
        this.showDrop = false;
        if (res.data.code === '0') {
          if (this.ty == 2) {
            this.uniqueNameList = res.data.data.lisDetailNames;
          } else {
            this.uniqueNameList = res.data.data.nameList;
          }
        }
      });
    },
    searchDrug(query) {
      if (!query) {
        this.drugList = [];
        return;
      }
      this.showDrop = true;
      let params = {
        type: 15,
        inputStr: query,
        sex: 3,
        age: 0
      };
      api.retrievalSearch(params).then(res => {
        this.showDrop = false;
        if (res.data.code === '0') {
          this.drugList = res.data.data.nameList;
        }
      });
    },
    onchange() {
      this.getRelatedMapping();
    },
    getRelatedMapping() {
      const { hisName, hisDetailName } = this.form;
      let params = {
        type: this.type,
        hisDetailName: hisDetailName,
        hisName: hisName
      };
      api.getRelatedMapping(params).then(res => {
        console.log('添加药品关联', res);
        this.showDrop = false;
        if (res.data.code === '0') {
          this.mapList = res.data.data;
        }
      });
    },
    // change方法 选中值发生变化时触发 当前的选中值
    changeWord(newValue) {
      this.form.searchText = newValue.name;
      this.form.icdCode = newValue.code;
      this.form.conceptId = newValue.id;
      this.getIndex = 6;
    },
    drugchangeWord(newValue) {
      this.form.formConceptId = newValue.id;
      this.form.form = newValue.name;
    },
    handleVisible(flag) {
      if (!flag) {
        this.uniqueNameList = [];
      }
    },
    // 获取焦点
    handleFocus() {},
    onblur() {
      let type, name;
      if (this.type == 1) {
        const { hisName, hisDetailName } = this.form;
        type = 1; // 1-化验大项、2-化验小项
        name = hisName;
        if (hisName !== '' && hisDetailName !== '') {
          type = 2;
          name = hisDetailName;
        }
      }
      this.getTermMatching(type, name);
    },
    clear(){
      const { hisName, hisDetailName } = this.form;
      this.getTermMatching(1, hisName);
    },
    getTermMatching(type, name) {
      let params = {
        type: type ? type : this.type,
        inputStr: name ? name : this.form.hisName
      };
      api.getTermMatching(params).then(res => {
        this.showDrop = false;
        if (res.data.code === '0') {
          this.tableData = res.data.data;
          this.getIndex = 6;
        }
      });
    },
    // 建立关联-参数处理
    submitForm() {
      this.$refs.relationForm.validate(valid => {
        if (valid) {
          const {
            searchText,
            hisName,
            hisDetailName,
            icdCode,
            conceptId,
            formConceptId,
            source,
            hisCode
          } = this.form;
          // 当标准术语是套餐时，细项必须为空
          if (this.searchType === 1 && hisDetailName !== '') {
            this.warning('医院术语与标准术语类型不匹配，请修改');
            return;
          }

          // 当标准术语是细项时，医院术语套餐和细项均不能为空
          if (this.searchType === 2) {
            if (hisName === '') {
              this.warning('医院术语与标准术语类型不匹配，请修改');
              return;
            } else if (hisDetailName === '') {
              this.warning('医院术语与标准术语类型不匹配，请修改');
              return;
            }
          }
          let params = {
            hisName: hisName,
            uniqueName: searchText,
            hisDetailName: hisDetailName,
            type: this.type,
            conceptId: conceptId,
            formConceptId: formConceptId,
            hisCode: hisCode,
            source: source ? source : 1
          };
          this.showSaveDialog(params);
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 建立关联-映射关系是否已存在
    showSaveDialog(params) {
      this.saveDisable = true; //提交保存按钮不可点击，返回结果时才可点击，防止频繁发送请求
      api
        .diseaseIsExistRecord(params)
        .then(res => {
          if (!res.data.data) {
            // 不存在,创建新的关联
            // 如果是编辑时,需要携带id
            if (this.isEdit) {
              params = { ...params, id: this.editId };
            }
            this.saveLisMapping(params, '保存成功', 'success');
          } else {
            // 已存在,提示修改
            this.warning('该条关联已存在，无法添加');
            this.saveDisable = false;
          }
        })
        .catch(err => {
          if (err.code === '900010001') {
            return false;
          }
          this.warning(err);
        });
    },
    // 初始化表单数据
    initForm() {
      this.form.hisName = '';
      this.form.searchText = '';
      this.form.icdCode = '';
      this.form.hisDetailName = '';
      this.form.form = '';
      this.form.conceptId = '';
      this.form.source = '';
    },
    // 映射关系不存在-建立关联
    saveLisMapping(params, msg, type) {
      api.saveOrUpdateDiseaseRecord(params).then(res => {
        if (res.data.code === '0') {
          this.warning(res.data.msg || msg, type);
          this.initForm();
          this.$emit('func', 'updata');
        } else {
          this.warning(res.data.msg);
        }
        this.saveDisable = false;
      });
    },
    // 关联已存在模态框
    showConfirmDialog(msg, resolve) {
      this.$alert(msg, '提示', {
        // customClass: 'confirmRealation',
        confirmButtonText: '是',
        // cancelButtonText: '否',
        // cancelButtonClass: 'cancelButton',
        type: 'warning'
      })
        .then(() => {
          resolve();
        })
        .catch(() => {
          this.saveDisable = false;
          this.warning('建立失败', 'error');
        });
    },
    warning(msg, type) {
      this.$message({
        showClose: true,
        message: msg,
        type: type || 'warning',
        duration: '1000'
      });
    },
    closeModal() {
      this.$emit('func', 'close');
    }
  }
};
</script>
<style lang="less" scoped>
.modal-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 21;
  .cover {
    background: #000;
    opacity: 0.2;
    width: 100%;
    height: 100%;
  }
  .modal-box {
    width: 950px;
    background: #fff;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    .modal-title {
      height: 40px;
      background: #e3eaf4;
      .close {
        float: right;
        margin: 3px 13px 0 0;
        font-size: 22px;
        color: #979797;
        cursor: pointer;
      }
    }
    .btns {
      display: inline-block;
      width: 70px;
      height: 34px;
      line-height: 34px;
      background: #48c5d7;
      border-radius: 4px;
      color: #fff;
      text-align: center;
      cursor: pointer;
      outline: none;
      border: none;
    }
    .cancel {
      background: #fff;
      color: #48c5d7;
      border: 1px #48c5d7 solid;
      margin-left: 40px;
    }
    .modal-body {
      padding: 34px 22px;
    }
    .modal-footer {
      margin-bottom: 60px;
      width: 100%;
      text-align: center;
    }
  }
}
.tab {
  max-width: 240px;
  min-width: 240px;
  //   position: absolute;
  //   top: 0;
  z-index: 999;
  margin-bottom: 15px;
  margin-top: -18px;
}
// .tabs {
//   max-width: 240px;
//   min-width: 240px;
//   position: absolute;
//   top: 0;
//   left: 250px;
// }
.mapList {
  padding: 0 20px 20px;
  font-size: 14px;
  line-height: 24px;
  & span {
    padding: 0 3px;
  }
}
.el-select-dropdown__list,
.el-select-dropdown__item {
  width: 219px;
  cursor: pointer;
}
.el-dropdown-menu__item:focus,
.el-checkbox__input.is-checked + .el-checkbox__label,
.el-dropdown-menu__item:not(.is-disabled):hover,
.el-button--text,
.el-date-table td.today span,
.el-radio__input.is-checked + .el-radio__label,
.el-pagination.is-background .el-pager li:not(.disabled):hover,
.el-select-dropdown__item.selected {
  font-size: 14px;
  padding: 0 20px;
  position: relative;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #606266;
  height: 34px;
  line-height: 34px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  width: 219px;
  cursor: pointer;
}
/deep/ .el-form-item__error {
  width: 150px;
}
/*********新增编辑***********/
.topBack {
  top: 0;
}
.titleBox {
  padding: 0 0 10px 0px;
}
/deep/.el-table th {
  background: #f7f7f7;
}
/deep/ .el-table td,
.el-table th.is-leaf {
  border-bottom: none;
}
.title-l {
  font-size: 14px;
  line-height: 40px;
  margin-left: 10px;
}
.title {
  width: 50%;
  float: left;
  font-size: 14px;
}
.leftBox,
.midBox,
.rightBox {
  width: 380px;
  float: left;
  height: 248px;
  font-size: 14px;
}
.midBox {
  width: 6%;
  padding: 50px 0 0 0;
  text-align: center;
}
.midTitle {
  width: 40px;
  margin: 0 auto;
}
.midLogo {
  margin: 0 auto;
}
.leftBox,
.rightBox {
  border: 1px solid #dcdfe6;
  padding: 20px 10px;
}
.rightBox {
  padding-right: 33px;
  height: 248px;
  overflow-y: auto;
}
.itemLabel {
  width: 100%;
  min-height: 50px;
  line-height: 50px;
  position: relative;
}
.itemLabelName,
.searchInput,
.searchName {
  float: left;
  color: #606266;
}
.itemLabelName {
  width: 150px;
}
.isRequired::before {
  content: '*';
  color: red;
}
.searchInput,
.mealNameItem {
  padding: 0 5px;
}
.searchInput,
.searchName {
  display: inline-block;
  height: 32px;
  line-height: 32px;
  border: 1px solid #a9a9a9;
  margin: 8px 0 0 0;
}

.searchName {
  text-align: center;
  border-left: none;
  cursor: pointer;
  padding: 0 12px;
  font-size: 16px;
}
.itemList {
  position: absolute;
  background: #fff;
  width: 162px;
  max-height: 150px;
  border: 1px solid #a9a9a9;
  left: 150px;
  top: 42px;
  z-index: 2;
  overflow-y: auto;
}
.itemList {
  width: calc(100% - 131px);
}
.mealNameItem {
  height: 30px;
  line-height: 30px;
  font-size: 14px;
  cursor: pointer;
}
.mealNameItem:hover {
  background: #f5f7fa;
}
.previewInfo {
  padding-left: 4px;
  display: inline-block;
  margin-top: 8px;
  // width: calc(100% - 160px);s
  line-height: 24px;
  overflow: hidden;
  word-wrap: break-word;
  word-break: break-all;
}
.sumbit {
  position: absolute;
  display: inline-block;
  width: 80px;
  height: 30px;
  line-height: 30px;
  border: 1px solid #a9a9a9;
  text-align: center;
  right: 100px;
}
.confirmRealation {
  .cancelButton {
    border: 1px solid #a9a9a9;
    span {
      color: #606266;
    }
  }
}
</style>