<?php
/**
 * @package merchant
 *
 * @author xaboy
 * @day 2020-05-07
 *
 *
 */

namespace app\common\repositories\user;


use app\common\dao\BaseDao;
use app\common\dao\shared\SharedProsperityBalanceLogDao;
use app\common\dao\user\UserBillDao;
use app\common\enum\CommonEnum;
use app\common\enum\shared\SharedProsperityBalanceLogEnum;
use app\common\enum\user\UserBillEnum;
use app\common\enum\user\UserCertificationEnum;
use app\common\model\user\UserBill;
use app\common\repositories\BaseRepository;
use app\common\repositories\gzc\GzcLogRepository;
use app\common\repositories\shared\SharedProsperityUserRepository;
use app\common\repositories\store\order\StoreOrderRepository;
use app\entity\data\shared\SharedProsperityBalanceLogEntity;
use app\entity\data\shared\SharedProsperityUserEntity;
use app\entity\data\user\UserBillEntity;
use app\entity\data\user\UserCertificationEntity;
use app\entity\data\user\UserEntity;
use app\utils\ArrayUtil;
use think\db\exception\DbException;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Db;
use think\Model;

/**
 * Class UserBillRepository
 * @package app\common\repositories\user
 * @author xaboy
 * @day 2020-05-07
 * @mixin UserBillDao
 */
class UserBillRepository extends BaseRepository
{
    /**
     * @var UserBillDao
     */
    protected $dao;

    /**
     * UserBillRepository constructor.
     * @param UserBillDao $dao
     */
    public function __construct(UserBillDao $dao)
    {
        $this->dao = $dao;
    }

    public function userList($where, $uid, $page, $limit)
    {
        $where['uid'] = $uid;
        $query = $this->dao->search($where)->order('create_time DESC')
            ->when(isset($where['status']) && $where['status'] !== '', function ($query) use ($where) {
                $query->whereLike('status', $where['status']);
            });
        $count = $query->count();
        $list = $query->setOption('field', [])->field('bill_id,pm,title,number,balance,mark,create_time,status,order_sn,mer_id')->page($page, $limit)->select();
        return compact('count', 'list');
    }

