<template>
  <div class="AddChemicalAndCommonMappingWrapper clearfix">
    <crumbs
      :title="isEdit ? '药品关联维护--修改关联' : '药品关联维护--添加关联'"
      class="topBack"
      :param="$route.params"
      linkTo="DrugManage"
    ></crumbs>
    <el-form
      :model="form"
      :rules="rules"
      label-position="right"
      label-width="120px"
      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="药品名称：" prop="hisName">
                <el-input v-model="form.hisName" clearable style="minWidth: 240px"></el-input>
              </el-form-item>
              <el-form-item label="药品名称预览：">
                <span class="previewInfo" style="minWidth: 240px">{{form.hisName}}</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="药品名称：" 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,idx) in uniqueNameList"
                    :key="idx"
                    :label="item.name"
                    :value="item.name"
                    :title="item.name"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="药品名称预览：">
                <span class="previewInfo" style="minWidth: 240px">{{form.searchText}}</span>
              </el-form-item>
              <el-form-item label="药品剂型：">
                <el-select
                  v-model="form.form"
                  placeholder="请选择"
                  clearable
                  style="width:100%;minWidth: 240px"
                >
                  <el-option
                    v-for="item in drugList"
                    :key="item.val"
                    :label="item.name"
                    :value="item.name"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>
      <div class="btn">
        <el-form-item>
          <el-button type="primary" :disabled="saveDisable" @click="submitForm">确定</el-button>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>
<script>
import api from '@api/icss.js';
import config from '@api/config';
export default {
  name: 'AddDrug',
  data() {
    return {
      isEdit: false,
      editId: '',
      uniqueNameList: [],
      form: {
        searchText: '', //搜索字段
        hisName: '',
        form: ''
      },
      rules: {
        hisName: [
          { required: true, message: '请输入药品名称', trigger: 'change' },
          { max: 80, message: '药品名称最多80字', trigger: 'change' }
        ],
        searchText: [
          { required: true, message: '请选择药品名称', trigger: 'change' }
        ]
      },
      saveDisable: false, //保存按钮禁止点击
      showDrop: false, //下拉框显示文字
      drugForm: config.drugForm,
      drugList: []
    };
  },
  created() {
    //修改
    const { isEdit, data } = this.$route.params;
    this.getDicList();
    if (isEdit) {
      this.isEdit = isEdit;
      this.editId = data.id;
      this.form.hisName = data.hisName;
      this.form.searchText = data.uniqueName;
      this.form.form = data.form;
    }
  },
  methods: {
    getDicList() {
      api.getDicList().then(res => {
        // console.log(res, '字典类型');
        // if (res.data.code === '0') {

        //   this.drugList = res.data.data && res.data.data['9'];

        // }

        if (res.data.code === '0') {
          let dragData = [];
          res.data.data &&
            res.data.data['9'].forEach(item => {
              if (item.val !== '0') {
                dragData.push(item);
              }
            });
          this.drugList = dragData;
        }
      });
    },

    // 搜索列表
    searchTerms(query) {
      if (!query) {
        this.uniqueNameList = [];
        return;
      }
      this.showDrop = true;
      let params = {
        type: 5, //药品
        inputStr: query,
        sex: 3,
        age: 0
      };
      api.retrievalSearch(params).then(res => {
        this.showDrop = false;
        if (res.data.code === '0') {
          this.uniqueNameList = res.data.data.drugNames;
        }
      });
    },
    changeWord() {},
    // 获取焦点
    handleFocus() {},

    handleVisible(flag) {
      if (!flag) {
        this.uniqueNameList = [];
      }
    },

    // 初始化表单数据
    initForm() {
      this.form.hisName = '';
      this.form.searchText = '';
    },

    // 建立关联-参数处理
    submitForm() {
      this.$refs.relationForm.validate(valid => {
        if (valid) {
          const { searchText, hisName, form } = this.form;
          let params = {
            hisName: hisName,
            uniqueName: searchText,
            form: form
          };
          this.showSaveDialog(params);
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 建立关联-映射关系是否已存在
    showSaveDialog(params) {
      this.saveDisable = true; //提交保存按钮不可点击，返回结果时才可点击，防止频繁发送请求
      api
        .drugIsExistRecord(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);
        });
    },

    // 映射关系不存在-建立关联
    saveLisMapping(params, msg, type) {
      api.saveOrUpdateDrugRecord(params).then(res => {
        if (res.data.code === '0') {
          this.warning(res.data.msg || msg, type);
          this.initForm();
          this.$router.push({
            name: 'DrugManage',
            params: Object.assign({}, this.$route.params, {
              currentPage: 1
            })
          });
        } else {
          this.warning(res.data.msg);
        }
        this.saveDisable = false;
      });
    },
    // 关联已存在模态框
    showConfirmDialog(msg, resolve) {
      this.$confirm(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'
      });
    }
  }
};
</script>
<style lang="less">
.AddChemicalAndCommonMappingWrapper {
  .AddChemicalAndCommonMappingBox {
    min-width: 940px;
  }
  color: #606266;
  .topBack {
    top: 0;
  }
  .titleBox {
    padding: 0 0 10px 0px;
  }
  .title {
    width: 50%;
    float: left;
    font-size: 14px;
  }
  .AddChemicalAndCommonMappingBox {
    padding: 20px 30px 20px 30px;
    margin: 70px 20px 0 20px;
    background: #fff;
  }
  .leftBox,
  .midBox,
  .rightBox {
    width: 40%;
    float: left;
    min-height: 200px;
    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 20px;
  }
  .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;
  }
  // .selectItemName {
  //   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;
  // }
  .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;
  }
  .btn {
    position: relative;
    background-color: #fff;
    margin: 0px 20px;
    padding: 20px;
    min-width: 960px;
    height: 80px;
    .el-button {
      position: absolute;
      right: 80px;
      top: 20px;
    }
  }
  .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>
