<?php
namespace app\api\logic;

use think\Exception;
use think\facade\Db;
use think\facade\Log;
use app\common\enum\RefundEnum;
use app\common\logic\BaseLogic;
use app\common\logic\RefundLogic;
use app\common\model\equity\UserEquity;
use app\common\model\equity\EquityConfig;
use app\common\model\refund\RefundRecord;
use app\common\model\equity\UserEquityLog;
use app\common\model\group_activity\GroupOrder;
use app\common\service\wechat\WeChatMnpService;
use app\common\model\group_activity\GroupActivity;
use app\common\model\group_activity\GroupUserOrder;


/**
 * 拼团活动逻辑处理
 * Class GroupActivityLogic
 * @package app\api\logic
 */
class GroupActivityLogic extends BaseLogic
{

    /**
     * 活动分类数据
     */
    public static function categoryList($id,$block_key = ''){
        
        return GroupActivity::getActivityList($id,$block_key);
        
    }

    /**
     * @notes 拼团活动详情
     * @param $id 拼团活动ID
     */
    public static function detail($id,$userId){
        $detail = GroupActivity::getDetail($id);

        if(!empty($detail)){
            $detail['timestamp'] = time();
            $detail['goods'] = self::getEquityGoods($detail['equity_id']);
            //查询用户是否已有付款订单
            $detail['order'] = GroupUserOrder::with('group_order')->where(['user_id'=>$userId,'group_activity_id'=>$id,'pay_status'=>1])->where('refund_status','<>',1)->field('id,status,num,pay_way,pay_time,pay_status,remark,create_time,group_order_id')->findOrEmpty()->toArray();
        }

        return $detail;
    }

    /**
     * 获取权益卡的商品信息
     */
    private static function getEquityGoods($equity_id){
        return EquityConfig::alias('a')->leftJoin('goods b','a.goods_id=b.id')
                        ->where('a.id',$equity_id)
                        ->field('a.id,a.equity_name,a.number,a.day_num,a.goods_id,b.service_image,b.goods_category_id')
                        ->findOrEmpty()
                        ->toArray();
    }

    /**
     * @notes 拼团订单详情
     */
    public static function orderDetail($order_id,$user_id,$url){
        
        $detail = GroupOrder::where(['id'=>$order_id])->findOrEmpty()->toArray();
        if(!empty($detail)){
            $detail['activity'] = GroupActivity::getDetail($detail['group_activity_id']);
            $detail['activity']['goods'] = self::getEquityGoods($detail['equity_id']); 
            $detail['is_paid'] = 0;
            $detail['order_id'] = 0;

            $detail['users'] = GroupUserOrder::alias('a')
                                ->leftJoin('user b','a.user_id=b.id')
                                ->where(['a.group_order_id'=>$order_id,'a.status'=>1])
                                ->field(['a.id','a.user_id','a.status','a.num','a.create_time','b.avatar','b.nickname'])
                                ->order('a.create_time','asc')
                                ->select()
                                ->toArray();
            foreach($detail['users'] as &$item){
                if (strpos($item['avatar'], 'http') === false && !empty($item['avatar'])) {
                    $item['avatar'] = config('custom.cdn_url').$item['avatar'];
                }
                if ($item['user_id'] == $user_id) {
                    $detail['is_paid'] = 1;
                    $detail['order_id'] = $item['id'];
                }
            }
            //如果开启了模拟成团，成团后，自动填补剩余人数
            if ($detail['status'] == 1 && $detail['num'] < $detail['activity']['participant_num']) {
                $num = $detail['activity']['participant_num'][0] - $detail['num'];
                $robot = self::getRobot($num,$url);
                $detail['users'] = array_merge($detail['users'],$robot);
                $detail['num'] = (int)$detail['activity']['participant_num'][0];
            }
            $detail['timestamp'] = time();
        }
        return $detail;
    }

    //模拟用户
    private static function getRobot($num,$url){

        $nicknames = ["草莓啵啵熊","甜心小奶喵","清风吟月","浅梦逸云","静听花落","星辰浅语","云卷云舒间","花影舞流年","月色如水柔","暖阳","星辰","云舒","悠然","素心","晚晴","素心","清风","月白","静雅","不羁的灵魂","独行侠逸风","叛逆的旋律","冷傲冰爵","烈焰狂歌者","酷玩潮咖","神秘暗影侠","朋克精灵","暴走的音符","个性涂鸦师","墨染书香","青衫烟雨客","素笺淡墨痕","简逸","微光","清风","浅笑","逸梦","逸尘","浅念","澜影","默言","素笺","心屿","墨染","弦音","竹影","浅酌","暮雪","星辰","雨薇","凝霜","云岫","流萤","晨曦","浅夏","诗韵","逸云","浅唱"];
        shuffle($nicknames);
        $users = [];
        $num = $num > 10 ? 10 : $num;
        for ($i=0; $i < $num; $i++) {
            $users[] = [
                'id' => 0,
                'user_id' => 0,
                'status' => 1,
                'avatar' => 'https://cdnweixiu.kyjlkj.com/resource/image/adminapi/default/default_avatar.png',
                'nickname' => $nicknames[$i],
            ];
        }
        return $users;
    }

