<template>
  <div v-if="currentNode.data.Type == 1 || currentNode.data.Type == 2">
    <q-input v-model="model.StartValue" @update:model-value="changeModelHandler" filled dense placeholder="请输入"></q-input>
  </div>
  <div v-if="currentNode.data.Type == 3">
    <q-select @update:model-value="radioModel.changeHandler" v-model="radioModel.model" map-options :options="radioModel.Option" :option-label="radioModel.label" :option-value="radioModel.val" filled dense></q-select>
  </div>
  <div v-if="currentNode.data.Type == 4">
    <q-select multiple @update:model-value="checkModel.changeHandler" v-model="checkModel.model" map-options :options="checkModel.Option" :option-label="checkModel.label" :option-value="checkModel.val" filled dense></q-select>
  </div>
  <div v-if="currentNode.data.Type == 7">
    <q-input v-model="model.StartValue" @update:model-value="integerModel.changeHandler" filled dense placeholder="请输入"></q-input>
  </div>

  <div v-if="currentNode.data.Type == 5 && dateModel.options.length > 0">
    <n-cascader class="vt-cascader" v-model:value="dateModel.model" multiple clearable placeholder="请选择" max-tag-count="responsive" expand-trigger="click" :options="dateModel.options" check-strategy="child" @update:value="dateModel.changeHandler" />
  </div>
  <div v-if="currentNode.data.Type == 6" class="vt-header-box">
    <q-input outlined dense v-model="dateRangeModel.formatRange" placeholder="请选择" readonly>
      <q-popup-proxy ref="rangeRefs" transition-show="scale" transition-hide="scale">
        <q-date v-model="dateRangeModel.model" range @range-end="dateRangeModel.changeHandler"></q-date>
      </q-popup-proxy>
    </q-input>
  </div>
</template>

