<template>
  <div
    class="field-tail__wrap"
    :class="[
      isMobile ? 'mobile-field-tail__wrap' : 'pc-field-tail__wrap',
      isMobile && hasErrors ? 'mobile-error-field-tail' : '',
      isMobile && type === 'number' ? 'mobile-number-field-tail' : '',
    ]"
    :style="{
      height: isMobile && hasErrors ? '' : 'auto',
      display: isMobile && hasErrors ? 'block' : '',
    }"
  >
    <small v-if="hasErrors" class="el-form-item__error">
      {{ errorMessage }}
    </small>
    <div v-if="!isMobile">
      <div v-if="readonly && tagFormatValue.length == 0" class="field-tail">
        <div v-if="isReadonlyTextarea">
          <div v-for="(item, index) in formatInputValue" :key="index">
            <p v-if="item" class="readonly_p">
              <slot name="prefix" class="el-input-group__append"></slot>
              <slot name="suffix" class="el-input-group__append"></slot>
              <slot name="prepend" class="el-input-group__append"></slot>
              {{ item }}
              <slot name="append" class="el-input-group__append"></slot>
            </p>
            <br v-else />
          </div>
        </div>
        <div
          v-else-if="
            (exhibitTextNumber || exhibitTextNumber == 0) && filterCurrency
          "
          class="filter-currency-wrap"
        >
          <span class="filter-currency-number">
            {{ exhibitTextNumber }}{{ company }}
          </span>
          <span class="filter-currency-text">{{ inputValue }}</span>
        </div>
        <el-input
          v-else-if="$readonlyInput"
          v-model="inputValue"
          disabled
        ></el-input>
        <span v-else>
          <slot name="prefix" class="el-input-group__append"></slot>
          <slot name="suffix" class="el-input-group__append"></slot>
          <slot name="prepend" class="el-input-group__append"></slot>
          <el-link
            v-if="hyperlink && hyperlink.url && hyperlink.url.length > 0"
            type="primary"
            :underline="false"
            :href="getHyperlinkUrl()"
            :target="getHyperlinkTarget()"
            @click="showDialog"
          >
            {{ currentShowValue }}
          </el-link>
          <span v-else class="text-readonly">
            {{
              timeRange == 'timeRange'
                ? currentShowValue.replace(/,/g, '-')
                : timeRange == 'dateRange'
                ? currentShowValue.replace(/,/g, '至')
                : currentShowValue
            }}
          </span>
          <template v-if="company && !filterCurrency">{{ company }}</template>
          <slot name="append" class="el-input-group__append"></slot>
        </span>
      </div>
      <template
        v-if="
          readonly &&
          tagFormatValue.constructor == Array &&
          tagFormatValue.length > 0 &&
          !isMobile
        "
      >
        <template v-for="(label, index) in tagFormatValue">
          <el-tooltip
            v-if="label && label !== ''"
            :key="index"
            class="tooltip-item"
            effect="dark"
            :content="label"
            placement="top-start"
          >
            <el-tag v-if="!isPrintMode" class="field-tail-tag">
              {{ label }}
            </el-tag>
            <span v-else class="field-tail-tag">{{ label }}</span>
          </el-tooltip>
        </template>
      </template>
    </div>
    <div v-if="isMobile" class="mobile-readonly-wrap">
      <div
        v-if="readonly && tagFormatValue.length == 0"
        class="field-tail"
        style="
          display: flex;
          justify-content: flex-end;
          align-items: center;
          width: 100%;
        "
      >
        <div v-if="isReadonlyTextarea">
          <div v-for="(item, index) in formatInputValue" :key="index">
            <p v-if="item" class="readonly_p mobile-readonly">
              {{ item }}
            </p>
            <br v-else />
          </div>
        </div>
        <el-input
          v-else-if="$readonlyInput"
          v-model="inputValue"
          disabled
        ></el-input>
        <span v-else class="mobile-readonly">
          <template
            v-if="exhibitTextNumber != null && exhibitTextNumber != undefined"
          >
            <div
              class="num-wrap"
              :class="{ 'is-thousand-num': filterthousandBit }"
            >
              <div v-if="filterCurrency" class="num-t">
                {{ exhibitTextNumber
                }}{{ company && filterCurrency ? company : '' }}
              </div>
              <div class="num-b">
                {{ currentShowValue
                }}{{ company && !filterCurrency ? company : '' }}
              </div>
            </div>
          </template>
          <template v-else>
            {{
              timeRange == 'timeRange'
                ? currentShowValue.replace(/,/g, '-')
                : timeRange == 'dateRange'
                ? currentShowValue.replace(/,/g, '至')
                : currentShowValue
            }}
            <template v-if="company && !filterCurrency">
              {{ company }}
            </template>
          </template>
        </span>
      </div>
      <template
        v-if="
          readonly &&
          tagFormatValue.constructor == Array &&
          tagFormatValue.length > 0
        "
      >
        <template v-if="isTag">
          <van-tag
            v-for="(item, index) in tagFormatValue"
            :key="index"
            class="tag"
            plain
            color="#409EFF"
          >
            {{ item }}
          </van-tag>
        </template>
        <template v-else>
          <span
            v-for="(label, index) in tagFormatValue"
            :key="index"
            class="mobile-readonly font14"
          >
            <span v-if="index != tagFormatValue.length - 1" class="font14">
              {{ label }},
            </span>
            <span v-else class="font14">
              {{ label }}
            </span>
          </span>
        </template>
      </template>
    </div>
    <!-- 超链接弹框 -->
    <ht-template-iframe-dialog ref="dialogIframe"></ht-template-iframe-dialog>
  </div>