    public function getList($where, $page, $limit)
    {
        if ($where["city"]){
            if ($where["city"] == '直辖区') {
                $city_id = Db::name("user_city")->where("city_name", $where["province"])->value("city_id");
            } else {
                $city_id = Db::name("user_city")->where("city_name",$where["city"])->value("city_id");
            }

            $where['city_id'] = $city_id;
            unset($where["city"]);
        }
        $query = $this->dao->searchJoin($where)->order('a.create_time DESC');
        $count = $query->count();
        $list = $query->page($page, $limit)->select();
        $order_type = 1;
//        dump($list);
//        return 1;
        $souxufee = systemConfig('yanglao');
        foreach ($list as &$v){
            if ($v["source"]==1) {
                $vorder_merchant=Db::name("order_merchant")->where(["out_trade_no"=>$v["order_sn"]])->find();
                $v["mer_id"]=$vorder_merchant["mer_id"];

                //消费金额
                $v["total_price"]=$vorder_merchant["money"];
                //可分佣金总额
                $v["extension_one"]=$vorder_merchant["available"];
                //分账给服务商的钱
                $v["service_money"]=$vorder_merchant["service_money"];
                //养老金
                $v["pension"]=$vorder_merchant["pension"];
                //刷卡手续费
                $v["swipe_fee"]=$vorder_merchant["swipe_fee"];
                $v["uid"]=$vorder_merchant["uid"];
                if ($vorder_merchant["uid"] > 0) {
                    $users=Db::name("user")->where("uid",$vorder_merchant["uid"])->field("nickname,phone")->find();
                    $v["nickname"]=$users["nickname"];
                    $v["phone"]=$users["phone"];
                } else {
                    $v["nickname"]=$vorder_merchant["nickname"]."【".($vorder_merchant["trade_type"]=="WX"?"微信用户":"支付宝用户")."】";
                    $v["phone"]=$vorder_merchant["pay_user_id"];

                }
            } else {
                if(strpos($v['order_sn'],'channel') !== false || strpos($v['order_sn'],'sIC') !== false ){
                    //渠道商
                    $channel_order = Db::name('channel_order') -> where('order_no',$v['order_sn']) -> find();
                    $v["mer_id"]='';
                    $v["total_price"]=$channel_order["pay_price"];
                    $v["extension_one"]=0;
                    $users=Db::name("user")->where("uid",$channel_order["uid"])->field("nickname,phone")->find();
                    $v["nickname"]=$users["nickname"];
                    $v["phone"]=$users["phone"];
                    $v["uid"]=$channel_order["uid"];
                    $v['mer_name'] = '开通渠道商';
                    $order_type = 2;
                }elseif (strpos($v['order_sn'],'annual') !== false || strpos($v['order_sn'],'sIM') !== false ){
                    //商户
                    $annual_cost_order=Db::name('merchant_annual_cost_order')-> where('order_no',$v['order_sn'])->find();
                    $v["mer_id"]='';
                    $v["total_price"]=$annual_cost_order["pay_price"];
                    $v["extension_one"]=0;
                    $users=Db::name("user")->where("uid",$annual_cost_order["uid"])->field("nickname,phone")->find();
                    $v["nickname"]=$users["nickname"];
                    $v["phone"]=$users["phone"];
                    $v["uid"]=$annual_cost_order["uid"];
                    $v['mer_name'] = '开通商户';
                    $order_type = 2;
                }else{
                    if(strpos($v['order_sn'],'sIO') !== false){
                        $v["mer_id"]='';
                        $v["total_price"]=strpos($v['mark'],'金卡') !== false ? '999' : '399';
                        $order_type = 2;
                    }else{
                        $store_order=Db::name("store_order")->where("order_sn",$v["order_sn"])->find();
                        $v["mer_id"]=$store_order["mer_id"];
                        $v["total_price"]=$store_order["total_price"];
                        $v["extension_one"]=$store_order["extension_one"];
                        $users=Db::name("user")->where("uid",$store_order["uid"])->field("nickname,phone")->find();
                        $v["nickname"]=$users["nickname"];
                        $v["phone"]=$users["phone"];
                        $v["uid"]=$store_order["uid"];
                    }
                }

                $v["pension"]=Db::name('user_bill')
                    ->where('commission_type',5)
                    ->where("order_sn",$v["order_sn"])
                    ->value('number');
                $v["swipe_fee"]=Db::name('admin_bill')
                    ->where('type',1)
                    ->where('status',1)
                    ->where("order_sn",$v["order_sn"])
                    ->value('number');

                //服务商分账的钱
                $service_money = bcsub($v["extension_one"], $v["pension"], 2);
//                $service_money=bcmul($v["total_price"],0.05,2);
                $v["service_money"]=$service_money;



            }

            $user_bill=Db::name("user_bill")
                ->alias('a')
                ->join('User b', 'a.uid = b.uid')
                ->field('a.bill_id,a.pm,a.title,a.number,a.balance,a.mark,a.create_time,a.status,b.nickname,b.phone,a.uid,a.order_sn,a.source,identity')
                ->where(["type"=>"commission","order_sn"=>$v["order_sn"]])
                ->select();


            $admin_bill=Db::name("admin_bill")->where("order_sn",$v["order_sn"])->select();
            foreach ($admin_bill as $q){
                $q["nickname"]="平台";
                $q["phone"]="---------";
                $user_bill[]=$q;
            }
            if ($v["uid"]==0){
                $user_bill[]=[
                    "nickname"=>"注：该用户未绑定app，未给到养老金",
                    "mark"=>$v["pension"]
                ];
            }
            $v["datalist"]=$user_bill;
            $mer =Db::name("merchant")->where("mer_id",$v["mer_id"])->find();
            $v["mer_name"]=$mer["mer_name"];

            if($order_type == 1){
                $mer_mory=bcsub(bcsub($v["total_price"],$v["extension_one"],2),$v["swipe_fee"],2);
                $user_bill[]=[
                    "identity"=>4,
                    "nickname"=>$mer["mer_name"],
                    "phone"=>$mer["mer_phone"],
                    "number"=>$mer_mory,
                    "mark"=>"用户到店支付成功消费".$v["total_price"]."元,商家货款".$mer_mory
                ];
            }


            if($order_type == 1){
                $countcommission=Db::name("user_bill")
                    ->where(["type"=>"commission","order_sn"=>$v["order_sn"]])
                    ->where("commission_type","<>",5)
                    ->sum("number");
                $jieyu=bcsub($v["service_money"],$countcommission,2);
                $user_bill[]=[
                    "nickname"=>"平台",
                    "phone"=>"----------",
                    "number"=>$jieyu,
                    "mark"=>"分账给服务商的钱".$v["service_money"]."元,结余".$jieyu
                ];
                $v['pingtai'] = $jieyu;
            }else{
                $countcommission=Db::name("user_bill")
                    ->where(["type"=>"commission","order_sn"=>$v["order_sn"]])
                    ->sum("number");
                $v["extension_one"] = $countcommission;
                $jieyu=bcsub($v["total_price"],$countcommission,2);
                $user_bill[]=[
                    "nickname"=>"平台",
                    "phone"=>"----------",
                    "number"=>$jieyu,
                    "mark"=>"总佣金+养老金：".$countcommission."元,结余".$jieyu
                ];
                $v['pingtai'] = $jieyu;
                //服务商分账的钱
                $service_money = bcsub($v["extension_one"], $v["pension"], 2);
                $v["service_money"]=$service_money;
            }

        }
        unset($v);

        $c = UserBill::getDB() -> count();
        $userBill = json_decode(Cache::get('userBill'),true);
//        dump($userBill);

        if(isset($userBill['count']) && $userBill['count'] == $c){
            $total1_query = [];
            $cardLists = $userBill['query'];
        }else{


            $total1_query = UserBill::getDB()
                ->alias('a')
                ->join('order_merchant b', 'a.order_sn = b.out_trade_no')
                ->join('merchant_intention c', 'a.mer_id = c.mer_id')
                ->field("b.money,b.available,b.service_money,b.pension,b.swipe_fee")
                ->where('a.source', 1)
                ->where("a.status",1)
                ->where("a.type_shop",0)
                ->when(isset($where['type']) && $where['type'] !== '', function ($query) use ($where) {
                    $query->where('a.type', $where['type']);
                })
                ->when(isset($where['user_time']) && $where['user_time'] !== '', function ($query) use ($where) {
                    getModelTime($query, $where['user_time'], 'a.create_time');
                })
                ->when(isset($where['city_id']) && $where['city_id'], function ($query) use ($where) {
                    $query->where('c.city_id', $where['city_id']);
                })
                ->when(isset($where['keyword']) && $where['keyword'] !== '', function ($query) use ($where) {
                    $query->whereLike('c.mer_name', "%{$where['keyword']}%");
                })
                ->group("a.order_sn")
                ->cursor();

            $total1_price = 0;
            $total1_extension_one = 0;
            $total1_service_money = 0;
            $total1_pension = 0;
            $total1_swipe_fee = 0;
            foreach ($total1_query as $total1) {
                $total1_price += $total1['money'];
                $total1_extension_one += $total1['available'];
                $total1_service_money += $total1['service_money'];
                $total1_pension += $total1['pension'];
                $total1_swipe_fee += $total1['swipe_fee'];
            }

            $cardLists=[
                ['className'=> 'el-icon-s-finance', 'count'=> bcadd($total1_price, 0, 2), 'field'=>'元', 'name'=> '消费总额' ],
                ['className'=> 'el-icon-s-finance', 'count'=> bcadd($total1_extension_one, 0, 2), 'field'=>'元', 'name'=> '可分佣总额' ],
                ['className'=> 'el-icon-s-finance', 'count'=> bcadd($total1_service_money, 0, 2), 'field'=>'元', 'name'=> '分给服务商的金额' ],
                ['className'=> 'el-icon-s-finance', 'count'=> bcadd($total1_pension, 0, 2), 'field'=>'元', 'name'=> '养老金' ],
                ['className'=> 'el-icon-s-finance', 'count'=> bcadd($total1_swipe_fee, 0, 2), 'field'=>'元', 'name'=> '刷卡手续费' ],
            ];



            $userBill1['count'] = $c;
            $userBill1['query'] = $cardLists;
            Cache::set('userBill',json_encode($userBill1));
        }



        return compact('count', 'list', 'cardLists', 'total1_query');
    }

