<!-- @desc:文本输入框组件  @auth:周兴  @time:2022/5/9 14:32 -->
<template>
  <div v-if="existsFlag" style="width: 100%;">
    <Poptip popper-class="input-popper-class" ref="pop" transfer trigger="focus" placement="top-start" v-model="visible"
            :disabled="!visible">
      <div class="close-div-class" :class="addTabInputFlag?'add-table-input':'' || clearable?'clearable-class':''">
        <Input size="small" ref="input" @on-blur="handleBlur" @on-focus="handleFocus" @on-click="$emit('on-click')"
               @on-clear="handleClear"
               @contextmenu.native.prevent
               @on-enter="$emit('on-enter')" @on-change="handleChange" @on-keyup="handleKeyup"
               @on-keydown="handleKeydown"
               @dblclick.native="copyValue()"
               :icon="icon"
               :show-word-limit="showWordLimit"
               :rows="textAreaRows"
               :disabled="disabled"
               :name="name" :readonly="readonly" v-model="value2" :placeholder="placeholderData"
               :class="readonly ? 'readonly-input' : null" :clearable="false" :type="inputType"
               :maxlength="maxlengthData" :number="number">
          <span v-if="prefix" class="prepend-class" slot="prepend">{{ prefix }}</span>
          <div v-show="unit" slot="append">{{ unit }}</div>
        </Input>
        <!--是否显示清除按钮-->
        <div v-if="clearable">
          <!--只有在聚焦时才会显示-->
          <div v-if="value2 && isFocus && (!readonly || magnifierFlag)" style="cursor: pointer" >
            <Icon slot="prefix" type="iconfont iconfont icon-clear" @click.stop="clearAll"/>
          </div>
          <div v-else style="width: 16px;height: 16px">
          </div>
        </div>
      </div>
      <div slot="content" class="pop-content">
        <div class="pop-item-content">{{ this.value2 }}</div>
      </div>
    </Poptip>
  </div>
</template>

