<template>
  <div class="page-body">
    <div class="address-box">
      <div class="adress-content">
        <span class="content-title">收货人</span>
        <div class="content-input borbottom">
          <input type="text" placeholder="请填写收货人姓名" @input="bindKeyInput($event, 'userName')"
            :value="saveMsg.userName" />
        </div>
      </div>
      <div class="adress-content">
        <span class="content-title"></span>
        <radio-group :value="saveMsg.userSex" @change="changRadio" class="radio-box borbottom">
          <view class="radio-list" v-for="(item, index) in sexList" :key="index">
            <radio :value="item.value" color="#4BCB7E" :checked="item.isChecked" @click="getSex(item)" />
            <text class="radio-unit">{{ item.name }}</text>
          </view>
        </radio-group>
      </div>
      <div class="adress-content borbottom">
        <span class="content-title">手机号</span>
        <div class="content-input">
          <input type="number" maxlength="11" placeholder="请填写收货人手机号" @input="bindKeyInput($event, 'mobilePhone')"
            :value="saveMsg.mobilePhone" />
        </div>
      </div>
      <view class="adress-content borbottom">
        <text class="content-title">收货地址</text>
        <view class="content-input address-content" style="text-align: left" @click="handleShowPopup">
          {{ saveMsg.address || "请选择收货地址" }}
          <image src="https://cdn-icons-png.flaticon.com/512/545/545682.png"
            style="width: 28rpx; height: 28rpx; margin-left: 12rpx" />
        </view>
      </view>
      <div class="textarea-content borbottom" v-if="streetList && streetList.length > 0">
        <span class="content-title">街道地址</span>
        <div class="content-input">
          <picker mode="selector" :range="streetList" range-key="region_name" :value="streetIndex"
            @change="handleChangeStreet">
            {{
              streetList[streetIndex] && streetList[streetIndex].region_name
                ? streetList[streetIndex].region_name
                : "请选择街道"
            }}
          </picker>
        </div>
      </div>

      <div class="textarea-content borbottom">
        <span class="content-title">详细地址</span>
        <div class="content-input">
          <textarea auto-height placeholder="例如：花园小区9号楼三单元202" @input="bindKeyInput($event, 'doorplate')"
            :value="saveMsg.doorplate"></textarea>
        </div>
      </div>

      <!-- 地址识别功能 -->
      <div class="address-recognition borbottom" v-if="addressRecognition.show">
        <span class="content-title">地址识别</span>
        <div class="content-input recognition-input">
          <textarea auto-height placeholder="请粘贴完整地址，如：北京市朝阳区三里屯街道工体北路8号" @input="onAddressRecognitionInput"
            :value="addressRecognition.inputText" class="recognition-textarea"></textarea>
          <div class="recognition-buttons" v-if="addressRecognition.showButtons">
            <view class="btn-cancel" @click="cancelAddressRecognition">取消</view>
            <view class="btn-recognize" @click="recognizeAddress">识别</view>
          </div>
        </div>
      </div>

      <div class="adress-content borbottom">
        <span class="content-title">标签</span>
        <div class="content-input tip-content">
          <span v-for="(u, i) in tipCodes" :key="i" class="tip-tag" :class="{ active: u.isChecked }"
            @click="tagClick(u)">{{ u.name }}</span>
        </div>
      </div>
      <div class="moren-content">
        <div>
          <p>设为默认地址</p>
          <p class="moren-text">每次购物时会优先选定该地址，方便您轻松购物</p>
        </div>
        <switch :checked="saveMsg.isDefault" activeColor="#07c160" inactiveColor="#fff" :size="30" @change="onChange" />
        <!-- <van-switch
          :checked="saveMsg.isDefault"
          active-color="#07c160"
          inactive-color="#fff"
          size="40rpx"
          @change="onChange"
        /> -->
      </div>
    </div>


    <!-- <div class="save-btn" @click="checkFn">保存并使用</div>
    <div class="del-btn" @click="deleteFn" v-if="pageMsg.id">删除地址</div> -->
    <view class="btnBox">
      <view class="saveBtn" @click="checkFn" :style="{ width: pageMsg.id ? '' : '100%' }">保存并使用</view>
      <view class="loginOut" @click="deleteFn" v-if="pageMsg.id">删除地址</view>
    </view>


    <uni-popup :show="pageMsg.isSelect" position="bottom" overlay="false" @close="handleClosePopup" ref="popup"
      :safe-area="false" custom-style="height: 760rpx;">
      <div class="addressSelecct">
        <div class="addressTitle">
          <span class="cancelText" @click="handleClosePopup">取消</span>
          <span class="confirmText" @click="getAddress">确认</span>
        </div>

        <picker-view :value="addressSelectIndex" @change="areaChange" class="picker-view">
          <picker-view-column>
            <view class="item" v-for="(item, index) in areaData" :key="index">{{
              item.region_name
            }}</view>
          </picker-view-column>
          <picker-view-column>
            <view class="item" v-for="(item, index) in city_list" :key="index">{{ item.region_name }}</view>
          </picker-view-column>
          <picker-view-column>
            <view class="item" v-for="(item, index) in county_list" :key="index">{{ item.region_name }}</view>
          </picker-view-column>
        </picker-view>

        <!-- <van-area
        :area-list="arealist"
        :value="pageMsg.provinceCode"
        @confirm="getAddress"
        @cancel="pageMsg.isSelect = false"
      /> -->
      </div>
    </uni-popup>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