<script>
import { inject, reactive, watch, onMounted, ref } from 'vue'
export default {
  props: {
    /**
     * 条件节点
     */
    node: Object
  },
  setup(props) {
    const model = inject('whereModel')

    const currentNode = ref(props.node)

    watch(
      () => props.node,
      val => {
        currentNode.value = val
        model.value.StartValue = ''
        model.value.EndValue = ''
        init(val)
      },
      { deep: true }
    )

    const changeModelHandler = () => {
      // console.log(model.value)
      // context.emit('update:modelValue', model.value)
    }

    //#region 封装的规则映射数据

    const radioModel = reactive({
      model: null,
      Option: [],
      val: 'Id',
      label: 'Name',
      changeHandler: val => {
        model.value.StartValue = `${val.Id}`
        changeModelHandler()
      }
    })

    const checkModel = reactive({
      model: [],
      Option: [],
      val: 'Id',
      label: 'Name',
      changeHandler: val => {
        let startValue = ''
        val.forEach((x, i) => {
          startValue += x.Id
          if (i < val.length - 1) {
            startValue += ','
          }
        })
        model.value.StartValue = startValue
        changeModelHandler()
      }
    })

    const integerModel = reactive({
      mask: '',
      nomuch: (val, len) => {
        val = val.replace(/[^\d.]/g, '') //清除"数字"和"."以外的字符
        val = val.replace(/^\./g, '') //验证第一个字符是数字而不是
        val = val.replace(/\.{2,}/g, '.') //只保留第一个. 清除多余的
        val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
        let lenStr = ''
        for (let i = 0; i < len; i++) {
          lenStr += '\\d'
        }
        let matchRule = ''
        eval(`matchRule=/^(\\-)*(\\d+)\\.(${lenStr}).*$/`)
        val = val.replace(matchRule, '$1$2.$3') //只能输入一个小数
        return val
      },
      changeHandler: val => {
        let temp = ''
        if (currentNode.value.data.Digits == 0) {
          temp = val.replace(/\D/gi, '')
          temp = temp ? parseInt(temp).toString() : ''
        } else {
          temp = integerModel.nomuch(val, currentNode.value.data.Digits)
        }
        console.log(temp)
        setTimeout(() => {
          model.value.StartValue = temp
          changeModelHandler()
        }, 200)
      }
    })

    const dateModel = reactive({
      options: [],
      model: [],
      init: () => {
        dateModel.options = []
        let year = new Date().getFullYear()
        for (let i = 1; i <= 12; i++) {
          let obj = {
            value: i < 10 ? '0' + i : '' + i,
            label: i + '月',
            children: []
          }
          let day = new Date(year, i, 0).getDate()
          for (let d = 1; d <= day; d++) {
            obj.children.push({
              value: (i < 10 ? '0' + i : '' + i) + '-' + (d < 10 ? '0' + d : '' + d),
              label: d + '日'
            })
          }
          dateModel.options.push(obj)
        }
      },
      changeHandler: val => {
        model.value.StartValue = val.toString()
      }
    })
    const rangeRefs = ref(null)
    const dateRangeModel = reactive({
      model: {},
      formatRange: '',
      refObj: ref(null),
      changeHandler: e => {
        if (e.from && e.to) {
          console.log(dateRangeModel.model)
          let tempFrom = e.from.year + '-' + (e.from.month > 9 ? e.from.month : `0${e.from.month}`) + '-' + (e.from.day > 9 ? e.from.day : `0${e.from.day}`)
          let tempTo = e.to.year + '-' + (e.to.month > 9 ? e.to.month : `0${e.to.month}`) + '-' + (e.to.day > 9 ? e.to.day : `0${e.to.day}`)
          dateRangeModel.formatRange = `${tempFrom} 至 ${tempTo}`
          model.value.StartValue = tempFrom
          model.value.EndValue = tempTo
          rangeRefs.value.hide()
          changeModelHandler()
        }
      }
    })

    const initRadioModel = node => {
      if (model.value.StartValue != '') {
        radioModel.model = node.data.OptionsList.find(x => x.Id == model.value.StartValue)
      } else {
        radioModel.model = node.data.OptionsList[0]
        model.value.StartValue = node.data.OptionsList[0].val
      }

      radioModel.Option = node.data.OptionsList
    }

    const initCheckModel = node => {
      if (model.value.StartValue != '') {
        const temp = model.value.StartValue.split(',')
        checkModel.model = []
        console.log(temp, node.data.OptionsList)
        node.data.OptionsList.forEach(x => {
          if (temp.indexOf(x.Id.toString()) != -1) {
            checkModel.model.push(x)
          }
        })
      } else {
        checkModel.model = [node.data.OptionsList[0]]
        model.value.StartValue = checkModel.model.Id
      }
      checkModel.Option = node.data.OptionsList
    }

    const initIntegerModel = node => {
      let mask = /^([^0][0-9]+|0)$/
      if (node.data.Digits > 0) {
        eval(`mask= /^(([^0][0-9]+|0)\\.([0-9]{1,${node.data.Digits}})$)|^([^0][0-9]+|0)$/`)
      }
      integerModel.mask = mask
    }

    const initDateModel = () => {
      dateModel.init()
      if (model.value.StartValue != '') {
        dateModel.model = model.value.StartValue.split(',')
      } else {
        dateModel.model = []
      }
    }

    const initDateRangeModel = () => {
      if (model.value.StartValue == '') {
        dateRangeModel.model = {}
        dateRangeModel.formatRange = ''
      } else {
        dateRangeModel.model = {
          from: model.value.StartValue.replaceAll('-', '/'),
          to: model.value.EndValue.replaceAll('-', '/')
        }
        console.log(dateRangeModel.model)
        dateRangeModel.formatRange = model.value.StartValue + ' 至 ' + model.value.EndValue
      }
    }
    //#endregion

    const init = node => {
      if (node.data.Type == 3) {
        initRadioModel(node)
      } else if (node.data.Type == 4) {
        initCheckModel(node)
      } else if (node.data.Type == 7) {
        initIntegerModel(node)
      } else if (node.data.Type == 5) {
        initDateModel()
      } else if (node.data.Type == 6) {
        initDateRangeModel()
      }

      changeModelHandler()
    }

    onMounted(() => {
      init(props.node)
    })

    return { model, currentNode, changeModelHandler, radioModel, checkModel, integerModel, dateModel, dateRangeModel, rangeRefs }
  }
}
</script>

<style>
.v-binder-follower-container {
  z-index: 99999999 !important;
}
.vt-cascader > div:first-child {
  padding-left: 0px !important;
  height: 40px !important;
  width: 186px;
}
.vt-cascader .n-base-selection .n-base-selection-tags {
  padding-left: 7px !important;
  height: 40px !important;
}
.vt-header-box .q-field--outlined.q-field--readonly .q-field__control:before {
  border-style: solid !important;
}
</style>
