import { createVNode as _createVNode } from "vue";
import _extends from "@babel/runtime/helpers/esm/extends";
import { computed, defineComponent, ref, watchEffect, toRefs } from 'vue';
import { SHOW_PARENT } from './Cascader';
import { booleanType, objectType, stringType } from '../_util/type';
import PropTypes from '../_util/vue-types';
import { initDefaultProps } from '../_util/props-util';
import useMergedState from '../_util/hooks/useMergedState';
import { fillFieldNames, toPathKey, toPathKeys } from './utils/commonUtil';
import useEntities from './hooks/useEntities';
import useMissingValues from './hooks/useMissingValues';
import useMaxLevel from '../vc-tree/useMaxLevel';
import { conductCheck } from '../vc-tree/utils/conductUtil';
import { formatStrategyValues, toPathOptions } from './utils/treeUtil';
import { useProvideCascader } from './context';
import RawOptionList from './OptionList';
import { useProvideBaseSelectProps } from '../vc-select/hooks/useBaseProps';
import { toReactive } from '../_util/toReactive';
export function panelProps() {
  return {
    // Value
    value: {
      type: [String, Number, Array]
    },
    defaultValue: {
      type: [String, Number, Array]
    },
    changeOnSelect: {
      type: Boolean,
      default: undefined
    },
    onChange: Function,
    prefixCls: String,
    checkable: {
      type: Boolean,
      default: undefined
    },
    fieldNames: objectType(),
    showCheckedStrategy: {
      type: String,
      default: SHOW_PARENT
    },
    // Options
    options: Array,
    loadData: Function,
    // Trigger
    expandTrigger: String,
    // Icon
    expandIcon: PropTypes.any,
    loadingIcon: PropTypes.any,
    direction: stringType(),
    notFoundContent: PropTypes.any,
    disabled: booleanType(false),
    /** @private Internal usage. Do not use in your production. */
    dropdownPrefixCls: String,
    customSlots: Object
  };
}
function isMultipleValue(value) {
  return Array.isArray(value) && Array.isArray(value[0]);
}
function toRawValues(value) {
  if (!value) {
    return [];
  }
  if (isMultipleValue(value)) {
    return value;
  }
  return (value.length === 0 ? [] : [value]).map(val => Array.isArray(val) ? val : [val]);
}
function noop() {}
export default defineComponent({
  name: 'VcCascaderPanel',
  inheritAttrs: false,
  props: initDefaultProps(panelProps(), {
    notFoundContent: 'Not Found'
  }),
  setup(props, {
    attrs
  }) {
    const multiple = computed(() => props.checkable);
    // =========================== Values ===========================
    const [rawValues, setRawValues] = useMergedState(props.defaultValue, {
      value: computed(() => props.value),
      postState: toRawValues
    });
    // ========================= FieldNames =========================
    const mergedFieldNames = computed(() => fillFieldNames(props.fieldNames));
    // =========================== Option ===========================
    const mergedOptions = computed(() => props.options || []);
    // Only used in multiple mode, this fn will not call in single mode
    const pathKeyEntities = useEntities(mergedOptions, mergedFieldNames);
    /** Convert path key back to value format */
    const getValueByKeyPath = pathKeys => {
      const keyPathEntities = pathKeyEntities.value;
      return pathKeys.map(pathKey => {
        const {
          nodes
        } = keyPathEntities[pathKey];
        return nodes.map(node => node[mergedFieldNames.value.value]);
      });
    };
    // =========================== Values ===========================
    const missingValuesInfo = useMissingValues(mergedOptions, mergedFieldNames, rawValues);
    // Fill `rawValues` with checked conduction values
    const [checkedValues, halfCheckedValues, missingCheckedValues] = [ref([]), ref([]), ref([])];
    const {
      maxLevel,
      levelEntities
    } = useMaxLevel(pathKeyEntities);
    watchEffect(() => {
      const [existValues, missingValues] = missingValuesInfo.value;
      if (!multiple.value || !rawValues.value.length) {
        [checkedValues.value, halfCheckedValues.value, missingCheckedValues.value] = [existValues, [], missingValues];
        return;
      }
      const keyPathValues = toPathKeys(existValues);
      const keyPathEntities = pathKeyEntities.value;
      const {
        checkedKeys,
        halfCheckedKeys
      } = conductCheck(keyPathValues, true, keyPathEntities, maxLevel.value, levelEntities.value);
      // Convert key back to value cells
      [checkedValues.value, halfCheckedValues.value, missingCheckedValues.value] = [getValueByKeyPath(checkedKeys), getValueByKeyPath(halfCheckedKeys), missingValues];
    });
    // =========================== Change ===========================
    const triggerChange = nextValues => {
      setRawValues(nextValues);
      // Save perf if no need trigger event
      if (props.onChange) {
        const nextRawValues = toRawValues(nextValues);
        const valueOptions = nextRawValues.map(valueCells => toPathOptions(valueCells, mergedOptions.value, mergedFieldNames.value).map(valueOpt => valueOpt.option));
        const triggerValues = multiple.value ? nextRawValues : nextRawValues[0];
        const triggerOptions = multiple.value ? valueOptions : valueOptions[0];
        props.onChange(triggerValues, triggerOptions);
      }
    };
    // =========================== Select ===========================
    const onInternalSelect = valuePath => {
      if (!multiple.value) {
        triggerChange(valuePath);
      } else {
        // Prepare conduct required info
        const pathKey = toPathKey(valuePath);
        const checkedPathKeys = toPathKeys(checkedValues.value);
        const halfCheckedPathKeys = toPathKeys(halfCheckedValues.value);
        const existInChecked = checkedPathKeys.includes(pathKey);
        const existInMissing = missingCheckedValues.value.some(valueCells => toPathKey(valueCells) === pathKey);
        // Do update
        let nextCheckedValues = checkedValues.value;
        let nextMissingValues = missingCheckedValues.value;
        if (existInMissing && !existInChecked) {
          // Missing value only do filter
          nextMissingValues = missingCheckedValues.value.filter(valueCells => toPathKey(valueCells) !== pathKey);
        } else {
          // Update checked key first
          const nextRawCheckedKeys = existInChecked ? checkedPathKeys.filter(key => key !== pathKey) : [...checkedPathKeys, pathKey];
          // Conduction by selected or not
          let checkedKeys;
          if (existInChecked) {
            ({
              checkedKeys
            } = conductCheck(nextRawCheckedKeys, {
              checked: false,
              halfCheckedKeys: halfCheckedPathKeys
            }, pathKeyEntities.value, maxLevel.value, levelEntities.value));
          } else {
            ({
              checkedKeys
            } = conductCheck(nextRawCheckedKeys, true, pathKeyEntities.value, maxLevel.value, levelEntities.value));
          }
          // console.log(checkedKeys, pathKeyEntities.value, props.showCheckedStrategy);
          // Roll up to parent level keys
          const deDuplicatedKeys = formatStrategyValues(checkedKeys, pathKeyEntities.value, props.showCheckedStrategy);
          nextCheckedValues = getValueByKeyPath(deDuplicatedKeys);
        }
        triggerChange([...nextMissingValues, ...nextCheckedValues]);
      }
    };
    // =========================== Context ===========================
    const {
      changeOnSelect,
      checkable,
      loadData,
      expandTrigger,
      expandIcon,
      loadingIcon,
      dropdownPrefixCls,
      customSlots
    } = toRefs(props);
    useProvideCascader({
      options: mergedOptions,
      fieldNames: mergedFieldNames,
      values: checkedValues,
      halfValues: halfCheckedValues,
      changeOnSelect,
      onSelect: onInternalSelect,
      checkable,
      searchOptions: ref([]),
      dropdownPrefixCls,
      loadData,
      expandTrigger,
      expandIcon,
      loadingIcon,
      dropdownMenuColumnStyle: ref(undefined),
      customSlots
    });
    useProvideBaseSelectProps(toReactive(_extends(_extends({}, toRefs(props)), {
      searchValue: '',
      open: true,
      showSearch: false,
      multiple,
      toggleOpen: noop
    })));
    return () => {
      const {
        prefixCls,
        notFoundContent
      } = props;
      const panelPrefixCls = `${prefixCls}-panel`;
      const isEmpty = !mergedOptions.value.length;
      return _createVNode("div", {
        "class": [panelPrefixCls, {
          [`${panelPrefixCls}-rtl`]: props.direction === 'rtl',
          [`${panelPrefixCls}-empty`]: isEmpty
        }, attrs.class],
        "style": attrs.style
      }, [isEmpty ? notFoundContent : _createVNode(RawOptionList, null, null)]);
    };
  }
});