<?php
namespace app\controllers\channelApi;
use Illuminate\Support\Facades\DB;
use Yii;
use app\models\common\Config;
use app\models\common\Member;
use app\models\common\WeChat;
use EasyWeChat\Factory;
class VipCardController extends CommonController
{
    public $enableCsrfValidation = false;
    //查看等级列表
    public function actionLevelList(){
        $uniacid=$this->wqData['uniacid'];
        $cardInfo=(new \yii\db\Query())
            ->from('{{%ybwm_user_card}}')
            ->where(['deleteAt'=>0,'display'=>1,'uniacid'=>$uniacid])->orderBy('level asc')->all();
        for($i=0;$i<count($cardInfo);$i++){
            $rights=json_decode($cardInfo[$i]['rights'],true);
            $cardInfo[$i]['rightsList']=(new \yii\db\Query())
                ->select('name,icon')
                ->from('{{%ybwm_core_category}}')
                ->where(['in','id',$rights])->all();
            $coupon=json_decode($cardInfo[$i]['coupon'],true);
            $cardInfo[$i]['couponList']=(new \yii\db\Query())
                ->select('name,id')
                ->from('{{%ybwm_coupon}}')
                ->where(['in','id',$coupon])->all();
        }

        return $this->result(1, '成功',$cardInfo);
    }
    //查看会员卡详情
    public function actionLevelInfo(){
        $result=axios_request();
        $level=$result['level']?:1;
        $uniacid=$this->wqData['uniacid'];
        $cardInfo=(new \yii\db\Query())
            ->from('{{%ybwm_user_card}}')
            ->where(['deleteAt'=>0,'level'=>$level,'uniacid'=>$uniacid])->one();
        $rights=json_decode($cardInfo['rights'],true);
        $cardInfo['rightsList']=(new \yii\db\Query())
            ->select('name,icon')
            ->from('{{%ybwm_core_category}}')
            ->where(['in','id',$rights])->all();
        $coupon=json_decode($cardInfo['coupon'],true);
        $cardInfo['couponList']=(new \yii\db\Query())
            ->select('name,id')
            ->from('{{%ybwm_coupon}}')
            ->where(['in','id',$coupon])->all();
        return $this->result(1, '成功',$cardInfo);
    }
    //开卡
    public function actionReceiveCard(){
        $result=axios_request();
        $uniacid=$this->wqData['uniacid'];
        $userId=$this->wqData['userId'];
        $cardInfo=(new \yii\db\Query())
            ->from('{{%ybwm_user_card}}')
            ->where(['deleteAt'=>0,'display'=>1,'uniacid'=>$uniacid])->orderBy('level asc')->one();
        if(!$cardInfo){
            return $this->result(2, '会员卡设置有误');
        }
        $data['userTel']=$result['userTel'];
        $data['birthday']=$result['birthday']?:'';
        $data['realName']=$result['realName']?:'';
        $data['vipCode']=randomAESKey(12);
        $data['level']=1;
        $data['sex']=$result['sex']?:1;
        $transaction = Yii::$app->db->beginTransaction();   //开始事务
        if($result['userTel']){
            $userInfo=(new \yii\db\Query())
                ->from('{{%ybwm_member}}')
                ->where(['userTel'=>$result['userTel'],'uniacid'=>$uniacid])
                ->one();
            if($userInfo&&$userInfo['id']!==$userId){
                return $this->result(2, '该手机号已被使用,请更换其他手机号');
            }
        }
        $res=Yii::$app->db->createCommand()->update('{{%ybwm_member}}', $data, ['id' =>$userId])->execute();
        if(!$res){
            $transaction->rollBack();//事务回滚
            return $this->result(2, '开卡失败','修改会员信息失败');
        }
        $record['userId']=$userId;
        $record['level']=1;
        $record['uniacid']=$uniacid;
        $record['createdAt']=time();
        $userRecord=Yii::$app->db->createCommand()->insert('{{%ybwm_user_card_record}}', $record)->execute();
        if(!$userRecord){
            $transaction->rollBack();//事务回滚
            return $this->result(2, '开卡失败','插入开卡记录失败');
        }
        if($cardInfo['isBalance']==1){
            $saveBalance=Member::saveBalance($userId, 2, $cardInfo['balance'], 1, '会员卡开卡',$uniacid);
            if(!$saveBalance){
                $transaction->rollBack();
                return $this->result(2, '失败','赠送余额失败');
            }
        }
        if($cardInfo['isIntegral']==1){
            $saveIntegral=Member::saveIntegral($userId, 2, $cardInfo['integral'], 1, '会员卡开卡',$uniacid);
            if(!$saveIntegral){
                $transaction->rollBack();
                return $this->result(2, '失败','赠送积分失败');
            }
        }
        if($cardInfo['isGrowth']==1){
            $saveGrowth=Member::saveGrowth($userId, 2, $cardInfo['growth'], 1, '会员卡开卡',$uniacid);
            if(!$saveGrowth){
                $transaction->rollBack();
                return $this->result(2, '失败','赠送成长值失败');
            }
        }
        $coupon=json_decode($cardInfo['coupon'],true);
        //发放优惠券
        $receiveCoupon=Member::receiveCoupon($coupon, $userId,12);
        if(!$receiveCoupon){
            $transaction->rollBack();
            return $this->result(2, '失败','发放优惠券失败');
        }
        $transaction->commit();
        return $this->result(1, '成功');

    }
    //获取会员卡开卡组件参数
    public function actionMemberCardParameter() {
        $uniacid=$this->wqData['uniacid'];
        $card=Config::getSystemSet('vipSet',$uniacid);
        if(!$card['cardId']){
            return $this->result(2, '未同步会员卡信息');
        }
        $app=Factory::officialAccount(WeChat::getWeChatTemplateConfig($uniacid));
        $accessToken = $app->access_token;
        $token = $accessToken->getToken(); // token 数组  token['access_token'] 字符串
        $url = "https://api.weixin.qq.com/card/membercard/activate/geturl?access_token=" . $token['access_token'];
        $data = array(
            "card_id" => $card['cardId'],
            "outer_str" => "vipCode",
        );

        $res = httpRequest($url, json_encode($data, JSON_UNESCAPED_UNICODE));
        //print_R($res);die;
        $res = json_decode($res, true);
        return $this->result(1, '成功', $res['url']);
    }
    //激活会员卡
    public function actionActivateMembership() {
        $request = Yii::$app->request;
        $result=axios_request();
        $uniacid=$this->wqData['uniacid'];
        if($request->isGet){
            return $this->result(2, '请求异常');
        }
        $card_id = $result['card_id'];
        $code = $result['code'];
        $userId = $this->wqData['userId'];
        $app=Factory::officialAccount(WeChat::getWeChatTemplateConfig($uniacid));
        $accessToken = $app->access_token;
        $token = $accessToken->getToken(); // token 数组  token['access_token'] 字符串
        $userData['WeChatCardCode'] = $code;
        $userData['WeChatCardId'] = $card_id;
        $userData['WeChatCard'] = 1;
        $userData['changeAt'] = time();
        $res=Yii::$app->db->createCommand()->update('{{%ybwm_member}}', $userData, ['id' =>$userId])->execute();
        if(!$res){
            return $this->result(2, '激活失败');
        }
        $user = (new \yii\db\Query())
            ->select('level,integral,balance')
            ->from('{{%ybwm_member}}')
            ->where(['id'=>$this->wqData['userId']])->one();
        $cardInfo=(new \yii\db\Query())
            ->from('{{%ybwm_user_card}}')
            ->where(['deleteAt'=>0,'level'=>$user['level'],'uniacid'=>$uniacid])->one();
        $url2 = "https://api.weixin.qq.com/card/membercard/activate?access_token=" . $token['access_token'];
        $data2 = array(
            "membership_number" => $code,
            "code" => $code,
            "card_id" => $card_id,
            "init_bonus" => $user['integral'], //初始积分
            "init_bonus_record" => '用户积分同步',
            "init_custom_field_value1" => $cardInfo['name'],
            "init_custom_field_value2" => "¥" . $user['balance'],
        );
        httpRequest($url2, json_encode($data2, JSON_UNESCAPED_UNICODE));
        return $this->result(1, '成功');
    }


}