<template>
  <div class="wl-area">
    <div @click="onClick" v-if="!only_Popup">
      <slot>
        <Field
          v-model="state.fieldValue"
          readonly
          clickable
          is-link
          :label="isFieldLabel ? fieldLabel : ''"
          :placeholder="fieldPlaceholder"
        />
      </slot>
    </div>
    <Popup
      v-model:show="show_visible"
      round
      position="bottom"
      get-container="body"
      :lazy-render="false"
      @click-overlay="click_overlay"
      :close-on-click-overlay="true"
    >
      <Picker
        ref="pickerRef"
        :title="title"
        value-key="name"
        :columns="state.columns"
        :columns-field-names="customFieldName"
        @change="onChange"
        v-model="modelValue1"
      >
        <template #columns-bottom>
          <div class="bottom-btn">
            <div
              class="btn"
              :class="{ 'btn--not': state.disableBtn }"
              @click.stop="onConfirm"
            >
              确认选择
            </div>
          </div>
        </template>
      </Picker>
    </Popup>
  </div>
</template>

<script lang="ts">
export default {
  name: "WlArea",
};
</script>

<script setup lang="ts">
import Api from "./api/index";
import Store from "@mobileUI/store/index";
import { ref, Ref, reactive, nextTick, watch, computed } from "vue";
import { Field, Picker, Popup, PickerInstance } from "vant";
const pickerRef: Ref<PickerInstance> = ref(null);
interface Props {
  /* 选中项绑定值 */
  modelValue: {
    key: number | string;
    name: string;
  };
  /* 选择器标题 */
  title?: string;
  /* 标签文本 */
  fieldLabel?: string;
  /* 文本默认值 */
  fieldPlaceholder?: string;
  /* 是否展示文本标签 */
  isFieldLabel?: boolean;
  /* 全局参数 */
  env_data: any;
  /*是否只需要弹窗效果不需要触发目标*/
  only_Popup: boolean;
  /*弹框启动器 */
  popup_visible: boolean;
}
const props = withDefaults(defineProps<Props>(), {
  modelValue: () => ({
    key: "000000",
    name: "请选择/请选择/请选择",
  }),
  title: "选择地址",
  fieldLabel: "地址",
  fieldPlaceholder: "省/市/区",
  isFieldLabel: true,
  only_Popup: false,
  popup_visible: false,
  env_data: () => ({
    node_env: "",
  }),
});

const state = reactive({
  fieldValue: "",
  pickerValue: [],
  showPicker: false,
  columns: [],
  disableBtn: true,
});
const customFieldName = {
  text: "name",
  value: "code",
  children: "children",
};
const show_visible = computed(() => state.showPicker || props.popup_visible);
const click_overlay = () => {
  state.showPicker = false;
  emit("update:popup_visible", false);
};
/* 获取省市区数据 */
const getRegionJson = async () => {
  const data = await Api.gePcaCodeJson();
  if (!Array.isArray(data)) return [];
  // 市、区增加不限选项
  data?.forEach((ep) => {
    ep.children = ep.children || []; // 香港、澳门处理
    ep.children?.unshift({
      children: [],
      code: ep.code,
      name: "不限",
    });
    ep.children?.forEach((ec) => {
      ec.children = ec.children || []; // 香港、澳门处理
      ec.children?.unshift({
        code: ec.code,
        name: "不限",
      });
    });
  });
  const secondColumns = data?.[0]?.children;
  const thirdColumns = secondColumns?.[0]?.children;
  const columnsPlaceholder = {
    name: "请选择",
    code: "000000",
  };
  data.unshift({
    ...columnsPlaceholder,
    children: [
      {
        ...columnsPlaceholder,
        children: [columnsPlaceholder, ...thirdColumns],
      },
      ...secondColumns,
    ],
  });
  return data;
};
/* 选中项绑定值处理 */
const setValue = async (name: string) => {
  if (!state.columns?.length) state.columns = await getRegionJson();
  nextTick(() => {
    if (state.columns?.length) {
      state.pickerValue = pickerRef.value?.getSelectedOptions()?.map((e) => ({
        code: e.code,
        name: e.name,
      }));
      if (name) state.fieldValue = name;
    }
  });
};
type choose_vale_obj = {
  code: string;
  name: string;
};
type choose_vale_arr = Array<choose_vale_obj>;
const emit = defineEmits<{
  (e: "confirm", val: choose_vale_arr): void;
  (e: "update:popup_visible", val: boolean): void;
}>();
/* 选项值改变 */
const onChange = (e) => {
  const params = e.selectedOptions.reduce((pre, next) => {
    pre.push({
      code: next.code,
      name: next.name,
    });
    return pre;
  }, []);
  state.pickerValue = params;
};
/* 回显文字处理 */
const setFieldValue = (arr) => {
  return arr
    ?.filter((e) => e.name && !e.name.includes("不限"))
    ?.map((e) => e.name)
    ?.join("/");
};
// /* 直辖市回显拼接直辖名 */
// const setName = (name) => {
//   const municipalitys = "北京市, 天津市, 重庆市, 上海市";
//   if (municipalitys.includes(`${name}`.substring(0, 3)))
//     return `${name}`.substring(0, 2) + `/${name}`;
//   return name;
// };
/* 确认选择 */
const onConfirm = () => {
  if (state.disableBtn) return;
  state.fieldValue = setFieldValue(state.pickerValue);
  emit("confirm", state.pickerValue);
  click_overlay();
};
const onClick = () => {
  state.showPicker = true;
};

/* 全局参数配置 */
watch(
  () => props.env_data,
  (val) => {
    Store.sid = val.sid;
    Store.corp_id = val.corp_id;
    Store.node_env = val.node_env;
    Store.token = val.token;
  },
  {
    immediate: true,
    deep: true,
  }
);

/* 选中项绑定值 */
const modelValue1 = ref<(string | number)[]>([]);
watch(
  () => props.modelValue,
  (val) => {
    setValue(val?.name);
    if (val?.key ?? false) {
      const province = +val.key.toString().slice(0, 2);
      const city = +val.key.toString().slice(0, 4);
      const district = val.key;
      modelValue1.value = [province, city, district];
    }
  },
  { immediate: true, deep: true }
);

/* 处理按钮是否disabled */
watch(
  () => state.pickerValue,
  (val) => {
    if (val) {
      if (!state.pickerValue?.length) return;
      if (state.pickerValue.every((e) => e.code != "000000")) {
        state.disableBtn = false;
      } else {
        state.disableBtn = true;
      }
    }
  },
  { immediate: true, deep: true }
);
</script>
<style scoped lang="scss">
:deep() {
  .van-picker__cancel,
  .van-picker__confirm {
    visibility: hidden;
  }
}
.bottom-btn {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: j(76);
  background: #ffffff;
  box-shadow: 0px -4px 12px rgba(0, 0, 0, 0.08);
  .btn {
    display: flex;
    justify-content: center;
    align-items: center;
    width: j(344);
    height: j(44);
    background: var(--wl-primary-color);
    border-radius: j(8);
    font-weight: 500;
    font-size: j(16);
    color: #ffffff;
    cursor: pointer;
  }
  .btn--not {
    background: var(--wl-primary-color-disabled);
  }
}
</style>
