<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 优惠券接口
 */
namespace app\allwin\controller\api\v4;
use app\allwin\controller\api\Base;
use app\allwin\model\Coupon as ModelCoupon;
use app\allwin\model\CouponUser;
use app\allwin\model\CouponOrder;
use app\allwin\model\AllwinConfig;
use app\common\model\SystemMemberForm;
use app\common\facade\WechatPay;

class Coupon extends Base{

    /**
     * 读取单个优惠券信息
     **/
    public function getCoupon(){
        $param['id']      = $this->request->param('id/d');
        $param['signkey'] = $this->request->param('signkey');
        $param['sign']    = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        $condition['member_miniapp_id'] = $this->miniapp_id;
        $condition['id']                = $param['id'];
        $coupon = ModelCoupon::where($condition)->find();
        if (empty($coupon)) {
            return enjson(204);
        }
        //判断用户已领取优惠券
        $user_coupon_id = [];
        if ($this->user) {
            $ids = CouponUser::userCouponIds($this->user->id);
            if (!empty($ids)) {
                $user_coupon_id = $ids;
            }
        }
        $data['id']        = $coupon['id'];
        $data['store_id']  = $coupon['store_id'];
        $data['types']     = $coupon['types'];
        $data['name']      = $coupon['name'];
        $data['size']      = $coupon['size'];
        $data['sizes']     = round($coupon['size']);
        $data['price']     = $coupon['price'];
        $data['amount']    = $coupon['types'] ? $coupon['discount'].'折':round($coupon['price']).'元';
        $data['discount']  = $coupon['discount'];
        $data['howmuch']   = $coupon['howmuch'];
        $data['img']       = $coupon['img'];
        $data['weekday']   = implode(',',weekdays(json_decode($coupon['weekday'])));
        $data['starttime'] = date('Y-m-d',$coupon['starttime']);
        $data['endtime']   = date('Y-m-d',$coupon['endtime']);
        $data['tips']      = $coupon['tips'];
        $data['state']     = in_array($coupon['id'],$user_coupon_id) ? 1 : 0;
        $data['rate']      = rate($coupon['num'],$coupon['num_of']);
        $data['store']['id']         = $coupon->store['id'];
        $data['store']['name']       = $coupon->store['name'];
        $data['store']['img']        = $coupon->store['img']."?x-oss-process=style/w100";
        $data['store']['address']    = $coupon->store['address'];
        $data['store']['telphone']   = $coupon->store['telphone'];
        $data['store']['state_text'] = $coupon->store['state_text'];
        $data['store']['is_top']     = $coupon->store['is_top'];
        $data['store']['tips']       = $coupon->store['tips'];
        $data['store']['tags']       = explode(',',$coupon->store['tags']);
        return enjson(200,'成功',$data);
    }