</template>
<script>
  import utils from '@/utils.js'
  import mobileMode from '@/mixins/mobileMode.js'

  export default {
    name: 'HtFieldTail',
    mixins: [mobileMode],
    props: {
      fieldName: {
        type: String,
        required: true,
      },
      timeRange: String,
      readonly: {
        type: Boolean,
        default: false,
      },
      inputValue: {
        type: [String, Number, Object, Array, Boolean],
      },
      tagFormatValue: {
        type: [Array],
        default() {
          return []
        },
      },
      writeable: {
        type: Boolean,
        default: true,
      },
      isTag: {
        type: Boolean,
        default: false,
      },
      company: String,
      filterCurrency: {
        type: Boolean,
        default: false,
      },
      filterthousandBit: {
        type: Boolean,
        default: false,
      },
      showCompanys: {
        type: String,
      },
      type: String,
      precision: Number,
      hyperlink: Object,
      exhibitTextNumber: [String, Number],
    },
    data() {
      return {
        scopeName: null,
        dialogVisible: false,
        tableIndex: 0,
      }
    },
    computed: {
      hyperlinkUrl: function () {
        var url = this.hyperlink
          ? this.hyperlink.url.replace(/\[index\]/g, `[${this.tableIndex}]`)
          : ''
        return url
      },
      fieldScopePath: function () {
        let path = this.fieldName
        if (this.scopeName) {
          path = `${this.scopeName}.${this.fieldName}`
        }
        return path
      },
      hasErrors: function () {
        this.$nextTick(() => {
          this.$emit(
            'hasErrors',
            this.errors && this.errors.has(this.fieldScopePath)
          )
        })
        return this.errors && this.errors.has(this.fieldScopePath)
      },
      errorMessage: function () {
        return this.errors && this.errors.first(this.fieldScopePath)
      },
      formatInputValue() {
        let value = []
        if (this.readonly && typeof this.inputValue === 'string') {
          if (this.inputValue.includes('↵')) {
            value = this.inputValue.split('↵')
          } else if (this.inputValue.includes('\n')) {
            value = this.inputValue.split('\n')
          } else {
            value = [this.inputValue]
          }
        }
        return value
      },
      isReadonlyTextarea() {
        return typeof this.inputValue === 'string'
          ? this.inputValue.includes('↵') || this.inputValue.includes('\n')
          : false
      },
      currentShowValue() {
        const isFormat =
          this.filterthousandBit || this.filterCurrency || this.showCompanys
        return this.type === 'number' && !isFormat && this.precision
          ? Number(this.inputValue).toFixed(this.precision)
          : this.inputValue
      },
      // 打印模式
      isPrintMode() {
        let value = false
        this.$store.state &&
          this.$store.state.user &&
          this.$store.state.user.isPrintMode &&
          (value = this.$store.state.user.isPrintMode)
        return value
      },
    },
    mounted() {
      setTimeout(() => {
        this.scopeName = utils.getSomeAttributeFromParentElement(
          this.$el.parentElement,
          'data-vv-scope'
        )
        const { subScopeEl, index } = utils.getSubScopeElAndIndex(
          this.$el.parentElement
        )
        this.tableIndex = index
        if (subScopeEl) {
          if (
            subScopeEl.getAttribute('row_readonly') == 'true' ||
            subScopeEl.getAttribute('row_readonly') === true
          ) {
            this.$emit('update:writeable', false)
          } else {
            const className = Array.prototype.find.call(
              subScopeEl.classList,
              (item) => item.startsWith('row_readonly__')
            )
            if (className && className == 'row_readonly__true') {
              this.$emit('update:writeable', false)
            }
          }
        }
      }, 50)
    },
    created() {
      this.$validator = this.$root.$validator
    },
    methods: {
      /**
       * openType:
        { key: 'dialog', value: '弹窗打开' },
        { key: 'newPage', value: '新增标签页' },
        { key: 'currentPage', value: '当前页面' },
       */
      getHyperlinkTarget() {
        if (
          this.hyperlink &&
          this.hyperlink.openType &&
          this.hyperlink.openType == 'newPage'
        ) {
          return '_blank'
        }
        return ''
      },
      getHyperlinkUrl() {
        if (
          this.hyperlink &&
          this.hyperlink.openType &&
          this.hyperlink.openType == 'dialog'
        ) {
          return null
        }
        // var url = this.hyperlink ? this.hyperlink.url : ''
        return utils.replaceVars4Url(this.hyperlinkUrl, this, true)
      },
      showDialog() {
        if (
          !(
            this.hyperlink &&
            this.hyperlink.openType &&
            this.hyperlink.openType == 'dialog'
          )
        ) {
          return
        }
        this.$refs.dialogIframe.showDialog({
          // title: '超链接弹框',
          url: utils.replaceVars4Url(this.hyperlinkUrl, this),
          dialogWidth: this.hyperlink.width ? this.hyperlink.width : 800,
          dialogHeight: this.hyperlink.width ? this.hyperlink.height : 600,
        })
      },
    },
  }
