<template>
  <view class="manage-alipay">
    <!-- 顶部导航栏 -->
    <custom-navbar
      :title="customName.popTitle"
      :showBack="true"
      @back="goBack"
    ></custom-navbar>

    <!-- 账号列表 -->
    <CommonList
      ref="groupRef"
      apiUrl="/user/userCard/list"
      :listScrollHeight="`calc(100vh - ${statusBarHeight * 2 + 280}rpx)`"
    >
      <template #listData="{ list }">
        <view class="account-list">
          <view class="account-card" v-for="(item, index) in list" :key="index">
            <view
              class="form-item"
              @click="selectAccount(item)"
              v-for="acItem in accountFormItems"
            >
              <text class="label">{{ acItem.label }}</text>
              <text class="value">{{ item[acItem.value] }}</text>
            </view>
            <view class="bottom-row">
              <view class="default-wrapper" @click.stop="setDefault(item.id)">
                <view style="display: flex; align-items: center">
                  <image
                    class="default-wrapper-img"
                    src="/static/images/wallet/default_yes.png"
                    v-if="item.is_default"
                  ></image>
                  <image
                    class="default-wrapper-img"
                    src="/static/images/wallet/default.png"
                    v-else
                  >
                  </image>
                  <text class="default-text">设为默认</text>
                </view>

                <view class="btn-group">
                  <view class="edit" @click.stop="editAccount(item)">修改</view>
                  <view class="delete" @click.stop="deleteAccount(item)"
                    >删除</view
                  >
                </view>
              </view>
            </view>
          </view>
        </view>
      </template>

      <!-- 空数据状态 -->
      <template #empty>
        <noData></noData>
      </template>
    </CommonList>

    <!-- 添加 -->
    <view class="button" @tap="goAdd">
      <view class="button-btn">
        {{ customName.btnText }}
      </view>
    </view>
  </view>
</template>

