<template>
  <div
    v-if="permission != 'n'"
    :class="[
      'inputs',
      formInputsDisplay == 'block'
        ? 'ht-form-inputs__block'
        : 'ht-form-inputs__inline',
    ]"
  >
    <div v-if="inputWriteable">
      <template v-if="isSubCellReadOnly">
        <input
          :value="inputVal"
          v-validate="inputValidate"
          type="hidden"
          :name="inputName"
          :data-vv-as="name"
        />
        <div @click="handleCellClick" class="sub-table-cell-readonly">
          <span>{{ inputVal }}</span>
        </div>
      </template>

      <template v-else>
        <input
          v-if="disabled && isValidate"
          v-model="inputVal"
          v-validate="inputValidate"
          type="hidden"
          :name="inputName"
          :data-vv-as="name"
        />
        <el-date-picker
          v-if="!isMobile"
          v-model="inputVal"
          v-validate="inputValidate"
          :size="inputSize"
          :name="inputName"
          :data-vv-as="name"
          :type="type"
          :format="dateFormat"
          :clearable="clearable"
          :value-format="dateFormat ? dateFormat : valueFormat"
          :popper-class="isHideSetNowTime ? 'hide-time' : ''"
          :placeholder="placeholder"
          :disabled="
            disabled ||
            (permission && permission === 'd') ||
            (permission_sub && permission_sub === 'd')
          "
          :readonly="readonly"
          :default-time="defaultTime"
          :picker-options="pickerOptions"
          @blur="handleBlur"
        />
        <div v-else>
          <div class="mobile-input-box mobile-input_date">
            <!-- 校验 -->
            <input
              v-show="!inputVal"
              v-model="inputVal"
              v-validate="validateRules"
              class="mobile_field_input"
              readonly
              :name="inputName"
              :data-vv-as="name"
            />
            <van-cell
              v-validate="!inputVal && validateRules"
              class="mobile-cell"
              :name="inputName"
              :data-vv-as="name"
              :value="inputVal"
              :is-link="
                !(readonly || disabled || (permission && permission === 'd'))
              "
              @click="handleShowPicker"
            >
              <template #title></template>
              <template #default>
                <span v-if="inputVal" class="cell-text">
                  {{ inputVal }}
                </span>
                <span v-else class="placeholder-class">
                  {{ mobilePlaceholder('请选择') }}
                </span>
                <van-icon
                  v-if="
                    inputVal &&
                    !(
                      readonly ||
                      disabled ||
                      (permission && permission === 'd')
                    )
                  "
                  name="clear"
                  color="#bfbfbf"
                  class="cell-close"
                  @click.stop="inputVal = ''"
                />
              </template>
            </van-cell>
          </div>
          <van-popup
            v-model="showPicker"
            get-container="body"
            round
            position="bottom"
          >
            <van-datetime-picker
              v-model="currentDate"
              confirm-button-text="确定"
              :type="type"
              :placeholder="placeholder"
              @cancel="cancelPopup"
              :min-date="minDate"
              :max-date="maxDate"
              @confirm="confirmDate"
            />
          </van-popup>
        </div>
      </template>
    </div>
    <ht-field-tail
      :field-name="inputName"
      :readonly="!inputWriteable"
      :input-value="inputVal"
      :hyperlink="hyperlink"
    />
  </div>