    /**
     *优惠券列表
     * @return void
     */
    public function couponList(){
        $param['cate_id']  = $this->request->param('cate_id/d',0);
        $param['types']    = $this->request->param('types/d',0);
        $param['page']     = $this->request->param('page/d',0);
        $param['keyword']  = $this->request->param('keyword','');
        $param['sign']     = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson(403,'签名失败');
        }
        //搜索条件
        $condition = [];
        $condition[] = ['is_platform','=',0];
        if($param['cate_id']){
            $condition[] = ['cate_id','=',$param['cate_id']];
        }
        switch ($param['types']) {
            case 1:
                $condition[] = ['is_check','=',1];
                break;
            case 2:
                $condition[] = ['is_vip','=',1];
                break;
            default:
                $condition[] = ['is_shop','=',1];
                break;
        }
        //搜索关键字
        if(!empty($param['keyword'])){
            $condition[] = ["name","like","%{$param['keyword']}%"];
        }
        $condition[] = ['member_miniapp_id','=',$this->miniapp_id];
        $condition[] = ['is_lock','=',0];
        $condition[] = ['is_end','=',0];
        $condition[] = ['num','>',0];
        $condition[] = ['endtime','>',time()];
        $coupon = ModelCoupon::where($condition)->order('is_top desc,sort desc,size desc')->paginate(6);
        if ($coupon->isEmpty()) {
            return enjson(204,'没有优惠券');
        }
        //判断用户已领取优惠券
        $user_coupon_id = [];
        if ($this->user) {
            $ids = CouponUser::userCouponIds($this->user->id);
            if (!empty($ids)) {
                $user_coupon_id = $ids;
            }
        }
        $data = [];
        foreach ($coupon as $key => $value) {
            $data[$key]['id']        = $value['id'];
            $data[$key]['store_id']  = $value->store->id;
            $data[$key]['store']     = $value->store->name;
            $data[$key]['address']   = $value->store->address;
            $data[$key]['img']       = $value['img'].'?x-oss-process=style/w100';
            $data[$key]['name']      = $value['name'];
            $data[$key]['size']      = $value['size'];
            $data[$key]['amount']    = round($value['size']);
            $data[$key]['tips']      = $value['tips'];
            $data[$key]['types']     = $value['types'];
            $data[$key]['price']     = $value['types'] ? $value['discount'].'折':$value['price'];
            $data[$key]['pay_price'] = $value['pay_price'];
            $data[$key]['theme']     = $value['theme'];
            $data[$key]['starttime'] = date('Y-m-d',$value['starttime']);
            $data[$key]['endtime']   = date('Y-m-d',$value['endtime']);
            $data[$key]['state']     = in_array($value['id'],$user_coupon_id) ? 1 : 0;
            $data[$key]['rate']      = rate($value['num'],$value['num_of']);
        }
        return enjson(200,'成功',$data);
    }

    /**
     * 用户发起领取优惠券
     */
    public function buyCoupon(){
        $this->isUserAuth();
        if (request()->isPost()) {
            $param['coupon_id'] = $this->request->param('coupon_id/d');
            $param['signkey']   = $this->request->param('signkey');
            $param['sign']      = $this->request->param('sign');
            $rel = $this->apiSign($param);
            if($rel['code'] != 200){
                return enjson($rel['code'],'签名验证失败');
            }
            $param['member_miniapp_id']  = $this->miniapp_id;
            $validate = $this->validate($param,'Dopay.coupon');
            if (true !== $validate) {
                return enjson(403,$validate);
            }
            //禁止重复领取
            $coupon_user = CouponUser::userCouponCount($this->user->id,$param['coupon_id']);
            if($coupon_user){
                return enjson(403,'禁止重复领取');
            }
            //读取优惠券
            $condition['member_miniapp_id'] = $this->miniapp_id;
            $condition['is_lock']           = 0;
            $condition['id']                = $param['coupon_id'];
            $coupon = ModelCoupon::where($condition)->find();
            if (empty($coupon)) {
                return enjson(403,'未找到优惠券');
            }
            if ($coupon->is_platform == 1) {
                return enjson(403,'这个优惠券不允许单独领取哦');
            }
            //免费或付费领取
            $state = 0;
            if($coupon->shop_price > 0){
                $order_no = 'BUYCP'.order_no();
                $payparm = [
                    'name'       => '付费购买优惠券['.$coupon->name.']',
                    'openid'     => $this->user->miniapp_uid,
                    'miniapp_id' => $this->miniapp_id,
                    'order_no'   => $order_no,
                    'total_fee'  => $coupon->shop_price*100,
                    'notify_url' => api(4,'allwin/couponnotify/index',$this->miniapp_id),
                ];
                //读取配置
                $setting = AllwinConfig::getConfig($this->miniapp_id);
                if($setting->is_psp == 1){
                    $default_mchid = model('MchId')->getMch(0, $this->miniapp_id);  //默认收款账户
                    if (empty($default_mchid)) {
                        return enjson(403,'未找到商户号');
                    }
                    $payparm['mchid'] = $default_mchid->mchid;  
                }
                $ispay = WechatPay::orderPay($payparm);
                if ($ispay['code'] == 0) {
                    return enjson(403,$ispay['msg']);
                }
                $paydata = $ispay['data'];
            }else{
                $order_no   = 'FREECP'.order_no();
                $state      = 1;
                $paydata    = [];
                $coupon_ids = json_encode([$param['coupon_id']]);
                CouponUser::addUserCoupon($coupon_ids,$this->user->id); //领取优惠券入库
            }
            //创建记录
            $vipdata                      = [];
            $vipdata['state']             = $state;
            $vipdata['coupon_ids']        = json_encode([$param['coupon_id']]);
            $vipdata['order_no']          = $order_no;
            $vipdata['amount']            = $coupon->shop_price;
            $vipdata['store_id']          = $coupon->store_id;
            $vipdata['user_id']           = $this->user->id;
            $vipdata['member_miniapp_id'] = $this->miniapp_id;
            $vipdata['update_time']       = time();
            $rel = CouponOrder::insert($vipdata);
            if($rel){
                if($coupon->shop_price > 0){
                    SystemMemberForm::addForm($this->miniapp_id,$this->user->id,substr($ispay['data']['package'],10));
                }
                return enjson(200,'成功',['pay' => $paydata,'isbuy' => $state]); 
            }else{
                return enjson(403,'领取优惠券失败');
            }
        }
    }
}