<template>
  <view>
    <view class="addr_list">
      <view class="addr_item" v-for="(item, index) in addrList" :key="index">
        <view class="contact_user" style="display: flex; justify-content: space-between; width: 100%">
          <view style="display: flex">
            <text class="contact_name">{{ item.contact_name }}</text>
            <text class="contact_phone">{{ item.contact_phone }}</text>
          </view>
          <view class="contact_shop text-ellipsis" style="width: 250rpx; text-align: end">
            <text v-if="item.shop_type">({{ $CONSTANTS.SHOP_TYPES[item.shop_type] }})&nbsp;</text>
            {{ item.contact_shop }}
          </view>
        </view>
        <view class="contact_addr">{{ item.contact_province }} {{ item.contact_city }} {{ item.contact_area }} {{ item.contact_addr }}</view>
        <view class="contact_handler">
          <view class="radio_label" @click="setDefault(index)">
            <image class="radio_icon" :src="item.is_default ? '../../static/icon/radioed.png' : '../../static/icon/radio.png'"></image>
            <text :class="item.is_default ? 'radioed_text' : ''">{{ item.is_default ? "已默认" : "设为默认" }}</text>
          </view>
          <view class="addr_right_btn" @click="removeAddr(index)">删除</view>
          <view class="addr_right_btn" @click="openForm(item)">编辑</view>
        </view>
      </view>
    </view>
    <view class="create_box">
      <button class="create_addr" @click="openForm()">新建收货地址</button>
    </view>
    <Empty v-if="!addrList.length" text="----- 还没有地址啦 -----" />
    <view class="to_bottom" v-if="isLast && addrList.length">-----到底啦-----</view>
    <uni-popup ref="addrForm" type="bottom" class="popup" background-color="#FFFFFF" @change="popupChange">
      <view class="contact_addr_form">
        <!-- 地区代表表单 -->
        <form class="info_form">
          <view class="form_group">
            <view class="group_title">收货人：</view>
            <view class="group_box">
              <input type="text" class="form_ctrl" placeholder="请输入收件人" maxlength="20" required="" v-model="addrRequest.contact_name" />
            </view>
          </view>
          <view class="form_group">
            <view class="group_title">手机号：</view>
            <view class="group_box">
              <input type="text" class="form_ctrl" placeholder="请输入手机号" maxlength="11" required="" v-model="addrRequest.contact_phone" />
            </view>
          </view>
          <view class="form_group">
            <view class="group_title">店铺名称：</view>
            <view class="group_box">
              <uni-combox v-model="addrRequest.contact_shop" :candidates="searchResults" @input="onSearchInput" @change="onSearchChange" placeholder="请输入营业执照全称"> </uni-combox>
            </view>
          </view>
          <view class="form_group">
            <view class="group_title">终端类型：</view>
            <view class="group_box">
              <view class="terminalType_radio">
                <view v-for="item in terminalType" :key="item.key">
                  <view style="display: flex; align-items: center" @click="handleRadioChange(item.key)">
                    <image class="radio_icon" :src="item.key === addrRequest.shop_type ? '../../static/icon/radioed.png' : '../../static/icon/radio.png'"></image>
                    &nbsp;<text style="font-size: 26rpx">{{ item.label }}</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
          <view class="form_group">
            <view class="group_title">所在地区：</view>
            <view class="group_box">
              <picker mode="multiSelector" class="form_ctrl" :value="cityValue" :range="cityArray" @columnchange="cityChange" @change="cityFinish">
                <view class="area_text">
                  <text v-if="addrRequest.contact_province">{{ addrRequest.contact_province }}</text>
                  <text v-if="addrRequest.contact_city">/{{ addrRequest.contact_city }}</text>
                  <text v-if="addrRequest.contact_area">/{{ addrRequest.contact_area }}</text>
                </view>
              </picker>
            </view>
          </view>
          <view class="form_group">
            <view class="group_title">详细地址：</view>
            <view class="group_box">
              <input type="text" class="form_ctrl" placeholder="请输入详细地址:街道/小区/门牌号" maxlength="64" required="" v-model="addrRequest.contact_addr" />
            </view>
          </view>
          <view class="form_group">
            <view class="group_title">设为默认</view>
            <view class="group_box">
              <switch color="#E03519" style="transform: scale(0.6); float: right" @change="defaultSwitch" :checked="addrRequest.is_default ? true : false" />
            </view>
          </view>
          <button class="submit_btn" @click="saveAddr">保存地址</button>
        </form>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { getProvinces, getMyCity, getAreas, getProvincesIndex, getCityIndex, getAreaIndex } from "../../utils/city";
