<template>
  <div class="el-bio-form">
    <!--字符串-->
    <el-tooltip
      v-if="itemList.fieldtype === 'string'"
      :disabled="itemList.showTool"
      :visible-arrow="false" class="item"
      placement="right-start"
      popper-class="input-tip">
      <template #content>
        <!-- 提示内容 -->
        <div class="input-tip__content">
          {{ itemList.value }}
        </div>
      </template>
      <div @mouseover="tooltipHover($event,itemList)">
        <el-input
          v-model="itemList.value"
          :clearable="clearable"
          :disabled="disabled||itemList.txtreadonly"
          :maxlength="itemList.wordLimit||255"
          :placeholder="placeholder">
        </el-input>
      </div>
    </el-tooltip>

    <!--下拉选-->
    <template v-else-if="itemList.fieldtype === 'select'">
      <Radio
        v-if="['1', '2'].includes(itemList.codelisttype)"
        :disabled="disabled" :itemList="itemList"
        @radioChange="selectChange"/>

      <el-tooltip
        v-else
        :disabled="itemList.showTool"
        :visible-arrow="false" class="item"
        placement="right-start"
        popper-class="input-tip">
        <template #content>
          <div class="input-tip__content">
            {{ selectDesp }}
          </div>
        </template>
        <div @mouseover="tooltipHover($event,itemList)">
          <el-select
            v-model="itemList.value"
            :clearable="clearable"
            :disabled="disabled"
            :filterable="filterable"
            :placeholder="placeholder?placeholder:''"
            @change="selectChange">
            <el-option
              v-for="(item, index) in itemList.selector"
              :key="index" :disabled="item.disabled"
              :label="item[itemList.labelKey || 'codedesp']||' '"
              :value="item[itemList.valueKey || 'codevalue']">
            </el-option>
          </el-select>
        </div>
      </el-tooltip>
    </template>

    <!--多选-->
    <template v-else-if="itemList.fieldtype === 'mselect'">
      <el-checkbox-group
        v-if="['1', '2'].includes(itemList.codelisttype)"
        v-model="itemList.value"
        :class="{'checkbox-block': itemList.codelisttype === '1'}"
        :disabled="disabled"
        @change="selectChange">
        <template v-for="(checkboxItem, checkboxIndex) in itemList.selector">
          <el-checkbox
            :key="checkboxIndex"
            :disabled="checkboxItem.disabled"
            :label="checkboxItem.codevalue">
            {{ checkboxItem.codedesp }}
          </el-checkbox>

          <br
            v-if="itemList.codelisttype === '2' && ( checkboxIndex + 1 ) % ( itemList.format || 1) === 0"
            :key="`key${checkboxIndex}`"/>
        </template>
      </el-checkbox-group>

      <el-select
        v-else
        v-model="itemList.value"
        :class="disabled?'disabled-multiple':''"
        :clearable="!disabled" :collapse-tags="collapseTags"
        :placeholder="placeholder"
        multiple
        @change="selectChange">
        <el-option
          v-for="(item, index) in itemList.selector"
          :key="index"
          :disabled="disabled"
          :label="item[itemList.labelKey || 'codedesp']"
          :value="item[itemList.valueKey || 'codevalue']">
        </el-option>
      </el-select>
    </template>

    <template v-else-if="['datetime', 'date'].includes(itemList.fieldtype)">
      <!--可编辑日期-->
      <BioDatePicker
        v-if="editActive"
        v-model="itemList.value"
        :disabled="disabled"
        :innerValue="innerValue"
        :item-list="itemList"
        :type="itemList.fieldtype === 'datetime' ? 'datetime' : 'date'"
        @selectChange="selectChange"/>

      <el-date-picker
        v-else
        v-model="itemList.value"
        :disabled="disabled"
        :editable="false"
        :format="formatV"
        :type="itemList.fieldtype"
        :value-format="formatV"
        @change="selectChange(true)">
        <!--dateLimit 限制日期大于等于当前天数-->
      </el-date-picker>
    </template>

    <!--daterange-->
    <el-date-picker
      v-else-if="['daterange', 'monthrange','datetimerange'].includes(itemList.fieldtype)"
      v-model="itemList.value"
      :disabled="disabled"
      :type="itemList.fieldtype"
      value-format="yyyy-MM-dd"
      @change="selectChange">
    </el-date-picker>

    <!--month-->
    <el-date-picker
      v-else-if="itemList.fieldtype === 'dateMonth'"
      v-model="itemList.value"
      :disabled="disabled"
      type="month"
      @change="selectChange(true)">
    </el-date-picker>

    <!--year-->
    <el-date-picker
      v-else-if="itemList.fieldtype === 'dateYear'"
      v-model="itemList.value"
      :disabled="disabled"
      type="year"
      @change="selectChange">
    </el-date-picker>

    <el-time-picker
      v-else-if="itemList.fieldtype === 'time'"
      v-model="itemList.value"
      :disabled="disabled"
      :format="itemList.format || innerValue.format"
      :value-format="itemList.format || innerValue.format"
      editable
      @change="selectChange">
    </el-time-picker>

    <!--日期时分秒-->
    <template v-else-if="itemList.fieldtype === 'timeSelect'">
      <el-time-picker
        v-model="itemList.value"
        :disabled="disabled"
        format="HH:mm"
        @change="selectChange">
      </el-time-picker>
    </template>

    <div v-else-if="itemList.fieldtype === 'clob'" style="position:relative;width: 100%">
      <el-input
        ref="biotextreaRef"
        v-model="itemList.value"
        :autosize="{ minRows: 1, maxRows: 40}"
        :disabled="disabled"
        :maxlength="itemList.wordLimit"
        :placeholder="placeholder"
        :show-word-limit="!!itemList.wordLimit"
        type="textarea">
      </el-input>
      <div ref="biotoolRef" class="textarea-hide">
        {{ itemList.value }}
      </div>
    </div>

    <div v-else-if="itemList.fieldtype === 'text'">
      {{ itemList.value }}
    </div>

    <!--多选可编辑-->
    <template v-else-if="itemList.fieldtype === 'selectcreat'">
      <el-select
        v-model="itemList.value"
        :allow-create="!disabled"
        :class="disabled?'disabled-multiple':''"
        :clearable="!disabled"
        :placeholder="placeholder"
        filterable
        multiple
        @change="selectChange">
        <el-option
          v-for="(item, index) in itemList.selector"
          :key="index"
          :disabled="disabled"
          :label="item[itemList.labelKey || 'codedesp']"
          :value="item[itemList.valueKey || 'codevalue']">
        </el-option>
      </el-select>
    </template>

    <!--密码-->
    <template v-else-if="itemList.fieldtype === 'password'">
      <el-input
        v-model="itemList.value"
        :clearable="clearable"
        :disabled="disabled"
        :maxlength="101"
        :show-password="true"
        type="password">
      </el-input>
    </template>

    <!--纯数字-->
    <template v-else-if="itemList.fieldtype === 'number'">
      <el-input
        v-model.number="itemList.value"
        :clearable="clearable"
        :disabled="disabled"
        :maxlength="101"
        oninput="value=value.replace(/[^0-9.]/g,'')"
        @change="selectChange">
      </el-input>
    </template>

    <!--小数-->
    <template v-else-if="itemList.fieldtype === 'decimals'">
      <el-input-number
        v-model="itemList.value" :disabled="disabled" :max="itemList.week?24:Infinity"
        :min="0"
        :precision="Number(itemList.precision)||1"
        controls-position="right"
        @change="selectChange">
      </el-input-number>
    </template>

    <!--级联选择-->
    <template
      v-if="itemList.fieldtype==='cascader'">
      <el-tooltip
        :disabled="!(itemList.label &&itemList.label.length > 10)"
        :visible-arrow="false"
        class="item" placement="right-start"
        popper-class="input-tip">
        <template #content>
          <div class="input-tip__content">
            {{ itemList.label }}
          </div>
        </template>
        <el-cascader
          v-model="itemList.value"
          :disabled="disabled"
          :options="itemList.selector"
          :show-all-levels="true"
          filterable
          size="mini"
          @change="selectChange"/>
      </el-tooltip>
    </template>
  </div>
