<template>
    <div class="PubTagGroupWrapper"
         @click="closeNameLis(1)"
    >
        <el-form
                class="groups"
                :rules="rules"
                ref="groups"
                :model="form"
                label-width="150px"
        >
            <el-form-item
                    label="选择归属："
                    prop="region1"
            >
                <!-- <span class="changeTips">改变归属后，填写单明细将会恢复到默认状态</span> -->
                <el-select
                        v-model="form.region1"
                        placeholder="请选择归属"
                        :disabled="!!editData.id"
                        @change="readyChangeSelect(1)"
                >
                    <el-option
                            v-for="item in Adscriptions"
                            :label="item.name"
                            :value="item.val"
                            :key="item.val"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item
                    label="选择类型："
                    prop="region2">
                <!-- <span class="changeTips">改变类型后，填写单明细将会恢复到默认状态</span> -->
                <el-select
                        v-model="form.region2"
                        placeholder="请选择类型"
                        :disabled="(!!editData.id&&editData.controlType!='1'&&editData.controlType!='2')  || !form.region1"
                        @change="readyChangeSelect(2)"
                >
                    <el-option
                            v-for="item in labelTypes" 
                            v-if="item.val!=6&&item.val!=7"
                            :label="item.name"
                            :value="item.val"
                            :key="item.val"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item
                    v-if="qaType==2"
                    :label="'是否为主要内容'"
                    prop="region12"
            >
                <el-select
                        v-model="form.region12"
                        :disabled="!form.region1||isEdit"
                        @change="sendData"
                >
                    <el-option
                            label="是"
                            value="0"
                    ></el-option>
                    <el-option
                            label="不是"
                            value="1"
                    ></el-option>
                </el-select>
            </el-form-item>

            <el-form-item
                    label="填写单系统名称："
                    prop="region3">
                <div @click.stop style="display:inline-block;">
                    <el-input
                            v-model="form.region3"
                            :disabled="!form.region1"
                            placeholder="请输入填写单系统名称"
                            @change="sendData"
                            @input="focusSystemName"></el-input>
                    <ul class="systemNames"
                        v-if="isNeedSearch&&systemNameShow">
                        <li v-for="item in systemNameLis"
                            class="ellipsis"
                            :key="item.conceptId"
                            @click="pushSystemName(item.name)">{{item.name}}</li>
                    </ul>
                </div>
                <span class="changeTips changeTipsName" v-if="qaType !=='1'">
                    当为症状时，填写单系统名称需要与医学标准术语内容相对应，如果没有可以先在医学标准术语中建立相关信息！未建立相关信息可能会影响系统使用！
                </span>
            </el-form-item>
            <el-form-item
                    :label="qaType==2?'填写单医生界面展示标准内容：':'填写单界面描述名称：'"
                    prop="region4"
            >
                <el-input
                        :disabled="!form.region1||(qaType==2&&form.region1==1)"
                        v-model="form.region4"
                        :placeholder="qaType==2?'请输入填写单医生界面展示标准内容':'请输入填写单界面描述名称'"
                        @change="sendData"
                ></el-input>
            </el-form-item>
          <!-- <el-form-item class="flag-box"  v-if="qaType =='1'&& form.region1 == '1' && form.region2 != '4'"> -->
          <el-form-item class="flag-box"  v-if="qaType =='1'&&form.region1==1&&(form.region2=='1'||form.region2=='9'||form.region2=='2')">
              <!-- <el-checkbox v-model="form.required"  label="必填" true-label="1" false-label="0"  @change="sendData"></el-checkbox> -->
              <!--<el-checkbox v-if="form.region2=='9'" v-model="form.specFlag" label="拼接到主诉" true-label="1" false-label="0"  @change="sendData"></el-checkbox>-->
              <el-checkbox v-if="(form.region2=='9')&&form.region1!='51'" :disabled="form.flag==='2'" v-model="form.flag" label="时间类型" true-label="1" false-label=""  @change="sendData"></el-checkbox>
              <el-checkbox v-if="(form.region2=='1'||form.region2=='2')&&form.region1!='51'" :disabled="form.flag==='1'" v-model="form.flag" label="诱因类型" true-label="2" false-label=""  @change="sendData"></el-checkbox>
              <!-- <el-checkbox v-if="form.region2=='8'" v-model="form.flag" label="伴随类型" true-label="3" false-label=""  @change="sendData"></el-checkbox> -->
          </el-form-item>
            <!-- <el-form-item
                    v-if="qaType==2"
                    label="填写单患者界面展示通俗内容："
                    prop="region5"
            >
                <el-input
                        :disabled="!form.region1"
                        v-model="form.region5"
                        placeholder="请输入填写单患者界面展示通俗内容"
                        @change="sendData"
                ></el-input>
            </el-form-item> -->
            <el-form-item
                    label="性别："
                    prop="region7"
            >
                <span class="changeTips">改变性别后，填写单明细将会恢复到默认状态</span>
                <el-select
                        v-model="form.region7"
                        :disabled="!!editData.id || !form.region1"
                        @change="readyChangeSelect(3)"
                >
                    <el-option
                            label="通用"
                            value="3"
                    ></el-option>
                    <el-option
                            label="男"
                            value="1"
                    ></el-option>
                    <el-option
                            label="女"
                            value="2"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item
                    label="年龄："
                    prop="region8"
                    class="ages"
            >
                <el-input
                        v-model.number="form.region8"
                        :disabled="!form.region1"
                        type="number"
                        ref="valage1"
                        @input="sendData"
                ></el-input>
            </el-form-item> ~
            <el-form-item
                    prop="region9"
                    class="ages maxAges"
            >
                <el-input
                        v-model.number="form.region9"
                        :disabled="!form.region1"
                        type="number"
                        ref="valage2"
                        @input="sendData"
                ></el-input>
            </el-form-item>
            <el-form-item label="填写单图片内容："
                          v-if="qaType==1&&form.region2&&form.region2!=4&&form.region2!=9"
                          prop="region13">
                <el-upload
                        :class="form.region13?'upload-hide':''"
                        :limit="1"
                        :action="uploadUrl"
                        list-type="picture"
                        :file-list="imgList"
                        :show-file-list="showFileList"
                        :on-remove="handleRemove"
                        :on-success="handleSuccess"
                        :on-error="handleError"
                        accept="image/*"
                        name="upfile">
                    <el-button slot="trigger" size="small" type="primary">上传图片</el-button>
                </el-upload>
            </el-form-item>
            <!-- <el-form-item
                    v-if="qaType==2&&form.region1=='1'&&form.region2=='4'"
                    label="医学教育说明："
                    prop="explains"
            >
                <el-input type="textarea" @input="sendData" v-model="form.explains" maxLength ='100' style="width: 500px;"></el-input>
            </el-form-item> -->
        </el-form>
    </div>