import Empty from "@/components/Empty/Empty.vue";

// 防抖函数
function debounce(func, wait) {
  let timeout;
  return function (...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, args), wait);
  };
}

export default {
  components: { Empty },
  data() {
    return {
      // 产品列表
      addrList: [],
      // 请求参数
      requestParam: {
        page: 1,
        status: 0,
      },
      // 保存地址
      addrRequest: {
        id: 0,
        contact_name: "",
        contact_phone: "",
        contact_province: "",
        contact_city: "",
        contact_area: "",
        contact_addr: "",
        contact_shop: "",
        is_default: 0,
        shop_type: 1,
      },
      // 是否最后一页
      isLast: false,
      // 是否请求中
      isReqing: false,
      // 所在地区
      cityArray: [[], [], []],
      cityValue: [0, 0, 0],
      // 自动弹出
      autoShowForm: false,
      // 异步通知
      AddrEmit: false,
      //终端类型
      terminalType: [
        { key: 1, label: "单店" },
        { key: 2, label: "连锁" },
        { key: 3, label: "诊所、社康等" },
      ],
      //获取的默认地址
      defaultAddr: {},
      //远程搜索返回的数据
      searchResults: [],
    };
  },
  onLoad(param) {
    this.AddrEmit = param.notify == "addr" ? true : false;
    this.autoShowForm = param.type == "create" ? true : false;
    // 获取列表
    this.getList();
    this.get_remark_addr();
  },
  onReady() {
    if (this.autoShowForm) {
      var that = this;
      // 500毫秒后自动弹出
      setTimeout(function () {
        that.openForm();
      }, 500);
    }
  },
  onShow() {
    // 替换对应的数据
    this.cityArray.splice(0, 1, getProvinces());
    this.cityArray.splice(1, 1, getMyCity(this.cityValue[0]));
    this.cityArray.splice(2, 1, getAreas(this.cityValue[0], this.cityValue[1]));
    // 默认地址
    this.addrRequest.contact_province = this.cityArray[0][this.cityValue[0]];
    this.addrRequest.contact_city = this.cityArray[1][this.cityValue[1]];
    this.addrRequest.contact_area = this.cityArray[2][this.cityValue[2]];
  },
  methods: {
    onSearchInput: debounce(function (inputVal, isSelect) {
      console.log("搜索关键字:", this.addrRequest.contact_shop);
      console.log("是否选择:", isSelect);
      if (isSelect) return;
      if (this.addrRequest.contact_shop.trim() === "" || this.addrRequest.contact_shop.length < 2) {
        this.searchResults = [];
        return;
      }
      this.$http.request("api/custom_addr/get_guess_addr", { contact_shop: this.addrRequest.contact_shop }).then((callback) => {
        // 获取成功
        if (callback.code == "success") {
          this.searchResults = callback.data.map((item, index) => ({
            text: item.contact_shop,
            value: index,
            ...item,
          }));
        }
      });
    }, 300),
    onSearchChange(event) {
      if (event.shop_type !== 0) this.addrRequest.shop_type = event.shop_type;
      this.addrRequest.contact_addr = event.contact_addr;
      const { contact_province, contact_city, contact_area } = event;
      const provinces = getProvincesIndex(contact_province);
      const city = getCityIndex(contact_city, provinces.city, provinces.index);
      const area = getAreaIndex(contact_area, city.area);
      this.cityValue = [provinces.index, city.index, area.index];
      this.cityArray.splice(1, 1, provinces.city);
      this.cityArray.splice(2, 1, city.area);
      this.addrRequest.contact_province = contact_province;
      this.addrRequest.contact_area = contact_area;
      this.addrRequest.contact_city = contact_city;
    },
    //获取get_remark_addr
    get_remark_addr() {
      this.$http.request("api/custom_addr/get_remark_addr").then((callback) => {
        // 获取成功
        if (callback.code == "success") {
          // 通知地址变更
          this.defaultAddr = callback.data;
        }
      });
    },
    // 获取列表
    getList() {
      // 登录提示
      if (!this.$checkAccess.alterLogin()) return;
      // 判断数据
      this.$http.request("api/custom_addr/get_list").then((callback) => {
        // 获取成功
        if (callback.code == "success") {
          this.addrList = callback.data;
          // 通知地址变更
          if (this.AddrEmit) uni.$emit("addr_list_change", { list: this.addrList });
        }
      });
    },
    // 打开弹窗
    openForm(item) {
      if (!item) {
        this.addrRequest.id = 0;
        this.addrRequest.contact_name = this.defaultAddr.contact_name;
        this.addrRequest.contact_phone = this.defaultAddr.contact_phone;
        this.addrRequest.contact_shop = this.defaultAddr.contact_shop;
        this.addrRequest.contact_addr = this.defaultAddr.contact_addr;
        this.addrRequest.is_default = 0;
        this.addrRequest.shop_type = this.defaultAddr.shop_type == "" ? 1 : this.defaultAddr.shop_type;
        const { contact_province, contact_city, contact_area } = this.defaultAddr;
        if (contact_province == "") {
          this.cityValue = [0, 0, 0];
          this.addrRequest.contact_province = "请选择";
          this.addrRequest.contact_city = "请选择";
          this.addrRequest.contact_area = "请选择";
        } else {
          const provinces = getProvincesIndex(contact_province);
          const city = getCityIndex(contact_city, provinces.city, provinces.index);
          const area = getAreaIndex(contact_area, city.area);
          this.cityValue = [provinces.index, city.index, area.index];
          this.cityArray.splice(1, 1, provinces.city);
          this.cityArray.splice(2, 1, city.area);
          this.addrRequest.contact_province = contact_province;
          this.addrRequest.contact_area = contact_area;
          this.addrRequest.contact_city = contact_city;
          if (contact_area == "") this.addrRequest.contact_area = "请选择";
          if (contact_city == "") this.addrRequest.contact_city = "请选择";
        }
      } else {
        if (!item.shop_type) item.shop_type = 1;
        const _cloneItem = JSON.parse(JSON.stringify(item));
        this.addrRequest = _cloneItem;
        const provinces = getProvincesIndex(item.contact_province);
        const city = getCityIndex(item.contact_city, provinces.city, provinces.index);
        const area = getAreaIndex(item.contact_area, city.area);
        this.cityValue = [provinces.index, city.index, area.index];
        this.cityArray.splice(1, 1, provinces.city);
        this.cityArray.splice(2, 1, city.area);
      }
      // 显示下单弹出层
      this.$refs.addrForm.open("bottom");
    },
    // 默认开关
    defaultSwitch(e) {
      this.addrRequest.is_default = e.detail.value ? 1 : 0;
    },
    // 弹出层
    popupChange(e) {
      // 禁止滚动穿透
      this.show = e.show;
    },
    // 城市修改
    cityChange(e) {
      // 替换三个选项
      this.cityValue.splice(e.detail.column, 1, e.detail.value);
      // 下一级设置为0
      if (e.detail.column == 0) {
        this.cityValue.splice(1, 1, 0);
        this.cityValue.splice(2, 1, 0);
      }
      if (e.detail.column == 1) {
        this.cityValue.splice(2, 1, 0);
      }
      // 替换对应的数据
      this.cityArray.splice(0, 1, getProvinces());
      this.cityArray.splice(1, 1, getMyCity(this.cityValue[0]));
      this.cityArray.splice(2, 1, getAreas(this.cityValue[0], this.cityValue[1]));
    },
    // 城市选中
    cityFinish(e) {
      this.addrRequest.contact_province = this.cityArray[0][e.detail.value[0]];
      this.addrRequest.contact_city = this.cityArray[1][[e.detail.value[1]]];
      this.addrRequest.contact_area = this.cityArray[2][[e.detail.value[2]]];
    },
    // 保存地址
    saveAddr() {
      // 判断姓名
      if (!this.addrRequest.contact_name) {
        uni.showToast({ icon: "none", title: "请填写收件人" });
        return;
      }
      if (this.addrRequest.contact_name.length < 2) {
        uni.showToast({ icon: "none", title: "请填写收件人完整姓名" });
        return;
      }
      if (!this.addrRequest.contact_shop) {
        uni.showToast({ icon: "none", title: "请填写店铺名称" });
        return;
      }
      if (!this.addrRequest.contact_phone) {
        uni.showToast({ icon: "none", title: "请填写收件人手机号" });
        return;
      }
      if (!this.addrRequest.contact_addr) {
        uni.showToast({ icon: "none", title: "请填写联系地址" });
        return;
      }
      if (this.addrRequest.contact_addr.length < 3) {
        uni.showToast({ icon: "none", title: "请填写可用联系地址" });
        return;
      }
      const _clone = JSON.parse(JSON.stringify(this.addrRequest));
      if (_clone.contact_province == "请选择" || _clone.contact_city == "请选择" || _clone.contact_area == "请选择") {
        uni.showToast({
          icon: "none",
          title: "请选择完整的省市区信息",
        });
        return;
      }
      // 请求状态
      uni.showLoading({ mask: true });
      // 请求路径
      var url = this.addrRequest.id ? "api/custom_addr/edit" : "api/custom_addr/add";
      // 授权成功以后，调用绑定
      this.$http.request(url, this.addrRequest, "post").then((re) => {
        // 关闭
        uni.hideLoading();
        // 成功的话
        if (re.code != "success") {
          // 跳转
          uni.showToast({ title: re.msg, icon: "none" });
          return;
        }
        // 地址变动
        this.getList();
        // 显示下单弹出层
        this.$refs.addrForm.close();
      });
    },
    // 删除地址
    removeAddr(index) {
      // 授权成功以后，调用绑定
      this.$http.request("api/custom_addr/del", { id: this.addrList[index].id }, "post").then((re) => {
        // 关闭
        uni.hideLoading();
        // 成功的话
        if (re.code != "success") {
          // 跳转
          uni.showToast({ title: re.msg, icon: "none" });
          return;
        }
        // 成功删除该项
        this.addrList.splice(index, 1);
        // 通知地址变更
        if (this.AddrEmit) uni.$emit("addr_list_change", { list: this.addrList });
      });
    },
    // 设置默认
    setDefault(index) {
      // 如果已经是默认状态
      if (this.addrList[index].is_default) return;
      // 授权成功以后，调用绑定
      this.$http.request("api/custom_addr/set_default", { id: this.addrList[index].id }, "post").then((re) => {
        // 关闭
        uni.hideLoading();
        // 成功的话
        if (re.code != "success") {
          // 跳转
          uni.showToast({ title: re.msg, icon: "none" });
          return;
        }
        // 更新其他的默认项
        for (let i in this.addrList) {
          this.addrList[i].is_default = 0;
        }
        // 成功修改值
        this.addrList[index].is_default = 1;
        // 通知地址变更
        if (this.AddrEmit) uni.$emit("addr_list_change", { list: this.addrList });
      });
    },
    handleRadioChange(key) {
      this.addrRequest.shop_type = Number(key);
    },
  },
};
</script>