    /*平台收益记录*/
    public function getAdminList($where, $page, $limit)
    {

        $query = Db::name("admin_bill")->alias('a')->join('User b', 'a.link_id = b.uid')
        ->field('a.*,b.nickname,b.account')
        ->when(isset($where['type']) && $where['type'] !== '', function ($query) use ($where) {
            $query->where('a.type', $where['type']);
        })->when(isset($where['date']) && $where['date'] !== '', function ($query) use ($where) {
            getModelTime($query, $where['date'], 'a.create_time');
        })->when(isset($where['keyword']) && $where['keyword'] !== '', function ($query) use ($where) {
            $query->whereLike('a.order_sn|b.nickname|b.account', "%{$where['keyword']}%");
        });
        $query = $query->order('a.create_time DESC');
        $count = $query->count();
        $list = $query->page($page, $limit)->select();
        $cardLists=[];
//        $cardLists=[
//            ['className'=> 'el-icon-s-goods', 'count'=>$count1, 'field'=>'个', 'name'=> '平台收入' ],
//            ['className'=> 'el-icon-s-goods', 'count'=>$count2, 'field'=>'个', 'name'=> '审核中' ],
//            ['className'=> 'el-icon-s-goods', 'count'=>$count3, 'field'=>'个', 'name'=> '未通过' ],
//        ];
        return compact('count', 'list','cardLists');
    }


