<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
          v-validate="inputValidate"
          :value="inputVal"
          type="hidden"
          :name="inputName"
          :data-vv-as="name"
        />
        <div class="sub-table-cell-readonly" @click="handleCellClick">
          <span>
            {{ inputValToJson }}
          </span>
        </div>
      </template>
      <template v-else>
        <el-time-picker
          v-if="!isMobile"
          v-model="inputVal"
          v-validate="inputValidate"
          :arrow-control="arrowControl"
          :name="inputName"
          :data-vv-as="name"
          :picker-options="pickerOptions"
          :disabled="
            disabled ||
            (permission && permission === 'd') ||
            (permission_sub && permission_sub === 'd')
          "
          :readonly="readonly"
          :editable="editable"
          :clearable="clearable"
          :size="inputSize"
          :start-placeholder="startPlaceholderVal"
          :end-placeholder="endPlaceholderVal"
          :is-range="isRange"
          :range-separator="rangeSeparator"
          :value-format="valueFormat"
          :format="format"
          :default-value="defaultValue"
          :placeholder="placeholder"
          @blur="handleBlur"
        ></el-time-picker>
        <div v-else class="mobile-date mobile-input-box">
          <div class="mobile-start">
            <div class="mobile-start_content">
              <div class="mobile-date_title">开始时间</div>
              <div class="date-value__box" @click="handleShowPicker">
                <span v-if="inputVal[0]" class="date-text">
                  {{ inputVal[0].replace(/-/g, '/') }}
                </span>
                <span v-else class="placeholder">
                  {{ mobilePlaceholder('请选择开始时间') }}
                </span>
              </div>
            </div>
            <van-icon
              v-if="
                (inputVal[0] && !disabled) ||
                (inputVal[0] && !(permission && permission === 'd'))
              "
              name="clear"
              color="#bfbfbf"
              class="cell-close"
              @click="clearDate('start')"
            />
            <div class="line1"></div>
            <div class="line2"></div>
          </div>
          <div class="mobile-end">
            <div class="mobile-end_content">
              <div class="mobile-date_title">结束时间</div>
              <div class="date-value__box" @click="handleShowPicker">
                <span v-if="inputVal[1]" class="date-text">
                  {{ inputVal[1].replace(/-/g, '/') }}
                </span>
                <span v-else class="placeholder">
                  {{ mobilePlaceholder('请选择结束时间') }}
                </span>
              </div>
            </div>
            <van-icon
              v-if="
                (inputVal[1] && !disabled) ||
                (inputVal[1] && !(permission && permission === 'd'))
              "
              name="clear"
              color="#bfbfbf"
              class="cell-close"
              @click="clearDate('end')"
            />
          </div>
          <van-popup
            v-model="showPicker"
            round
            position="bottom"
            :lazy-render="false"
            @click-overlay="closePopup"
          >
            <div class="header_top">
              <span style="color: #969799" @click="closePopup">取消</span>
              <span style="color: #409eff" @click="comfirm">确定</span>
            </div>
            <div
              style="
                display: flex;
                justify-content: center;
                align-items: center;
              "
            >
              <van-picker
                ref="startTimePicker"
                title="开始时间"
                :columns="startColumns"
                @change="startTimeChange"
              />
              至
              <van-picker
                ref="endTimePicker"
                title="结束时间"
                :columns="endColumns"
                @change="endTimeChange"
              />
            </div>
          </van-popup>
        </div>
      </template>
    </div>
    <ht-field-tail
      :field-name="inputName"
      :readonly="!inputWriteable"
      :input-value="value"
      time-range="timeRange"
    />
  </div>