</template>

<script>
import BioDatePicker from './components/DatePick';
import Radio from './components/Radio';
import _ from 'lodash';
import {getSelectValueDesp} from '../../../src/utils/bioknow/utils';

export default {
  name: 'BioForm',

  props: {
    innerValue: {
      type: Object
    },

    itemList: {
      type: Object,
      required: true
    },

    collapseTags: {
      type: Boolean,
      default: false,
      required: false
    },

    index: {
      type: String
    },

    itemRow: {
      type: Object
    },

    disabled: {
      type: Boolean
    },

    clearable: {
      type: Boolean,
      default: true
    },

    placeholder: {
      type: String
    },
    filterable: {
      type: Boolean,
      default: false
    }
  },

  components: {
    BioDatePicker,
    Radio
  },

  computed: {
    formatV() {
      let _format = '';

      if (this.itemList) _format = this.itemList.sysformat || this.itemList.format || '';
      if (this.innerValue) _format = _format || this.innerValue.sysformat || this.innerValue.format || '';

      return _format;
    },

    editActive() {
      let flag = false;

      if (_.has(this.itemList, 'editActive')) {
        flag = this.itemList.editActive;
      } else if (_.has(this.innerValue, 'editActive')) {
        flag = this.innerValue.editActive;
      }

      return flag;
    },

    selectDesp() {
      return _.has(this.itemList, 'selectdesp') ? this.itemList.selectdesp : this.$options.filters.selectValue(this.itemList);
    }
  },

  mounted() {
    // 针对文本框滚动条问题做出的特殊处理
    if (this.$refs.biotextreaRef) {
      const style = document.defaultView.getComputedStyle(this.$refs.biotoolRef);
      setTimeout(() => {
        this.$refs.biotextreaRef.$refs.textarea.style.height = style.height;
        if (this.$refs.biotextreaRef.$refs.textarea.scrollHeight > this.$refs.biotextreaRef.$refs.textarea.clientHeight) {
          if (this.$refs.biotextreaRef.$refs.textarea.clientHeight < 358) {
            this.$refs.biotextreaRef.$refs.textarea.style.height = this.$refs.biotextreaRef.$refs.textarea.clientHeight + 20 + 'px';
          }
        }
        this.$refs.biotoolRef.remove();
      }, 1);
    }
  },

  methods: {
    selectChange(isDate = false, tip = true) {
      const selected = getSelectValueDesp(this.itemList);

      this.$set(this.itemList, 'valueDesp', selected.valueDesp);

      // el 多选的值会按照点击顺序存储
      if (this.itemList.fieldtype === 'mselect') {
        this.$set(this.itemList, 'value', selected.mselectValue);
      }

      this.$emit('selectChange', {
        itemList: this.itemList,
        index: this.index,
        row: this.itemRow,
        selectItem: selected.selectItem,
        isEdit: tip
      });
    },

    // 判断字段是否溢出隐藏，用于控制悬浮文字框的显隐
    tooltipHover(e, itemList) {
      this.$set(itemList, 'showTool', false);
      const curStyle = window.getComputedStyle(e.target, '');
      const textSpan = document.createElement('span');
      textSpan.style.fontSize = curStyle.fontSize;
      textSpan.style.fontWeight = curStyle.fontWeight;
      textSpan.style.fontFamily = curStyle.fontFamily;
      textSpan.style.border = curStyle.border;
      textSpan.innerHTML = e.target.value;
      if (!e.target.value) return this.$set(itemList, 'showTool', true);
      let left = 0;
      let right = 0;
      if (curStyle.paddingLeft) left = Number(curStyle.paddingLeft.split('px')[0]);
      if (curStyle.paddingRight) right = Number(curStyle.paddingRight.split('px')[0]);
      document.body.appendChild(textSpan);
      if (e.target.offsetWidth > (textSpan.offsetWidth + left + right)) this.$set(itemList, 'showTool', true);
      document.body.removeChild(textSpan);
    },

    changeValue(ev, itemList) {
      itemList.value = ev;
    }
  }
};
</script>

