<?php
/**
 * 优惠券
 */
namespace app\smartbc\controller\api\v1;
use app\smartbc\controller\api\Base;
use app\smartbc\model\SmartbcCoupon;
use app\smartbc\model\SmartbcStore;
use app\smartbc\model\SmartbcCouponUser;
use app\smartbc\model\SmartbcConfig;
use app\smartbc\model\SmartbcStoreUnion;
use think\Db;

class Coupon extends Base{

    protected $config;

    /**
     * 初始化当前应用管理员是不是联盟城市账户
     * @return void
     */
    public function initialize() {
        parent::initialize();
        $this->isUserAuth();
        $this->config = SmartbcConfig::getConfig($this->member_miniapp_id);
    }

    /**
     * 领取优惠券
     * @return void
     */
    public function getCoupon(){
        $param['id']        = $this->request->param('id');
        $param['store_id']  = $this->request->param('store_id'); //引荐的店铺id
        $sign = $this->apiSign($param);
        if ($sign['code'] != 200) {
            return enjson($sign['code'],'签名验证失败');
        }
        $couponUser = SmartbcCouponUser::where(['member_miniapp_id' => $this->miniapp_id,'coupon_id' => $param['id'],'uid' => $this->user->id,'is_end' => 0])->find();
        if(!empty($couponUser)){
            return enjson(200,'已经拥有该优惠券',$couponUser);
        }
        if($param['id']){
            $info = SmartbcCoupon::where(['member_miniapp_id' => $this->miniapp_id,'id' => $param['id'],'is_end' => 0])->find();
            if(!empty($info)){
                $is_group = SmartbcStoreUnion::isGroup($param['id'],$param['store_id'],$this->miniapp_id);
                $data['member_miniapp_id'] = $this->miniapp_id;
                $data['store_id']          = $info->store_id;
                $data['coupon_id']         = $info->id;
                $data['uid']               = $this->user->id;
                $data['is_end']            = 0;
                $data['types']             = $info->types;
                $data['name']              = $info->name;
                $data['price']             = $info->price;
                $data['discount']          = $info->discount;
                $data['howmuch']           = $info->howmuch;
                $data['amount']            = $info->amount;
                $data['tips']              = $info->tips;
                $data['group_ids']         = $is_group ?? 0;
                $data['parent_store_id']   = !empty($param['store_id']) ? $param['store_id'] : 0;
                $data['update_time']       = time();
                $data['create_time']       = time();
                $rel = SmartbcCouponUser::create($data);
                if($rel){
                    return enjson(200,$rel);
                }
                return enjson(204);
            }
        }
        return enjson(403,'未找到优惠券');
    }

    /**
     * 已领取的优惠券信息
     * @return void
     */
    public function couponInfo(){
        $param['id'] = $this->request->param('id'); 
        $rel = $this->apiSign($param);
        if ($rel['code'] != 200) {
            return enjson($rel['code'],'签名验证失败');
        }
        $info = SmartbcCouponUser::with(['coupon' => function($query) {
            $query->field('id,create_time');
        },'store' => function($query) {
            $query->field('id,name,address,longitude,latitude,img,telphone');
        }])->where(['member_miniapp_id' => $this->miniapp_id,'id' => $param['id']])->find();
        if (empty($info)) {
            return enjson(404,'未找到优惠券');
        }
        $info->store->img =  $info->store->img."?x-oss-process=style/w100";
        if(!empty($this->qqgps)){
            $info->store->distance = getDistance($this->qqgps['lng'],$this->qqgps['lat'],$info->store->longitude,$info->store->latitude);
        }
        return enjson(200,$info);
    }

   /**
    * 用户已领优惠券
    * @return void
    */
    public function userCoupon(){
        $param['type']   = $this->request->param('type/d',0);
        $param['page']   = $this->request->param('page/d',1);
        $rel = $this->apiSign($param);
        if ($rel['code'] != 200) {
            return enjson($rel['code'],'签名验证失败');
        }
        $condition[] = ['member_miniapp_id','=',$this->miniapp_id];
        $condition[] = ['uid','=',$this->user->id];
        switch ($param['type']){
            case 1:
                $condition[] = ['is_end','=',0];
                $condition[] = ['types','=',0];
                break;
            case 2:
                $condition[] = ['types','=',1];
                $condition[] = ['money','=',0];
                break;
            case 3:
                $condition[] = ['is_end','=',1];
                $condition[] = ['money','=',0];
            default;
                $condition[] = ['is_end','=',0];
                break;
        }
        $coupon = SmartbcCouponUser::with(['store' => function($query) {
            $query->field('id,name,img');
        }])->where($condition)->order('create_time desc')->page($param['page'],10)->select();
        if ($coupon->isEmpty()) {
            return enjson(204);
        }
        foreach ($coupon as $key => $info){
            $coupon[$key]->end_time = $info->create_time + $this->config->end_time * 60 * 60;
        }
        return enjson(200,$coupon);
    }
    