// import newArea from "../../../common/newArea.js";

export default {
  data() {
    // let areaData = newArea;
    return {
      sexList: [
        {
          name: "先生",
          value: 1,
          isChecked: false,
        },
        {
          name: "女士",
          value: 2,
          isChecked: false,
        },
      ],
      tipCodes: [
        {
          name: "家",
          isChecked: false,
          value: 1000,
        },
        {
          name: "公司",
          isChecked: false,
          value: 2000,
        },
        {
          name: "其他",
          isChecked: false,
          value: 3000,
        },
      ],
      saveMsg: {
        userName: "",
        userSex: 1,
        mobilePhone: "",
        address: "",
        doorplate: "",
        isDefault: false,
        tagType: "",
      },
      areaData: [],
      // areaData: areaData,
      pageMsg: {
        id: "",
        address: {},
        provinceCode: 110101,
        isSelect: false,
      },
      city_list: [],
      county_list: [],
      addressSelectIndex: [0, 0, 0],
      streetList: [],
      streetIndex: -1,
      // 地址识别相关数据
      addressRecognition: {
        show: true, // 是否显示地址识别区域
        inputText: '', // 输入的地址文本
        showButtons: false, // 是否显示取消和识别按钮
      },
    };
  },
  computed: {
    ...mapGetters(["user"]),
  },
  methods: {
    // 拿到省份数据 默认数据
    async handleGetProviceCode() {
      let req = {
        level: 1,
        page: 1,
        pageSize: 999,
      };
      const data = await this.$api.$postNode("/pino/region/list", req);
      let list = data.data.data.result;
      console.log("datadsdsa", list);
      this.areaData = list;

      let cityReq = {
        parentId: list[0].region_id,
        page: 1,
        pageSize: 999,
      };
      const cityData = await this.$api.$postNode("/pino/region/list", cityReq);
      console.log("cityData", cityData);
      let citylist = cityData.data.data;
      this.city_list = citylist;

      let countyReq = {
        parentId: citylist[0].region_id,
        page: 1,
        pageSize: 999,
      };
      const countyData = await this.$api.$postNode(
        "/pino/region/list",
        countyReq
      );
      console.log("countyData", countyData);
      let countylist = countyData.data.data;
      this.county_list = countylist;
      console.log("countylist", countylist);
    },
    async areaChange(e) {
      console.log("e", e);
      let cityIndex = e.detail.value[0];
      let cityReq = {
        parentId: this.areaData[cityIndex].region_id,
        page: 1,
        pageSize: 999,
      };
      const cityData = await this.$api.$postNode("/pino/region/list", cityReq);
      let citylist = cityData.data.data;
      this.city_list = citylist;

      let countyReq = {
        parentId: citylist[e.detail.value[1]].region_id,
        page: 1,
        pageSize: 999,
      };
      const countyData = await this.$api.$postNode(
        "/pino/region/list",
        countyReq
      );
      console.log("countyData", countyData);
      let countylist = countyData.data.data;
      this.county_list = countylist;

      // let countyIndex = e.detail.value[1];
      // this.county_list = this.city_list[countyIndex].children;
      this.addressSelectIndex = e.detail.value;
      this.$forceUpdate();
    },
    // 切换街道
    handleChangeStreet(e) {
      console.log("e", e);
      this.streetIndex = Number(e.target.value);
    },
    handleShowPopup() {
      this.$refs.popup.open("bottom");
      console.log("areaData", this.areaData);

      this.pageMsg.isSelect = true;
    },
    handleClosePopup() {
      this.$refs.popup.close();
      this.pageMsg.isSelect = false;
    },
    changRadio(e) { },
    getSex(item) {
      this.saveMsg.userSex = item.value;
    },
    bindKeyInput(event, name) {
      this.saveMsg[name] = event.mp.detail.value;
    },
    onChange(e) {
      console.log("e", e);
      this.saveMsg.isDefault = e.detail.value;
      this.$forceUpdate();
    },
    async handleGetStreetData() {
      let streetReq = {
        parentId: this.county_list[this.addressSelectIndex[2]].region_id,
        page: 1,
        pageSize: 999,
      };
      const streetData = await this.$api.$postNode(
        "/pino/region/list",
        streetReq
      );
      console.log("streetData", streetData);
      let streetList = streetData.data.data;
      this.streetList = streetList;
    },
    getAddress(obj) {
      console.log("this.addressSelectIndex", this.addressSelectIndex);
      this.handleClosePopup();
      let content = this.addressSelectIndex;
      this.saveMsg.address =
        this.areaData[content[0]].region_name +
        this.city_list[content[1]].region_name +
        this.county_list[content[2]].region_name;

      this.pageMsg.address = content;
      console.log("this.saveMsg", this.saveMsg);
      this.handleGetStreetData();
    },
    checkFn() {
      let _this = this;
      let flag = 0;
      console.log("_this.saveMsg", this.saveMsg);

      for (let element in this.saveMsg) {
        if (_this.saveMsg[element] === "") {
          let msg = "";
          switch (element) {
            case "userName":
              msg = "收货人";
              break;
            case "mobilePhone":
              msg = "手机号";
              break;
            case "address":
              msg = "收货地址";
              break;
            case "doorplate":
              msg = "详细地址";
              break;
            case "tagType":
              msg = "标签";
              break;
          }
          uni.showToast({
            title: "请完善您的" + msg + "信息",
            icon: "none",
          });
          flag += 1;
          return false;
        }
      }
      if (!/^[1][3,4,5,7,8,9][0-9]{9}$/.test(_this.saveMsg.mobilePhone)) {
        uni.showToast({
          title: "请输入正确的手机号",
          icon: "none",
        });
        return false;
      }
      // 街道选择是可选的，如果有街道列表但未选择，允许保存
      // if (this.streetList && this.streetList.length > 0) {
      //   if (this.streetIndex >= 0) {
      //   } else {
      //     uni.showToast({
      //       title: "请选择街道地址！",
      //       icon: "none",
      //     });
      //     return false;
      //   }
      // }
      if (flag === 0) {
        this.saveFn();
      }
    },
    saveFn() {
      // let _this = this
      let arr = JSON.parse(JSON.stringify(this.saveMsg));
      let msg = "添加成功";
      arr.action_type = "SaveAddress";
      if (this.pageMsg.id) {
        arr.addressId = this.pageMsg.id;
        msg = "更新成功";
      }
      arr.requestType = "application/x-www-form-urlencoded";
      arr.isDefault = Number(arr.isDefault);

      let [provinceIndex, cityIndex, countryIndex] = this.addressSelectIndex;

      arr.addressCode = [
        this.areaData[provinceIndex].region_id,
        this.city_list[cityIndex].region_id,
        this.county_list[countryIndex].region_id,
        this.streetList && this.streetList.length > 0 && this.streetIndex >= 0
          ? this.streetList[this.streetIndex].region_id
          : "",
      ];

      console.log("arr", arr);

      this.$api.postCoop(arr).then(function (res) {
        if (res.ResultCode === "100") {
          uni.showToast({
            title: msg,
            icon: "none",
          });
          setTimeout(() => {
            uni.navigateBack({
              delta: 1,
            });
          }, 1000);
        }
      });
    },
    // 编辑进入的时候 默认把选择栏的数据变为 他记录里面的
    async defaultAddressSelect(obj) {
      console.log("defaultAddressSelect", obj);
      console.log("areaData", this.areaData);
      let [areaId, cityId, countyId, streetId] =
        obj.MEMBERADDRESS_CODE.split(",");
      let areaIndex = 0;
      let cityIndex = 0;
      let countyIndex = 0;
      let streetIndex = 0;

      let req = {
        level: 1,
        page: 1,
        pageSize: 999,
      };
      const data = await this.$api.$postNode("/pino/region/list", req);
      let list = data.data.data.result;
      console.log("datadsdsa", list);
      this.areaData = list;

      if (this.areaData && this.areaData.length > 0) {
        this.areaData.forEach((item, index) => {
          if (item.region_id === areaId) {
            areaIndex = index;
          }
        });
      }

      let cityReq = {
        parentId: this.areaData[areaIndex].region_id,
        page: 1,
        pageSize: 999,
      };
      const cityData = await this.$api.$postNode("/pino/region/list", cityReq);
      console.log("cityData", cityData);
      let citylist = cityData.data.data;
      this.city_list = citylist;

      if (this.city_list && this.city_list.length > 0) {
        this.city_list.forEach((item, index) => {
          if (item.region_id === cityId) {
            cityIndex = index;
          }
        });
      }

      let countyReq = {
        parentId: citylist[cityIndex].region_id,
        page: 1,
        pageSize: 999,
      };
      const countyData = await this.$api.$postNode(
        "/pino/region/list",
        countyReq
      );
      console.log("countyData", countyData);

      let countylist = countyData.data.data;
      this.county_list = countylist;
      if (this.county_list && this.county_list.length > 0) {
        this.county_list.forEach((item, index) => {
          if (item.region_id === countyId) {
            countyIndex = index;
          }
        });
      }

      let streetReq = {
        parentId: this.county_list[countyIndex].region_id,
        page: 1,
        pageSize: 999,
      };
      const streetData = await this.$api.$postNode(
        "/pino/region/list",
        streetReq
      );
      console.log("streetData", streetData);
      let streetList = streetData.data.data;
      if (streetList && streetList.length > 0) {
        streetList.forEach((item, index) => {
          if (item.region_id === streetId) {
            streetIndex = index;
          }
        });
      }
      this.streetList = streetList;
      this.addressSelectIndex = [areaIndex, cityIndex, countyIndex];
      this.streetIndex = streetIndex;
    },
    getMsg() {
      let _this = this;
      let arr = {
        action_type: "GetAddressDetail",
        requestType: "application/x-www-form-urlencoded",
        addressId: this.pageMsg.id,
      };
      this.$api.postCoop(arr).then(function (res) {
        if (res.ResultCode === "100") {
          let data = res.Data;
          console.log("res.Data", res.Data);

          if (data.USER_SEX === 1) {
            _this.sexList[0].isChecked = true;
          } else if (data.USER_SEX === 2) {
            _this.sexList[1].isChecked = true;
          }
          console.log("_this.sexList", _this.sexList);
          _this.saveMsg = {
            userName: data.USER_NAME,
            userSex: data.USER_SEX,
            mobilePhone: data.MOBILEPHONE,
            address: data.MEMBERADDRESS_CODE ? data.ADDRESS : "",
            doorplate: data.MEMBERADDRESS_CODE ? data.DOORPLATE : "",
            isDefault: Boolean(data.ISDEFAULT),
            tagType: data.TAGTYPE,
          };
          _this.tipCodes.map((n) => {
            if (n.value === data.TAGTYPE) {
              n.isChecked = true;
            }
          });
          _this.defaultAddressSelect(data);

          // _this.$forceUpdate()
        }
      });
    },
    tagClick(item) {
      this.tipCodes.map((n) => {
        n.isChecked = false;
      });
      item.isChecked = true;
      this.saveMsg.tagType = item.value;
    },
    deleteFn() {
      let _this = this;
      let arr = {
        action_type: "DelAddress",
        requestType: "application/x-www-form-urlencoded",
        addressId: this.pageMsg.id,
      };
      let msg = "删除成功";
      uni.showModal({
        title: "温馨提示",
        content: "您是否确认删除该收货地址信息？",
        cancelText: "取消",
        confirmText: "确认",
        success: (res) => {
          if (res.confirm) {
            _this.$api.postCoop(arr).then(function (res) {
              if (res.ResultCode === "100") {
                uni.showToast({
                  title: msg,
                  icon: "none",
                });
                setTimeout(() => {
                  uni.navigateBack({
                    delta: 1,
                  });
                }, 1000);
              }
            });
          } else {
          }
        },
      });
    },
    loadIndustry() {
      // 新增收货地址时，如果是内部会员则提供默认填写名字和电话
      if (this.user.INDUSTRY_MEMBERSHIP_ID) {
        this.saveMsg.userName = this.user.MEMBERSHIP_NAME;
        this.saveMsg.mobilePhone = this.user.MEMBERSHIP_MOBILEPHONE;
      }
    },
    // 拿到微信地址
    handleGetWxAddress() {
      let _this = this;
      wx.authorize({
        scope: "scope.address",
        success() {
          wx.chooseAddress({
            success(res) {
              console.log("this.addressSelectIndex", _this.addressSelectIndex);
              console.log("areaData", _this.areaData);
              console.log("county_list", _this.county_list);
              let areaIndex = 0;
              let cityIndex = 0;
              let countyIndex = 0;
              console.log("21", res.provinceName.split("省")[0]);

              if (_this.areaData && _this.areaData.length > 0) {
                _this.areaData.forEach((item, index) => {
                  let name = item.name;
                  if (item.name && item.name.indexOf("省") === -1) {
                    name = name + "省";
                  }
                  if (name === res.provinceName) {
                    areaIndex = index;
                  }
                });
              }

              _this.city_list = _this.areaData[areaIndex] && _this.areaData[areaIndex].children ? _this.areaData[areaIndex].children : [];
              console.log("city_list", _this.city_list);

              if (_this.city_list && _this.city_list.length > 0) {
                _this.city_list.forEach((item, index) => {
                  let name = item.name;
                  if (item.name.indexOf("市") === -1) {
                    name = name + "市";
                  }
                  if (name === res.cityName) {
                    cityIndex = index;
                  }
                });
              }
              _this.county_list = _this.city_list[cityIndex] && _this.city_list[cityIndex].children ? _this.city_list[cityIndex].children : [];
              if (_this.county_list && _this.county_list.length > 0) {
                _this.county_list.forEach((item, index) => {
                  let name = item.name;
                  if (name === res.countyName) {
                    countyIndex = index;
                  }
                });
              }

              console.log("countyIndex", countyIndex);
              _this.addressSelectIndex = [areaIndex, cityIndex, countyIndex];

              _this.saveMsg.userName = res.userName;
              _this.saveMsg.mobilePhone = res.telNumber;
              _this.saveMsg.address =
                res.provinceName + res.cityName + res.countyName;
              _this.saveMsg.doorplate = res.detailInfo;

              console.log(res); // 返回用户选择的收货地址信息
              // res 包含的字段
              // res.userName // 收货人姓名
              // res.postalCode // 邮政编码
              // res.provinceName // 省
              // res.cityName // 市
              // res.countyName // 区
              // res.detailInfo // 详细地址
              // res.telNumber // 联系电话
            },
            fail(err) {
              console.log(err);
            },
          });
        },
        fail() {
          console.log("用户授权失败");
        },
      });
    },

    // 地址识别相关方法
    onAddressRecognitionInput(event) {
      this.addressRecognition.inputText = event.mp.detail.value;
      // 当有输入内容时显示按钮
      this.addressRecognition.showButtons = this.addressRecognition.inputText.trim().length > 0;
    },

    cancelAddressRecognition() {
      this.addressRecognition.inputText = '';
      this.addressRecognition.showButtons = false;
    },

    async recognizeAddress() {
      if (!this.addressRecognition.inputText.trim()) {
        uni.showToast({
          title: '请输入地址信息',
          icon: 'none'
        });
        return;
      }

      try {
        const result = await this.parseAddress(this.addressRecognition.inputText);
        if (result.success) {
          // 设置省市区
          if (result.province && result.city && result.district) {
            await this.setAddressFromRecognition(result);
          }

          // 设置详细地址
          if (result.detail) {
            this.saveMsg.doorplate = result.detail;
          }

          // 清空识别输入框
          this.cancelAddressRecognition();

          uni.showToast({
            title: '地址识别成功',
            icon: 'success'
          });
        } else {
          uni.showToast({
            title: result.message || '地址识别失败，请检查地址格式',
            icon: 'none',
            duration: 3000
          });
        }
      } catch (error) {
        uni.showToast({
          title: '识别失败，请重试',
          icon: 'none',
          duration: 3000
        });
      }
    },

    parseAddress(addressText) {
      return new Promise((resolve) => {
        try {
          // 地址解析正则表达式（使用非贪婪匹配）
          const provinceRegex = /(北京市|上海市|天津市|重庆市|[\u4e00-\u9fa5]{2,}?省|[\u4e00-\u9fa5]{2,}?自治区)/;
          const cityRegex = /([\u4e00-\u9fa5]{2,}?市|[\u4e00-\u9fa5]{2,}?地区|[\u4e00-\u9fa5]{2,}?州|[\u4e00-\u9fa5]{2,}?盟)/;
          const districtRegex = /([\u4e00-\u9fa5]{2,}?区|[\u4e00-\u9fa5]{2,}?县|[\u4e00-\u9fa5]{2,}?市)/;
          const streetRegex = /([\u4e00-\u9fa5]{2,}?街道|[\u4e00-\u9fa5]{2,}?镇|[\u4e00-\u9fa5]{2,}?乡)/;

          let currentText = addressText.trim();
          let province = '', city = '', district = '', street = '', detail = '';

          console.log('解析地址:', addressText);
          console.log('初始文本:', currentText);

          // 提取省份
          const provinceMatch = currentText.match(provinceRegex);
          if (provinceMatch) {
            province = provinceMatch[1];
            currentText = currentText.replace(province, '').trim();
            console.log('省份:', province, '剩余:', currentText);
          }

          // 提取城市
          const cityMatch = currentText.match(cityRegex);
          if (cityMatch) {
            city = cityMatch[1];
            currentText = currentText.replace(city, '').trim();
            console.log('城市:', city, '剩余:', currentText);
          }

          // 提取区县
          const districtMatch = currentText.match(districtRegex);
          if (districtMatch) {
            district = districtMatch[1];
            currentText = currentText.replace(district, '').trim();
            console.log('区县:', district, '剩余:', currentText);
          }

          // 提取街道
          const streetMatch = currentText.match(streetRegex);
          if (streetMatch) {
            street = streetMatch[1];
            currentText = currentText.replace(street, '').trim();
            console.log('街道:', street, '剩余:', currentText);
          }

          // 剩余的作为详细地址
          detail = currentText;
          console.log('详细地址:', detail);

          console.log('解析结果:', { province, city, district, street, detail });

          if (province && city && district) {
            resolve({
              success: true,
              province: province,
              city: city,
              district: district,
              street: street,
              detail: detail
            });
          } else {
            resolve({
              success: false,
              message: ``
            });
          }
        } catch (error) {
          console.error('地址解析错误:', error);
          resolve({
            success: false,
            message: '地址解析错误'
          });
        }
      });
    },

    async setAddressFromRecognition(result) {
      try {
        // 先获取所有省份数据
        if (!this.areaData || this.areaData.length === 0) {
          await this.handleGetProviceCode();
        }

        let provinceIndex = -1, cityIndex = -1, districtIndex = -1;

        // 查找省份
        this.areaData.forEach((item, index) => {
          if (item.region_name === result.province ||
            item.region_name.includes(result.province.replace('省', '').replace('市', '').replace('自治区', ''))) {
            provinceIndex = index;
          }
        });

        if (provinceIndex === -1) {
          throw new Error('未找到匹配的省份');
        }

        // 获取城市数据
        const cityReq = {
          parentId: this.areaData[provinceIndex].region_id,
          page: 1,
          pageSize: 999,
        };
        const cityData = await this.$api.$postNode("/pino/region/list", cityReq);
        this.city_list = cityData.data.data;

        // 查找城市
        this.city_list.forEach((item, index) => {
          if (item.region_name === result.city ||
            item.region_name.includes(result.city.replace('市', '').replace('州', '').replace('地区', '').replace('盟', ''))) {
            cityIndex = index;
          }
        });

        if (cityIndex === -1) {
          throw new Error('未找到匹配的城市');
        }

        // 获取区县数据
        const districtReq = {
          parentId: this.city_list[cityIndex].region_id,
          page: 1,
          pageSize: 999,
        };
        const districtData = await this.$api.$postNode("/pino/region/list", districtReq);
        this.county_list = districtData.data.data;

        // 查找区县
        this.county_list.forEach((item, index) => {
          if (item.region_name === result.district ||
            item.region_name.includes(result.district.replace('区', '').replace('县', '').replace('市', ''))) {
            districtIndex = index;
          }
        });

        if (districtIndex === -1) {
          throw new Error('未找到匹配的区县');
        }

        // 设置选中的地址
        this.addressSelectIndex = [provinceIndex, cityIndex, districtIndex];
        this.saveMsg.address =
          this.areaData[provinceIndex].region_name +
          this.city_list[cityIndex].region_name +
          this.county_list[districtIndex].region_name;

        // 获取街道数据
        await this.handleGetStreetData();

        // 如果解析出了街道信息，尝试匹配街道选择器
        if (result.street && this.streetList && this.streetList.length > 0) {
          let streetIndex = -1;
          this.streetList.forEach((item, index) => {
            if (item.region_name === result.street ||
              item.region_name.includes(result.street.replace('街道', '').replace('镇', '').replace('乡', ''))) {
              streetIndex = index;
            }
          });

          // 只有匹配到才设置，匹配不到就保持默认不选择
          if (streetIndex !== -1) {
            this.streetIndex = streetIndex;
          } else {
            // 街道不匹配时，保持默认状态（不选择任何街道）
            this.streetIndex = -1;
          }
        } else {
          // 没有解析到街道信息时，也保持不选择状态
          this.streetIndex = -1;
        }

      } catch (error) {
        console.error('地址设置错误:', error);
        throw error;
      }
    },
  },
  onUnload() {
    this.saveMsg = {
      userName: "",
      userSex: 1,
      mobilePhone: "",
      address: "",
      doorplate: "",
      isDefault: 0,
      tagType: "",
    };
    this.tipCodes.map((n) => {
      n.isChecked = false;
    });
    // 重置地址识别状态
    this.addressRecognition = {
      show: true,
      inputText: '',
      showButtons: false,
    };
  },
  onLoad(option) {
    this.pageMsg.id = option.id || "";
    // this.city_list = this.areaData[0].children;
    // this.county_list = this.city_list[0].children;
    // console.log("this.city_list", this.city_list);
    // console.log("this.county_list", this.county_list);

    if (option.id) {
      this.getMsg();
    } else {
      // 拿到省份数据
      this.handleGetProviceCode();
      if (option.type === "getWx") {
        // 导入微信的地址
        this.handleGetWxAddress();
      } else {
        // 原本的老方法
        this.loadIndustry();
      }
    }
    this.$utils.addUserBehaviorNew();
  },
};
</script>