    /**
     * @notes 用户订单详情
     */
    public static function userOrderDetail($order_id,$userId){
        $detail = GroupUserOrder::with('groupOrder')->where(['id'=>$order_id, 'user_id' => $userId])->field('id,mobile,sn,status,num,pay_way,pay_time,pay_status,refund_status,remark,create_time,group_order_id,group_activity_id,user_equity_id,area,address')->findOrEmpty()->toArray();
        if ($detail) {
            $detail['is_refund'] = 0;
            if ($detail['pay_status'] == 1 && $detail['refund_status'] == 0) {
                if ($detail['user_equity_id'] > 0) {
                    $detail['is_refund'] = UserEquityLog::where('user_equity_id', $detail['user_equity_id'])->count() > 0 ? 0 : 1;
                } else {
                    $detail['is_refund'] = 1;
                }
            }
            $detail['activity'] = GroupActivity::getDetail($detail['group_activity_id']);
            $detail['activity']['goods'] = self::getEquityGoods($detail['groupOrder']['equity_id']); 
            $detail['timestamp'] = time();
        }
        return $detail;
    }

    /**
     * 提交订单
     * @param array $params
     * @return array|false
     */
    public static function submitOrder($params)
    {
        Db::startTrans();
        try {
            $userOrder = GroupUserOrder::where(['group_activity_id' => $params['group_activity_id'], 'user_id' => $params['user_id'],'refund_status' => 0])->where("pay_status","<>",1)->findOrEmpty()->toArray();
            if ($userOrder && $userOrder['pay_status'] == 1) {
                throw new Exception('您已参加过该活动！');
            }

            $activity = GroupActivity::getDetail($params['group_activity_id']); //活动详情
            if (!$activity) {
                throw new Exception('拼团活动不存在！'); //拼团活动不存在
            }
            //校验活动时间
            if (time() < strtotime($activity['start_time'])) {
                throw new Exception('拼团活动未开始！'); //拼团活动未开始
            }
            if (time() > $activity['end_time']) {
                throw new Exception('拼团活动已结束！'); //拼团活动已结束
            }
            //限制数量最大值：5
            $num = isset($params['num']) && $params['num'] > 0 ? $params['num'] : 1;
            if ($num > 5) {
                throw new Exception('下单数量不能超过5个！'); 
            }
            $order_amount = $activity['price'][0];
            
            //加入已开的拼团单
            $groupOrder = GroupOrder::where(['group_activity_id' => $params['group_activity_id'], 'status' => 0])->where('num','<',100)->findOrEmpty()->toArray();
            if (empty($groupOrder)) {
                //生成拼团单
                $data = [
                    'sn' => generate_sn(GroupOrder::class, 'sn'),
                    'group_category_id' => $activity['group_category_id'],
                    'group_activity_id' => $params['group_activity_id'],
                    'property_head_id' => $activity['property_head_id'],
                    'equity_id' => $activity['equity_id'],
                    'goods_id' => EquityConfig::where('id', $activity['equity_id'])->value('goods_id'),
                    'user_id' => $params['user_id'],
                    'origin_price' => $activity['origin_price'],
                    'price' => $order_amount,
                    'create_time' => time(),
                    'end_time'   => $activity['end_time'] //time() + $activity['form_time_limit'] * 60 * 60,
                ];
                $groupOrder = GroupOrder::create($data);
            }

            //生成用户拼单订单
            $data = [
                'sn' => generate_sn(groupUserOrder::class, 'sn'),
                'mobile' => $params['mobile'],
                'group_order_id' => $groupOrder['id'],
                'group_activity_id' => $params['group_activity_id'],
                'user_id' => $params['user_id'],
                'area'  => $params['area'],
                'address' => $params['address'],
                'remark' => isset($params['remark']) ? $params['remark'] : '',
                'order_amount' => bcmul($order_amount,$num,2),
                'num' => $num,
                'order_terminal' => $params['terminal'],
            ];
            if ($userOrder) {
                $data['create_time'] = time();
                $data['update_time'] = $data['delete_time'] = null;
                GroupUserOrder::where('id',$userOrder['id'])->update($data); 
            } else {
                $userOrder = GroupUserOrder::create($data);    
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }

        return [
            'order_id' => (int)$userOrder['id'],
            'sn' => $groupOrder['sn'],
            'id' => (int)$groupOrder['id'],
        ];
    }

    /**
     * 取消订单
     * @param $params
     * @return false|void
     */
    public static function cancelOrder($params)
    {
        Db::startTrans();
        try {
            $detail =  GroupUserOrder::where([
                    'user_id' => $params['user_id'],
                    'id'=>$params['order_id']
                ])->field('id,status')->findOrEmpty()->toArray();
            if(empty($detail)){
                throw new Exception('订单不存在');
            }
            if($detail['status'] == 1){
                throw new Exception('已支付订单不支持取消');
            }
            if($detail['status'] != 0){
                throw new Exception('当前订单不支持取消');
            }

            //将用户订单状态更新为已取消
            GroupUserOrder::where('id',$detail['id'])->update(['status' => 3, 'pay_status' => 2]);
            
            Db::commit();
            return true;
        }
        catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    /**
     * 订单退款
     * @param $params
     * @return false|void
     */
    public static function refundOrder($params)
    {
        Db::startTrans();
        try {
            $order =  GroupUserOrder::where([
                    'user_id' => $params['user_id'],
                    'id'=>$params['order_id']
                ])->field('id,group_order_id,sn,status,num,paid_amount,order_amount,pay_status,pay_way,user_equity_id,user_id,order_terminal,transaction_id')->findOrEmpty()->toArray();
            if(empty($order)){
                throw new Exception('订单不存在');
            }
            if($order['status'] != 1 || $order['pay_status'] != 1){
                throw new Exception('当前订单不支持退款');
            }
            if ($order['user_equity_id']) {
                //判断权益卡是否已使用
                $used = UserEquityLog::where(['user_equity_id' => $order['user_equity_id'],'user_id' => $params['user_id']])->count();
                if ($used) {
                    throw new Exception('当前权益卡已使用，不支持退款');
                }
                //删除用户权益卡
                $userEquity = UserEquity::where(['id' => $order['user_equity_id'],'user_id' => $params['user_id']])->findOrEmpty();
                $userEquity->delete();
            }

            //将用户订单状态更新为申请退款
            GroupUserOrder::where('id',$order['id'])->update(['status' => 2,'refund_status' => 1]);

            //更新拼团订单
            GroupOrder::where('id',$order['group_order_id'])->update([
                'num' => Db::raw('num-'.$order['num']),
            ]);

            // 生成退款记录
            $recordSn = generate_sn(RefundRecord::class, 'sn');
            $record = RefundRecord::create([
                'sn' => $recordSn,
                'user_id' => $order['user_id'],
                'order_id' => $order['id'],
                'order_sn' => $order['sn'],
                'order_type' => RefundEnum::ORDER_TYPE_GROUP,
                'order_amount' => $order['paid_amount'],
                'refund_amount' => $order['paid_amount'],
                'refund_type' => RefundEnum::TYPE_ADMIN,
                'transaction_id' => $order['transaction_id'] ?? '',
                'refund_way' => RefundEnum::getRefundWayByPayWay($order['pay_way']),
            ]);

            // 退款
            $result = RefundLogic::refund($order, $record['id'], $order['paid_amount'], 1);
            
            $flag = true;
            $resultMsg = '退款成功';
            if ($result !== true) {
                $flag = false;
                $resultMsg = RefundLogic::getError();
                Db::rollback();
            } else {
                Db::commit();
            }

            return [$flag, $resultMsg];
        }
        catch (\Exception $e) {
            Db::rollback();
            self::$error = $e->getMessage();
            Log::write("[拼团订单退款失败]:".$e->getMessage());
            return [false, $e->getMessage()];
        }
    }

    public static function deleteOrder($params):bool
    {
        try{
            $order =  GroupUserOrder::where([
                'user_id' => $params['user_id'],
                'id' => $params['order_id']
            ])->findOrEmpty();
            if($order->isEmpty()){
                throw new \Exception('订单不存在');
            }

            if($order['status'] == 1){
                throw new Exception('已支付订单不支持删除');
            }

            $order->delete();
            return true;
        } catch(\Exception $e){
            self::setError($e->getMessage());
            return false;
        }
    }

    /**
     * 获取拼团订单分享二维码
     * @return string|void
     */
    public static function getQRCode($params,$url)
    {
        try {
            $mnp_page = 'pages/web_view/group';
            
            $scene_page = 'team';
            $response = (new WeChatMnpService())->getUnlimitedQRCode(
                'page='.$scene_page.'&id='.$params['id'].'&oid='.$params['order_id']."&cid=".$params['category_id'],
                $mnp_page,
                env('miniprogram.mini_env_version', 'release'),
                false
            );
            $qrcode = $response->getContent();
            if(!is_dir('./uploads/wx_qrcode/'.date('Ymd'))){
                mkdir('./uploads/wx_qrcode/'.date('Ymd'));
            }
            $file_name = 'uploads/wx_qrcode/'.date('Ymd').'/'.time().rand(1000,9999).'.png';
            file_put_contents($file_name, $qrcode);
            return $url.'/'.$file_name;
        } catch (\Throwable $e) {
            Log::info('getQRCode:'.$e->getMessage());
            return '';
        }
    }
}