<template>
    <view class="page">
        <view class="integral-mine">
            <view class="integral-mine-head">
                <view class="mine-head-cell-top">
                    <view class="integral-shop" @tap="toShop" data-type="shop">
                        <image :src="imgHost + '/images/icon/user/integral-shop@2x.png'" mode="" />
                        <text>积分商城</text>
                    </view>
                    <view class="integral-rule" @tap="toRule">
                        <text>规则</text>
                        <image :src="imgHost + '/images/icon/user/help@2x.png'" mode="" />
                    </view>
                </view>
                <view class="mine-head-cell-mid">
                    <view class="integral-available-label">可用积分</view>
                    <view class="integral-available-text">{{ integralMemberInfo.availableIntegralValue || '0' }}</view>
                </view>
                <view class="mine-head-cell-btm">
                    <view class="integral-cell">
                        <text class="label">累计积分：</text>
                        <text class="num">{{ integralMemberInfo.accumulativeIntegralValue || '0' }}</text>
                    </view>
                    <view class="integral-cell">
                        <text class="label">今日已获得积分：</text>
                        <text class="num">{{ integralMemberInfo.todayObtainIntegralValue || 0 }}</text>
                    </view>
                </view>
            </view>
            <van-tabs active="{{ tabActive }}" sticky="{{ true }}" line-height="4px" title-active-color="#67A5FD"
                color="#67A5FD">
                <van-tab title="积分明细">
                    <view class="integral-list">
                        <view class="item" v-for="(item, index) in integralDetail.listData" :key="index">
                            <view class="dot"></view>
                            <view class="intro">
                                <text class="intro-text">{{ item.obtainName }}</text>
                                <text class="datetime">{{ item.gmtUpdated }}</text>
                            </view>
                            <view class="num-validity-period">
                                <text class="num">{{ item.type == 1 ? '+' : (item.type == 2 ? '-' : '') }}{{
                                    item.integralValue }}</text>
                                <text class="validity-period">{{ item.invalidType == 1 ? '有效期至：' + item.validityTime :
                                    '永久有效' }}</text>
                            </view>
                        </view>
                    </view>
                </van-tab>
                <van-tab title="兑换记录">
                    <view class="exchange-list">
                        <block wx:if="{{ exchangeRecord.listData }}">
                            <view class="item" v-for="(item, index) in exchangeRecord.listData" :key="index" @tap="toShop"
                                data-type="exchange">
                                <view class="item-l">
                                    <image
                                        :src="item.type == 3 ? item.integralCoupon.icon : item.integralShopGoods.goodsImg"
                                        mode="" />
                                    <view class="name">
                                        <text class="product-title">{{ item.type == 3 ? item.integralCoupon.name :
                                            item.integralShopGoods.goodsName }}</text>
                                        <text class="datetime">{{ item.gmtUpdated }}</text>
                                    </view>
                                </view>
                                <view class="item-r">
                                    <text class="num">-{{ item.integralValue }}</text>
                                    <view class="to-detail">
                                        <text>查看详情</text>
                                        <uni-icons type="right" size="12px" color="#A6A6A6" />
                                    </view>
                                </view>
                            </view>
                        </block>
                        <view class="no-data" wx:else>
                            <empty />
                        </view>
                    </view>
                </van-tab>
            </van-tabs>
        </view>
    </view>
</template>