<script>
export default {
  name: 'InputPop',
  inject: {
    prop: {
      type: String,
      default: null
    },
    required: {
      type: Boolean,
      default: false
    },
    dkFormItem: {
      type: Object,
      default: null
    }
  },
  props: {
    icon: {
      type: String,
      default: ''
    },
    //input值
    value: {
      type: String,
      default: ''
    },
    //字段名
    prop: {
      type: String,
      default: ''
    },
    //单位
    unit: {
      type: String,
      default: null
    },
    //名称
    name: {
      type: String,
      default: null
    },
    //最大长度
    maxlength: {
      type: String,
      default: '100'
    },
    //只读
    readonly: {
      type: Boolean,
      default: false
    },
    //只读
    disabled: {
      type: Boolean,
      default: false
    },
    //将用户的输入转换为 Number 类型
    number: {
      type: Boolean,
      default: false
    },
    // 是否显示清除标识
    clearable: {
      type: Boolean,
      default: true
    },
    // 是否显示多行文本
    textareaFlag: {
      type: Boolean,
      default: false
    },
    //是否开启提示
    popVisible: {
      type: Boolean,
      default: true
    },
    //前缀
    prefix: {
      type: String,
      default: null
    },
    //是否以密码形式显示
    password: {
      type: Boolean,
      default: false
    },
    //提示信息
    placeholder: {
      type: String,
      default: null
    },
    // 是否自动转大写
    upperFlag: {
      type: Boolean,
      default: true,
    },
    // 是否是为联系电话（电话是11位，允许0在首位）
    telephone: {
      type: Boolean,
      default: false
    },
    // 电话的最大位数（满足000001此类纯数字序号）
    telephoneMaxDigits: {
      type: Number,
      default: 11
    },
    // 是否显示输入字数统计，可以配合 maxlength 使用
    showWordLimit: {
      type: Boolean,
      default: false,
    },
    // 放大镜
    magnifierFlag: {
      type: Boolean,
      default: false
    },
    // 行数
    areaRows: {
      type: Number,
      default: 1
    },
    // 添加tab中使用
    addTabInputFlag: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    const vm = window.vm;
    return {
      vm: vm,
      existsFlag: true,
      value2: '',
      placeholderData: null,
      label: '',
      visible: false,
      isFocus: false,
      inputType: 'text',
      maxlengthData: '100',
      textAreaRows: 3,                // 默认行数
      popWidth: '200px',
    }
  },
  watch: {
    value2(n, o) {
      //只有在聚焦时才会显示tip
      if (this.isFocus) {
        this.setPopVisible(n);  //设置tip是否可见
      }
      if (n) {
        setTimeout(() => {
          // 清除提示信息
          this.clearErrMessage();
        }, 100)
      }
      this.$emit('input', n?.trim())
    },
    value(n, o) {
      if (n == null || n == 'null' || n == undefined) {
        this.value2 = ''
      } else {
        this.value2 = n
      }
    },
    readonly(n, o) {
      // 给提示信息赋值
      setTimeout(() => {
        this.setReadOnly(n)
      }, 500)
    },
    unit(n, o) {
      this.$refs.input.slotReady = !!n
    },
    placeholder(n, o) {
      // console.log('bbbb',n)
      // // 给提示信息赋值
      // this.setReadOnly(this.readonly)
    }
  },
  methods: {
    /**
     * @desc   : 复制单元格
     * @author : 周兴
     * @date   : 2022/6/9 9:31
     */
    copyValue() {
      if (this.value2) {
        this.$message.success(vm.$t('copySuccess') + '：' + this.value2);
        //创建一个input框
        const input = document.createElement("input");
        input.setAttribute("style", "z-index:-1000;position: absolute;bottom:0;")
        //将指定的DOM节点添加到body的末尾
        document.body.appendChild(input);
        //设置input框的value值为直播地址
        input.setAttribute("value", this.value2);
        //选取文本域中的内容
        input.select();
        //copy的意思是拷贝当前选中内容到剪贴板
        //返回值为一个Boolean，如果是 false 则表示操作不被支持或未被启用
        if (document.execCommand("copy")) {
          document.execCommand("copy");
        }
      }
    },
    /**
     * @desc   : 清空
     * @author : 周兴
     * @date   : 2023/1/13 10:35
     */
    clearAll() {
      this.handleClear();
    },
    /**
     * @desc   : 值改变事件
     * @author : 周兴
     * @date   : 2022/7/21 18:32
     */
    handleChange(e) {
      if (this.upperFlag && !this.textareaFlag) {
        let selectionStart = e.target.selectionStart;
        // 转大写
        let value = this.value2;
        // 转大写
        if (value) {
          value = value.toUpperCase();
        }
        this.value2 = value;
        // 中间输入的时候把光标移动回来
        setTimeout(() => {
          e.target.selectionStart = selectionStart;
          e.target.selectionEnd = selectionStart;
        }, 30)
      }
      if(this.value2){
        this.isFocus = true;
      }
      this.$emit('on-change', this.value2)
    },
    /**
     * @desc   : 键盘弹起事件，解决中文输入后的数据
     * @author : 周兴
     * @date   : 2022/8/18 15:02
     */
    handleKeyup(e) {
      this.$emit('on-keyup', e)
      if(this.readonly){
        return;
      }
      if (this.telephone) {
        if (this.value2) {
          this.value2 = this.value2.replace(/[^\d]/g, '');
        }
      }
    },
    /**
     * @desc   : 键盘事件
     * @author : 周兴
     * @date   : 2022/4/12 10:26
     */
    handleKeydown(e) {
      this.$emit('on-keydown', e);
      // 不是电话不控制
      if (this.telephone) {
        //backspace,delete,enter,tab，左右不控制
        if (e.keyCode === 8 || e.keyCode === 9 || e.keyCode === 46 || e.keyCode === 37
          || e.keyCode === 39 || e.keyCode === 13) {
          return;
        }
        //ctrl+v,ctrl+c不控制
        if ((e.key === 'v' || e.key === 'c') && e.ctrlKey) {
          return;
        }
        //不允许其他非数字按键输入
        if ((e.keyCode < 48 || e.keyCode > 57)
          && (e.keyCode < 96 || e.keyCode > 105)
          && e.keyCode != 110 && e.keyCode != 190 && e.keyCode != 189) {
          e.preventDefault();
        }
        //查看是否有选中数据，再输入的情况(除小数点外)
        let selectedLength = e.target.selectionEnd - e.target.selectionStart;
        if (selectedLength > 0) {
          return;
        }
        // 如果内容已经包括负号，输入的负号就不允许
        if (this.value2 && this.value2.indexOf('-') >= 0 && e.key === '-') {
          e.preventDefault();
        }
        let num = this.value2 + "" + e.key;
        //说明是插入到字符串中的
        if (e.target.selectionEnd < e.target.value.length) {
          num = this.$libaray.insertStr(e.target.value, e.target.selectionEnd, e.key)
        }
        //判断是否包括负数
        if (num.length > this.telephoneMaxDigits) {
          e.preventDefault();
        }
      }
    },
    /**
     * @desc   : 焦点移入事件
     * @author : 周兴
     * @date   : 2022/4/14 11:07
     */
    handleFocus(e) {
      this.isFocus = true;
      this.setPopVisible(this.value2);  //设置tip是否可见
      this.$emit('on-focus', e)
    },
    /**
     * @desc   : 聚焦
     * @author : 周兴
     * @date   : 2022/11/30 14:37
     */
    focus() {
      if (this.textareaFlag) {
        this.$refs.input.$refs.textarea.focus()
      } else {
        this.$refs.input.$refs.input.focus()
      }
    },
    /**
     * @desc   : 清空
     * @author : 周兴
     * @date   : 2022/4/13 14:51
     */
    handleClear() {
      this.value2 = null;
      this.focus()
      this.$emit('on-clear')
    },
    /**
     * @desc   : 光标离开事件
     * @author : 周兴
     * @date   : 2022/4/11 15:09
     */
    handleBlur(e) {
      this.visible = false;
      setTimeout(()=>{
        this.isFocus = false;
      },200)
      this.value2 = this.value2?.trim();
      this.$emit('on-blur', e);
      if (this.telephone) {
        if (this.value2) {
          this.value2 = this.value2.replace(/[^\d]/g, '');
        }
      }
    },
    /**
     * @desc   : 控件只读时的处理
     * @author : 周兴
     * @date   : 2022/3/4 11:12
     */
    setReadOnly(value) {
      // 给提示信息赋值
      if (value) {
        if (!this.magnifierFlag) {
          this.placeholderData = null
        } else {
          this.placeholderData = this.placeholder;
        }
        // 给输入框赋值灰色背景
      } else {
        this.placeholderData = this.placeholder == null ? (vm.$t('inputWords', {'search-name': this.label})) : this.placeholder
      }
    },
    /**
     * @desc   : 设置pop是否可见
     * @author : 周兴
     * @date   : 2022/4/14 10:54
     */
    setPopVisible(value) {
      if (value && value.length > 0 && this.popVisible && !this.password) {
        // 如果输入的文字超出才会给出pop
        if (this.$refs.input.$refs.input && this.$refs.input.$refs.input.scrollWidth > this.$refs.input.$refs.input.clientWidth + 5) {
          this.visible = true;
          // 设置pop的宽度
          this.setPopWidth();
        } else {
          this.visible = false;
        }
      } else {
        this.visible = false;
      }
    },
    /**
     * @desc   : 设置pop的宽度
     * @author : 周兴
     * @date   : 2023/11/17 8:31
     */
    setPopWidth(){
      let inputWidth = this.$refs['input'].$el.offsetWidth;
      if (inputWidth < 200) {
        this.popWidth = '200px';
      } else {
        this.popWidth = inputWidth + 'px';
      }
    },
  },
  beforeDestroy() {
    this.existsFlag = null;
  },
  mounted() {
    if (this.dkFormItem) {
      this.dkFormItem.setItems(this);   // 把当前组件赋值给formItem
    }
    this.$refs.input.slotReady = this.$refs.input.append && this.unit
  },
  created() {
    if (this.value == null || this.value == 'null' || this.value == undefined) {
      this.value2 = ''
    } else {
      this.value2 = this.value.trim();
    }
    //获取名称
    let name = null
    if (!this.dkFormItem || !this.dkFormItem.label) {
      if (this.name) {
        // 给label赋值
        name = this.name
      } else {
        name = this.prop
      }
      // 获取国际化名称
      this.label = vm.$t(name)
    } else {
      this.label = this.dkFormItem.label
    }
    this.maxlengthData = this.maxlength;
    // 给提示信息赋值
    this.setReadOnly(this.readonly)
    if (this.password) {
      this.inputType = 'password'
      this.visible = false;
    } else if (this.textareaFlag) {
      this.inputType = 'textarea'
      if (this.maxlength === '100') {
        this.maxlengthData = vm.$config.textAreaMaxLength;
      }
    } else {
      this.inputType = 'text'
    }
    // 行数
    this.textAreaRows = this.areaRows;
  }
}
</script>
<style scoped>