</template>
<script>
  import HtFieldTail from '../../FieldTail/index'
  import locale from '@/mixins/locale.js'
  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: 'HtTimePicker',
    components: {
      HtFieldTail,
    },
    mixins: [
      locale,
      permission,
      inputName,
      form,
      mobileMode,
      popupMode('showPicker'),
      tableFieldReadOnly,
    ],
    props: {
      value: String,
      readonly: {
        type: Boolean,
        default: false,
      },
      disabled: {
        type: Boolean,
        default: false,
      },
      clearable: {
        type: Boolean,
        default: true,
      },
      editable: {
        type: Boolean,
        default: true,
      },
      defaultValue: {
        type: [String, Date],
      },
      valueFormat: {
        type: String,
        default: 'HH:mm:ss',
      },
      format: {
        type: String,
        default: 'HH:mm:ss',
      },
      rangeSeparator: {
        type: String,
        default: '-',
      },
      pickerOptions: {
        type: Object,
        default() {
          return {}
        },
      },
      arrowControl: {
        type: Boolean,
        default: false,
      },
      isRange: {
        type: Boolean,
        default: false,
      },
      endPlaceholder: {
        type: String,
      },
      startPlaceholder: {
        type: String,
      },
    },
    data() {
      return {
        showPicker: false,
        dateVal: '',
        startTime: '',
        endTime: '',
        startColumns: [],
        endColumns: [],
        columns: [
          // 第一列
          {
            values: [],
          },
          // 第二列
          {
            values: [],
          },
          // 第二列
          {
            values: [],
          },
        ],
      }
    },
    computed: {
      startPlaceholderVal() {
        return this.startPlaceholder
          ? this.startPlaceholder
          : this.t('ht.date.startTime')
      },
      endPlaceholderVal() {
        return this.endPlaceholder
          ? this.endPlaceholder
          : this.t('ht.date.endTime')
      },
      inputVal: {
        get: function () {
          if (this.value && this.isRange && this.value.constructor == String) {
            return this.value.split(',')
          }
          return this.value
        },
        set: function (val) {
          if (val && this.isRange && val.constructor == Array) {
            this.$emit('input', val.join(','))
            return
          }
          this.$emit('input', val)
        },
      },
    },
    mounted() {
      for (let i = 0; i <= 23; i++) {
        this.columns[0].values.push(i < 10 ? `0${i}` : i)
      }
      for (let i = 0; i <= 59; i++) {
        this.columns[1].values.push(i < 10 ? `0${i}` : i)
        this.columns[2].values.push(i < 10 ? `0${i}` : i)
      }
      this.startColumns = JSON.parse(JSON.stringify(this.columns))
      this.endColumns = JSON.parse(JSON.stringify(this.columns))
      if (this.isMobile) {
        this.addMobileTopLabelClass()
      }
    },
    methods: {
      handleBlur() {
        // element会触发blur事件，且参数为vue实例对象，在veeValidate中会将该对象识别为日期的值导致必填校验失效。
        // 这里再次触发校验，让其对该控件的值再做一次校验。
        setTimeout(() => {
          this.$validator.validate(this.inputName)
        }, 10)
      },
      comfirm() {
        this.inputVal = [this.startTime, this.endTime]
        // 判断开始时间是否小于或等于结束时间
        if (this.timeToSec(this.startTime) > this.timeToSec(this.endTime)) {
          // 如果不符合，清空开始时间和结束时间
          this.inputVal = []
          let msg = '开始时间不能晚于结束时间！'
          if (this.isMobile) {
            this.$toast.fail({ message: msg, duration: 2500 })
          } else {
            this.$message.warning(msg)
          }
        }
        this.showPicker = false
      },
      startTimeChange(picker, value) {
        this.$refs.startTimePicker.getValues().join(':')
        this.startTime = value.join(':')
      },
      endTimeChange(picker, value) {
        this.$refs.endTimePicker.getValues().join(':')
        this.endTime = value.join(':')
      },
      handleShowPicker() {
        if (
          this.readonly ||
          this.disabled ||
          (this.permission && this.permission === 'd')
        )
          return
        const currentHours = `00${new Date().getHours()}`.slice(-2)
        const currentMinutes = `00${new Date().getMinutes()}`.slice(-2)
        const currentSeconds = `00${new Date().getSeconds()}`.slice(-2)
        const defaultTime = `${currentHours}:${currentMinutes}:${currentSeconds}`
        // 有 inputVal 就取默认的，没有就取当前时间
        this.startTime = this.inputVal[0] || defaultTime
        this.endTime = this.inputVal[1] || defaultTime
        this.initDefaultSelect(this.startTime, this.endTime)
        this.showPicker = true
      },
      // 设置默认选择项
      initDefaultSelect(startTime, endTime) {
        const startTimeArr = startTime.split(':')
        const endTimeArr = endTime.split(':')
        this.$refs.startTimePicker.setIndexes(startTimeArr)
        this.$refs.endTimePicker.setIndexes(endTimeArr)
      },
      // 关闭弹窗
      closePopup() {
        this.showPicker = false
        this.startTime = ''
        this.endTime = ''
        this.startColumns.forEach((i) => delete i.defaultIndex)
        this.endColumns.forEach((i) => delete i.defaultIndex)
      },
      clearDate(type) {
        let arr = this.inputVal ? JSON.parse(JSON.stringify(this.inputVal)) : []
        if (type === 'start') {
          arr[0] = ''
        } else {
          arr[1] = ''
        }
        this.$emit('input', arr.join(','))
      },
      //将时分秒转为时间戳
      timeToSec(time) {
        if (time !== null) {
          var s = ''
          var hour = time.split(':')[0]
          var min = time.split(':')[1]
          var sec = time.split(':')[2]
          s = Number(hour * 3600) + Number(min * 60) + Number(sec)
          return s
        }
      },
    },
  }
</script>
<style lang="scss" scoped>
  div.inputs.ht-form-inputs__inline {
    // width: auto;
  }
  .inputs {
    div.el-date-editor--timerange[aria-invalid='true'] {
      border-color: #f56c6c;
    }
  }
  .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;
    }
  }
  .van-picker {
    flex: 1;
  }
  .header_top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 14px;
    padding: 0 16px;
    height: 44px;
  }
  .cell {
    display: flex;
    align-items: center;
    padding: 0;
    .van-cell__value {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      .cell-text {
        color: #262626;
        font-size: 14px;
      }
      .cell-close {
        margin-left: 4px;
      }
    }
    .placeholder-class {
      color: #bfbfbf;
      font-size: 14px;
    }
  }

  .mobile-date {
    width: 100%;
    display: flex;
    .mobile-start,
    .mobile-end {
      display: flex;
      align-items: center;
      width: 50%;
      margin: 15px 0;
      line-height: normal;
      .mobile-start_content,
      .mobile-end_content {
        height: 43px;
        margin-right: 8px;
        .date-text {
          color: #262626;
          font-size: 14px;
        }
      }
    }
    .mobile-end {
      padding-left: 15px;
    }
    .mobile-start {
      position: relative;
      overflow: hidden;
      .line1 {
        width: 1px;
        background: #e6e6e6;
        position: absolute;
        right: 0;
        top: 50%;
        height: 100%;
        transform: rotate(167deg);
        transform-origin: top left;
      }
      .line2 {
        width: 1px;
        background: #e6e6e6;
        position: absolute;
        right: 1px;
        top: 50%;
        height: 100%;
        transform-origin: top left;
        transform: rotate(13deg);
      }
    }
    .mobile-date_title {
      color: #8c8c8c;
      font-size: 12px;
      margin-bottom: 8px;
      text-align: left;
    }
    .placeholder {
      font-size: 14px;
      color: #bfbfbf;
    }
  }
</style>