    /**
     * 根据定位推荐附近同圈子的优惠券
     * @return void
     */
    public function couponTop(){
        $param['store_id']  = $this->request->param('store_id/d',0);   //来自哪个商家
        $rel = $this->apiSign($param);
        if ($rel['code'] != 200) {
            return enjson($rel['code'],'签名验证失败');
        }
        $store = SmartbcStore::where(['member_miniapp_id' => $this->miniapp_id,'id' => $param['store_id'],'is_lock' => 0])->find();
        if(empty($store)){
            return enjson(204);
        }
        if(empty($this->qqgps['lat']) || empty($this->qqgps['lng'])){
            return enjson(204);
        }
        $prefix = config('database.prefix');
        $latitude  = $this->qqgps['lat'];
        $longitude = $this->qqgps['lng'];
        $sql = 'select id,img,name from '.$prefix.'smartbc_store where latitude > '.$latitude .'-1 and latitude < '.$latitude .'+1 and longitude > '.$longitude.'-1 and longitude < '.
            $longitude.'+1 %s and id != '.$param['store_id'].' order by ACOS(SIN(('.$latitude .' * 3.1415) / 180 ) *SIN((latitude * 3.1415) / 180 ) +COS(('.$latitude .
            ' * 3.1415) / 180 ) * COS((latitude * 3.1415) / 180 ) *COS(('.$longitude.'* 3.1415) / 180 - (longitude * 3.1415) / 180 ) ) * 6380 asc limit 20';
        $ex = 'and id in(select store_id from  '.$prefix.'smartbc_store_union where group_id in (select group_id from '.$prefix.'smartbc_store_union where member_miniapp_id = '.$this->miniapp_id.' and store_id = '.$param['store_id'].
            ' and type = 0 )  and type = 0 )';
        $unionList = Db::query(sprintf($sql,$ex)); //附近商圏店铺查询
        if(count($unionList) == 0){
            $ex = 'and cate_id = '. $store->cate_id;
            $unionList = Db::query(sprintf($sql,$ex));   //附近同行业店铺查询
        }
        if(count($unionList) == 0){
            $unionList = Db::query(sprintf($sql,''));  //附近店铺查询
        }
        $store = [];
        foreach($unionList as $key => $val){ 
            $store[$val['id']] = $val;
        } 
        $store_ids =  implode(',',array_column($unionList,'id'));
        $list = Db::query('SELECT * FROM '.$prefix.'smartbc_coupon WHERE id >= (SELECT floor( RAND() * ((SELECT MAX(id) FROM '.$prefix.'smartbc_coupon)-(SELECT MIN(id) FROM '.$prefix.'smartbc_coupon)) + (SELECT MIN(id) FROM '.$prefix.'smartbc_coupon))) and member_miniapp_id = '.
            $this->miniapp_id.' and is_lock = 0 and is_end = 0 and store_id in ('.$store_ids.') ORDER BY id LIMIT 15;');
        if (count($list)) {
            return enjson(200,'success',['coupon' => $list,'store' => $store]);
        }
        return enjson(204);
    }


    //如果要切换优惠券,可以选择的列表
    public function couponSelect(){
        $param['store_id']  = $this->request->param('store_id/d', 0);
        $rel = $this->apiSign($param);
        if ($rel['code'] != 200) {
            return enjson($rel['code'],'签名验证失败');
        }
        $list =  SmartbcCoupon::where(['member_miniapp_id' => $this->miniapp_id,'store_id' => $param['store_id'],'is_lock' => 0,'is_end' => 0])->order('is_top desc,sort desc,create_time desc')->paginate(20);
        if ($list->isEmpty()) {
            return enjson(204,'error');
        }
        return enjson(200,'success',$list);
    }

    //用户到店更换优惠券
    public function couponSwitch(){
        $param['id']        = $this->request->param('id');  //用户优惠券id  SmartbcCouponUser
        $param['coupon_id'] = $this->request->param('coupon_id');  //要切换的优惠券id
        $rel                = $this->apiSign($param);
        if ($rel['code'] != 200) {
            return enjson($rel['code'], '签名验证失败');
        }
        $info    = SmartbcCouponUser::where(['member_miniapp_id' => $this->miniapp_id, 'id' => $param['id'], 'is_end' => 0])->find();
        $newInfo = SmartbcCoupon::where(['member_miniapp_id' => $this->miniapp_id, 'id' => $param['coupon_id'], 'is_end' => 0,'is_lock' => 0])->find();
        if (!empty($info) && !empty($newInfo) && $info->store_id == $newInfo->store_id) {
            $data['member_miniapp_id'] = $this->miniapp_id;
            $data['store_id']          = $newInfo->store_id;
            $data['coupon_id']         = $newInfo->id;
            $data['uid']               = $this->user->id;
            $data['is_end']            = 0;
            $data['types']             = $newInfo->types;
            $data['name']              = $newInfo->name;
            $data['price']             = $newInfo->price;
            $data['discount']          = $newInfo->discount;
            $data['howmuch']           = $newInfo->howmuch;
            $data['tips']              = $newInfo->tips;
            $data['update_time']       = $info->create_time;
            $data['create_time']       = $info->create_time;
            $code                      = SmartbcCouponUser::create($data);
            if ($code) {
                $info->is_end = 1;
                $info->save();
                return enjson(200, 'success');
            }
            return enjson(204, 'error');
        }
        return enjson(204, 'error');
    }