</template>
<script>
  import HtFieldTail from '../../FieldTail/index'
  import permission from '@/mixins/permission.js'
  import inputName from '@/mixins/inputName.js'
  import form from '@/mixins/form.js'
  import mobileMode from '@/mixins/mobileMode.js'
  import popupMode from '@/mixins/popupMode.js'
  import tableFieldReadOnly from '@/mixins/tableFieldReadOnly.js'
  export default {
    name: 'HtDate',
    components: {
      HtFieldTail,
    },
    mixins: [
      permission,
      inputName,
      form,
      mobileMode,
      tableFieldReadOnly,
      popupMode('showPicker'),
    ],
    props: {
      value: String,
      defaultTime: {
        type: String,
      },
      showDate: {
        type: Boolean,
        default: false,
      },
      day: Number,
      format: {
        type: String,
        default: 'yyyy-MM-dd HH:mm:ss',
      },
      valueFormat: {
        type: String,
        default: 'yyyy-MM-dd HH:mm:ss',
      },
      readonly: {
        type: Boolean,
        default: false,
      },
      clearable: {
        type: Boolean,
        default: true,
      },
      disabled: {
        type: Boolean,
        default: false,
      },
      isServerDate: {
        type: Boolean,
        default: false,
      },
      pickerOptions: {
        type: Object,
        default() {
          return {}
        },
      },
      hyperlink: Object,
      isValidate: {
        type: Boolean,
        default: false,
      },
      isHideSetNowTime: {
        type: Boolean,
        default: false,
      },
      minDate: {
        type: Date,
        default: new Date(1925, 1, 1),
      },
      maxDate: {
        type: Date,
        default: new Date(2125, 1, 1),
      },
    },
    data() {
      return {
        type: 'datetime',
        showPicker: false,
      }
    },
    computed: {
      dateFormat: function () {
        const format = this.format ? this.format : this.valueFormat
        return this.userAgentMobile ? format.replace(/-/g, '/') : format
      },
      inputVal: {
        get: function () {
          // 只读情况
          if (!this.inputWriteable) {
            let date = this.value
            if (this.value && this.value.constructor == String) {
              let showV = this.value.replace(/-/g, '/')
              return new Date(showV).format(this.format)
            }
            return date && date.constructor == Date
              ? date.format(this.format)
              : date
          }
          const mobileDate =
            this.value && this.isMobile && typeof this.value === 'string'
              ? this.value.replace(/-/g, '/')
              : this.value
          const dateReg = /^[0-9,/:-\s]+$/

          return isNaN(this.value) &&
            !isNaN(Date.parse(new Date(mobileDate))) &&
            dateReg.test(this.value)
            ? this.isMobile
              ? new Date(mobileDate).format(this.format)
              : new Date(this.value).format(this.format)
            : ''
        },
        set: function (val) {
          if (val && val.constructor == Date) {
            this.$emit('input', val.format(this.format || this.valueFormat))
          } else {
            this.$emit('input', val)
          }
        },
      },
      currentDate: {
        get: function () {
          if (this.inputVal) {
            return new Date(this.inputVal)
          }
          return new Date()
        },
        set: function (val) {},
      },
      validateRules() {
        return this.disabled && !this.isValidate ? '' : this.inputValidate
      },
    },
    watch: {
      format: {
        handler(val) {
          // 通过日期格式来判断控件类型：日期、日期时间
          if (/^\w{4}-\w{1,2}-\w{1,2}$/.test(val)) {
            this.type = 'date'
          }
        },
        immediate: true,
      },
    },
    created() {
      this.initDate()
    },
    methods: {
      handleBlur() {
        // element会触发blur事件，且参数为vue实例对象，在veeValidate中会将该对象识别为日期的值导致必填校验失效。
        // 这里再次触发校验，让其对该控件的值再做一次校验。
        setTimeout(() => {
          this.$validator.validate(this.inputName)
        }, 10)
      },
      // 初始化日期
      initDate() {
        //是否显示当前日期
        if (!this.value && this.showDate) {
          // 设定为获取服务器当前时间 并且 提供了获取的方法
          if (this.isServerDate && this.$requestConfig.getCurrentServerTime) {
            this.$requestConfig
              .getCurrentServerTime(this.dateFormat)
              .then((resp) => this.formatAndSetDate(new Date(resp)))
          } else {
            this.formatAndSetDate(new Date())
          }
        }
      },
      formatAndSetDate(date) {
        if (this.day) {
          //是否指定了相隔的天数
          date = new Date(date.getTime() + this.day * 24 * 60 * 60 * 1000)
        }
        this.inputVal = date.format(this.format || this.valueFormat)
      },
      confirmDate(val) {
        const dateObj = new Date(val)
        const year = dateObj.getFullYear()
        const month = `00${dateObj.getMonth() + 1}`.slice(-2)
        const date = `00${dateObj.getDate()}`.slice(-2)
        const hour = `00${dateObj.getHours()}`.slice(-2)
        const min = `00${dateObj.getMinutes()}`.slice(-2)
        const second = `00${dateObj.getSeconds()}`.slice(-2)
        this.showPicker = false
        let inputVal = year + '-' + month + '-' + date
        if (this.type === 'datetime') {
          inputVal = inputVal + ' ' + hour + ':' + min + ':' + second
        }
        this.inputVal = inputVal
        this.handleBlur()
      },
      handleShowPicker() {
        if (
          this.readonly ||
          this.disabled ||
          (this.permission && this.permission === 'd')
        )
          return
        this.showPicker = true
      },
      cancelPopup() {
        this.handleBlur()
        this.showPicker = false
      },
    },
  }
</script>
<style lang="scss" scoped>
  div[aria-invalid='true'] ::v-deep .el-input__inner,
  div[aria-invalid='true'] ::v-deep .el-input__inner:focus {
    border-color: #f56c6c;
  }
  .mobile-input-box {
    height: 32px;
    position: relative;
  }
  .mobile-input_date {
    .mobile_field_input {
      background: transparent;
    }
  }
  .mobile_field_input {
    border: none;
    width: 100%;
    height: 32px;
    position: absolute;
  }
  .van-cell[aria-invalid='true'] {
    border: none;
  }
  .cell {
    position: absolute;
    top: 0;
    left: 0;
    display: flex;
    align-items: center;
    .van-cell__value {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      .cell-text {
        color: #262626;
        font-size: 14px;
      }
      .cell-close {
        margin-left: 8px;
      }
    }
    .placeholder-class {
      color: #bfbfbf;
      font-size: 14px;
    }
  }
  .inputs.ht-form-inputs__block {
    ::v-deep {
      .el-date-editor {
        width: 100%;
      }
    }
  }
  .van-cell {
    min-height: 32px;
    padding-top: 3px;
    padding-bottom: 0;
    padding-right: 0;
    &::after {
      display: none;
    }
    .van-cell__title {
      width: 1px;
      flex-grow: 0;
    }
  }
  .mobile-cell {
    padding: 0;
    display: flex;
    align-items: center;
    .van-cell__value {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      .cell-text {
        color: #262626;
        font-size: 14px;
        text-align: right;
      }
      .cell-close {
        margin-left: 4px;
      }
    }
    .placeholder-class {
      color: #bfbfbf;
      font-size: 14px;
      text-align: right;
    }
  }
</style>
<style lang="scss">
  .el-picker-panel.hide-time {
    .el-button--text.el-picker-panel__link-btn {
      display: none;
    }
  }
</style>