</template>
<script>
  import api from '@api/preTreat.js';
  import utils from '@api/utils.js';
  import config from '@api/config.js';

  /**
   * titlePar 顶部显示左（有默认值可不填）
   * titleSub  顶部显示右（有默认值可不填）
   * form 当前页面传到父组件的数据（region10，region11暂时不用）
   * submitForm 基本信息验证必填项
   * validatePass 基本信息必填项验证成功回调
   * 父组件根据form.region2改变底部组件操作项
   */

  // 归属和填写单类型限制：

// 症状情况(val:1)：单选（val:1）、多选（val:2）、多列填写（val:3）、输入框（val:6）、数字输入框（val:7）、文本域（val:5）

// 诊疗情况(val:51)：单选（val:1）、多选（val:2）、多列填写（val:3）、输入框（val:6）、数字输入框（val:7）、文本域（val:5）、上传图片（val:4）

// 其他史(val:3)：单选（val:1）、多选（val:2）、多列填写（val:3）、输入框（val:6）、数字输入框（val:7）、文本域（val:5）

// 补充内容(val:52)：单选（val:1）、多选（val:2）、多列填写（val:3）、输入框（val:6）、数字输入框（val:7）、文本域（val:5）

  export default {
    props:['editData','qaType','isEdit','isCopy'],      //qaType:独立1/组合2填写单
    data() {
      var validatePass1 = (rule, value, callback) => {
        this.validateSystomName(value,callback,1)
      };
      var validateNameLength = (value,callback,type)=>{
        const limit = (type===2||type===3)&&(this.qaType==2&&this.form.region1==1)?7:30;
        let name = '';
        switch (type){
          case 1:
            name='系统名称';
            break;
          case 2:
            name=this.qaType==1?'界面描述名称':'医生界面标准内容';
            break;
          case 3:
            name='患者界面通俗内容';
            break;
        }
        if(value.length>limit){
          callback(new Error(name+'不能超过'+limit+'个字'));
        }
      };

      var validatePass2 = (rule, value, callback) => {
        const editData = this.$props.editData;
        if(editData.id && value == editData.tagName){ //修改系统名称没变就不再校验
          callback();
        }else{
          validateNameLength(value,callback,1);
          this.validateSystomName(value,callback,2);
        }
      };
      var validatePass11 = (rule, value, callback) => {
        validateNameLength(value,callback,2);
        this.validateSystomName(value,callback,11)
      };
      var validatePass12 = (rule, value, callback) => {
        validateNameLength(value,callback,3);
        this.validateSystomName(value,callback,1)
      };
      var validateLength = (rule, value, callback) => {
        if(value.length>29){
          callback(new Error('不能超过30字'));
        }else{
          callback();
        }
      };
      var validateNum = (rule, value, callback)=>{
        if(value<0||(''+value).indexOf('.')>-1){
          callback(new Error('请输入正整数'));
        }else{
          callback();
        }
      };

      return {
        form: {
          region1: '',    //归属
          region2: '',     //填写单类型
          region3: '',      //系统名称
          region4: '',      //医生界面名称
          region5: '',      //患者界面名称
          region6: '',      //填写单界面描述问题名称
          region7: '3',       //性别
          region8: '0',          //最小年龄
          region9: '200',         //最大年龄
          region12: '0',        //是否为主要内容
          region13:'',          //上传图片
          specFlag:'0',         //拼接到主诉
          required: '0',        //必填
          flag:'',          //控件类型：时间类型1、诱因类型2、伴随类型3
        },
        //isNeedSearch: false, //是否需要查询（系统名称）
        imgList:[],
        showFileList:false,
        uploadUrl:config.urls.uploadImg,        //图片上传地址
        labelTypesMaps: {       // 归属和填写单类型限制
          '1':['1','2','3','5','8','9','10'], //症状情况
          '51':['1','2','3','4','5','9','10'],    //诊疗情况
          '3':['1','2','3','5','9','10'],         //其他史
          '52':['1','2','3','5','9','10']            //补充内容
        },
        combinLabelMaps:{
          '1':['4'], //症状情况
          '51':['4','6'],    //诊疗情况
          '3':['4','6'],         //其他史
          '52':['4','6']            //补充内容
        },
        rules: {
          region1: [
            { required: true, message: '请选择归属', trigger: 'change' }
          ],
          region2: [
            { required: true, message: '请选择类型', trigger: 'change' }
          ],
          region3: [
            { required: true, message: '请输入填写单系统名称', trigger: 'change' },
            { validator: validatePass2, trigger: 'blur' },
          ],
          region4: [
            { required: true, message: '请输入填写单医生界面名称', trigger: 'change' },
            { validator: validatePass11, trigger: 'blur' },
          ],
          region5: [
            { required: true, message: '请输入填写单患者界面名称', trigger: 'change' },
            { validator: validatePass12, trigger: 'blur' },
          ],
          region6: [
            { required: true, message: '请输入填写单界面描述名称', trigger: 'change' },
            { validator: validatePass1, trigger: 'blur' },
          ],
          region7: [
            { required: true, message: '请选择性别', trigger: 'change' }
          ],
          region8: [
            { required: true, message: '请输入最小年龄', trigger: 'change' },
            { validator: validateNum, trigger: 'blur' },
          ],
          region9: [
            { required: true, message: '请输入最大年龄', trigger: 'change' },
            { validator: validateNum, trigger: 'blur' },
          ],
          region12: [
            { required: true, message: '请选择是否为主要内容', trigger: 'change' }
          ],
        },
        Adscriptions: [],
        labelTypes: [],
        labelTypesList: [],
        systemNameShow: false,//系统名称列表显示
        systom:null,      //填写单系统名称存在与否
      }
    },
    computed: {
      isNeedSearch() {
        return this.qaType==2&&this.form.region1==1;
      },
    },
    mounted() {
      this.getDropList();
      //编辑时赋值
      const editData = this.$props.editData;
      if(editData.id){
        const trans = utils.transPretreatKeys(editData,this.qaType==1);
        this.form = Object.assign({},this.form,trans);
        if(this.isCopy){            //复制时系统名称界面名称置空
          this.form.region3='';
          this.form.region4='';
          this.form.region5='';
        }
        const imgUrl = trans.region13;
        if(imgUrl){
          this.imgList = [{name:'',url:imgUrl.replace('{imageUrlPrefix}',config.imgHost)}];
          this.showFileList = true;
        }
      };

      this.$emit('changeVal', this.form, false);
    },
    /*watch: {
      newName(nextVal, prevVal) {
        if (this.isNeedSearch && nextVal != prevVal && (this.form.region12 == 0)) {
          this.focusSystemName()
        }
      },
    },*/
    methods: {
      handleRemove(){
        this.showFileList=false;
        this.form.region13 = '';
        this.imgList=[];
      },
      handleSuccess(response){
        if(response.code==='0'){
          this.showFileList = true;
          this.form.region13 = '{imageUrlPrefix}'+response.data.url;
          this.sendData();
        }else{
          this.imgList = [];
          this.showFileList=false;
          this.warning(response.msg);
        }
      },
      handleError(err, file, fileList){
        this.showFileList=false;
      },
      getDropList() {
        return api.getPreTypeList().then((res) => {
          if (res.data.code === '0') {
            const {isEdit,isCopy} = this.$route.params;
            if(this.qaType == 1){
              this.Adscriptions = res.data.data[1];
              this.labelTypesList = res.data.data[2];
            }else{
              if(isEdit||isCopy){
                this.Adscriptions = res.data.data[1];
                this.labelTypesList = res.data.data[3];
              }else{
                this.Adscriptions = (res.data.data[1]).slice(0,1);
                this.form.region1 = '1'
                this.labelTypesList = (res.data.data[3]).slice(0,1);
                this.form.region2 = '4'
              }
            }

            const editData = this.$props.editData;
            //编辑时，单选、多选可互相切换
            if(editData.controlType=='1'||editData.controlType=='2'){
              this.labelTypes = this.labelTypesList.filter((it)=>{
                return it.val==='1'||it.val==='2';
              })
            }else{
              this.labelTypes = this.labelTypesList;
            }
          }
        })
      },
      validateSystomName(name,callback,flg) {
        if(flg == 1){
          let tmpVal = this.form.region5;
          if(tmpVal.trim() == ''){
            callback(new Error('填写单界面描述名称不能为空'));
          }else{
            this.form.region5 = tmpVal.trim();
            callback();
          }
        }else if(flg == 2){
          let tmpVal = this.form.region3;
          if(tmpVal.trim() == ''){
            callback(new Error('填写单系统名称不能为空'));
          }else{
            this.form.region3 = tmpVal.trim();
            callback();
          }
        }else if(flg == 11){
          let tmpVal = this.form.region4;
          if(tmpVal.trim() == ''){
            callback(new Error('填写单医生界面名称不能为空'));
          }else{
            this.form.region4 = tmpVal.trim();
            callback();
          }
        }
      },
      sendData() {
        this.$emit('changeVal', Object.assign({},this.form), false)
      },
      readyChangeSelect(type) {
        if(type === 1) {
          this.initForm();
          const maps = this.qaType==1?this.labelTypesMaps:this.combinLabelMaps;
          this.labelTypes = this.labelTypesList.filter(item => maps[this.form.region1].includes(item.val));
        }
        //if(type === 2||type === 3) {
        this.form.flag = '';
          this.sendData();
        //}
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$emit('validatePass', this.form, false);
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      focusSystemName() {       //系统名称搜索标准词
        if(!this.isNeedSearch){
          return;
        }
        if (this.form.region3.trim() == '') {
          this.systemNameShow = false;
          this.systemNameLis = [];
          return;
        }
        let params = {
          "libType": [1],
          "name": this.form.region3
        };
        api.indexByLexicon(params).then((res) => {
          if (res.data.code === '0') {
            this.systemNameLis = res.data.data;
            if (res.data.data.length > 0) {
              this.systemNameShow = true;
            } else {
              this.systemNameShow = false;
            }
          }
        })
      },
      pushSystemName(val) {
        this.form.region3 = val;
        if(this.qaType==2&&this.form.region1==1){
          this.form.region4 = val;
        }
        this.systemNameShow = false;
        this.sendData();
      },
      closeNameLis(flg) {
        if (flg == 1) {
          this.systemNameShow = false;
        } else if (flg == 2) {
          if (this.systemNameLis.length > 0) {
            this.systemNameShow = true;
          } else {
            this.systemNameShow = false;
          }
        }
      },
      warning(msg, type) {
        this.$message({
          showClose: true,
          message: msg,
          type: type || 'warning'
        })
      },
      initForm() {
        this.form.region2 = '';
        this.form.region7 = '3';
        this.form.region12 = '0';
        this.form.region13 = '';
        //this.form.region5 = '';
        //this.form.region12 = '1';
      },
    }
  }
</script>
<style lang="less">
    .normalVal .el-input{
        width: auto;
        display: inline-block;
    .el-input__inner {
        width: 40px;
        padding: 0 5px;
    }
    }
    .el-upload-list--picture .el-upload-list__item-name{
        display: none;
    }
    .PubTagGroupWrapper .fix-inp .el-col .el-input__inner{
        width: 100%;
        display: inline-block;
    }
    .PubTagGroupWrapper .fix-inp .el-col-4{
        text-align: center;
    }
    .PubTagGroupWrapper .fix-inp .el-col-8{
        text-align: center;
    }

    .groups {
        background-color: #fff;
        padding: 20px;
        margin: 20px 20px -20px 20px;
    .el-form-item__content,
    .el-input__inner {
        height: 30px;
        line-height: 30px;
        width: 200px;
    }
    .el-form-item {
        margin-bottom: 20px;
    }
    .el-form-item__error {
        width: 200px;
        top: 28px;
    }
    .el-form-item__label {
        line-height: 30px;
        text-align: left;
    }
    .el-input__icon {
        line-height: 30px;
    }
    .ages .el-input {
        display: inline-block;
        width: auto;
    .el-input__inner {
        width: 40px;
        padding: 0 5px;
    }

    .el-input__inner::-webkit-outer-spin-button,
    .el-input__inner::-webkit-inner-spin-button {
        -webkit-appearance: none;
    }

    .el-input__inner[type="number"] {
        -moz-appearance: textfield;
    }
    }
    .el-message-box__btns .el-button--default {
        color: #606266 !important;
    }
    }
    .el-upload-list{
        float: left;
    }
    .upload-hide .el-upload--picture{
        display: none;
    }
    .PubTagGroupWrapper .groups .flag-box {
     .el-form-item__content{
         width:100%;
     }
        label:not(:first-child){
            margin-left: 20px;
        }
    }
</style>

