<template>
    <div>
        <crumbs :title="title" :param="$route.params" linkTo="CombineFeild"></crumbs>
        <div class="contents">
            <div class="content">
                <el-form ref="form" :label-position="labelPosition" label-width="118px" :model="form" :rules="rules">
                    <el-form-item label="所属医院：" prop="hospitalId">
                        <el-select v-model="form.hospitalId"
                                   placeholder="请选择"
                                   :disabled="isCopy || isEdit"
                                   size="small">
                            <el-option
                                    v-for="item in hisTypes"
                                    :key="item.val"
                                    :label="item.name"
                                    :value="Number(item.val)">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="所属模块：" prop="modeId">
                        <el-select v-model="form.modeId"
                                   placeholder="请选择"
                                   :disabled="isCopy || isEdit"
                                   size="small">
                            <el-option
                                    v-for="item in fieldTypes"
                                    :key="item.val"
                                    :label="item.name"
                                    :value="Number(item.val)">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="备注：" prop="tagName">
                        <el-input type="text" placeholder="请输入备注" v-model.trim="form.tagName"></el-input>
                    </el-form-item>
                    <el-form-item label="显示名称：" prop="name">
                        <el-input type="text" placeholder="请输入显示名称" v-model.trim="form.name"></el-input>
                    </el-form-item>
                    
                    <el-form-item label="组合内容：" prop="moduleInfo" class="formItem isRequired">
                        <div class="moduleInfoItem" v-for="(item,index) in combineInfoList">
                            <div class="searchBox">
                                <el-input v-model.trim="item.searchName"  placeholder="搜索字段单元" @input="searchFiled(index)">
                                </el-input>
                                <ul v-if="searchIndex == index &&  item.searchResult.length > 0" class="searchResultBox">
                                    <li class="searchItem" 
                                        v-for="searchItem in item.searchResult" 
                                        :title="searchItem.tagName"
                                        @click="selectSearchFiled(searchItem,index)"
                                    >
                                        {{searchItem.tagName}}
                                    </li>
                                </ul>
                            </div>
                            <div>
                                <p>已选择字段：</p>
                                <div class="selectFiledBox">
                                     <div class="orderBox">
                                            <span class="el-icon-arrow-up order"  @click="upFiled(index)"></span>
                                            <span  class="el-icon-arrow-down order" @click="downFiled(index)"></span> 
                                        </div>
                                    <div class="selectFiled" v-for="(it,ii) in item.selectFiled">
                                        <span class="filedName" :class="{activeFiledName: item.activeIndex == ii}" @click="setActiveIndex(index,ii)">{{it.tagName}}
                                            <span class="el-icon-circle-close delFiled" @click="delSelected(ii,index)"></span>
                                        </span>
                                    
                                    </div>
                                </div>
                                
                            </div>
                        </div>
                    </el-form-item>
                    <el-button class="disclButn" size="small" type="primary" :disabled = 'saveDisable' @click="comfirn('form')">确定</el-button>
                </el-form>
            </div>
        </div>
    </div>