<script>
import $http from "@/utils/https";
import Util from '@/utils/utils';
import httpConfig from '@/utils/httpConfig'
export default {
    data() {
        return {
            imgHost: httpConfig?.imgHost || '',
            userData: {},
            tabActive: 1,
            integralMemberInfo: {
                accumulativeIntegralValue: null, // 累计积分 integer
                availableIntegralValue: null, // 可用积分 integer
                todayObtainIntegralValue: null, // 今日获得积分 integer
            },
            pageNum: 1,
            pageSize: 100,
            integralUserId: null,
            integralDetail: [],
            // {
            //   description: '签到', //描述 string
            //   gmtCreate: '', // string yyyy-MM-dd HH:mm:ss
            //   gmtUpdated: '2023-4-23 15:48:35', // string yyyy-MM-dd HH:mm:ss
            //   integralAccountId: null, // 积分用户ID integer
            //   integralValue: 500, // 积分 integer
            //   invalidType: 0, // 积分是否永久有效：0-永久有效、1-到期失效  integer
            //   lossWay: null, // integer
            //   obtainName: '', // 获取/使用 方式名称 string
            //   obtainWay: null, // integer
            //   sourceId: '', // 关联物ID或者是订单号 string
            //   tenantId: null, // integer
            //   type: 1, // 类型:1-增加,2-减少 integer
            //   userId: null, // integer
            //   validityTime: '2025-12-31', // string 积分失效时间
            //   vipLevelId: null, // 会员等级ID integer
            // }
            exchangeRecord: [],
            // {
            //   businessRemarks: '', // string 商家备注
            //   checkCode: '', // string 积分商品核销码
            //   delFlag: false, // boolean 是否删除
            //   expressCompany: '', // string 快递公司
            //   expressNumber: '', // string 快递单号
            //   gmtCreate: '', // string 创建时间
            //   gmtUpdated: '2023-3-27 13:34:56', // string 更新时间
            //   goodsNumber: '', // integer 商品数量
            //   integralShopGoods: { // 积分商品
            //     goodsDesc: '', // string 商品详情
            //     goodsImg: '', // string 商品头图
            //     goodsName: '商品名称', // string 商品名称
            //     goodsType: '', // integer 商品类型：1-服务商品、2-实物商品、3-优惠券
            //     id: null, // integer ID
            //   },
            //   integralValue: 300, // integer 所需积分
            //   operationTime: '', // string 核销/发货时间
            //   orderNumber: '', // string 订单编号
            //   orderStatus: '', // string 积分订单状态：1-待收货、2-待核销、3、已完成
            //   receiveAddress: '', // string 收货地址
            //   receiver: '', // string 收货人
            //   sourceId: '', // integer 兑换物ID
            //   type: 2, // integer 积分兑换类型：1-服务商品，2-实物商品，3-优惠券
            //   userId: null, // integer 
            //   userRemarks: '', // string 备注
            // }
            hospShopAppId: null, // 医院商城小程序AppID
        }
    },
    onLoad(options) {
        this.getUserData()
        if (options.hasOwnProperty('integralUserId') && options.integralUserId) {
            this.setData({
                integralUserId: options.integralUserId
            }, () => {
                this.getIntegralStatistics() // 获取统计数据
                this.getIntegralDetail() // 获取积分明细记录
                this.getExchangeRecord() // 获取兑换记录
                this.getHospAppID() // 获取APPID列表
            })
        }
        if (options.hasOwnProperty('tab')) {
            this.setData({
                tabActive: parseInt(options.tab)
            })
        }
    },
    methods: {
        // 设置用户信息到data
        getUserData() {
            let userData = this.$cache.get('userData');
            console.log(userData)
            if (!userData) {
                uni.showToast({
                    icon: 'none',
                    title: '未获取到就诊人信息，请选择就诊人重试',
                })
                return false
            }
            this.setData({
                userData
            })
            return true
        },
        // 获取积分统计
        getIntegralStatistics() {
            let {
                userData,
                integralUserId
            } = this
            let data = {
                params: [{
                    patID: userData.hisPatID || '',
                    hospCode: userData.hisHospID || '',
                    userId: integralUserId, // 积分会员ID
                    serviceType: 1, // 1:当前会员信息， 2:会员列表
                }]
            }
            $http.post("urlS", this, {
                code: "WX01020",
                data: data,
                namespace: 'N',
                success: function (res) {
                    // console.log('统计数据',res)
                    if (+res.errorCode === 0) {
                        this.setData({
                            integralMemberInfo: res.result.data
                        });
                    }
                }
            });
        },
        // 获取积分明细
        getIntegralDetail() {
            let {
                pageNum,
                pageSize,
                integralUserId,
                userData
            } = this
            let data = {
                params: [{
                    pageNum,
                    pageSize,
                    userId: integralUserId, // 积分会员ID
                }]
            }
            $http.post("urlS", this, {
                code: "WX01028",
                data: data,
                namespace: 'N',
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setData({
                            integralDetail: res.result.data
                        });
                    }
                }
            });
        },
        // 兑换记录
        getExchangeRecord() {
            let {
                userData,
                pageNum,
                pageSize,
                integralUserId
            } = this
            let data = {
                params: [{
                    pageNum,
                    pageSize,
                    userId: integralUserId, // 积分会员ID
                }]
            }
            $http.post("urlS", this, {
                code: "WX01016",
                data: data,
                namespace: 'N',
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setData({
                            exchangeRecord: res.result.data
                        });
                    }
                }
            });
        },
        // 获取医院小程序appid
        getHospAppID() {
            let {
                userData
            } = this
            let data = {
                params: [{
                    hospitalCode: userData.hisHospID
                }]
            }
            $http.post("urlS", this, {
                code: "WX01030",
                data: data,
                namespace: 'N',
                success: function (res) {
                    if (+res.errorCode === 0 && res.result.data) {
                        this.setData({
                            hospShopAppId: res.result.data.appId
                        });
                    }
                }
            });
        },
        toRule() {
            const { integralUserId } = this.data
            uni.navigateTo({
                url: '/pages/mine/pages/integralMember/integralRule/index?integralUserId=' + integralUserId
            })
        },
        // 跳转积分商城
        toShop(e) {
            const { hospShopAppId } = this
            const type = e.currentTarget.dataset.type
            if (!hospShopAppId) {
                uni.showToast({
                    icon: 'none',
                    title: '应用ID不存在，请回退再操作'
                })
                return
            }
            let path = 'pages/vip/shop/index/index'
            if (type != 'shop') {
                path = 'pages/vip/points/index'
            }
            console.log(path, hospShopAppId)
            //#ifndef MP-WEIXIN
            uni.navigateToMiniProgram({
                appId: hospShopAppId,
                path: path,
                extraData: {},
                success() {
                    console.log('打开商场成功')
                },
                fail() {
                    console.log('打开商场失败')
                }
            })
            //#endif
            //#ifndef MP-ALIPAY
            uni.showModal({
                title: "提示",
                content: "支付宝端暂不支持，敬请期待！",
                showCancel: false
            })
            //#endif
        }
    }
}
</script>

