<template>
  <div class="wl-area">
    <div @click="showPicker = true">
      <template v-if="$slots.default">
        <slot />
      </template>
      <template v-else>
        <van-field
          :value="fieldValue"
          readonly
          clickable
          is-link
          :label="isFieldLabel ? fieldLabel : ''"
          :placeholder="fieldPlaceholder"
        />
      </template>
    </div>
    <van-popup
      v-model="showPicker"
      round
      position="bottom"
      get-container="body"
      :lazy-render="false"
    >
      <van-picker
        ref="pickerRef"
        show-toolbar
        :title="title"
        value-key="name"
        :columns="columns"
        @change="onChange"
      >
        <template #columns-bottom>
          <div class="bottom-btn">
            <div
              class="btn"
              :class="{ 'btn--not': disableBtn }"
              @click.stop="onConfirm"
            >
              确认选择
            </div>
          </div>
        </template>
      </van-picker>
    </van-popup>
  </div>
</template>

<script>
import Api from "./api/index";
import Store from "@packages/store/index.js";
export default {
  name: "WlArea",
  props: {
    /* 选中项绑定值 */
    value: {
      type: Object,
      default: () => {
        return {};
      },
    },
    /* 选择器标题 */
    title: {
      type: String,
      default: "选择地址",
    },
    /* 标签文本 */
    fieldLabel: {
      type: String,
      default: "地址",
    },
    /* 文本默认值 */
    fieldPlaceholder: {
      type: String,
      default: "省/市/区",
    },
    /* 是否展示文本标签 */
    isFieldLabel: {
      type: Boolean,
      default: true,
    },
    /* 全局参数 */
    env_data: {
      type: Object,
      default: () => {
        return {
          node_env: "",
        };
      },
    },
  },
  data() {
    return {
      fieldValue: "",
      pickerValue: [],
      showPicker: false,
      columns: [],
      disableBtn: true,
    };
  },
  methods: {
    /* 选中项绑定值处理 */
    async setValue(name) {
      if (!this.columns?.length) this.columns = await this.getRegionJson();
      this.$nextTick(() => {
        if (this.columns?.length && name) {
          this.fieldValue = name;
          this.$refs.pickerRef?.setValues(name?.split("/"));
          this.onChange();
        }
      });
    },
    /* 获取省市区数据 */
    async getRegionJson() {
      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({
            children: [],
            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;
    },
    /* 选项值改变 */
    onChange() {
      const data = this.$refs.pickerRef.getValues();
      data?.forEach((e) => {
        if (e.children) delete e.children;
      });
      this.pickerValue = data;
    },
    /* 确认选择 */
    onConfirm() {
      if (this.disableBtn) return;
      this.fieldValue = this.setFieldValue(this.pickerValue);
      this.$emit("confirm", this.pickerValue);
      this.showPicker = false;
    },
    /* 回显文字处理 */
    setFieldValue(arr) {
      return arr
        ?.filter((e) => e.name && !e.name.includes("不限"))
        ?.map((e) => e.name)
        ?.join("/");
    },
    /* 直辖市回显拼接直辖名 */
    // setName(name) {
    //   const municipalitys = ["北京市", "天津市", "重庆市", "上海市"];
    //   if (municipalitys.includes(`${name}`.substring(0, 3)))
    //     return `${name}`.substring(0, 2) + `/${name}`;
    //   return name;
    // },
  },
  watch: {
    /* 全局参数配置 */
    env_data: {
      handler(val) {
        Store.sid = val.sid;
        Store.corp_id = val.corp_id;
        Store.node_env = val.node_env;
      },
      immediate: true,
      deep: true,
    },
    /* 选中项绑定值 */
    value: {
      handler(val) {
        // this.setValue(this.setName(val.name));
        this.setValue(val.name);
      },
      immediate: true,
      deep: true,
    },
    /* 处理按钮是否disabled */
    pickerValue: {
      handler(val) {
        if (!val || !val?.length) {
          this.disableBtn = true;
          return;
        }
        if (val?.every((e) => e.code != "000000")) this.disableBtn = false;
        else this.disableBtn = true;
      },
      immediate: true,
      deep: true,
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .van-picker__cancel,
::v-deep .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: #1c9fff;
    border-radius: j(8);
    font-weight: 500;
    font-size: j(16);
    color: #ffffff;
    cursor: pointer;
  }
  .btn--not {
    background: #96deff;
  }
}
</style>
