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

<script lang="ts">
  import { get, last } from 'lodash';
  import { defineComponent, onMounted, computed } 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('请选择矿名'),
      /** 选择器选择深度，1即执法处，2即区县，3即矿区 */
      level: propTypes.number.def(3),
      /** 最后一级矿名选择时传递出去的值对应的字段 */
      valueField: propTypes.string,
    },
    emits: ['change', 'update:value'],
    setup(props, { emit }) {
      // const { createMessage } = useMessage();
      const mineStore = useMineStore();
      const { getMine, getMineCode, getMinePath, getMineTree } = storeToRefs(mineStore);

      // const shownText = computed(() => getMine.value.departName || '-');
      const innerValue = computed(() => getMinePath.value.map((e) => e.id));
      const options = getMineTree;

      /**
       * change事件
       * @param e
       */
      function handleChange(value: any[]) {
        mineStore.setMineById(last(value));

        let val;
        if (props.valueField) {
          val = get(getMine.value, props.valueField);
        } else {
          val = getMineCode.value;
        }
        emit('update:value', val);
        emit('change', val);
      }

      onMounted(() => {
        mineStore.fetchMineTree();
        // mineStore.fetchMineTree(props.level);
      });

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