</script>

<style lang="scss" scoped>
  .el-form-item__error {
    display: flex;
    align-items: center;
    padding-top: 0px;
    z-index: 9;
    &::before {
      display: inline-block;
      content: '\e79d';
      font-family: element-icons !important;
      speak: none;
      font-style: normal;
      font-weight: 400;
      font-variant: normal;
      text-transform: none;
      line-height: 1;
      vertical-align: baseline;
      display: inline-block;
      -webkit-font-smoothing: antialiased;
      font-size: 12px;
    }
  }

  .field-tail {
    display: block;
    word-break: break-all;
    word-wrap: break-word;
    font-size: 14px;
    .filter-currency-wrap {
      display: flex;
      flex-direction: column;
      span {
        line-height: 20px;
      }
    }
  }
  .field-tail-tag {
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .field-tail-tag + .field-tail-tag {
    margin-left: 5px;
  }
  td .el-form-item__error,
  th .el-form-item__error {
    //transform: scale(0.9);
  }
  td .el-form-item__error,
  th .el-form-item__error {
    top: calc(100% - 1px);
  }
  .cell .el-form-item__error {
    top: calc(100% - 0px);
    position: static !important;
  }
  div[name='online-form'] .cell .el-form-item__error {
    top: calc(100% - 0px);
    position: absolute !important;
    overflow: visible;
    text-align: left;
  }
  .readonly_p {
    margin: 0;
  }
  .pc-field-tail__wrap {
    position: relative;
    .el-form-item__error {
      position: absolute;
    }
  }
  .mobile-field-tail__wrap {
    ::v-deep .el-form-item__error {
      color: #ff0000;
      font-size: 12px;
      line-height: 1;
      right: 0;
      bottom: 5px;
      left: auto;
      top: auto;
      justify-content: flex-end;
      &::before {
        display: none;
      }
    }
    .mobile-readonly {
      display: inline-block;
      line-height: 24px;
      padding: 12px 0;
    }
  }
  .mobile-error-field-tail {
    position: absolute;
    bottom: -6px;
    width: 100%;
  }
  .num-wrap {
    .num-t,
    .num-b {
      display: block;
      height: auto;
      line-height: normal;
      font-size: 0.32rem;
      text-align: right;
      // position: absolute;

      right: 0;
    }
    .num-t {
      top: 20%;
      font-size: 14px;
    }
    .num-b {
      margin-top: 4px;
      top: 55%;
      font-size: 14px;
    }
  }
  .is-thousand-num {
    .num-b {
      position: unset;
    }
  }
  .mobile-sunpop-content {
    .mobile-number-field-tail {
      .el-form-item__error {
        right: -10px;
      }
    }
  }
  .sub-div-mobile {
    .mobile-number-field-tail {
      .el-form-item__error {
        right: -10px;
      }
    }
  }

  .text-readonly {
    line-height: 1.2;
  }

  .font14 {
    font-size: 14px;
  }
  .tag {
    font-size: 12px;
    margin-left: 8px;
  }
</style>