</template>
<script type="text/javascript">
  import api from '@api/qualityControl.js';
  export default {
    name:'FieldMatch',
    data(){
      return{
        // data:{},
        list:[],
        labelPosition:'left',
        isFirst:true,
        isEdit: false,
        isCopy:false,
        title:'组合字段维护-添加组合字段',
        form:{
          modeId:"",
          hospitalId:"",
          name:'',
          tagType:4,        //固定
          controlType: 0,
          name:'',
          val:'',
          tagName:'',
          addLine:0,
          bold:0,
          position:0,
          retract:0,
          casesEntryIds:'',
          questionMappings:[]
        },
        id:null,
        rules:{
          hospitalId:{ required: true, message: '请选择所属医院', trigger: ['blur', 'change']},
          modeId:{ required: true, message: '请选择所属模块', trigger: ['blur', 'change']},
          tagName:{ required: true, message: '请输入备注', trigger: ['blur', 'change']},
          /*name:[{ required: true, message: '请输入显示名称',trigger: ['blur', 'change'] }],*/
        },
       
        saveDisable: false,  //保存按钮禁止点击
        fieldTypes:[],
        hisTypes:[],
         searchIndex: -1,
        combineInfoList:[
                {   
                    searchName:"",
                    activeIndex: -1,
                    searchResult:[
                    ],
                    selectFiled:[
                       
                    ]
                }
            ]
      }
    },
    created(){
      this.getAllTypes();
      let {isCopy,isEdit,data} = this.$route.params;
      if(isEdit  || isCopy){
        if(isEdit){
          this.title='组合字段维护-修改组合字段';
          this.id = data.id
          this.isEdit = isEdit
        }
        this.form = Object.assign({},data);
        if(isCopy){
          this.title='组合字段维护-复制组合字段';
          this.isCopy = isCopy
          this.form.tagName = ""
          this.form.id=""
        }
        let questionMappings = this.form.questionMapping ||[]
        let selectFiled = []
        for(let i = 0;  i < questionMappings.length; i++){
          selectFiled.push(questionMappings[i])
        }
        this.combineInfoList[0].selectFiled = selectFiled
        this.form.questionMapping = []
      }
    },
    methods:{
      getAllTypes(){
        /*if(localStorage.getItem("qcModuleTypes")){
          this.hisTypes = JSON.parse(localStorage.getItem("qcHospitalTypes"));
          this.fieldTypes = JSON.parse(localStorage.getItem("qcModuleTypes"));
          return ;
        }*/
        //获取枚举信息
        api.getQcTypes().then((res)=>{
          if(res.data.code==="0"){
            const data = res.data.data;
            /*localStorage.setItem("qcFieldTypes",JSON.stringify(data[11]));
            localStorage.setItem("qcModuleTypes",JSON.stringify(data[12]));
            localStorage.setItem("qcHospitalTypes",JSON.stringify(data[13]));*/
            this.hisTypes = data[13];
            this.fieldTypes =data[12];
          }else{
            this.warning("获取枚举信息失败");
          }
        });
      },
       searchFiled(index){
          this.searchIndex = index
          const searchName = this.combineInfoList[index].searchName
          if(!searchName){
              return
          }
          if(this.form.hospitalId === ''){
            this.warning("请选择所属医院")
            return
          }
          if(this.form.modeId === ''){
            this.warning("请选择所属模块")
            return
          }
          const param = {
              tagName: searchName,
              hospitalId: this.form.hospitalId,
              modeId:  [this.form.modeId],
              tagType: [1]
          }
          api.getQCName(param).then(res =>{
              if(res.data.code == '0'){
                    this.combineInfoList[index].searchResult = []
                    this.combineInfoList[index].searchResult.push(...res.data.data)
              }
          }).catch(e =>{
              console.log(e)
          })
        
      },
      selectSearchFiled(searchItem,index){
          this.combineInfoList[index].selectFiled.push(searchItem)
          this.searchIndex = -1
          this.combineInfoList[index].searchName=""
          this.combineInfoList[index].searchResult = []
      },
      upFiled(index){
          let activeIndex = this.combineInfoList[index].activeIndex
          if(activeIndex == 0 || activeIndex == -1){
              return
          }
          const current = this.combineInfoList[index].selectFiled[activeIndex]
          const currentPre = this.combineInfoList[index].selectFiled[activeIndex-1]
          this.combineInfoList[index].selectFiled.splice(activeIndex-1,2,current,currentPre)
          this.combineInfoList[index].activeIndex--
      },
      downFiled(index){
            let activeIndex = this.combineInfoList[index].activeIndex
          if(activeIndex == this.combineInfoList[index].selectFiled.length -1 || activeIndex == -1){
              return
          }
          const current = this.combineInfoList[index].selectFiled[activeIndex]
          const currentNext = this.combineInfoList[index].selectFiled[activeIndex+1]
          this.combineInfoList[index].selectFiled.splice(activeIndex,2,currentNext,current)
            this.combineInfoList[index].activeIndex++

      },
      setActiveIndex(index, ii){
            let activeIndex = this.combineInfoList[index].activeIndex
            if( ii === activeIndex) {
                this.combineInfoList[index].activeIndex = -1
            } else {
                this.combineInfoList[index].activeIndex = ii
            }
            
      },
        delSelected(ii,index){
          this.combineInfoList[index].selectFiled.splice(ii,1)
          
      },
      comfirn(form){
        /*if(!this.form.name.trim() || !this.form.refreshTime.trim()){
          this.$message({
            message:'请填写相关内容',
            type:'warning'
          });
          return
        }*/
         const {hospitalId,modeId,tagName} = this.form
        if(!hospitalId){
          this.warning("请选择所属医院");
          return
        }
         if(!modeId){
          this.warning("请选择所属模块");
          return
        }
         if(!tagName){
          this.warning("请输入备注");
          return
        }
        // this.$refs[form].validate((valid) => {
          // if (valid) {
            let questionMappings = []
            const combineInfoList = this.combineInfoList
            for(let i = 0; i < combineInfoList.length; i++){
              const selectFiledList = combineInfoList[i].selectFiled
              for(let j = 0; j < selectFiledList.length; j++){
                questionMappings.push({
                  sonQuestion: selectFiledList[j].id
                })
              }
            }
            if(questionMappings.length === 0){
              this.warning('请添加组合内容')
              return
            }
            this.form = Object.assign({}, this.form,{questionMappings: questionMappings})
            if(this.id && !this.isCopy){//修改
              const param = Object.assign({},this.form,{id:this.id})
              this.saveDisable = true  //提交保存按钮不可点击，返回结果时才可点击，防止频繁发送请求
              api.addFieldMatch({questionWrapper:param}).then((res)=>{
                if(res.data.code==0){
                  this.$message({
                    message:"修改成功",
                    type:'success'
                  });
                  //返回带搜索条件的首页
                  this.$router.push({
                    name: 'CombineFeild',
                    params: Object.assign({}, this.$route.params, {currentPage: 1})
                  });
                }else{
                  this.$message({
                    message:res.data.msg,
                    type:'warning'
                  });
                }
                this.saveDisable = false
              })
            }else{//添加
              const params = Object.assign({},this.form);
              this.saveDisable = true;  //提交保存按钮不可点击，返回结果时才可点击，防止频繁发送请求
              api.addFieldMatch({questionWrapper:params}).then((res)=>{
                if(res.data.code==0){
                  this.$message({
                    message:"添加成功",
                    type:'success'
                  })
                  this.$router.push({name: 'CombineFeild'});
                }else{
                  this.$message({
                    message:res.data.msg,
                    type:'warning'
                  });
                }
                this.saveDisable = false
              })
            }
          // } else {
          //   return false;
          // }
        // });
      },
      warning(msg, type,time) {
          this.$message({
              showClose: true,
              message: msg,
              type: type || 'warning',
              duration:time || '3000'
          })
      },
    }
  }