<script>
import CommonList from "@/components/common/CommonList.vue";
import request from "@/utils/request";
export default {
  components: {
    CommonList,
  },
  data() {
    return {
      statusBarHeight: 0,
      queryData: {
        user_type: getApp().globalData.artisanType,
        type: 1,
      },
      accounts: [],
      radioList: [
        {
          name: "支付宝",
          value: 1,
          btnText: "+ 添加支付宝账号",
          popTitle: "支付宝账号管理",
        },
        {
          name: "银行卡",
          value: 3,
          btnText: "+ 添加银行卡号",
          popTitle: "银行卡管理",
        },
      ],
    };
  },
  computed: {
    customName() {
      let data = this.radioList.find(
        (item) => item.value == this.queryData.type
      );
      if (!data) {
        return {};
      }
      return data;
    },
    accountFormItems() {
      const { type } = this.queryData;
      const formConfig = {
        1: [
          { label: "支付宝账号", value: "card_no" }, // 支付宝账号对应card_no
          { label: "姓名", value: "name" },
          { label: "手机号", value: "phone" },
        ],
        3: [
          { label: "银行卡号", value: "card_no" }, // 所属银行对应bank
          { label: "所属银行", value: "bank" }, // 所属银行对应bank
          { label: "姓名", value: "name" || "" },
          { label: "手机号", value: "phone" || "" },
          { label: "开户行", value: "bank_name" || "" }, // 开户行对应bank_name
        ],
      };
      return formConfig[type] || [];
    },
  },
  onLoad(options) {
    const systemInfo = uni.getSystemInfoSync();
    this.statusBarHeight = systemInfo.statusBarHeight;
    if (options.type) {
      this.queryData.type = options.type;
    }
    this.$nextTick(() => {
      this.search();
    });
  },
  methods: {
    goAdd() {
      uni.navigateTo({
        url: `/pages/wallet/alipay?type=${this.queryData.type}`,
      });
    },
    goBack() {
      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2];
      if (prevPage) {
        if (prevPage.$vm && typeof prevPage.$vm.getAccount === "function") {
          // prevPage.$vm.getAccount(); // 存在则调用
        }
      }
    },
    selectAccount(item) {
      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2];
      if (prevPage) {
        if (prevPage.$vm && typeof prevPage.$vm.getAccount === "function") {
          prevPage.$vm.getAccount(item); // 存在则调用
        }
      }
      uni.navigateBack({
        delta: 1,
      });
    },
    search() {
      // 触发列表刷新
      this.$refs.groupRef.manualRefresh(this.queryData);
    },

    // 设置默认
    setDefault(id) {
      uni.$uv.throttle(() => {
        request
          .post("/user/UserCard/setDefault", {
            id,
          })
          .then((res) => {
            console.log(res, "======");
            if (res.code == 200) {
              // uni.showToast({
              //   title: "已设为默认",
              //   icon: "success",
              // });
              let commonList = this.$refs.groupRef;
              if (!commonList || !commonList.listData) return; // 避免组件未加载或数据不存在的情况

              // 遍历数组，更新is_default状态
              commonList.listData = commonList.listData.map((item) => {
                return {
                  ...item, // 保留其他属性
                  is_default: item.id === id ? 1 : 0, // 匹配id则设为1，否则设为0
                };
              });
            } else {
              uni.showToast({
                title: "设置失败",
                icon: "none",
              });
            }
          });
      }, 500);
    },

    // 弹出编辑弹窗
    editAccount(data) {
      uni.navigateTo({
        url: `/pages/wallet/alipay?data=${encodeURIComponent(
          JSON.stringify(data)
        )}`,
      });
    },

    // 删除用户卡
    deleteAccount(data) {
      // const accountId = this.accounts[index].id;
      uni.showModal({
        content: `确认删除账号 ${data.card_no}？`,
        success: (res) => {
          if (res.confirm) {
            // 1. 本地先删除（优化用户体验）
            uni.showLoading({
              title: "删除中",
            });
            uni.$uv.throttle(() => {
              request
                .post("/user/UserCard/del", {
                  id: data.id,
                })
                .then((res) => {
                  console.log(res, "======");
                  if (res.code == 200) {
                    let commonList = this.$refs.groupRef;
                    if (!commonList || !commonList.listData) return; // 避免组件未加载或数据不存在的情况
                    let newList = commonList.listData.filter(
                      (item) => item.id !== data.id
                    );
                    commonList.listData = newList; // 重新赋值触发响应式更新
                    uni.showToast({
                      title: "已删除",
                      icon: "success",
                    });
                  } else {
                    uni.showToast({
                      title: "删除失败",
                      icon: "none",
                    });
                  }
                })
                .finally(() => {
                  uni.hideLoading();
                });
            }, 500);
          }
        },
      });
    },
  },
};
</script>

<style lang="less" scoped>
.manage-alipay {
  background-color: #f7f7f7;
  height: 100vh;
  padding: 0;
  font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
  // padding-bottom: 120rpx;
}

.account-list {
  padding: 20rpx 16rpx;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.account-card {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 28rpx 32rpx;
  // box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.form-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1rpx solid #f1f1f1;
  padding: 20rpx 0;
}

.label {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  width: 180rpx;
}

.value {
	word-break: break-all;
  font-size: 30rpx;
  font-weight: normal;
  color: #333;
  flex: 1;
  margin-left: 30rpx;
}

.bottom-row {
  margin-top: 20rpx;
  width: 100%;
}

.default-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .default-wrapper-img {
    width: 30rpx;
    height: 30rpx;
  }
}

.default-text {
  margin-left: 12rpx;
  font-size: 30rpx;
}

.btn-group {
  display: flex;
  gap: 40rpx;
}

.edit,
.delete {
  width: 84rpx;
  height: 50rpx;
  background: #f7f7f7;
  border-radius: 6rpx;
  font-weight: 400;
  font-size: 26rpx;
  color: #333333;
  line-height: 37rpx;
  text-align: left;
  font-style: normal;
  display: flex;
  align-items: center;
  justify-content: center;
}

//列表样式
.common-list {
  background-color: transparent !important;

  ::v-deep .list-container {
    padding: 0;
  }
}

.button {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 120rpx;
  background-color: #fafafa;
  display: flex;
  justify-content: center;

  .button-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 666rpx;
    height: 84rpx;
    border-radius: 69rpx;
    border: 2rpx solid #e8101e;
    font-weight: 500;
    font-size: 32rpx;
    color: #e8101e;
    line-height: 45rpx;
    text-align: left;
    font-style: normal;
  }
}
</style>
