<?php
namespace app\common\command;

use think\facade\Db;
use think\facade\Log;
use think\console\Input;
use think\console\Output;
use think\console\Command;
use app\common\enum\WorkEnum;
use app\common\enum\RefundEnum;
use app\common\logic\RefundLogic;
use app\common\model\equity\UserEquity;
use app\common\model\equity\EquityConfig;
use app\common\model\recharge\OrderGoods;
use app\common\model\refund\RefundRecord;
use app\common\model\equity\UserEquityLog;
use app\common\model\works\GroupServiceWork;
use app\common\model\group_activity\GroupUserOrder;
use app\common\model\group_activity\GroupOrder as GroupOrderModel;

/*
** 拼团订单，活动结束，校验是否拼团成功， 如果成功，则给用户发放权益卡，失败批量退款
*/
class GroupOrder extends Command
{
    protected function configure()
    {
        $this->setName('group_order')
            ->setDescription('拼团结束，发放权益卡或批量退款');
    }

    protected function execute(Input $input, Output $output)
    {
        //更新拼团结束的订单状态
        $this->updateGroupOrder();

        //生成拼团工单
        $this->createGroupServiceWork();

    }

    /**
     * 生成拼团工单
     */
    public function createGroupServiceWork()
    {
        $list = GroupOrderModel::where(['status' => 1, 'work_status' => 1])->limit(100)->column('id');
        foreach($list as $group_order_id) {
            $goods = [];
            $category = GroupOrderModel::alias('a')
                        ->leftJoin('group_activity_category b','a.group_category_id=b.id')
                        ->leftJoin('group_activity c','a.group_activity_id=c.id')
                        ->where('a.id', $group_order_id)
                        ->field('b.service_time,c.price,c.work_amount,c.settlement_amount')
                        ->findOrEmpty()
                        ->toArray(); 
            try {
                //查询拼团用户订单
                $userOrder = GroupUserOrder::alias('a')
                            ->leftJoin('user b','a.user_id=b.id')
                            ->where('group_order_id', $group_order_id)
                            ->where('pay_status', 1)
                            ->where('refund_status', 0)
                            ->field('a.*,b.mobile')
                            ->select()
                            ->toArray();
                        
                if (empty($userOrder)) {
                    return true;
                }

                Db::startTrans();
                foreach ($userOrder as $k => $item) {
                    if (empty($goods)) {
                        $goods = UserEquity::alias('a')->leftJoin('goods b','a.goods_id=b.id')
                            ->where('a.id', $item['user_equity_id'])
                            ->field('a.number,a.goods_id,b.*')
                            ->findOrEmpty()
                            ->toArray();
                    }
                    //生成拼团服务工单
                    $work_data = [
                        'work_sn' => generate_sn(GroupServiceWork::class, 'work_sn'),
                        'real_name' => '',
                        'mobile' => $item['mobile'],
                        'address' => $item['area'].$item['address'],
                        'title' => $goods['goods_name']."*".$item['num'],
                        'category_type' => $goods['category_type'],
                        'goods_category_ids' => $goods['goods_category_ids'],
                        'goods_category_id' => $goods['goods_category_id'],
                        'work_pay_status'=>WorkEnum::IS_PAY_STATUS,
                        'appointment_time' => $category['service_time'],
                        'user_id'=>$item['user_id'],
                        'user_equity_id'=>0,
                        'third_type'=>1,
                        'remark' => '拼团用户订单：'.$item['id'],
                        'user_equity_id' => $item['user_equity_id'],
                        'group_order_id' => $group_order_id,
                        'group_user_order_id' => $item['id'],
                        'work_total'=>$item['paid_amount'],
                        'work_amount' => bcmul($category['work_amount'], $item['num'], 2),
                        'settlement_amount' => bcmul($category['settlement_amount'], $item['num'], 2),
                        'work_pay_status' => 2,
                    ];
                    
                    $service_work = GroupServiceWork::create($work_data);

                    //生成订单服务详情
                    OrderGoods::create([
                        'sn' => $service_work['work_sn'],
                        'goods_id' => $goods['goods_id'],
                        'category_type' => $goods['category_type'],
                        'goods_category_ids' => $goods['goods_category_ids'],
                        'goods_category_id' => $goods['goods_category_id'],
                        'goods_name' => $goods['goods_name'],
                        'goods_image' => $goods['goods_image'],
                        'goods_video' => $goods['goods_video'],
                        'goods_number' => $goods['goods_number'],
                        'good_unit' => $goods['good_unit'],
                        'goods_size' => $goods['goods_size'],
                        'goods_type' => $goods['goods_type'],
                        'goods_brand' => $goods['goods_brand'],
                        'install_guide' => $goods['install_guide'],
                        'goods_payment_type'=>$goods['goods_payment_type'],
                        'base_service_fee' => $goods['base_service_fee'],
                        'service_total' => $goods['service_total'],
                        'service_fee' => $goods['service_fee'],
                        'service_image' => $goods['service_image'],
                        'warranty_period'=>$goods['warranty_period'],
                        'fee_schedule' => $goods['fee_schedule'],
                        'goods_status' => $goods['goods_status'],
                    ]);
                    
                    //更新用户的权益卡剩余次数
                    UserEquity::where('id', $item['user_equity_id'])->update(['number' => 0, 'update_time' => time()]);

                    //记录用户的权益卡使用记录
                    UserEquityLog::create([
                        'user_id' => $item['user_id'],
                        'number' => $goods['number'],
                        'user_equity_id' => $item['user_equity_id'],
                        'create_time' => time(),
                    ]);
                }

                GroupOrderModel::where('id', $group_order_id)->update(['work_status' => 2]);
                Db::commit();
            
                return true;
            } catch (\Exception $e) {
                Db::rollback();
                Log::write("拼团订单批量生成服务工单异常:".$e->getMessage());
                return false;
            }
        }
        
    }