/deep/ .ivu-input-wrapper-small .ivu-input-icon {
  transform: none !important;
}


/*只读颜色*/
.readonly-input > /deep/ .ivu-input {
  background-color: #f3f3f3 !important;
}

.ivu-poptip {
  width: 100%;
}

/deep/ .ivu-poptip-rel {
  width: 100%;
}

.prepend-class {
  padding: 6px 8px;
  margin: -8px -8px;
  font-size: inherit;
  font-weight: normal;
  line-height: 1;
  color: #515a6e;
  text-align: center;
  background-color: #f8f8f9;
  border: 1px solid #dcdee2;
  border-radius: 2px;
}

/deep/ .ivu-input-group-append {
  font-weight: 400;
  line-height: 1;
  color: #515a6e;
  text-align: center;
  background-color: #f8f8f9;
  border: 1px solid #dcdee2;
  border-left: none !important;
}

.pop-content {
  width: 255px;
  min-width: 200px;
  /*background: #e9edf1;*/
  padding: 10px;
  border: 1px #a5acb5;
  overflow-y: auto;
  overflow-x: hidden;
}

.pop-item-content {
  padding: 5px 5px 5px 5px;
  width: 250px;
  white-space: pre-wrap;
  word-break: break-all;
}

/deep/ .ivu-input-word-count {
  z-index: 10 !important;
}

/deep/ .clearable-class .ivu-input-wrapper {
  width: calc(100% - 16px) !important;
}

.add-table-input /deep/ .ivu-input {
  height: 22px !important;
  width: 70px !important;
  margin: -16px -15px -10px -15px !important;
  border: none !important;
}

.add-table-input /deep/ .ivu-input-wrapper {
  width: 100% !important;
}


</style>