    /**
     * 以下商家管理
     * ##########################################
     * @return void
     * 添加和修改优惠券
     */
    public function edit(){
        $param['id']        = $this->request->param('id');
        $param['types']     = $this->request->param('types/d',0);
        $param['price']     = $this->request->param('price/d',0);
        $param['amount']    = $this->request->param('amount/d',0);
        $param['discount']  = $this->request->param('discount/s',0);
        $param['howmuch']   = $this->request->param('howmuch/d',0);
        $param['name']      = $this->request->param('name/s');
        $param['tips']      = $this->request->param('tips/s');
        $rel = $this->apiSign($param);
        if ($rel['code'] != 200) {
            return enjson($rel['code'],'签名验证失败');
        }
        $validate = $this->validate($param,'Coupon.edit');
        if(true !== $validate){
            return enjson(403,$validate);
        }
        $store = SmartbcStore::manageStore($this->user->id);
        if(!$store){
            return enjson(404,'无法找到该商家');
        }
        switch ($param['types']) {
            case 1:
                $param['price']  = 0;
                $param['amount'] = 0;
                break;
            case 2:
                $param['price']    = 0;
                $param['discount'] = 0;
                break;
            default:
                $param['discount'] = 0;
                $param['amount']  = 0;
                break;
        }
        $param['is_top']  = 0;
        $coupon = new SmartbcCoupon();
        if($param['id']){
            $info = $coupon->where(['member_miniapp_id' => $this->miniapp_id,'id' => $param['id']])->find();
            if(!$info){
                return enjson(403,'未找到要修改的优惠券');
            }
            if($info->is_super){
                return enjson(403,'超级券禁止修改');
            }
            if($info->is_lock){
                return enjson(403,'锁定的券禁止修改');
            }
            $result = $coupon->allowField(true)->save($param,['id' => $param['id']]);
        }else{
            $param['member_miniapp_id'] = $this->miniapp_id;
            $param['store_id']          = $store->id;
            $param['create_time']       = time();
            $param['update_time']       = time();
            $result                     = $coupon->create($param);
        }
        return enjson(200,'优惠券设置成功');
    }

    /**
     * 指定商家的优惠券(管理员)
     * @return void
     */
    public function storeCoupon(){
        $rel = $this->apiSign();
        if ($rel['code'] != 200) {
            return enjson($rel['code'],'签名验证失败');
        }
        //判断是修改还是创建
        $store = SmartbcStore::manageStore($this->user->id);
        if(empty($store)){
            return enjson(404,'你不是商家');
        }
        $coupon = SmartbcCoupon::where(['member_miniapp_id' => $this->miniapp_id,'store_id' => $store->id,'is_end' => 0])->order('is_top desc,sort desc,create_time desc')->select();
        if ($coupon->isEmpty()) {
            return enjson(204);
        }
        return enjson(200,$coupon);
    }

    
    /**
     * 显示单个优惠券信息
     * @return void
     */
    public function storeCouponInfo(){
        $param['id']        = $this->request->param('id');  //优惠券id
        $rel = $this->apiSign($param);
        if ($rel['code'] != 200) {
            return enjson($rel['code'],'签名验证失败');
        }
        //判断是修改还是创建
        $store = SmartbcStore::manageStore($this->user->id);
        if(empty($store)){
            return enjson(404,'你不是商家');
        }
        $info = SmartbcCoupon::where(['member_miniapp_id' => $this->miniapp_id,'id' => $param['id'],'store_id' => $store->id])->find();
        if (empty($info)) {
            return enjson(404,'未找到优惠券');
        }
        $count = SmartbcCouponUser::where(['coupon_id' => $info->id])->count(); //已领取
        $order = SmartbcCouponUser::where(['coupon_id' => $info->id,'is_end' => 0,'money' => 0])->count();  //待使用
        $money = SmartbcCouponUser::where(['coupon_id' => $info->id,'is_end' => 1])->sum('money');  //共优惠
        return enjson(200,['coupon' => $info,'count' => $count,'order' => $order,'money' => $money]);
    }

     //商户删除优惠券
    public function storeCouponDel(){
        $param['id'] = $this->request->param('id/d',0);
        $rel = $this->apiSign($param);
        if ($rel['code'] != 200) {
            return enjson($rel['code'],'签名验证失败');
        }
        //判断是修改还是创建
        $store = SmartbcStore::manageStore($this->user->id);
        if(empty($store)){
            return enjson(404,'你不是商家');
        }
        $coupon = SmartbcCoupon::where(['member_miniapp_id' => $this->miniapp_id,'store_id' => $store->id,'id' => $param['id'],'is_lock' => 0,'is_super' => 0,'is_end' => 0])->find();
        if (empty($coupon)) {
            return enjson(404,'当前优惠券禁止删除');
        }
        $coupon->is_end = 1;
        $coupon->save();
        return enjson(200,'成功删除优惠券');
    }
}