    /**
     * @param int $uid
     * @param string $category
     * @param string $type
     * @param int $pm
     * @param array $data
     * @return BaseDao|Model
     * @author xaboy
     * @day 2020-05-07
     */
    public function bill(int $uid, string $category, string $type, int $pm, array $data)
    {
        $data['category'] = $category;
        $data['type'] = $type;
        $data['uid'] = $uid;
        $data['pm'] = $pm;
        $bill = $this->dao->create($data);
//        if($category == 'now_money'){
//            $tempData = ['tempCode' => 'USER_BALANCE_CHANGE','id' => $bill->bill_id];
//            Queue::push(SendTemplateMessageJob::class,$tempData);
//        }
        return $bill;
    }

    /**
     * @param int $uid
     * @param string $category
     * @param string $type
     * @param array $data
     * @return BaseDao|Model
     * @author xaboy
     * @day 2020-05-07
     */
    public function incBill(int $uid, string $category, string $type, array $data)
    {
        return $this->bill($uid, $category, $type, 1, $data);
    }

    /**
     * @param int $uid
     * @param string $category
     * @param string $type
     * @param array $data
     * @return BaseDao|Model
     * @author xaboy
     * @day 2020-05-07
     */
    public function decBill(int $uid, string $category, string $type, array $data)
    {
        return $this->bill($uid, $category, $type, 0, $data);
    }

