<template>
  <div
    v-if="permission != 'n'"
    :class="[
      'inputs',
      isMobile
        ? ''
        : 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 class="sub-table-cell-readonly" @click="handleCellClick">
          <span>
            {{ inputValToJson }}
          </span>
        </div>
      </template>
      <template v-else>
        <el-date-picker
          v-if="!isMobile"
          v-model="inputVal"
          v-validate="inputValidate"
          :name="inputName"
          :data-vv-as="name"
          :type="dateType"
          :picker-options="pickerOptions"
          :popper-class="popperClass"
          :disabled="
            disabled ||
            (permission && permission === 'd') ||
            (permission_sub && permission_sub === 'd')
          "
          :readonly="readonly"
          :editable="editable"
          :clearable="clearable"
          :size="inputSize"
          :start-placeholder="startPlaceholderVal"
          :end-placeholder="endPlaceholderVal"
          :range-separator="rangeSeparator"
          :format="format"
          :value-format="valueFormat"
          :default-value="defaultValue"
          :default-time="defaultTime"
          :placeholder="placeholder"
          :unlink-panels="unlinkPanels"
          @change="(val) => $emit('change', val)"
          @blur="() => $emit('blur')"
          @focus="() => $emit('focus')"
        ></el-date-picker>
        <div v-else class="mobile-date mobile-input-box">
          <!-- 校验 -->
          <ht-input
            v-model="inputValidateVal"
            type="hidden"
            class="mobile-date-picker__validate"
            :name="name"
            :data-vv-as="name"
            :validate="
              inputVal && inputVal.filter(Boolean).length === 1
                ? {
                    method: {
                      callback: () => {
                        return inputVal && inputVal.filter(Boolean).length !== 1
                      },
                      message:
                        inputVal && inputVal[0]
                          ? '请选择结束时间'
                          : '请选择开始时间',
                    },
                  }
                : inputValidate
            "
          ></ht-input>
          <div class="mobile-start">
            <div class="mobile-start_content">
              <div class="mobile-date_title">开始时间</div>
              <div class="date-value__box" @click="showDateSelect('start')">
                <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="showDateSelect('end')">
                <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"
            get-container="body"
          >
            <van-datetime-picker
              v-model="currentDate"
              :type="
                dateType === 'datetimerange' || dateType === 'datetime'
                  ? 'datetime'
                  : 'date'
              "
              title="选择年月日"
              @confirm="dateConfirm"
              :min-date="minDate"
              :max-date="maxDate"
              @cancel="showPicker = false"
            />
          </van-popup>
        </div>
      </template>
    </div>
    <ht-field-tail
      :field-name="inputName"
      :readonly="!inputWriteable"
      :input-value="value"
      :hyperlink="hyperlink"
      time-range="dateRange"
    />
  </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 utils from '@/utils.js'
  import popupMode from '@/mixins/popupMode.js'
  import tableFieldReadOnly from '@/mixins/tableFieldReadOnly.js'

  export default {
    name: 'HtDatePicker',
    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],
      },
      defaultTime: {
        type: String,
      },
      format: {
        type: String,
        default: 'yyyy-MM-dd HH:mm:ss',
      },
      valueFormat: {
        type: String,
        default: 'yyyy-MM-dd HH:mm:ss',
      },
      popperClass: String,
      rangeSeparator: {
        type: String,
        default: '-',
      },
      pickerOptions: {
        type: Object,
        default() {
          return {
            shortcuts: [
              {
                text: '最近一周',
                onClick(picker) {
                  const end = new Date()
                  const start = new Date()
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                  picker.$emit('pick', [start, end])
                },
              },
              {
                text: '最近一个月',
                onClick(picker) {
                  const end = new Date()
                  const start = new Date()
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                  picker.$emit('pick', [start, end])
                },
              },
              {
                text: '最近三个月',
                onClick(picker) {
                  const end = new Date()
                  const start = new Date()
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
                  picker.$emit('pick', [start, end])
                },
              },
            ],
          }
        },
      },
      startPlaceholder: {
        type: String,
      },
      endPlaceholder: {
        type: String,
      },
      unlinkPanels: {
        type: Boolean,
        default: false,
      },
      hyperlink: Object,
      minDate: {
        type: Date,
        default: new Date(1925, 1, 1),
      },
      maxDate: {
        type: Date,
        default: new Date(2125, 1, 1),
      },
    },
    data() {
      return {
        currentType: '', // 当前选择日期类型 start end
        showPicker: false,
        dateVal: '',
      }
    },
    computed: {
      dateType() {
        return /^\w{4}-\w{1,2}-\w{1,2}$/.test(this.format)
          ? 'daterange'
          : 'datetimerange'
      },
      startPlaceholderVal() {
        return this.startPlaceholder
          ? this.startPlaceholder
          : this.t('ht.date.startDate')
      },
      endPlaceholderVal() {
        return this.endPlaceholder
          ? this.endPlaceholder
          : this.t('ht.date.endDate')
      },
      inputVal: {
        get: function () {
          if (this.value && this.value.constructor == String) {
            return this.value.split(',')
          }
          return this.value
        },
        set: function (val) {
          if (val && val.constructor == Array) {
            this.$emit('input', val.join(','))
            return
          }
          this.$emit('input', val)
        },
      },
      currentDate: {
        get: function () {
          if (this.inputVal) {
            return new Date(this.inputVal)
          }
          return new Date()
        },
        set: function (val) {},
      },
      inputValidateVal() {
        return this.inputVal && this.inputVal.filter(Boolean).length
          ? this.inputVal.join(',')
          : ''
      },
    },
    mounted() {
      if (this.isMobile) {
        this.addMobileTopLabelClass()
      }
    },
    methods: {
      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(','))
      },
      dateConfirm(val) {
        let arr = this.inputVal ? JSON.parse(JSON.stringify(this.inputVal)) : []
        if (this.currentType === 'start') {
          arr[0] =
            this.dateType === 'datetimerange' || this.dateType === 'datetime'
              ? utils.formatDate(val)
              : utils.formatDateYear(val)
        } else {
          arr[1] =
            this.dateType === 'datetimerange' || this.dateType === 'datetime'
              ? utils.formatDate(val)
              : utils.formatDateYear(val)
        }
        // 判断开始时间是否小于或等于结束时间
        if (new Date(arr[0]).getTime() > new Date(arr[1]).getTime()) {
          // 如果不符合，清空开始时间和结束时间
          arr = []
          let msg = '开始时间不能晚于结束时间！'
          if (this.isMobile) {
            this.$toast.fail({ message: msg, duration: 2500 })
          } else {
            this.$message.warning(msg)
          }
        }
        this.$emit('input', arr.join(','))
        this.showPicker = false
      },
      showDateSelect(type) {
        if (this.disabled || (this.permission && this.permission === 'd'))
          return
        this.currentType = type
        this.showPicker = true
      },
    },
  }
</script>
<style lang="scss" scoped>
  div.inputs.ht-form-inputs__inline {
    // width: auto;
  }
  .inputs {
    div.el-date-editor--daterange[aria-invalid='true'],
    div.el-date-editor--datetimerange[aria-invalid='true'] {
      border-color: #f56c6c;
    }
    position: relative;
  }
  .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: 10px;
    }
    .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;
    }
    .placeholder {
      font-size: 14px;
      color: #bfbfbf;
    }
    ::v-deep {
      .mobile-date-picker__validate {
        width: 0 !important;
        position: unset;
      }
    }
  }
</style>