<style lang="stylus" scoped>
.borbottom {
  border-bottom: 2rpx solid #eee;
}

.page-body {
  padding: 40rpx 0;
}

.addressSelecct {
  width: 100vw;
  height: 300px;
  background: #fff;

  .addressTitle {
    width: 100%;
    box-sizing: border-box;
    padding: 16rpx 32rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #F5F6F7;

    .cancelText {
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 28rpx;
      color: #716F69;
      line-height: 40rpx;
      text-align: left;
      font-style: normal;
    }

    .confirmText {
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 28rpx;
      color: #009F43;
      line-height: 28rpx;
      text-align: justify;
      font-style: normal;
    }
  }

  .picker-view {
    width: 100%;
    height: 100%;

    .item {
      line-height: 60rpx;
      text-align: center;
    }
  }
}

.address-box {
  background: #fff;
  font-size: 28rpx;
  color: #454545;
  padding: 0 32rpx;
}

.adress-content {
  height: 96rpx;
  line-height: 96rpx;
  display: flex;
  align-items: center;
}

.textarea-content {
  padding: 32rpx 0;
  // line-height 96rpx
  display: flex;
  // align-items center
}

textarea {
  width: 98%;
  // height 96rpx
  line-height: 30rpx;
  padding-top: 4rpx;
}

