<?php

namespace app\models\store;

use app\models\routine\RoutineFormId;
use app\models\routine\RoutineTemplate;
use app\models\user\User;
use app\models\user\WechatUser;
use app\models\wechat\WechatTemplate;
use crmeb\basic\BaseModel;
use crmeb\services\WechatTemplateService;
use crmeb\services\MiniProgramService;
use crmeb\traits\ModelTrait;
use PDOStatement;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Log;
use think\facade\Route;

/**
 * TODO 助力Model
 * Class StoreAssistanceActive
 * @package app\models\store
 */
class StoreAssistanceActive extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

    /**
     * 模型名称
     * @var string
     */
    protected $name = 'store_assistance_active';

    use ModelTrait;

    public static function merSet($mer_id, $alias = '')
    {
        return $mer_id ? self::where($alias ? $alias . '.mer_id' : 'mer_id', $mer_id) : new self;
    }

    /*
     * 获取助力完成的用户
     * @param int $uid 用户id
     * @return array
     * */
    public static function getAssistanceOkList($uid)
    {
        $list = self::alias('a')->where('a.status', 2)->where('a.is_refund', 0)->where('a.uid', '<>', $uid)->join('User u', 'u.uid=a.uid', 'right')->column('nickname', 'id');
        $msg = [];
        foreach ($list as &$item) {
            $msg[] = $item .= '助力成功';
        }
        return $msg;
    }

    /*
     * 获取助力完成的商品总件数
     * */
    public static function getAssistanceOkSumTotalNum($id)
    {

        return self::where('status', 2)->where('is_refund', 0)->sum('total_num');
    }

    /**
     * 获取一条助力数据
     * @param $id
     * @param bool $mer_id
     * @return mixed
     */
    public static function getAssistanceUserOne($id, $mer_id = false)
    {
        $model = self::merSet($mer_id, 'p');
        $model = $model->alias('p');
        $model = $model->field('p.*,u.nickname,u.avatar');
        $model = $model->where('id', $id);
        $model = $model->join('user u', 'u.uid = p.uid');
        return $model->find();
    }

    /**
     * 获取助力的团员
     * @param $id
     * @return mixed
     */
    public static function getAssistanceMember($id)
    {
        $model = new self();
        $model = $model->alias('p');
        $model = $model->field('p.*,u.nickname,u.avatar');
        $model = $model->where('k_id', $id);
        $model = $model->where('is_refund', 0);
        $model = $model->join('user u', 'u.uid = p.uid');
        $model = $model->order('id asc');
        return $model->select();
    }

    /**
     * 设置结束时间
     * @param $idAll
     * @return $this
     */
    public static function setAssistanceStopTime($idAll)
    {
        $model = new self();
        $model = $model->where('id', 'IN', $idAll);
        return $model->update(['stop_time' => time(), 'status' => 2]);
    }

    /**
     * 获取正在助力的数据  发起人
     * @param int $cid 商品id
     * @param int $isAll 是否查找所有助力
     * @return array
     */
    public static function getAssistanceAll($cid, $isAll = false)
    {
        $model = new self();
        $model = $model->alias('p');
        $model = $model->field('p.id,p.uid,p.people,p.price,p.stop_time,u.nickname,u.avatar');
        $model = $model->where('stop_time', '>', time());
        $model = $model->where('p.status', 1);
        $model = $model->where('p.cid', $cid);
        $model = $model->where('p.k_id', 0);
        $model = $model->where('p.is_refund', 0);
        $model = $model->order('p.add_time desc');
        $model = $model->join('user u', 'u.uid = p.uid');
        $list = $model->select();
        $list = count($list) ? $list->toArray() : [];
        if ($isAll) {
            $assistanceAll = [];
            foreach ($list as &$v) {
                $v['count'] = self::getAssistancePeople($v['id'], $v['people']);
                $v['h'] = date('H', $v['stop_time']);
                $v['i'] = date('i', $v['stop_time']);
                $v['s'] = date('s', $v['stop_time']);
                $assistanceAll[] = $v['id'];//助力发起人ID
                $v['stop_time'] = (int)$v['stop_time'];
            }
            return [$list, $assistanceAll];
        }
        return $list;
    }

    /**
     * 获取还差几人
     */
    public static function getAssistancePeople($kid, $people)
    {
        $model = new self();
        $model = $model->where('k_id', $kid)->where('is_refund', 0);
        $count = $model->count();
        return bcsub($people, $count, 0);
    }

    /**
     * 判断是否发送模板消息 0 未发送 1已发送
     * @param $uidAll
     * @return int|string
     */
    public static function isTpl($uidAll, $pid)
    {
        if (is_array($uidAll))
            $count = self::where('uid', 'IN', implode(',', $uidAll))->where('is_tpl', 0)->where('id|k_id', $pid)->count();
        else
            $count = self::where('uid', $uidAll)->where('is_tpl', 0)->where('k_id|id', $pid)->count();
        return $count;
    }

    /**
     * 助力成功提示模板消息
     * @param $uidAll
     * @param $pid
     */
    public static function orderAssistanceAfter($uidAll, $pid)
    {
        $assistanceInfo = self::where('p.id|p.k_id', $pid)->alias('p')->field(['p.people', 't.title', 'p.add_time', 'p.order_id', 'u.nickname'])->join('user u', 'u.uid = p.uid')->join('store_assistance t', 'p.cid = t.id')->find();
        if (!$assistanceInfo) return false;
        foreach ($uidAll as $key => &$item) {
            $openid = WechatUser::uidToOpenid($item, 'openid');
            $routineOpenid = WechatUser::uidToOpenid($item, 'routine_openid');
            $nickname = WechatUser::uidToOpenid(self::where('id', $pid)->value('uid'), 'nickname');
            if ($openid) { //公众号模板消息
//                $firstWeChat = '亲，您的助力已经完成了';
                $keyword1WeChat = self::where('id|k_id', $pid)->where('uid', $item)->value('order_id');
                $keyword2WeChat = self::alias('p')->where('p.id|p.k_id', $pid)->where('p.uid', $item)->join('store_assistance c', 'c.id=p.cid')->value('c.title');
//                $remarkWeChat = '点击查看订单详情';
//                $urlWeChat = Route::buildUrl('order/detail/' . $keyword1WeChat)->suffix('')->domain(true)->build();
//                WechatTemplateService::sendTemplate($openid, WechatTemplateService::ORDER_USER_GROUPS_SUCCESS, [
//                    'first' => $firstWeChat,
//                    'keyword1' => $keyword1WeChat,
//                    'keyword2' => $keyword2WeChat,
//                    'remark' => $remarkWeChat
//                ], $urlWeChat);
                $wechatTemplate = new WechatTemplate();
                $wechatTemplate->sendOrderAssistanceUseSuccess($item, $keyword1WeChat, $keyword2WeChat, $pid);
            } else if ($routineOpenid) {// 小程序模板消息
                RoutineTemplate::sendAssistanceSuccess($item, $assistanceInfo['title'], $assistanceInfo['nickname'] ?? '', $assistanceInfo['add_time'], $assistanceInfo['people'], '/pages/order_details/index?order_id=' . $assistanceInfo['order_id']);
            }
        }
        self::beginTrans();
        $res1 = self::where('uid', 'IN', implode(',', $uidAll))->where('id|k_id', $pid)->update(['is_tpl' => 1]);
        self::checkTrans($res1);
    }

    /**
     * 助力失败发送的模板消息
     * @param $uid
     * @param $pid
     */
    public static function orderAssistanceAfterNo($uid, $pid, $fillTilt = '', $isRemove = false)
    {
        $store = self::alias('p')->where('p.id|p.k_id', $pid)->field('c.*')->where('p.uid', $uid)->join('store_assistance c', 'c.id=p.cid')->find();
        $assistance = self::where('id|k_id', $pid)->where('uid', $uid)->find();
        $openid = WechatUser::uidToOpenid($uid, 'openid');
        $routineOpenid = WechatUser::uidToOpenid($uid, 'routine_openid');
        $wechatTemplate = new WechatTemplate();
        if ($isRemove) {
            if ($openid) {//公众号发送模板消息
//                $urlWeChat = Route::buildUrl('order/detail/' . $assistance->order_id)->suffix('')->domain(true)->build();
//                WechatTemplateService::sendTemplate($openid, WechatTemplateService::ORDER_USER_GROUPS_LOSE, [
//                    'first' => '亲，您的助力取消',
//                    'keyword1' => $store->title,
//                    'keyword2' => $assistance->price,
//                    'keyword3' => $assistance->price,
//                    'remark' => '点击查看订单详情'
//                ], $urlWeChat);
                $wechatTemplate->sendOrderAssistanceClone($uid, $assistance, $store->title);
            } else if ($routineOpenid) {//小程序发送模板消息
                RoutineTemplate::sendAssistanceFail($uid, $store->title, $assistance->people, '亲，您的助力取消，点击查看订单详情', '/pages/order_details/index?order_id=' . $assistance->order_id);
            }
        } else {
            if ($openid) {//公众号发送模板消息
//                $urlWeChat = Route::buildUrl('order/detail/' . $assistance->order_id)->suffix('')->domain(true)->build();
//                WechatTemplateService::sendTemplate($openid, WechatTemplateService::ORDER_USER_GROUPS_LOSE, [
//                    'first' => '亲，您的助力失败',
//                    'keyword1' => $store->title,
//                    'keyword2' => $assistance->price,
//                    'keyword3' => $assistance->price,
//                    'remark' => '点击查看订单详情'
//                ], $urlWeChat);
                $wechatTemplate->sendOrderAssistanceClone($uid, $assistance, $store->title);
            } else if ($routineOpenid) {//小程序发送模板消息
                RoutineTemplate::sendAssistanceFail(
                    $uid,
                    $store->title,
                    $assistance->people,
                    '亲，您助力失败，自动为您申请退款，退款金额为：' . $assistance->price,
                    '/pages/order_details/index?order_id=' . $assistance->order_id
                );
            }
        }
        self::where('id', $pid)->update(['status' => 3, 'stop_time' => time()]);
        self::where('k_id', $pid)->update(['status' => 3, 'stop_time' => time()]);
    }

    /**
     * 获取当前助力数据返回订单编号
     * @param $id
     * @param $uid
     * @return array|false|PDOStatement|string|\think\Model
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getCurrentAssistance($id, $uid)
    {
        $assistance = self::where('id', $id)->where('uid', $uid)->find();
        if (!$assistance) $assistance = self::where('k_id', $id)->where('uid', $uid)->find();
        return StoreOrder::where('id', $assistance['order_id_key'])->value('order_id');
    }

    public static function systemPage($where)
    {
        $model = new self;
        $model = $model->alias('p');
        $model = $model->field('p.*,c.title,u.nickname,u.avatar');
        $model = self::getModelTime($where, $model, "p.add_time");
        if ($where['status']) $model = $model->where('p.status', $where['status']);
        if ($where['mer_id']) $model = $model->where('p.mer_id', $where['mer_id']);
        $model = $model->where('p.k_id', 0);
        $model = $model->order('p.id desc');
        $model = $model->join('StoreAssistance c', 'c.id=p.cid');
        $model = $model->join('user u', 'u.uid = p.uid');
        $count = $model->count();
        $list = $model->page((int)$where['page'], (int)$where['limit'])
            ->select()
            ->each(function ($item) {
                $item['count_people'] = self::where('k_id', $item['id'])->count();
            });
        return compact('count', 'list');
    }

    public static function isAssistanceBe($data, $id)
    {
        $data['id'] = $id;
        $count = self::where($data)->count();
        if ($count) return $count;
        $data['k_id'] = $id;
        $count = self::where($data)->count();
        if ($count) return $count;
        else return 0;
    }

    /**
     * 创建助力
     * @param $order
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function createAssistanceActive($order)
    {
        $order = StoreOrder::tidyOrder($order, true, false, $order['mer_id'])->toArray();
        $openid = WechatUser::uidToOpenid($order['uid'], 'openid');
        $routineOpenid = WechatUser::uidToOpenid($order['uid'], 'routine_openid');
        $product = StoreAssistance::where('id', $order['assistance_id'])->field('effective_time,title')->find();
        if ($product) {
            if (!$order['assistance_active_id']) {//助力不存在
                $res = false;
                $assistance['uid'] = $order['uid'];//用户id
                $assistance['order_id'] = $order['order_id'];//订单id  生成
                $assistance['order_id_key'] = $order['id'];//订单id  数据库id
                $assistance['total_num'] = $order['total_num'];//购买个数
                $assistance['total_price'] = $order['pay_price'];//总金额
                $assistance['k_id'] = 0;//助力id
                foreach ($order['cartInfo'] as $v) {
                    $assistance['cid'] = $v['assistance_id'];//助力商品id
                    $assistance['pid'] = $v['product_id'];//商品id
                    $assistance['people'] = StoreAssistance::where('id', $v['assistance_id'])->value('people');//几人助力
                    $assistance['price'] = $v['productInfo']['price'];//单价
                    $assistance['stop_time'] = bcadd(time(), bcmul($product->effective_time, 3600, 0), 0);//结束时间
                    $assistance['add_time'] = time();//开团时间
                    $assistance['mer_id'] = $order['mer_id'];//所属商户
                    $res1 = self::create($assistance)->toArray();
                    $res2 = StoreOrder::where('id', $order['id'])->update(['assistance_active_id' => $res1['id']]);
                    $res = $res1 && $res2;
                    $assistance['id'] = $res1['id'];
                }
                // 开团成功发送模板消息
                if ($openid && $order['is_channel'] != 1) { //公众号模板消息
//                    $urlWeChat = Route::buildUrl('/order/detail/' . $assistance['order_id'])->suffix('')->domain(true)->build();
//                    WechatTemplateService::sendTemplate($openid, WechatTemplateService::OPEN_PINK_SUCCESS, [
//                        'first' => '您好，您已成功开团！赶紧与小伙伴们分享吧！！！',
//                        'keyword1' => $product->title,
//                        'keyword2' => $assistance['total_price'],
//                        'keyword3' => $assistance['people'],
//                        'remark' => '点击查看订单详情'
//                    ], $urlWeChat);
                    $wechatTemplate = new WechatTemplate();
                    $wechatTemplate->sendOrderAssistanceUseSuccess($order['uid'], $assistance, $product->title);
                } else if ($routineOpenid && $order['is_channel'] == 1) {
                    $nickname = User::where('uid', $order['uid'])->value('nickname');
                    RoutineTemplate::sendAssistanceSuccess(
                        $order['uid'], $product->title,
                        $nickname,
                        $assistance['add_time'],
                        $assistance['people'],
                        '/pages/order_details/index?order_id=' . $assistance['order_id']
                    );
                }
                if ($res) return true;
                else return false;
            }
        } else {
            Log::error('助力支付成功读取商品数据失败订单号：' . $order['order_id']);
            return false;
        }
    }

    /**
     * 助力人数完成时，判断全部人都是未退款状态
     * @param $assistanceIds
     * @return bool
     */
    public static function setAssistanceStatus($assistanceIds)
    {
        $orderAssistance = self::where('id', 'IN', $assistanceIds)->where('is_refund', 1)->count();
        if (!$orderAssistance) return true;
        else return false;
    }

    /*
    *  助力完成更改数据写入内容
    * @param array $uidAll 当前助力uid
    * @param array $idAll 当前助力assistance_active_id
    * @param array $assistanceT 团长信息
    * @return int
    * */
    public static function AssistanceComplete($uidAll, $idAll, $uid, $assistanceT)
    {
        $assistanceBool = 6;
        try {
            if (self::setAssistanceStatus($idAll)) {
                self::setAssistanceStopTime($idAll);
                if (in_array($uid, $uidAll)) {
                    if (self::isTpl($uidAll, $assistanceT['id'])) self::orderAssistanceAfter($uidAll, $assistanceT['id']);
                    $assistanceBool = 1;
                } else  $assistanceBool = 3;
            }
            return $assistanceBool;
        } catch (\Exception $e) {
            self::setErrorInfo($e->getMessage());
            return $assistanceBool;
        }
    }

    /**
     * 更改助力订单状态
     */
    public static function changeAssistanceActiveStatus($uidAll, $idAll, $uid, $assistanceT)
    {
        if (self::setAssistanceStatus($idAll)) {
            self::setAssistanceStopTime($idAll);
        }
    }

    /*
     * 助力失败 退款
     * @param array $assistanceAll 助力数据,不包括团长
     * @param array $assistanceT 团长数据
     * @param int $assistanceBool
     * @param boolen $isRunErr 是否返回错误信息
     * @param boolen $isIds 是否返回记录所有助力id
     * @return int| boolen
     * */
    public static function AssistanceFail($assistanceAll, $assistanceT, $assistanceBool, $isRunErr = true, $isIds = false)
    {
        self::startTrans();
        $assistanceIds = [];
        try {
            if ($assistanceT['stop_time'] < time()) {//助力时间超时  退款
                $assistanceBool = -1;
                array_push($assistanceAll, $assistanceT);
                foreach ($assistanceAll as $v) {
                    if (StoreOrder::orderApplyRefund(StoreOrder::getAssistanceOrderId($v['order_id_key']), $v['uid'], '助力时间超时') && self::isTpl($v['uid'], $assistanceT['id'])) {
                        if ($isIds) array_push($assistanceIds, $v['id']);
                        self::orderAssistanceAfterNo($assistanceT['uid'], $assistanceT['id']);
                    } else {
                        if ($isRunErr) return $assistanceBool;
                    }
                }
            }
            self::commit();
            if ($isIds) return $assistanceIds;
            return $assistanceBool;
        } catch (\Exception $e) {
            self::rollback();
            return $assistanceBool;
        }
    }

    /*
     * 获取助力人和发起人和助力总人数
     * @param array $assistanceActive
     * @return array
     * */
    public static function getAssistanceMemberAndAssistanceK($assistanceActive)
    {
        //查找助力团员和团长
        if ($assistanceActive['k_id']) {
            $assistanceAll = self::getAssistanceMember($assistanceActive['k_id']);
            $assistanceT = self::getAssistanceUserOne($assistanceActive['k_id']);
        } else {
            $assistanceAll = self::getAssistanceMember($assistanceActive['id']);
            $assistanceT = $assistanceActive;
        }
        $assistanceT = $assistanceT->hidden(['order_id', 'total_price', 'cid', 'pid', 'add_time', 'k_id', 'is_tpl', 'is_refund'])->toArray();
        $assistanceAll = $assistanceAll->hidden(['total_price', 'cid', 'pid', 'add_time', 'k_id', 'is_tpl', 'is_refund'])->toArray();
        $count = count($assistanceAll);
        $count = (int)bcsub($assistanceT['people'], $count, 0);
        $idAll = [];
        $uidAll = [];
        //收集助力用户id和助力id
        foreach ($assistanceAll as $k => $v) {
            $idAll[$k] = $v['id'];
            $uidAll[$k] = $v['uid'];
        }
        $idAll[] = $assistanceT['id'];
        $uidAll[] = $assistanceT['uid'];
        return [$assistanceAll, $assistanceT, $count, $idAll, $uidAll];
    }

    /*
     * 取消助力
     * @param int $uid 用户id
     * @param int $assistance_active_id 团长id
     * @return boolean
     * */
    public static function removeAssistance($uid, $cid, $assistance_active_id, $nextAssistanceT = null)
    {
        $assistanceT = self::where('uid', $uid)
            ->where('id', $assistance_active_id)
            ->where('cid', $cid)
            ->where('k_id', 0)
            ->where('is_refund', 0)
            ->where('status', 1)
            ->where('stop_time', '>', time())
            ->find();
        if (!$assistanceT) return self::setErrorInfo('未查到助力信息，无法取消');
        self::startTrans();
        try {
            list($assistanceAll, $assistanceT, $count, $idAll, $uidAll) = self::getAssistanceMemberAndAssistanceK($assistanceT);
            if (count($assistanceAll)) {
                if (self::getAssistancePeople($assistance_active_id, $assistanceT['people'])) {
                    //助力未完成，助力有成员取消开团取 紧跟团长后助力的人
                    if (isset($assistanceAll[0])) $nextAssistanceT = $assistanceAll[0];
                } else {
                    //助力完成
                    self::AssistanceComplete($uidAll, $idAll, $uid, $assistanceT);
                    return self::setErrorInfo(['status' => 200, 'msg' => '助力已完成，无法取消']);
                }
            }
            //取消开团
            if (StoreOrder::orderApplyRefund(StoreOrder::getAssistanceOrderId($assistanceT['order_id_key']), $assistanceT['uid'], '助力取消开团') && self::isTpl($assistanceT['uid'], $assistanceT['id'])) {
                self::orderAssistanceAfterNo($assistanceT['uid'], $assistanceT['id'], '助力取消开团', true);
            } else
                return self::setErrorInfo(['status' => 200, 'msg' => StoreOrder::getErrorInfo()], true);
            //当前团有人的时候
            if (is_array($nextAssistanceT)) {
                self::where('id', $nextAssistanceT['id'])->update(['k_id' => 0, 'status' => 1, 'stop_time' => $assistanceT['stop_time']]);
                self::where('k_id', $assistanceT['id'])->update(['k_id' => $nextAssistanceT['id']]);
                StoreOrder::where('order_id', $nextAssistanceT['order_id'])->update(['assistance_active_id' => $nextAssistanceT['id']]);
            }
            self::commitTrans();
            return true;
        } catch (\Exception $e) {
            return self::setErrorInfo($e->getLine() . ':' . $e->getMessage() . ':' . $e->getFile(), true);
        }
    }

    /**
     * 获取当前商品参与的人数
     * @param int $assistanceId
     * @return int|string
     */
    public static function getCountPeopleAll($assistanceId = 0, $mer_id = '')
    {
        if (!$assistanceId) return self::merSet($mer_id)->where('status', 2)->count();
        return self::merSet($mer_id)->where('cid', $assistanceId)->where('status', 2)->count();
    }

    /**
     * 获取当前商品参与的团数
     * @param int $assistanceId
     * @return int|string
     */
    public static function getCountPeopleAssistance($assistanceId = 0, $mer_id = '')
    {
        if (!$assistanceId) return self::merSet($mer_id)->where('k_id', 0)->where('status', 2)->count();
        return self::merSet($mer_id)->where('cid', $assistanceId)->where('k_id', 0)->where('status', 2)->count();
    }

    /**
     * 参与助力
     */
    public static function attendAssistance($uid, $parent_assistance_id)
    {
        $assistanceActive = self::get($parent_assistance_id);
        $product = StoreAssistance::where('id', $assistanceActive['cid'])->field('effective_time,title')->find();
        if ($product) {
            $res = false;
            $assistance['uid'] = $uid;
            if (self::isAssistanceBe($assistance, $parent_assistance_id)) return false;
            $assistance['order_id'] = $assistanceActive['order_id'];
            $assistance['order_id_key'] = $assistanceActive['order_id_key'];
            $assistance['total_num'] = $assistanceActive['total_num'];
            $assistance['total_price'] = $assistanceActive['total_price'];
            $assistance['cid'] = $assistanceActive['cid'];
            $assistance['pid'] = $assistanceActive['pid'];
            $assistance['people'] = $assistanceActive['people'];
            $assistance['price'] = $assistanceActive['price'];
            $assistance['add_time'] = time();
            $assistance['stop_time'] = 0;
            $assistance['k_id'] = $parent_assistance_id;
            $assistance['is_tpl'] = 0;
            $assistance['is_refund'] = 0;
            $assistance['is_separate_account'] = 0;
            $assistance['status'] = 1;
            $assistance['mer_id'] = $assistanceActive['mer_id'];//所属商户
            $res = self::create($assistance)->toArray();
        } else {
            Log::error('助力读取商品数据失败订单号：' . $order['order_id']);
        }
        if ($res) return true;
        else return false;
    }

    /**
     * 处理奖励
     */
    public static function treatmentAward($order_id, $mer_id = '')
    {
        $order = StoreOrder::get($order_id);
        $parent = self::where('mer_id', $mer_id)->where('order_id_key', $order_id)->where('k_id', 0)->find();
        $childs = self::where('mer_id', $mer_id)->where('order_id_key', $order_id)->where('k_id', '<>', 0)->select();
        $assistance = StoreAssistance::get($order['assistance_id']);

        // 选择发起人的订单作为分账的账单
        $transaction_id = $order['transaction_id']; // 微信订单号
        $out_order_no = $order['order_id'];

        // 计算发起人和参与者的分账金额
        $price = $order['pay_price'];
        $p_separate_account = $assistance['p_separate_account'];
        $c_separate_account = $assistance['c_separate_account'];
        $p_amount = bcmul($price, $p_separate_account / 100, 2);  //bcmul：2个任意精度数字乘法计算
        $c_amount = bcmul($price, $c_separate_account / 100, 2);  //bcmul：2个任意精度数字乘法计算
        $p_separate_account_amount = floor($p_amount * 100); // 发起人分账金额，以分为单位
        $c_separate_account_amount = floor($c_amount * 100); // 参与者分账金额，以分为单位

        $p_user_info = WechatUser::get($parent['uid']);

        $receivers[] = array(
            'type' => 'PERSONAL_OPENID',
            'account' => $p_user_info['routine_openid'],
            'amount' => $p_separate_account_amount,
            'description' => '您发起的助力人数已满，给您发了一笔现金奖励' . ($p_amount) . '元'
        );

        // 记录发起人分账开始的信息
        $p_separate_account_record = new StoreSeparateAccountRecord;
        $p_separate_account_record['product_id'] = $assistance['product_id'];
        $p_separate_account_record['active_product_id'] = $assistance['id'];
        $p_separate_account_record['type'] = 4;
        $p_separate_account_record['money'] = $p_amount;
        $p_separate_account_record['active_id'] = $parent['id'];
        $p_separate_account_record['order_id'] = $order_id;  // OK
        $p_separate_account_record['uid'] = $parent['uid'];
        $p_separate_account_record['state'] = 0; // 默认为失败
        $p_separate_account_record['notice'] = "分账失败";
        $p_separate_account_record['mer_id'] = $parent['mer_id'];
        $p_separate_account_record['start_time'] = time();
        $p_separate_account_record['end_time'] = 0;
        $p_separate_account_record->save();

        // 添加发起人为分账接受方
        $res1 = MiniProgramService::addReceiver($p_user_info['routine_openid'], $mer_id); // 添加发起人为分账接受方

        // 处理参与者（添加分账人及加入分账列表）
        foreach ($childs as $key => $value) {
            $uid = $value['uid'];
            $c_user_info = WechatUser::get($uid);
            $res2 = MiniProgramService::addReceiver($c_user_info['routine_openid'], $mer_id); // 添加分账接收方
            // 记录参与者分账开始的信息
            $c_separate_account_record = new StoreSeparateAccountRecord;
            $c_separate_account_record['product_id'] = $assistance['product_id'];
            $c_separate_account_record['active_product_id'] = $assistance['id'];
            $c_separate_account_record['type'] = 4;
            $c_separate_account_record['money'] = $c_amount;
            $c_separate_account_record['active_id'] = $value['id'];
            $c_separate_account_record['order_id'] = $order_id;
            $c_separate_account_record['uid'] = $value['uid'];
            $c_separate_account_record['status'] = 0; // 默认为失败
            $c_separate_account_record['notice'] = "分账失败";
            $c_separate_account_record['mer_id'] = $value['mer_id'];
            $c_separate_account_record['start_time'] = time();
            $c_separate_account_record['end_time'] = 0;
            $c_separate_account_record->save();
            $receivers[] = array(
                'type' => 'PERSONAL_OPENID',
                'account' => $c_user_info['routine_openid'],
                'amount' => $c_separate_account_amount,
                'description' => '您参与的助力人数已满，给您发了一笔现金奖励' . ($c_amount) . '元'
            );
        }
        if($transaction_id){
            $res = MiniProgramService::multi_profit_sharing($transaction_id, $out_order_no, $receivers, $mer_id);
            $res = json_decode($res, true);

            $separateAccount = StoreSeparateAccountRecord::where('order_id', $order_id)->select();
            if ($res['return_code'] == 'SUCCESS') {
                foreach ($separateAccount as $key => $value) {
                    $value['state'] = 1;
                    $value['notice'] = "分账成功";
                    $value['end_time'] = time();
                    $value->save();
                }
                MiniProgramService::profit_sharing_finish($order['transaction_id'], $order['order_id'], $order['mer_id']);
            }
        }
        
    }

    /**
     * 记录本次助力分账奖励
     */
    public static function recordAssistanceMoney($order_id)
    {
        $assistance_active = self::where('order_id_key', $order_id)->find();
        $assistance = StoreAssistance::get($assistance_active['cid']);
        $order = StoreOrder::get($order_id);
        $price = $order['pay_price'];
        $assistance->assistance_money += bcmul($price, $assistance['p_separate_account'] / 100, 2) + $assistance['people'] * bcmul($price, $assistance['c_separate_account'] / 100, 2);
        $assistance->save();
    }
}