import { ref, watch, defineComponent, Ref, computed } from 'vue';
import {
  getDatePickerProps,
  getEditorEmits,
  useNamespace,
} from '@ibiz-template/vue-util';
import '@ibiz-template/theme/style/components/editor/ibiz-date-range/ibiz-date-range.scss';

export const IBizDateRange = defineComponent({
  name: 'IBizDateRange',
  props: getDatePickerProps(),
  emits: getEditorEmits(),
  setup(props, { emit }) {
    const ns = useNamespace('date-range');
    const c = props.controller;

    const editorModel = c!.model;

    // 类型
    const type = ref('daterange');
    switch (editorModel.editorType) {
      case 'DATERANGE':
        type.value = 'datetimerange';
        break;
      case 'DATERANGE_NOTIME':
        type.value = 'daterange';
        break;
      default:
        type.value = 'datetimerange';
    }

    // 格式
    const format = ref('yyyy-MM-dd');
    // 值格式化
    const valueFormat = c!.valueFormat;
    if (valueFormat) {
      // 根据值格式化改变type
      if (valueFormat === 'YYYY-MM') {
        type.value = 'month';
      } else if (valueFormat === 'YYYY') {
        type.value = 'year';
      }
      const tempFormat: string = valueFormat
        .replace('YYYY', 'yyyy')
        .replace('DD', 'dd');
      format.value = tempFormat;
    }

    // 值分割符
    let valueSeparator = ',';
    // 在范围选择器里取消两个日期面板之间的联动
    let unlinkPanels = false;
    // 选择范围时的分隔符
    let rangeSeparator = '至';
    if (editorModel.editorParams) {
      if (editorModel.editorParams.valueSeparator) {
        valueSeparator = editorModel.editorParams.valueSeparator;
      }
      if (editorModel.editorParams.rangeSeparator) {
        rangeSeparator = editorModel.editorParams.rangeSeparator;
      }
      if (editorModel.editorParams.unlinkPanels) {
        unlinkPanels = Object.is('true', editorModel.editorParams.unlinkPanels);
      }
    }

    // 关系表单项集合
    const refFormItem: Ref<string[]> = ref([]);
    const editorItems = editorModel.source.getPSEditorItems();
    if (editorItems && editorItems.length > 0) {
      const editorItemNames: string[] = editorItems.map(
        (item: IData) => item.id,
      );
      refFormItem.value = editorItemNames;
    }

    const curValue = computed({
      get() {
        let value: string[] = [];
        if (refFormItem.value.length > 0) {
          refFormItem.value.forEach((name: string) => {
            if (props.data[name]) {
              value.push(props.data[name]);
            }
          });
        } else if (props.value && typeof props.value === 'string') {
          value = props.value.split(valueSeparator);
        }
        return value;
      },
      set(dates: string[]) {
        if (dates && dates.length > 0) {
          emit('change', dates.join(valueSeparator));
          if (refFormItem.value.length > 0) {
            dates.forEach((date: string, index: number) => {
              emit('change', date, refFormItem.value[index]);
            });
          }
        } else {
          emit('change', null);
          if (refFormItem.value.length > 0) {
            refFormItem.value.forEach((date: string, index: number) => {
              emit('change', null, refFormItem.value[index]);
            });
          }
        }
      },
    });

    // 处理值变更
    const handleChange = (dates: string[], _dateType: IData) => {
      curValue.value = dates;
    };

    const onOpenChange = (isOpen: boolean) => {
      emit('operate', isOpen);
    };

    const inputRef = ref();

    if (props.autoFocus) {
      watch(inputRef, newVal => {
        if (newVal) {
          const input = newVal.$el.getElementsByTagName('input')[0];
          input.click();
        }
      });
    }

    return {
      ns,
      c,
      editorModel,
      type,
      format,
      handleChange,
      onOpenChange,
      inputRef,
      rangeSeparator,
      curValue,
      unlinkPanels,
    };
  },
  render(h) {
    return (
      <div
        class={[
          this.ns.b(),
          this.disabled ? this.ns.m('disabled') : '',
          this.readonly ? this.ns.m('readonly') : '',
        ]}
      >
        {h('IDatePicker', {
          ref: 'inputRef',
          props: {
            ...this.c.customProps,
            value: this.curValue,
            transfer: true,
            type: this.type,
            format: this.format,
            placeholder: this.c!.placeHolder,
            disabled: this.disabled,
            readonly: this.readonly,
            separator: this.rangeSeparator,
            splitPanels: this.unlinkPanels,
          },
          on: {
            'on-change': this.handleChange,
            'on-open-change': this.onOpenChange,
          },
        })}
      </div>
    );
  },
});
