<template>
    <div>
        <crumbs :title="title" :param="$route.params" linkTo="BaseField"></crumbs>
        <div class="contents">
            <div class="content">
            <el-form ref="form" :label-position="labelPosition" label-width="125px" :model="form" :rules="rules">
                <el-form-item label="所属医院：" prop="hospitalId">
                    <el-select v-model="form.hospitalId"
                               placeholder="请选择"
                                 @change="changeHospital"
                               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="请选择"
                               @change="changeModule"
                               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="form.tagName"></el-input>
                </el-form-item>
                <el-form-item label="显示名称：" prop="name">
                    <el-input type="text" placeholder="请输入显示名称" v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="取值字段：" prop="value">
                    <el-input type="text" placeholder="请输入取值字段" v-model="form.val"></el-input>
                    
                </el-form-item>
                <el-form-item label="关联缺陷条目：" prop="casesEntryIds">
                    <el-select filterable
                               multiple
                               v-model="casesEIds"
                               placeholder="请选择"
                               class="big-select"
                               size="small">
                        <el-option
                                v-for="item in flawList"
                                :key="item.id"
                                :label="item.name"
                                :value="String(item.id)">
                        </el-option>
                    </el-select>
                    
                </el-form-item>
                <el-form-item>
                    <el-checkbox v-model="form.monoLine" :true-label="Number(1)" :false-label="Number(0)">独占一行</el-checkbox>
                    <el-checkbox v-model="form.addLine" :true-label="Number(1)" :false-label="Number(0)">内容换行</el-checkbox>
                    <el-checkbox v-model="form.position" :true-label="Number(1)" :false-label="Number(0)">靠右显示</el-checkbox>
                    <el-checkbox v-model="form.bold" :true-label="Number(1)" :false-label="Number(0)">内容加粗</el-checkbox>
                    <el-checkbox v-model="form.retract" :true-label="Number(1)" :false-label="Number(0)">内容缩进</el-checkbox>
                </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,
        title:'字段映射维护-添加字段映射',
        casesEIds:'',
        form:{
          tagType:1,        //固定
          modeId:"",
          hospitalId:"",
          name:'',
          val:'',
          tagName:'',
          monoLine:0,
          addLine:0,
          bold:0,
          position:0,
          retract:0,
          casesEntryIds:'',
          quesCasesEntryVOList:[]
        },
        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'] }],*/
        },
        copy:null,
        saveDisable: false,  //保存按钮禁止点击
        flawList:[],
        hisTypes:[],
        fieldTypes:[],
      }
    },
    created(){
      this.getAllTypes();
      let {isCopy,info} = this.$route.params;
      this.copy=isCopy;
      if(info){
        const infoCopy =  Object.assign({},info);
        isCopy?infoCopy.id="":"";
        // infoCopy.casesEntryIds?this.casesEIds = infoCopy.casesEntryIds.split(","):'';
        let tmpArr = [],tmpArr1 = []
        for(let i = 0;i < infoCopy.quesCasesEntryDTOList.length;i++){
          let obj = {
            name:infoCopy.quesCasesEntryDTOList[i].casesEntryName,
            casesEntryName:infoCopy.quesCasesEntryDTOList[i].casesEntryName,
            id:infoCopy.quesCasesEntryDTOList[i].casesEntryId,
            casesEntryId:infoCopy.quesCasesEntryDTOList[i].casesEntryId
          }
          tmpArr.push(""+infoCopy.quesCasesEntryDTOList[i].casesEntryId)
          tmpArr1.push(obj)
        }
        infoCopy.quesCasesEntryDTOList?this.casesEIds = tmpArr:'';
        infoCopy.quesCasesEntryVOList = [...tmpArr1];
        this.title=isCopy?"字段映射维护-复制字段映射":'字段映射维护-修改字段映射';
        this.form = infoCopy;
        this.getQcFlawList(tmpArr1);
      }else{
        let hospitalId = localStorage.getItem("qcSelectHospital")&&Number(localStorage.getItem("qcSelectHospital")) || "";
        let modeId = localStorage.getItem("qcSelectModule")&&Number(localStorage.getItem("qcSelectModule"))  || "";
    
        let qcSelecttModuleNme = localStorage.getItem("qcSelectModuleName");
        this.form.hospitalId = hospitalId
        this.form.modeId = modeId
        this.form.tagName = qcSelecttModuleNme
        this.getQcFlawList()
      }
    },
    watch:{
      "casesEIds":function(val){
        this.form.casesEntryIds = val.join(",");
        let tmp = []
        for(let i = 0;i < val.length;i++){
          let obj = {
            casesEntryId:val[i],
            id:val[i],
          }
          tmp.push(obj)
        }
        this.form.quesCasesEntryVOList = tmp
      }
    },
    methods:{
      changeHospital(val){
         localStorage.setItem("qcSelectHospital",val);
           
        this.getQcFlawList()
        this.form.modeId=""
        this.form.quesCasesEntryDTOList =[]
        this.casesEIds=[]
      },
      changeModule(val){
         localStorage.setItem("qcSelectModule",val);
         const qcSelecttModuleNme  = this.fieldTypes.find(item => Number(item.val) === val).name + '-'
         this.form.tagName = qcSelecttModuleNme
          localStorage.setItem("qcSelectModuleName",qcSelecttModuleNme);
        this.getQcFlawList()
         this.form.quesCasesEntryDTOList =[]
        this.casesEIds=[]
      },
      getQcFlawList(val){
        const { hospitalId, modeId } = this.form
        if(hospitalId === '' || modeId === ''){
          return
        }
        const param={modeId:modeId,hospitalId:hospitalId,name:"",filter:1,size:500};
        api.getQcFlawList(param).then((res)=>{
          if(res.data.code==="0") {
            const data = res.data.data;
            this.flawList = []
            this.flawList = data.records;
            let info = this.$route.params.info;
            if(info){
              const infoCopy =  Object.assign({},this.form);

              
              for(let i = 0;i < infoCopy.quesCasesEntryDTOList.length;i++){
                let obj = {
                  name:infoCopy.quesCasesEntryDTOList[i].casesEntryName,
                  casesEntryName:infoCopy.quesCasesEntryDTOList[i].casesEntryName,
                  id:infoCopy.quesCasesEntryDTOList[i].casesEntryId,
                  casesEntryId:infoCopy.quesCasesEntryDTOList[i].casesEntryId
              }
              this.flawList.unshift(obj)
            }
            }
          }else{
            this.warning("获取缺陷条目失败");
          }
        });
      },
      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]));
          }else{
            this.warning("获取枚举信息失败");
          }
        });
      },
      comfirn(form){
        /*if(!this.form.name.trim() || !this.form.refreshTime.trim()){
          this.$message({
            message:'请填写相关内容',
            type:'warning'
          });
          return
        }*/
        this.$refs[form].validate((valid) => {
          if (valid) {
            const { val } = this.form
            let regex = /(?<=【)(.+?)(?=】)/g;
             let regex2 = /[^\u4e00-\u9fa5|a-zA-Z0-9]+/
            const matchVal = val.match(regex) ||[]
            let illegalCode = false
            for(let i = 0; i < matchVal.length; i++){
              if(regex2.test(matchVal[i])){
                illegalCode = true
              }
            }
            if(illegalCode){
              this.warning("取值字段【】含有非法字符")
              return;
            }

            if(this.form.id){//修改
              const param = Object.assign({},this.form);
              this.saveDisable = true;  //提交保存按钮不可点击，返回结果时才可点击，防止频繁发送请求
              api.addFieldMatch({questionWrapper:param}).then((res)=>{
                if(res.data.code==0){
                  this.$message({
                    message:"修改成功",
                    type:'success'
                  });
                  //返回带搜索条件的首页
                  this.$router.push({
                    name: 'BaseField',
                    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: 'BaseField'});
                }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>
    .content .el-form-item.is-success .el-input__inner{
        border-color: #ccc;
    }
</style>
<style lang="less" scoped>
    .content {
        background: #fff;
        padding: 20px 20px 50px;
        color: #545455;
        min-width: 980px;
        position: relative;
        .el-checkbox{
            display: inline-block;
        }
    }
    .el-form-item{
        width: 600px;
    }
    .el-select.big-select{
        width: 360px;
    }
</style>