<style>
.no-data {
  padding: 60rpx 0;
}

.integral-mine {
  padding: 30rpx 24rpx 0;
  padding-bottom: calc(env(safe-area-inset-bottom) + 40rpx);
}

.integral-mine-head {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 353rpx;
  padding: 30rpx 40rpx;
  background: linear-gradient(180deg, #96BBF0, #9FD4F3);
  border-radius: 10rpx;
}

.mine-head-cell-top {
  display: flex;
  justify-content: space-between;
}

.integral-shop {
  display: flex;
  align-items: center;
  height: 50rpx;
  background: #467FCE;
  border-radius: 25rpx;
  padding: 0 26rpx;
  font-size: 24rpx;
  color: #fff;
  line-height: 1;
}

.integral-shop image {
  width: 26rpx;
  height: 28rpx;
  margin-right: 15rpx;
}

.integral-rule {
  display: flex;
  align-items: center;
  height: 50rpx;
  color: #fff;
  line-height: 1;
  font-size: 24rpx;
}

.integral-rule image {
  width: 26rpx;
  height: 26rpx;
  margin-left: 15rpx;
}

.mine-head-cell-mid {
  display: flex;
  flex-direction: column;
  font-weight: bold;
}

.integral-available-label {
  font-size: 30rpx;
  color: #333;
}

.integral-available-text {
  font-size: 60rpx;
  color: #fff;
}

.mine-head-cell-btm {
  display: flex;
  justify-content: space-between;
  font-size: 24rpx;
  font-weight: 400;
}

.integral-cell .label {
  color: #666666;
}

.integral-cell .num {
  color: #fff;
}

.van-tabs__scroll {
  background-color: #f7f7f7 !important;
}

/*积分明细*/
.integral-list,
.exchange-list {
  background: #fff;
  margin-top: 10rpx;
  padding: 16rpx 75rpx;
  min-height: 300rpx;
}

.integral-list .item,
.exchange-list .item {
  display: flex;
  justify-content: space-between;
  padding: 16rpx 0;
  line-height: 1;
}

.integral-list .item .intro,
.integral-list .item .num-validity-period {
  display: flex;
  flex-direction: column;
}

.integral-list .item .dot {
  position: absolute;
  left: 24rpx;
}

.integral-list .item .dot::before {
  position: absolute;
  content: "";
  height: 150%;
  width: 4rpx;
  background: #D1E4FE;
  top: 4rpx;
  left: 8rpx;
  height: 108rpx;
}

.integral-list .item .dot::after {
  position: absolute;
  content: "";
  width: 16rpx;
  height: 16rpx;
  background: #67A5FD;
  border-radius: 50%;
  top: 4rpx;
}

.integral-list .item:last-child .dot::before {
  display: none;
}

.integral-list .item .intro .intro-text {
  font-size: 24rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 22rpx;
}

.integral-list .item .intro .datetime {
  font-size: 20rpx;
  color: #A6A6A6;
}

.integral-list .item .num-validity-period .num {
  font-size: 24rpx;
  color: #67A5FD;
  font-weight: bold;
  text-align: right;
  margin-bottom: 22rpx;
}

.integral-list .item .num-validity-period .validity-period {
  font-size: 20rpx;
  color: #A6A6A6;
  text-align: right;
}

/*兑换记录*/
.exchange-list {
  padding: 0;
}
.exchange-list .item {
  padding: 30rpx 20rpx;
  border-bottom: 2rpx solid rgba(0,0,0,0.1);
}
.exchange-list .item .item-l {
  display: flex;
}
.exchange-list .item .item-l image {
  width: 120rpx;
  height: 120rpx;
  background: #C4C4C4;
  margin-right: 20rpx;
}

.exchange-list .item .item-l .name {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 6rpx 0;
}
.exchange-list .item .item-l .name .product-title {
  
  font-size: 24rpx;
  font-weight: bold;
  color: #333333;
}
.exchange-list .item .item-l .name .datetime {
  font-size: 22rpx;
  color: #A6A6A6;
}

.exchange-list .item .item-r {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 6rpx 0;
}

.exchange-list .item .item-r .num {
  font-size: 24rpx;
  color: #67A5FD;
  text-align: right;
  padding-right: 8rpx;
}
.exchange-list .item .item-r .to-detail {
  display: flex;
  align-items: center;
}

.exchange-list .item .item-r .to-detail text {
  color: #A6A6A6;
  font-size: 20rpx;
}
</style>