<?php

namespace app\models\order;

use app\admin\model\system\StoreBill;
use app\models\system\SystemStore;
use crmeb\traits\ModelTrait;
use crmeb\basic\BaseModel;
use think\Exception;
use app\models\user\{User, UserBill};
use crmeb\services\PHPExcelService;

/**
 * B子订单详情
 * Class ArticleCategory
 * @package app\models\article
 */
class PaymentReceived extends BaseModel
{
    use ModelTrait;

    protected function getTypeAttr($value)
    {
        switch ($value) {
            case 0:
                return '余额';
                break;
            case 1:
                return '消费券';
                break;
            case 2:
                return '积分';
                break;
        }

    }

    /**
     * 生成订单唯一id
     * @param $uid 用户uid
     * @return string
     */
    public static function getNewOrderId()
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = number_format((floatval($msec) + floatval($sec)) * 1000, 0, '', '');
        $orderId = 'qr_' . $msectime . mt_rand(10000, 99999);
        while (self::be(['order_id' => $orderId])) $orderId = 'qr_' . $msectime . mt_rand(10000, 99999);
        return $orderId;
    }

    /**
     * 创建支付
     * @param $pay_type
     * @param $code
     * @param $pay_uid
     * @param $collect_uid
     * @param $amount
     */
    public static function Create_Payment($pay_type, $code, $pay_uid, $collect_uid, $amount, $type = 0)
    {
        self::beginTrans();
        $order_id = self::getNewOrderId();
        $add_time = time();
        $pay_user = User::find($pay_uid);
        $collect_user = User::find($collect_uid);
        try {
            switch ($type) {
                case 0:
                    $field = "now_money";
                    $title = "余额";
                    break;
                case 1:
                    $field = "consumer";
                    $title = "消费券";
                    break;
                case 2:
                    $field = "integral";
                    $title = "积分";
                    break;
            }
            if (bcsub($pay_user[$field], $amount, 2) < 0) return self::setErrorInfo($title . '不足!', true);
            $paid = 1;
            $pay_time = time();
            if ($collect_user['user_store_id'] == 0) {
                $transfer = bcdiv(bcmul($amount, sys_config('pay_collection_commission'), 2), 100, 2);
                $recommend = bcdiv(bcmul($amount, sys_config('pay_collection_recommend'), 2), 100, 2);
            } else {
                $transfer = bcdiv(bcmul($amount, sys_config('store_pay_collection_commission'), 2), 100, 2);
                $recommend = bcdiv(bcmul($amount, sys_config('store_pay_collection_recommend'), 2), 100, 2);
            }
            $service_charge = $transfer;
            $res = self::create(compact('pay_type', 'pay_uid', 'code', 'collect_uid', 'amount', 'order_id', 'add_time', 'paid', 'pay_time', 'service_charge', 'type'));
            if ($res) {
                $now_money = bcsub($amount, $transfer, 2);
                @file_put_contents("pay.txt", 'uid:' . $pay_uid . 'collect_uid:' . $collect_uid . '--' . $amount . '--' . $transfer . '--' . $now_money);
                User::where('uid', $pay_uid)->dec($field, $amount)->update();
                $res2 = UserBill::expend("扫码付款-" . $title, $pay_uid, 'now_money', 'qr_des_' . $field, $amount, $res['id'], bcsub($pay_user[$field], $amount, 2), '支付给' . $collect_user['nickname'] . $amount . $title, 1);
                $str = sprintf("收到%s用户%.2f%s,到账:%.2f%s,手续费:%.2f", $pay_user['nickname'], $amount, $title, $now_money, $title, $transfer);
                $store = SystemStore::get($collect_user['user_store_id']);
                if ($collect_user['user_store_id'] > 0 && $store && $field == 'now_money') {
                    $res1 = StoreBill::income('扫码收款-' . $title, $collect_user['user_store_id'], 'product_sale', $now_money, $res['id'], bcadd($store['money'], $now_money, 2), $str);
                    $res2 = SystemStore::bcInc($collect_user['user_store_id'], 'money', $now_money, 'id');
                } else {
                    User::where('uid', $collect_uid)->inc($field, $now_money)->update();
                    $res1 = UserBill::income('扫码收款-' . $title, $collect_uid, 'now_money', 'qr_add_' . $field, $now_money, $res['id'], bcadd($collect_user[$field], $now_money, 2), $str);
                }
                $spread = User::get($collect_user['spread_uid']);
                $res3 = true;
                if ($spread && $recommend > 0) {
                    User::where('uid', $spread['uid'])->inc($field, $recommend)->update();
                    $res3 = UserBill::income("扫码付款推荐奖-" . $title, $spread['uid'], 'now_money', 'qr_recommend_' . $field, $recommend, $res['id'], bcadd($spread[$field], $recommend, 2), '推荐用户收款' . $title . '获得推荐奖', 1);
                }
            }
            if ($res && $res1 && $res2 && $res3) {
                self::commitTrans();
            } else {
                self::rollbackTrans();
            }
            return $res;
        } catch (Exception $e) {
            echo $e->getMessage();
            self::rollbackTrans();
        }
        return false;
    }

    /**
     * 获取支付信息
     * @param $order_id
     */
    public static function getPayment($order_id)
    {
        $info = self::where('order_id', $order_id)->find();
        if ($info) {
            $info = $info->toArray();
            $info['pay_user'] = User::find($info['pay_uid'])->toarray();
            $info['collect_user'] = User::find($info['collect_uid'])->toarray();
        }
        return $info;
    }

    /**
     * 获取列表
     * @param $where
     */
    public static function lst($where)
    {
        $model = new self;
        if (isset($where['data']) && $where['data'] != '') $model = $model->getModelTime($where, $model);
        if (isset($where['pay_type']) && $where['pay_type'] > -1) $model = $model->where('pay_type', $where['pay_type']);
        if (isset($where['way']) && isset($where['way']) != '') {
            switch ($where['way']) {
                case 'pay':
                    if (isset($where['uid']) && $where['uid'] > 0) $model = $model->where('pay_uid', $where['uid']);
                    break;
                case 'collect':
                    if (isset($where['uid']) && $where['uid'] > 0) $model = $model->where('collect_uid', $where['uid']);
                    break;
            }
        } else {
            if (isset($where['uid']) && $where['uid'] > 0) $model = $model->where('pay_uid|collect_uid', $where['uid']);
        }
        if (isset($where['is_tip']) && $where['is_tip'] > -1) $model = $model->where('is_tip', $where['is_tip']);
        $count = $model->count();
        $data = $model->page($where['page'], $where['limit'])->select();
        $data = $data ? $data->toArray() : [];
        foreach ($data as &$v) {
            $v['pay_user'] = User::find($v['pay_uid'])->toarray();
            $v['collect_user'] = User::find($v['collect_uid'])->toarray();
        }
        if (isset($where['excel']) && $where['excel'] == 1) {
            $pay_type = ['收款码', '扫付款码'];
            foreach ($data as $index => $item) {
                $export[] = [
                    $item['order_id'],
                    $item['pay_name'] => $item['pay_user']['real_name'] . ":" . $item['pay_user']['uid'],
                    $item['amount'],
                    $item['collect_name'] => $item['collect_user']['real_name'] . ":" . $item['collect_user']['uid'],
                    $item['add_time'],
                    $item['pay_type'] => $pay_type[$item['pay_type']],
                ];
            }
            PHPExcelService::setExcelHeader(['订单号', '付款人', '金额', '收款人', '时间', '方式', '类型'])
                ->setExcelTile('收付码', '收付码列表' . time(), ' 生成时间：' . date('Y-m-d H:i:s', time()))
                ->setExcelContent($export)
                ->ExcelSave();
        }
        return compact('count', 'data');
    }

    public static function collection($uid)
    {
        $card_no = User::where('uid', $uid)->value('merchant_no');
        if (empty(trim($card_no))) {
            $card_no = User::max('merchant_no');
            if (intval($card_no) < 10000000000) {
                $card_no = "10000000001";
            } else {
                $card_no = str_pad(bcadd($card_no, 1), 11, "0", STR_PAD_LEFT);
            }
            User::edit(['merchant_no' => $card_no], $uid);
        }
        return $card_no;
    }
}