    /**
     * 更新拼团结束的订单状态
     */
    protected function updateGroupOrder()
    {
        $last_id = 0;
        while($last_id >= 0) {
            $list = GroupOrderModel::alias('a')
                        ->leftJoin('group_activity_category b','a.group_category_id=b.id')
                        ->where('a.status',0)
                        ->where('a.end_time','<',time())
                        ->where('a.id','>',$last_id)
                        ->field('a.id,a.num,a.equity_id,b.participant_num,b.is_simulate_form,b.simulate_num')
                        ->order('a.id','asc')
                        ->limit(30)
                        ->select()->toArray();
                        
            if (!$list) {
                $last_id = -1;
                break;
            }
            foreach($list as $item) {
                $last_id = $item['id'];

                $orderList = GroupUserOrder::where([
                    'group_order_id' => $item['id'],
                    'pay_status' => 1,
                    'status' => 1,
                    'refund_status' => 0,
                ])
                ->field('id,user_id,sn,remark,num,order_amount,pay_way,transaction_id,order_terminal')->order('id','asc')->select()->toArray();
                //拼团总数量
                $total = GroupUserOrder::where([
                            'group_order_id' => $item['id'],
                            'pay_status' => 1,
                            'status' => 1,
                            'refund_status' => 0,
                        ])->sum('num');
                if (($item['is_simulate_form'] == 1 && $total >= $item['simulate_num']) || ($item['is_simulate_form'] == 0 && $total >= $item['participant_num'])) {
                    //模拟成团
                    $this->gruopSuccess($item,$orderList,$total);
                } else {
                    //拼团失败
                    $this->groupFail($item,$orderList,$total);
                }
            }
        }
        
    }

    /**
     * 拼团成功(给已支付的用户发放权益卡)
     * @param $item
     */
    protected function gruopSuccess($order,$orderList,$total)
    {
        $max_id = UserEquity::max('id');
        try {
            Db::startTrans();
            $equityConfig = EquityConfig::where('id',$order['equity_id'])->findOrEmpty()->toArray();
            foreach($orderList as $item) {
                //用户发放权益卡
                $max_id++;
                //创建用户权益卡
                $userEquity = UserEquity::create([
                    'user_id' => $item['user_id'],
                    'equity_id' => $order['equity_id'],
                    'goods_id' => $equityConfig['goods_id'],
                    'number' => $item['num'],//拼团购买数量
                    'create_time' => time(),
                    'end_time' => time() + $equityConfig['day_num'] * 86400,
                    'remark' => '拼团单id：'.$item['id'],
                    'code' => generateRandomString((8-strlen($max_id)),2).$max_id,
                ]);
                //更新用户拼团订单
                GroupUserOrder::where('id',$item['id'])->update(['user_equity_id' => $userEquity->id]);
            }

            //更新拼团订单
            GroupOrderModel::where('id',$order['id'])->update([
                'status' => 1,
                'num' => $total
            ]);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('拼团失败，批量退款失败：'.$e->getMessage());
        }
    }

    
    /*
     * 批量退款，关闭订单
     * @param $item
    */
    protected function groupFail($order,$list,$total)
    {
        try {
            Db::startTrans();
            foreach($list as $item) {
                $remark = $item['remark'] ?? '';

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

                // 退款
                $result = RefundLogic::refund($item, $record['id'], $item['order_amount'], 1);
                
                if ($result !== true) {
                    //退款失败
                    $remark .= RefundLogic::getError();
                    GroupUserOrder::where('id',$item['id'])->update(['remark' => $remark]);
                } else {
                    //退款成功
                    GroupUserOrder::where('id',$item['id'])->update(['status' => 2,'refund_status' => 2]);
                }

            }

            //更新拼团订单
            GroupOrderModel::where('id',$order['id'])->update([
                'status' => 2,
                'num' => $total
            ]);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('拼团失败，批量退款失败：'.$e->getMessage());
        }
    }

}