    /**
     * 添加 bill 数据
     * @param int $uid
     * @param int $commissionType
     * @param int $pm
     * @param float $number
     * @param string $category
     * @param string $type
     * @param string $source
     * @param int $orderType
     * @param int $typeShop
     * @param int $orderId
     * @param string $mark
     * @param string $title
     * @param string $orderSn
     * @return UserBillEntity
     */
    public function addUserBill(int $uid, int $commissionType, int $pm, float $number, string $category, string $type, string $source, int $orderType, int $typeShop = 0, int $orderId = 0, string $mark = '', string $title = '', string $orderSn = ''): UserBillEntity
    {

        $merId = 0;
        if ($typeShop == UserBillEnum::TYPE_SHOP['Platform']['code']) {
            /** @var StoreOrderRepository $storeOrderRepository */
            $storeOrderRepository = app()->make(StoreOrderRepository::class);
            $storeOrderEntity = $storeOrderRepository->getStoreOrderEntityByOrderId($orderId);
            if (empty($storeOrderEntity->getOrderId())) {
                throw new ValidateException('未查询到订单信息');
            }
            $orderId = $storeOrderEntity->getOrderId();
            $orderSn = $storeOrderEntity->getOrderSn();
            $merId = $storeOrderEntity->getMerId();
        }

        /** @var UserBillEntity $userBillEntity */
        $userBillEntity = UserBillEntity::newInstance();
        $userBillEntity->setUid($uid)
            ->setLinkId($orderId)
            //UserBillEnum::PM['INCOME']['code']
            ->setPm($pm)
            ->setTitle($title ?: ArrayUtil::getEnumNameByCode($commissionType, UserBillEnum::COMMISSION_TYPE))
            ->setCategory($category)
            ->setType($type)
            ->setNumber($number)
            ->setMark($mark)
            ->setStatus(UserBillEnum::STATUS['PENDING']['code'])
            ->setCommissionType($commissionType)
            ->setOrderSn($orderSn)
            ->setTypeShop($typeShop)
            ->setMerId($merId)
            // UserBillEnum::SOURCE['ONLINE']['code']
            ->setSource($source)
            ->setOrderType($orderType)
            ->setIsRedBrokerage(UserBillEnum::IS_RED_BROKERAGE['NORMAL']['code'])
            ->setGzc(UserBillEnum::GZC_STATUS['NOT_ENTERED']['code'])
            ->setIsGzc(UserBillEnum::IS_GZC['NOT_STARTED']['code']);

        return $this->createByEntity($userBillEntity);
    }

    /**
     * 写入 数据
     * @param UserBillEntity $userBillEntity
     * @return UserBillEntity
     */
    public function createByEntity(UserBillEntity $userBillEntity): UserBillEntity
    {
        $result = $this->dao->create($userBillEntity->toUnderlineArray())->toArray();
        /** @var UserBillEntity $entity */
        $entity = UserBillEntity::newInstance($result);
        return $entity;
    }

    /**
     * @param int $billId
     * @return UserBillEntity
     */
    public function getUserBillEntityByBillId(int $billId): UserBillEntity
    {
        $entityList = $this->getUserBillEntityListByBillIdList([$billId]);
        $entity = array_shift($entityList);
        if ($entity instanceof UserBillEntity) {
            return $entity;
        } else {
            /** @var UserBillEntity */
            return UserBillEntity::newInstance();
        }
    }

    /**
     * 获取Bill实体集合 根据 Id集合
     * @param array $billIdList
     * @return UserBillEntity[]
     */
    public function getUserBillEntityListByBillIdList(array $billIdList): array
    {
        return $this->dao->getUserBillEntityListByBillIdList($billIdList);
    }

    /**
     * 获取Bill实体集合 根据 订单类型 订单Id集合 待结算状态
     * @param string $typeShop
     * @param array $orderIdList
     * @return UserBillEntity[]
     */
    public function getUserBillEntityListByOrderIdListAndPending(string $typeShop, array $orderIdList): array
    {
        return $this->dao->getUserBillEntityListByOrderIdListAndPending($typeShop, $orderIdList);
    }

    /**
     * @param string $typeShop
     * @param string $orderSn
     * @return UserBillEntity
     */
    public function getUserBillEntityByTypeShopAndOrderSn(string $typeShop, string $orderSn): UserBillEntity
    {
        return $this->dao->getUserBillEntityByTypeShopAndOrderSn($typeShop, $orderSn);
    }

    /**
     * @param $dataList
     * @return array
     */
    public function batchUpdateUserBillDataByDataList($dataList): array
    {
        return $this->dao->saveAll($dataList);
    }