</script>
<style lang="less" scoped>
    .content {
        background: #fff;
        padding: 20px 20px 50px;
        color: #545455;
        min-width: 980px;
        position: relative;
    }
    .el-form-item{
        width: 600px;
    }
    /deep/.el-input__inner {
      height: 30px;
      line-height: 30px;
    }
    .moduleInfoItem{
      width: 500px;
      min-height: 200px;
      padding: 0 50px 0 50px;
      border: 1px solid #dcdfe6;
      border-radius: 5px;
      margin-bottom: 20px;
      position: relative;
    }
    .searchBox{
      width: 500px;
      position: relative;
    }
    .searchResultBox{
    position: absolute;
    width: 500px;
    box-sizing: border-box;
    max-height: 200px;
    overflow-y: auto;
    background: #fff;
    z-index: 2;
    border: 1px solid #48c5d7;
}
.searchItem{
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    cursor: pointer;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
.searchItem:hover{
    background-color: #F5F7FA;
}
.selectFiled{
    position: relative;
}
.orderBox{
    position: absolute;
    left: -50px;
    top: 50%;
    width: 50px;
    height: 84px;
    margin-top: -42px;
}
.selectFiledBox{
    position: relative;
    min-height: 120px;
}
.order{
    display: inline-block;
    width: 30px;
    height: 30px;
    font-size: 30px;
    margin-left: 5px;
    border: 1px solid #dcdfe6;
    cursor: pointer;
   
}
.delFiled{
    position: absolute;
    top: -8px;
    right: -6px;
    cursor: pointer;
}
.delFiled{
    top: -7px;
    right: -9px;
}
.filedName{
    position: relative;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 5px 10px;
}
.activeFiledName{
    border: 1px solid #48C5D7;
}
.isRequired::before{
     content: '*';
    color: #F56C6C;
    margin-right: 4px;
    float: left;
   line-height: 36px;
   font-size: 14px;
   position: relative;
   top: 2px;
}
</style>