<template>
	<div style="position:relative;">
		
		<el-input
			v-if="isShowStepBox"
			v-model="addDate"
      :class="{'highlight': highlight,'selfDatePicker':true}"
			:style="{'border-bottom': isShowRed ? `1px solid ${isShowRed}` : ''}"
			type="text"
			@change="handleEnter"
      clearable
      ref="add"
      v-bind:disabled="isDisable"
      :placeholder="placeholderEnable || placeholder || $t('components.请选择')"
		></el-input>
    <i class="date-pick-btn el-icon-date" >
      <el-date-picker
        ref="picker"
        :id="id"
        v-model="model"
        v-bind="attrs"
        v-on="$listeners"
        :editable="false"
        :clearable="false"
        v-bind:disabled="isDisable"
        :value-format="valueFormat" :format="format" @change="handleChange"
        :picker-options="pickerOptionsFormat()"
      ></el-date-picker>
    </i>
	</div>
</template>

<script>
import commonDepend from '~/mixin/commonDepend.js'
import markSetShowRed from '~/components/business/componentMixins/markSetShowRed.js'
import moment from 'moment'
import _ from 'lodash'
export default {
	inject: {
		root: {
			default: () => null
		}
	},
	data () {
		return {
      addDate: '',
      dateList: []
		}
	},
	mixins: [commonDepend, markSetShowRed],
	props: {
		value: {
			default: ''
		},
		disabled: {
			type: Boolean,
			default: false
		},
		valueFormat: {
			type: String,
			default: 'yyyy-MM-dd'
		},
		format: {
			type: String,
			default: 'yyyy-MM-dd'
		},
		id: {
			type: String,
			default: undefined
    },
    placeholder:{
      type: String,
      default: null
    },
    // 此对象为markset或者modifySet所在的对象,如果传了此对象可以标记当前对象下的字段为红色下划线
    markSetData: {
      type: Object,
      default: () => null
    },
		customModifykey: {
			type: String,
      default: null
		},
		isShowStepBox: {
			type: Boolean,
      default: true
    },
    pickerOptions:{
      type: Object,
      default:()=>{}
    }
	},
	computed: {
		model: {
			get() {
				return this.value
			},
			set(newVal) {
				this.$emit('input', newVal)
			}
		},
		mode() {
			return this.$store.state.Status.mode
		},
		isDisable: {
			get() {
				return this.mode === 'display' || this.disabled
			}
		},
    placeholderEnable(){
      let label = this.$parent.label
      let curLabel = ''
      if (label) {
        curLabel = this.$i18n.locale === 'en' ? this.$t('components.请选择') + ' ' +  this.$t('components.' + label) : this.$t('components.请选择') + this.$t('components.' + label)
      }
      return curLabel
    },
		highlight() {
			return this.$store.state.Status.highlights.indexOf(this.id) !== -1
		},
		attrs() {
			if (this.mode === 'display' || this.disabled) {
				let { placeholder, ...rest } = this.$attrs
				return rest
			}
			return this.$attrs
    },
    dataFormat(){
      return (this.valueFormat||this.format).toUpperCase()
    }
  },
  watch:{
    value(){
      this.updateToAdd()
    },
    disabled(newVal) {
      if (newVal) {
        this.resetValidate()
      }
    }
  },
  mounted(){
		this.updateToAdd()
		this.initDateList()
  },
	methods: {
    updateToAdd(){
      if(this.value&&moment(this.value).isValid){
       this.addDate = moment(this.value).format(this.dataFormat);
      }else{
        this.addDate = ""
      }
    },
		handleChange (val) {
			if (!this.customModifykey) {
				// 添加isModify属性
				this.changeModify()
				let value = val || this.model
				let curDate = moment(value).format('YYYY-MM-DD')
        if (this.dateList.includes(curDate)) {
          this.$notify({
            title: `您选中的 ${curDate} 是节假日`,
            type: 'warning',
            duration: 3000
          })
        }
			}
    },
		handleEnter () {
			let val = this.addDate
      if(!val) {
				//都清空
        this.$emit('input', null)
        this.$nextTick(()=>this.$emit("change"))
        return
      }
      // 处理输入小数时,四舍五入成天
      val = !isNaN(val) ? Number(val).toFixed(0) : val
      //8位数字按照年月日处理
      if(!/^\d{8}$/g.test(val) && /^[+-]?\d+$/g.test(val)){
        if (val.startsWith('-')) {
          let addDate = val.substr(1)
          if(addDate.length > 3){
            this.showTip()
            return
          }
          let mom = moment(this.value||undefined).subtract(addDate, "days");
          let newval = mom.format(this.dataFormat)
          if(this.pickerOptions && this.pickerOptions.disabledDate){
            if(this.pickerOptions.disabledDate(mom.toDate())){
              this.addDate = this.model
              return this.$message({
                  message:  newval+"日期不可选",
                  type:"warning"
                })
            }
					}
          this.$emit('input', newval)
					this.addDate = newval
          this.handleChange(newval)
        }else{
          if (val.startsWith('+')) {
            val = val.substr(1)
          }
          if(val.length > 3){
            this.showTip()
            return
          }	
          let mom = moment(this.value||undefined).add(val, "days")
          let newval  = mom.format(this.dataFormat);

          if(this.pickerOptions && this.pickerOptions.disabledDate){
            if(this.pickerOptions.disabledDate(mom.toDate())){
              this.addDate = this.model
              return this.$message({
                  message:  newval+"日期不可选",
                  type:"warning"
                })
            }
					}
					this.$emit('input', newval)
          this.addDate = newval
        	this.handleChange(newval)
				}
        this.$nextTick(()=>this.$emit("change"))
        return
      }
      let mom = moment(val)
      if(mom.isValid()){
				let newval  = mom.format(this.dataFormat)
        this.$emit('input', newval)
        this.addDate = newval
				this.$nextTick(()=>this.$emit("change"))
        this.handleChange(newval)
        return
      }

     this.showTip()
    },
    showTip(){
      this.$message({
            message:"请输入正负3位以内数字或正确日期",
            type:"warning"
          })
       //重置   
      this.addDate = this.model
    },
    pickerOptionsFormat() {
      let options = {
        ...this.pickerOptions,
        cellClassName: (time) => {
					this.initDateList()
          if ((this.dateList && this.dateList.includes(moment(time).format('YYYY-MM-DD')))) {
            return 'badge'
          }
        }
      }
      return options;
		},
		initDateList () {
			let cur = 'CNY'
			if (this.root && this.root.buildCommonData) {
				let buildCommonData = this.root.buildCommonData(this.root.model, this.root.trnName)
				if (buildCommonData) {
					let maxCur = _.get(buildCommonData, ['cbsMap', 'MAX', 'cur'])
					let opn1Cur = _.get(buildCommonData, ['cbsMap', 'OPN1', 'cur'])
					let nom1Cur = _.get(buildCommonData, ['cbsMap', 'NOM1', 'cur'])
					cur = maxCur || opn1Cur || nom1Cur || 'CNY'
				}
			}
			let dateMap = {}
			let localHolidays = localStorage.getItem('localHolidays')
			if (localHolidays && cur) {
				dateMap = JSON.parse(localHolidays)
				this.dateList = dateMap[cur]
			}
		}
	}
}
</script>

<style>
  .el-input.highlight .el-input__inner {
    border-color: red;
  }
  .date-pick-btn{
    /* position: relative !important; */
    cursor: pointer;
    position: absolute;
    left: 5px;
    top: 9px;
    color: var(--primary-color);
  }
  .date-pick-btn .el-date-editor{
    position: absolute;
    top:0;
    left: 0;
    opacity: 0;
  }
  .selfDatePicker .el-input__inner{
    padding-left: 25px !important;
  }
  .badge > div ::after {
    width: 14px;
    height: 14px;
    position: absolute;
    content: 'H';
    right: -10px;
    top: -7px;
    text-align: center;
    line-height: 12px;
    border-radius: 50%;
    color: #fff;
    background: red;
    transform: scale(0.7);
	}
	.el-input__prefix{
	height: 16px!important;
}
</style>