    /**
     * 将 账单 记录设置为生效状态 并对用户的 对应 字段进行增减
     * @param array $idList
     * @return array
     */
    public function executeByIdList(array $idList): array
    {
        $userBillEntityList = $this->getUserBillEntityListByBillIdList($idList);
        // 忽略 已经生效的 记录
        $userBillEntityList = array_filter($userBillEntityList, function($entity) {
            return $entity->getStatus() != UserBillEnum::STATUS['VALID']['code'];
        });

        if (!empty($userBillEntityList)) {
            $pensionUidList = [];
            // 获取所有记录的 归属人
            $userIdList = array_map(function ($userBillEntity) use (&$pensionUidList) {
                // 获取 养老金记录
                if ($userBillEntity->getCommissionType() == UserBillEnum::COMMISSION_TYPE['PENSION']['code']) {
                    $pensionUidList[] = $userBillEntity->getUid();
                }
                return $userBillEntity->getUid();
            }, $userBillEntityList);

            // 获取用户 映射信息
            /** @var UserRepository $userRepository */
            $userRepository = app()->make(UserRepository::class);
            /** @var UserEntity[] $userEntityMapByUid */
            $userEntityMapByUid = [];
            if (!empty($userIdList)) {
                $userEntityMapByUid = $userRepository->getUserEntityMapByUidList($userIdList);
            }
            // 获取实名认证 映射信息 (养老金记录 结算时 需要确定 所属人是否已经实名认证 如果实名认证了 需要推到养老金公证处明细表里 并修改养老金记录的推送状态)
            /** @var UserCertificationEntity[] $userCertificationEntityMapByUid */
            $userCertificationEntityMapByUid = [];
            if (!empty($pensionUidList)) {
                /** @var UserCertificationRepository $userCertificationRepository */
                $userCertificationRepository = app()->make(UserCertificationRepository::class);
                $userCertificationEntityMapByUid = $userCertificationRepository->getUserCertificationEntityMapByUidListApproved($pensionUidList);
            }
            /** @var GzcLogRepository $gzcLogRepository */
            $gzcLogRepository = app()->make(GzcLogRepository::class);

            $updateUserEntityList = [];
            $updateUserBillEntityList = [];
            foreach ($userBillEntityList as $userBillEntity) {
                if (empty($userBillEntity->getBillId()) || empty($userBillEntity->getUid())) {
                    // throw new ValidateException('无效的账单记录');
                    continue;
                }
                if (!empty($userBillEntity->getTakeTime())) {
                    throw new ValidateException("该账单记录已更新，请勿重复操作({$userBillEntity->getBillId()})");
                }

                $userEntity = $userEntityMapByUid[$userBillEntity->getUid()];
                if (empty($userEntity) || empty($userEntity->getUid())) {
                    throw new ValidateException("未查询到用户信息({$userBillEntity->getBillId()})");
                }

                // 更新 用户信息
                /** @var UserEntity $updateUserEntity */
                $updateUserEntity = $updateUserEntityList[$userEntity->getUid()] ?? UserEntity::newInstance();
                $updateUserEntity->setUid($userEntity->getUid());
                // 更新 账单 记录
                /** @var UserBillEntity $updateUserBillEntity */
                $updateUserBillEntity = $updateUserBillEntityList[$userBillEntity->getBillId()] ?? UserBillEntity::newInstance();
                // 更新 账单记录 状态
                $updateUserBillEntity
                    ->setBillId($userBillEntity->getBillId())
                    ->setStatus(UserBillEnum::STATUS['VALID']['code'])
                    ->setTakeTime(time());

                if (in_array($userBillEntity->getCommissionType(), [
                    UserBillEnum::COMMISSION_TYPE['DIRECT_REFERRAL']['code'],
                    UserBillEnum::COMMISSION_TYPE['LOCKED_CUSTOMER']['code'],
                    UserBillEnum::COMMISSION_TYPE['PLATFORM_REWARD']['code'],
                    UserBillEnum::COMMISSION_TYPE['SHARE_EARNINGS']['code']
                ])) {
                    // 直推奖
                    if (is_null($updateUserEntity->getBrokeragePrice())) {
                        $updateUserEntity->setBrokeragePrice($userEntity->getBrokeragePrice());
                    }
                    // 更新用户 佣金 信息
                    if ($userBillEntity->getPm() == UserBillEnum::PM['EXPEND']['code']) {
                        if ($updateUserEntity->getBrokeragePrice() < $userBillEntity->getNumber()) {
                            throw new ValidateException('用户佣金不足');
                        }
                        $updateUserEntity->setBrokeragePrice(bcsub($updateUserEntity->getBrokeragePrice(), $userBillEntity->getNumber(), 2));
                    } else {
                        $updateUserEntity->setBrokeragePrice(bcadd($updateUserEntity->getBrokeragePrice(), $userBillEntity->getNumber(), 2));
                    }

                } else if ($userBillEntity->getCommissionType() == UserBillEnum::COMMISSION_TYPE['PENSION']['code']) {

                    if ($userBillEntity->getGzc() == UserBillEnum::GZC_STATUS['NOT_ENTERED']['code']) {
                        if (!empty($userCertificationEntityMapByUid[$userBillEntity->getUid()])) {
                            $userCertificationEntity = $userCertificationEntityMapByUid[$userBillEntity->getUid()];
                            // 创建公证处记录
                            $gzcLogRepository->addGzcLog(
                                $userCertificationEntity->getUid(),
                                $userCertificationEntity->getUserName(),
                                $userCertificationEntity->getMobile(),
                                $userCertificationEntity->getUserCard(),
                                $userBillEntity->getTypeShop(),
                                $userBillEntity->getLinkId(),
                                $userBillEntity->getNumber()
                            );

                            // 养老金
                            if (is_null($updateUserEntity->getAnnuity())) {
                                $updateUserEntity->setAnnuity($userEntity->getAnnuity());
                            }
                            $updateUserEntity->setAnnuity(bcadd($updateUserEntity->getAnnuity(), $userBillEntity->getNumber(), 2));

                            // 几笔养老金
                            if (is_null($updateUserEntity->getAnnuityNum())) {
                                $updateUserEntity->setAnnuityNum($userEntity->getAnnuityNum());
                            }
                            $updateUserEntity->setAnnuityNum(bcadd($updateUserEntity->getAnnuityNum(), 1));

                            // 更新佣金记录
                            $updateUserBillEntity
                                ->setGzc(UserBillEnum::GZC_STATUS['ENTERED']['code'])
                                ->setIsGzc(UserBillEnum::IS_GZC['NOT_STARTED']['code']);
                        }
                    }
                }

                $updateUserEntityList[$userEntity->getUid()] = $updateUserEntity;
                $updateUserBillEntityList[$userBillEntity->getBillId()] = $updateUserBillEntity;
            }
            if (!empty($updateUserEntityList)) {
                $userRepository->batchUpdateUserDataByDataList(
                    array_map(function (UserEntity $updateUserEntity) {
                        return $updateUserEntity->toUnderlineArray();
                    }, $updateUserEntityList)
                );
            }

            if (!empty($updateUserBillEntityList)) {
                $this->batchUpdateUserBillDataByDataList(
                    array_map(function (UserBillEntity $updateUserBillEntity) {
                        return $updateUserBillEntity->toUnderlineArray();
                    }, $updateUserBillEntityList)
                );
            }
        }

        return $idList;
    }

    /**
     * @param $start
     * @param $end
     * @return array
     * @author 史晨
     * @date 2026/2/11 14:29
     * 共富感恩奖佣金查询
     */
    public function getListForSharedProsperityThank($start, $end)
    {
        $status = UserBillEnum::STATUS['VALID']['code'];
        $merId = [
            CommonEnum::DESIGN_MERCHANT_ID['WonderfulLiving']['code'],
            CommonEnum::DESIGN_MERCHANT_ID['Repurchase']['code'],
            CommonEnum::DESIGN_MERCHANT_ID['SharedProsperity']['code'],
        ];
        $commission_type = [
            CommonEnum::COMMISSION_TYPE['DIRECT_REFERRAL']['code'],
            CommonEnum::COMMISSION_TYPE['SHARE_EARNINGS']['code']
        ];
        $params = [
            'start' => $start,
            'end' => $end,
            'status' => $status,
            'merId' => $merId,
            'commissionType' => $commission_type
        ];
        return $this->dao->getListData($params);
    }
}
