<template>
  <a-cascader
    :value="innerValue"
    :options="getDepartTree"
    :placeholder="placeholder"
    :field-names="{
      label: 'departName',
      value: 'id',
      children: 'childDepart',
    }"
    :show-search="showSearch"
    :allow-clear="allowClear"
    :change-on-select="changeOnSelect"
    @change="handleChange"
  >
    <template #displayRender="{ labels }">
      {{ labels[labels.length - 1] }}
    </template>
  </a-cascader>
  <!-- <a-input>{{ shownText }}</a-input> -->
</template>

<script lang="ts">
  import { last } from 'lodash';
  import { defineComponent, computed, onUnmounted } from 'vue';
  // import { useMessage } from '/@/hooks/web/useMessage';
  import { propTypes } from '/@/utils/propTypes';
  import { useMineStore } from '/@/store/modules/mine';
  import { storeToRefs } from 'pinia';

  export default defineComponent({
    name: 'MineCascader',
    props: {
      value: propTypes.string.def(''),
      placeholder: propTypes.string.def('全部'),
      /** 根节点ID，如果传入，组件将过滤该节点下的节点 */
      rootId: propTypes.string,
      showSearch: propTypes.bool.def(true),
      allowClear: propTypes.bool.def(true),
      changeOnSelect: propTypes.bool.def(true),
      resetOnDestroy: propTypes.bool.def(true),
    },
    emits: ['change', 'update:value'],
    setup(props, { emit }) {
      // const { createMessage } = useMessage();
      const mineStore = useMineStore();
      const { getDepartPath, getDepartTree, getDepartId, getMineCode } = storeToRefs(mineStore);

      if (props.resetOnDestroy) {
        const rawID = getDepartId.value;
        onUnmounted(() => {
          mineStore.clearDepart();
          mineStore.setDepartById(rawID);
        });
      }

      if (props.rootId) {
        mineStore.filterDepartTree((e) => e.id === props.rootId);
        mineStore.clearDepart();

        onUnmounted(() => {
          mineStore.restoreDepartTree();
        });
      }

      // const shownText = computed(() => getDepart.value.departName || '-');
      const innerValue = computed(() => getDepartPath.value.map((e) => e.id));
      const options = getDepartTree;

      /**
       * change事件
       * @param e
       */
      function handleChange(value: any[]) {
        console.log('debug change', value, getMineCode.value);
        mineStore.setDepartById(last(value));
        console.log('debug aftter', value, getMineCode.value);

        const val = getMineCode.value;
        emit('update:value', val);
        emit('change', val);
      }

      handleChange([getDepartId.value]);

      return {
        innerValue,
        options,
        getDepartTree,
        handleChange,
      };
    },
  });
</script>