<style lang="less">
.addr_list {
  width: 730rpx;
  display: block;
  overflow: hidden;
  margin: 0rpx auto;
  .addr_item {
    display: block;
    font-size: 24rpx;
    overflow: hidden;
    line-height: 40rpx;
    padding: 15rpx 10rpx;
    border-radius: 15rpx;
    padding-bottom: 0rpx;
    margin-bottom: 10rpx;
    background-color: #ffffff;
    .contact_user {
      display: block;
      font-size: 24rpx;
      line-height: 50rpx;
      .contact_name {
        font-size: 26rpx;
        font-weight: bold;
        margin-right: 16rpx;
      }
      .contact_shop {
        float: right;
      }
    }
    .contact_addr {
      display: block;
      font-size: 24rpx;
      line-height: 30rpx;
      padding: 10rpx 5rpx;
      border-bottom: 2rpx solid #dddddd;
    }
    .contact_handler {
      height: 60rpx;
      display: block;
      line-height: 60rpx;
      font-size: 20rpx;
      .radio_label {
        float: left;
        height: 60rpx;
        line-height: 60rpx;
        .radio_icon {
          width: 40rpx;
          height: 40rpx;
          vertical-align: middle;
        }
        .radioed_text {
          color: #e03519;
        }
      }
      .addr_right_btn {
        float: right;
        height: 40rpx;
        display: block;
        line-height: 40rpx;
        padding: 10rpx 35rpx;
      }
    }
  }
}
.create_box {
  left: 0rpx;
  width: 750rpx;
  height: 140rpx;
  display: block;
  position: fixed;
  bottom: var(--window-bottom);
  .create_addr {
    width: 700rpx;
    height: 80rpx;
    display: block;
    color: #ffffff;
    font-size: 30rpx;
    overflow: hidden;
    line-height: 80rpx;
    padding: 0rpx 0rpx;
    text-align: center;
    margin: 0rpx auto;
    margin-top: 20rpx;
    border-radius: 40rpx;
    background-color: #e03519;
  }
}
.popup {
  .info_form {
    display: block;
    overflow: hidden;
    padding: 20rpx 0rpx;
    padding-top: 80rpx;
    background: #ffffff;
    .form_group {
      display: block;
      line-height: 60rpx;
      padding: 20rpx 35rpx;
      height: 56rpx;
      .group_title {
        float: left;
        width: 160rpx;
        display: block;
        overflow: hidden;
        font-size: 30rpx;
        margin-right: 20rpx;
      }
      .group_box {
        float: left;
        width: 480rpx;
        display: block;
        .radio_icon {
          width: 50rpx;
          height: 50rpx;
          vertical-align: middle;
        }
        .form_ctrl {
          height: 56rpx;
          font-size: 24rpx;
          padding: 0rpx 20rpx;
          line-height: 56rpx;
          border: 2rpx solid #dddddd;
        }
        .area_text {
          width: 446rpx;
          font-size: 20rpx;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
        .group_image {
          width: 200rpx;
          height: 200rpx;
        }
        .choose_image {
          display: block;
          width: 200rpx;
          height: 200rpx;
          font-size: 38rpx;
          text-align: center;
          line-height: 200rpx;
          border: 2rpx solid #dddddd;
        }
        .terminalType_radio {
          display: flex;
          justify-content: space-around;
        }
      }
    }
    .submit_btn {
      width: 700rpx;
      height: 80rpx;
      display: block;
      color: #ffffff;
      font-size: 30rpx;
      overflow: hidden;
      line-height: 80rpx;
      padding: 0rpx 0rpx;
      text-align: center;
      margin: 20rpx auto;
      margin-top: 40rpx;
      border-radius: 40rpx;
      background-color: #e03519;
    }
  }
}
</style>
