<?php

namespace app\models\user;

use crmeb\basic\BaseModel;
use crmeb\services\MiniProgramService;
use crmeb\services\WechatService;
use crmeb\traits\ModelTrait;

class UserBrokerage extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

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

    use ModelTrait;

    protected $insert = ['add_time'];

    protected function setAddTimeAttr()
    {
        return time();
    }

    /**
     * 获取用户该笔订单返现信息
     */
    public static function getUserOrderBrokerageInfo($order)
    {
        $brokerageSelf = self::getUserSelfBrokerageInfo($order);
        $brokerageOther = self::getUserOtherBrokerageInfo($order);
        $countSelf = !empty($brokerageSelf) ? 1 : 0;
        $countOther = $brokerageOther ? count($brokerageOther) : 0;
        return [$brokerageSelf, $brokerageOther, $countSelf, $countOther];
    }

    /**
     * 获取用户来自自己的返现信息
     */
    public static function getUserSelfBrokerageInfo($order)
    {
        $model = new self;
        $model = $model->where('uid', $order['uid']);
        $model = $model->where('order_id', $order['id']);
        $model = $model->where('card_id', $order['card_id']);
        $model = $model->where('role', 1);
        $model = $model->where('mer_id', $order['mer_id']);
        return $model->find();
    }

    /**
     * 获取用户来自他人的返现信息
     */
    public static function getUserOtherBrokerageInfo($order)
    {
        $model = new self;
        $model = $model->where('uid', $order['uid']);
        $model = $model->where('order_id', '<>', $order['id']);
        $model = $model->where('parent_order_id', $order['id']);
        $model = $model->where('card_id', $order['card_id']);
        $model = $model->where('role', 2);
        $model = $model->where('mer_id', $order['mer_id']);
        $list = $model->select();
        return count($list) ? $list->toArray() : [];
    }

    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
     * @return bool|string
     */
    public static function getNewRefundNo()
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = number_format((floatval($msec) + floatval($sec)) * 1000, 0, '', '');
        $refundNo = 'tk' . $msectime . mt_rand(10000, 99999);
        if (self::be(['refund_no' => $refundNo])) $refundNo = 'tk' . $msectime . mt_rand(10000, 99999);
        return $refundNo;
    }

    /**
     * 创建用户返佣记录
     */
    public static function addUserBrokerage($uid, $card_id, $order_id, $parent_order_id = 0, $refund_no, $role, $refund_price, $refund_percent, $poundage, $mer_id)
    {
        $add_time = time();
        return self::create(compact('uid', 'card_id', 'order_id', 'parent_order_id', 'refund_no', 'role', 'refund_price', 'refund_percent', 'poundage', 'add_time', 'mer_id'));
    }

    /**
     * 获取用户返现记录
     */
    public static function getUserBrokerageList($where)
    {
        $model = self::setWhere($where, null, 'a', 'u.nickname')->join('user u', 'u.uid=a.uid')->join('user_recharge_card c', 'c.id=a.order_id')->field(['a.*', 'u.nickname', 'u.avatar']);
        $list = $model->page($where['page'], $where['limit'])->select();
        $list = count($list) ? $list->toArray() : [];
        foreach ($list as &$item) {
            $item['_add_time'] = $item['add_time'] ? date('Y-m-d H:i:s', $item['add_time']) : '暂无';
            switch ($item['role']) {
                case 1:
                    $item['role_type'] = '自己';
                    break;
                case 2:
                    $item['role_type'] = '他人';
                    break;
            }
        }
        $count = self::setWhere($where, null, 'a', 'u.nickname')->join('user u', 'u.uid=a.uid')->join('user_recharge_card c', 'c.id=a.order_id')->count();
        return compact('list', 'count');
    }

    /**
     * 设置查询条件
     * @param $where
     * @param null $model
     * @param string $alias
     * @param string $join
     * @return $this
     */
    public static function setWhere($where, $model = null, $alias = '', $join = '')
    {
        $model = is_null($model) ? new self() : $model;
        if ($alias) {
            $model = $model->alias('a');
            $alias .= '.';
        }
        if ($where['data']) $model = self::getModelTime($where, $model, "{$alias}add_time");
        if ($where['role'] != '') $model = $model->where("{$alias}role", $where['role']);
        if ($where['nickname']) $model = $model->where("{$alias}uid|{$alias}order_id" . ($join ? '|' . $join : ''), 'LIKE', "%$where[nickname]%");
        if ($where['mer_id']) $model = $model->where("{$alias}mer_id", $where['mer_id']);
        if ($where['uid']) $model = $model->where("{$alias}uid", $where['uid']);
        if ($where['order_id']) $model = $model->where("{$alias}order_id", $where['order_id']);
        return $model->order("{$alias}add_time desc");
    }
}