<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 分账队列
 */
namespace app\smartbc\model;
use think\Model;

class SmartbcQueen extends Model{
    
    protected $pk     = 'id';
    
    //商家
    public function store(){
        return $this->hasOne('SmartbcStore','id','store_id');
    }
    
    //用户
    public function user(){
        return $this->hasOne('app\common\model\SystemUser','id','uid');
    }

    /**
     * 创建分账队列
    * $data[] = [
    *     'member_miniapp_id' => 应用ID,
    *     'store_id'          => 店铺ID,
    *     'uid'               => 0,
    *     'mch_id'            => 商户ID,
    *     'amount'            => 金额分
    *     'transaction_id'    => 微信支付订单号,
    *     'out_order_no'      => 支付订单号,
    *     'is_finish'         => 0,
    *     'types'             => 1, （0用户/1商家）
    *     'msg'               => 日志内容,
    * ];
     */
    public static function createQueen(array $data){
        $mch_queen = [];
        $uid_queen = [];
        foreach ($data as $value) {
            switch ($value['types']) {
                case 0:  //个人
                    if(!isset($uid_queen[$value['uid']])){
                        $uid_queen[$value['uid']] = $value;
                        $uid_queen[$value['uid']]['msg'] = $value['msg'].'(￥'.money($value['amount']/100).')';
                    }else{
                        $uid_queen[$value['uid']]['amount'] += $value['amount'];
                        $uid_queen[$value['uid']]['msg'] .= ' | '.$value['msg'].'(￥'.money($value['amount']/100).')';
                    }
                    break;
                case 1:   //商家
                    if(!isset($mch_queen[$value['mch_id']])){
                        $mch_queen[$value['mch_id']] = $value;
                        $mch_queen[$value['mch_id']]['msg'] = $value['msg'].'(￥'.money($value['amount']/100).')';
                    }else{
                        $mch_queen[$value['mch_id']]['amount'] += $value['amount'];
                        $mch_queen[$value['mch_id']]['msg'] .= ' | '.$value['msg'].'(￥'.money($value['amount']/100).')';
                    }
                    break;
                default:
                    $mch_queen[$value['mch_id']] = $value;
                    break;
            }
        }
        $mch = array_values($mch_queen);
        $uid = array_values($uid_queen);
        $queen = array_merge($mch,$uid);
        if(empty($queen)){
            return;
        }
        return self::insertAll($queen);
    } 
}