<?php
namespace App\Models\order\mysql;

use Api\PhpUtils\Mysql\MysqlBase;
use App\Exception\BaseException;

class PayOrderClearingItem extends MysqlBase
{
    const TABLE_NAME = 'pay_order_clearing_item';
    const CONFIG_INDEX = 'pay';


    public static function marketSaleCount($accountId) {

        $ret = [
            'transit_fund'=>0,
            'history_fund'=>0,
        ];

        if($accountId == 0) {
            return $ret;
        }

        /**/
        $sql = "select sum(poci.`pay_amount`) as 'pay_amount', notify_account_status  from pay_order_clearing_item poci 
join pay_order_item poi on poi.`order_item_id` = poci.`order_item_id` 
where poci.pay_sub_type = 105 and poci.account_id = ? and poi.refund_order_status = 0 group by notify_account_status ";

        /*
        $sql = "select  sum(poci.`pay_amount`) as 'pay_amount', 
notify_account_status  from pay_order_clearing_item poci 
join pay_order_item poi on poi.`order_item_id` = poci.`order_item_id` 
where 
not exists (select 1 from refund_order ro where ro.`order_item_id` = poci.`order_item_id`) and 
poci.pay_sub_type = 105 and poci.account_id = ? 
group by notify_account_status ";
        */

        /*
        type=1: 该团长历史累计分销佣金收入总和
        type=2: 该团长当前未结算分销佣金总和
         */
        try{
            $medoo = self::getConnection(self::READ);
            $medoo->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
            $sth = $medoo->pdo->prepare($sql);
            $sth->execute([$accountId]);

            while ($row = $sth->fetch(\PDO::FETCH_ASSOC)) {

                if($row['notify_account_status'] == 2) {
                    $ret['history_fund'] += $row['pay_amount'];

                } else {
                    $ret['transit_fund'] += $row['pay_amount'];
                }
            }

            return $ret;

        }catch (\PDOException $e) {
            throw new BaseException(['msg'=>'数据查询错误:' . $e->getMessage(), 'code'=>'2401']);
        }
    }


}