<style lang="scss" scoped>
.el-bio-form {
  display: inline-block;
}

::v-deep .input-tip {
  &__content {
    max-width: 200px;
    @media (max-width: 1400px) {
      max-width: 150px;
    }
  }
}

.bio-textrea {
  width: 100%;
  min-height: 20px;
  max-height: 300px;
  _height: 120px;
  margin-left: auto;
  cursor: auto;
  margin-right: auto;
  padding: 3px 5px;
  outline: 0;
  border: 1px solid #a0b3d6;
  font-size: 12px;
  border-radius: 3px;
  line-height: 24px;
  word-wrap: break-word;
  overflow-x: hidden;
  overflow-y: auto;
}

/*文本框下的隐藏盒子*/
.textarea-hide {
  width: 100%;
  position: absolute;
  visibility: hidden;
  top: 0;
  z-index: -999;
  padding: 5px 15px;
  white-space: pre-wrap;
  overflow-wrap: break-word;
  overflow: auto;
  line-height: 1.5;
  box-sizing: border-box;
  width: 100%;
  font-size: inherit;
  color: #606266;
  background-color: #FFFFFF;
  background-image: none;
  border: 1px solid #DCDFE6;
  font-family: Arial;
  border-radius: 4px;
  min-height: 30px;
  display: block;
  resize: vertical !important;
  color: #606266;
  background-color: #FFFFFF;
  background-image: none;
  letter-spacing: normal;
  text-transform: none;
  text-indent: 0px;
  text-shadow: none;
  word-spacing: normal;
  text-align: start;
  appearance: auto;
  -webkit-rtl-ordering: logical;
  cursor: text;
  white-space: pre-wrap;
  overflow-wrap: break-word;
  word-break: break-word;
}
</style>
