<template>
  <view>
    <click-input
      preIcon="map-pin-ellipse"
      :disabled="readonly"
      :placeholder="formProps.placeholder || '请选择'"
      @click="chooseLocation"
      :value="_value"
    >
    </click-input>
    <!-- <cc-selectDity :province="area.province" :city="area.city" :area="area.area" :show="show"
			@sureSelectArea="selectOk" @hideShow="show = false" @changeClick="change"></cc-selectDity> -->
    <Popup v-model:show="show" position="bottom">
      <Cascader
        title="请选择"
        :value="cascaderValue"
        :field-names="{
          text: 'label',
          value: 'value',
          children: 'children',
        }"
        :options="dataOptions"
        @close="show = false"
        @finish="selectOk"
        @change="onChangeSelect"
      />
    </Popup>
    <!-- <tki-tree ref="locationTree" idKey='value' :range="dataOptions"
			rangeKey="label" confirmColor="#4e8af7" :selectParent="true" /> -->
  </view>
</template>
x
<script setup>
import { ref, computed, reactive, onMounted } from "vue";
import ClickInput from "@/components/ClickInput.vue";
import { Cascader, Popup } from "vant";
import "vant/lib/index.css";

const props = defineProps({
  formProps: {
    type: Object,
    default: () => {
      return {};
    },
  },
  modelValue: String,
  readonly: Boolean,
});
const cascaderValue = ref("");
const locationTree = ref(null);

// const province = ref('广东省')
// const city = ref('广州市')
// const area = ref('天河区')

const dataOptions = ref([]);
const classifyListUp = ref([]);

function loadOptionsData() {
  try {
    dataOptions.value = props.formProps.options;
    console.log(3333, dataOptions.value);
    classifyListUp.value = classifyListFn(dataOptions.value);
    // console.log(55555, JSON.stringify(props.formProps.options));
    // console.log(2222, props.formProps.checkStrictly);
    // console.log(2222, props.formProps.showAllLevels);
    // console.log(2222, props.formProps.disabled);
  } catch (e) {
    console.log(e);
  }
}
const classifyListFn = (dataList, reduceList = []) => {
  dataList.forEach((item) => {
    reduceList.push(item);
    if (item.children) {
      classifyListFn(item.children, reduceList);
    } else if (item.itemList) {
      classifyListFn(item.itemList, reduceList);
    }
  });
  return reduceList;
};
onMounted(() => {
  console.log(1111, JSON.stringify(props.formProps.placeholder));
  loadOptionsData();
});

const area = reactive({
  province: "江西省",
  city: "南昌市",
  area: "南昌县",
});
const setData = (dataList, id, str) => {
  return dataList
    .filter((item) => id.includes(item.value))
    .map((item) => item.label)
    .join(str);
};
const searchDataList = (dataList, label) => {
  return dataList.find((item) => {
    if (item.children instanceof Array && item.children.length > 0) {
      return searchDataList(item.children, label);
    } else if (item.label == label) {
      return item;
    }
    return undefined;
  });
};
const delayering = (dataList, label, newResult = []) => {
  dataList instanceof Array &&
    dataList.forEach((item) => {
      if (item.children instanceof Array && item.children.length > 0) {
        delayering(item.children, label, newResult);
        const find = item.children.find((item) => item.label == label);
        if (find) {
          // console.log(123, item);
          delayering(props.formProps.options, item.label, newResult);
          newResult.unshift(item);
        }
      }
      if (item.label == label) {
        // console.log(456, item);
        newResult.unshift(item);
      }
    });
  return newResult;
};

const delayering2 = (dataList, valueList) => {
  if (!(dataList instanceof Array)) return [];
  
  return dataList.reduce((result, item) => {
    if (valueList.includes(item.value)) {
      result.push(item);
    }
    if (item.children instanceof Array && item.children.length > 0) {
      const childrenMatches = delayering2(item.children, valueList);
      result.push(...childrenMatches);
    }
    return result;
  }, []);
};

const _value = computed({
  get() {
    console.log(8282, props.modelValue);
    if ((props.modelValue || "").trim() === "") {
      return null;
    } else {
      let v = props.modelValue.split("-");
      const resultList = props.formProps.options;
      const some = v.some((item) => {
        return !isNaN(Number(item))
      })
      if(props.formProps.showAllLevels){
        // console.log(222, resultList, v, some);
        if(some) {
          // console.log(345, delayering2(props.formProps.options, v));
          return delayering2(props.formProps.options, v).map(item => item.label).join("/")
        } else {
          const delayerList = delayering(resultList, v);
          // console.log(222, delayerList);
          const result = delayerList.reduce((prev, cur) => {
            if(prev.indexOf(cur.label) === -1){
                prev.push(cur.label)
            }
            return prev
          },[])
          return result.join("-")
        }
      }
      if (some) {
        // console.log(99999,delayering2(props.formProps.options, v[v.length - 1]));
        // .map(item => item.label).join("-")
        return delayering2(props.formProps.options, v[v.length - 1]).map(item => item.label).join("/")
      } else {
        return  v;
      }
      // const searchList = searchDataList(classifyListUp.value, v)
      // console.log(333, JSON.stringify(searchList));
      // if(searchList) {
      //     console.log(4444, JSON.stringify(treeData(searchList.children, v)));
      // }

      // v = props.formProps.showAllLevels ? v : v[v.length - 1];
      return !props.formProps.showAllLevels
        ? v
        : setData(classifyListUp.value, v, "-");
    }
  },
  set(val) {
    console.log(222, val);
    emits("update:modelValue", val);
  },
});

const emits = defineEmits(["update:modelValue"]);

const show = ref(false);

function chooseLocation() {
  if (props.formProps.disabled) return;
  if (!props.readonly) {
    show.value = true;
  }
}

function selectOk({ selectedOptions }) {
  // console.log(JSON.stringify(selectedOptions));
  // if (props.formProps.showAllLevels) {
  //   _value.value = selectedOptions.map((option) => option.label).join("/");
  // } else {
  //   _value.value = selectedOptions[selectedOptions.length - 1].label;
  // }
  _value.value = selectedOptions.map((option) => option.value).join("-");

  show.value = false;
}

const onChangeSelect = ({ selectedOptions }) => {
  if(!props.formProps.checkStrictly) return;
  _value.value = selectedOptions.map((option) => option.value).join("-");
}

function change(p, c, a) {
  area.province = p;
  area.city = c;
  area.area = a;
}
</script>

<style lang="less" scoped></style>