.content-input {
  flex: 1;

  input {
    width: 98%;
    height: 96rpx;
    line-height: 96rpx;
  }
}

.address-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.tip-content {
  display: flex;
  align-items: center;
  // justify-content flex-end
}

.tip-tag {
  text-align: center;
  border-radius: 6rpx;
  border: 2rpx solid #dcdcdc;
  font-size: 22rpx;
  height: 42rpx;
  line-height: 41rpx;
  width: 100rpx;
  color: #666;
  margin: 0 20rpx;
}

.tip-tag.active {
  color: #4BCB7E;
  border-color: #4BCB7E;
  background: #E7F8EE;
}

.content-title {
  min-width: 168rpx;
}

.radio-box {
  padding: 0rpx 0rpx;
  font-size: 26rpx;
  flex: 8;
  height: 96rpx;

  .radio-list {
    width: 48%;
    display: inline-block;

    .radio-unit {
      font-size: 26rpx;
      line-height: 96rpx;
    }
  }
}

.moren-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx 0;
}

.moren-text {
  font-size: 24rpx;
  color: #999;
}

.save-btn {
  margin: 60rpx auto 30rpx auto;
  height: 80rpx;
  width: 660rpx;
  // background linear-gradient(to right,#A17356,#D8AA8B)
  // color #ffffff
  background: linear-gradient(to right, #1f1f1f, #62605f);
  color: #f0dccf;
  border-radius: 10rpx;
  font-size: 28rpx;
  line-height: 80rpx;
  text-align: center;
}

 .btnBox {
        width: 100%;
        box-sizing: border-box;
        padding: 0 32rpx;
        margin-top: 32rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .saveBtn {
            width: calc(50% - 16rpx);
            border-radius: 48rpx;
            background-color: #07C160;
            font-weight: 400;
            font-size: 32rpx;
            color: #FFFFFF;
            text-align: center;
            font-style: normal;
            padding: 24rpx 0;
        }

        .loginOut {
            width: calc(50% - 16rpx);
            border-radius: 48rpx;
            font-weight: 400;
            font-size: 32rpx;
            color: #07C160;
            text-align: center;
            font-style: normal;
            padding: 24rpx 0;
            border: 1px solid #07C160;
            box-sizing: border-box;
        }
    }

.del-btn {
  margin: 0 auto;
  height: 80rpx;
  width: 660rpx;
  background: #e9e9e9;
  border-radius: 10rpx;
  color: #999;
  font-size: 28rpx;
  line-height: 80rpx;
  text-align: center;
}

// 地址识别相关样式
.address-recognition {
  padding: 32rpx 0;
  display: flex;
  align-items: flex-start;
}

.recognition-input {
  position: relative;
  
  .recognition-textarea {
    width: 100%;
    min-height: 80rpx;
    max-height: 200rpx;
    line-height: 30rpx;
    padding: 12rpx;
    border: 2rpx solid #dcdcdc;
    border-radius: 8rpx;
    font-size: 28rpx;
    color: #333;
    background-color: #fff;
    
    &:focus {
      border-color: #07c160;
    }
  }
  
  .recognition-buttons {
    display: flex;
    justify-content: flex-end;
    gap: 16rpx;
    margin-top: 16rpx;
    
    .btn-cancel, .btn-recognize {
      padding: 12rpx 24rpx;
      border-radius: 24rpx;
      font-size: 26rpx;
      text-align: center;
      cursor: pointer;
      min-width: 80rpx;
      line-height: 1;
    }
    
    .btn-cancel {
      background-color: #f5f5f5;
      color: #666;
      border: 1rpx solid #dcdcdc;
      
      &:active {
        background-color: #e9e9e9;
      }
    }
    
    .btn-recognize {
      background-color: #07c160;
      color: #fff;
      border: 1rpx solid #07c160;
      
      &:active {
        background-color: #05a04f;
      }
    }
  }
}
</style>
