<?php
/**
 *
 * @author: xaboy<365615158@qq.com>
 * @day: 2018/3/3
 */

namespace app\admin\model\system;

use crmeb\basic\BaseModel;
use crmeb\services\workerman\ChannelService;
use crmeb\traits\ModelTrait;


/**
 * TODO 用户提现
 * Class UserExtract
 * @package app\models\user
 */
class StoreExtract extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

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

    use ModelTrait;

    //审核中
    const AUDIT_STATUS = 0;
    //未通过
    const FAIL_STATUS = -1;
    //已提现
    const SUCCESS_STATUS = 1;

    protected static $extractType = ['alipay', 'bank', 'weixin'];

    protected static $extractTypeMsg = ['alipay' => '支付宝', 'bank' => '银行卡', 'weixin' => '微信'];

    protected static $status = array(
        -1 => '未通过',
        0 => '审核中',
        1 => '已提现'
    );

    /**
     * 用户自主提现记录提现记录,后台执行审核
     * @param array $userInfo 用户个人信息
     * @param array $data 提现详细信息
     * @return bool
     */
    public static function userExtract($userInfo, $data)
    {
        if (!in_array($data['extract_type'], self::$extractType))
            return self::setErrorInfo('提现方式不存在');
        $userInfo = SystemStore::get($userInfo['id']);
        $extractPrice = $userInfo['money'];
        if ($extractPrice < 0) return self::setErrorInfo('提现余额不足' . $data['money']);
        if ($data['money'] > $extractPrice) return self::setErrorInfo('提现余额不足' . $data['money']);
        if ($data['money'] <= 0) return self::setErrorInfo('提现余额大于0');
        $balance = bcsub($userInfo['money'], $data['money'], 2);
        $commission = bcmul($data['money'], bcdiv($userInfo['commission'], 100, 3), 2);
        if ($balance < 0) $balance = 0;
        $insertData = [
            'uid' => $userInfo['id'],
            'extract_type' => $data['extract_type'],
            'extract_price' => $data['money'],
            'add_time' => time(),
            'balance' => $balance,
            'status' => self::AUDIT_STATUS,
            'commission' => $commission,
        ];
        if (isset($data['name']) && strlen(trim($data['name']))) $insertData['real_name'] = $data['name'];
        else $insertData['real_name'] = $userInfo['nickname'];
        if (isset($data['cardnum'])) $insertData['bank_code'] = $data['cardnum'];
        else $insertData['bank_code'] = '';
        if (isset($data['bankname'])) $insertData['bank_address'] = $data['bankname'];
        else $insertData['bank_address'] = '';
        if (isset($data['weixin'])) $insertData['wechat'] = $data['weixin'];
        else $insertData['wechat'] = $userInfo['nickname'];
        if ($data['extract_type'] == 'alipay') {
            if (!$data['alipay_code']) return self::setErrorInfo('请输入支付宝账号');
            $insertData['alipay_code'] = $data['alipay_code'];
            $mark = '使用支付宝提现' . $insertData['extract_price'] . '元，手续费:' . $insertData['commission'] . ",实际到账:" . bcsub($insertData['extract_price'], $insertData['commission'], 2);
        } else if ($data['extract_type'] == 'bank') {
            if (!$data['cardnum']) return self::setErrorInfo('请输入银行卡账号');
            if (!$data['bankname']) return self::setErrorInfo('请输入开户行信息');
            $mark = '使用银联卡' . $insertData['bank_code'] . '提现' . $insertData['extract_price'] . '元，手续费:' . $insertData['commission'] . ",实际到账:" . bcsub($insertData['extract_price'], $insertData['commission'], 2);
        } else {
            if (!$data['weixin']) return self::setErrorInfo('请输入微信账号');
            $mark = '使用微信提现' . $insertData['extract_price'] . '元';
        }
        self::beginTrans();
        try {
            $res1 = self::create($insertData);
            if (!$res1) return self::setErrorInfo('提现失败');
            $res2 = SystemStore::edit(['money' => $balance], $userInfo['id'], 'id');
            $res3 = StoreBill::expend('提现', $userInfo['id'], 'extract', $data['money'], $res1['id'], $balance, $mark);
            $res = $res2 && $res3;
            if ($res) {
                self::commitTrans();
                //发送模板消息
                return true;
            } else return self::setErrorInfo('提现失败!');
        } catch (\Exception $e) {
            self::rollbackTrans();
            return self::setErrorInfo('提现失败!');
        }
    }

    /**
     * 获得用户提现总金额
     * @param $uid
     * @return mixed
     */
    public static function userExtractTotalPrice($uid, $status = 1, $where = [])
    {
        return self::getModelTime($where, self::where('uid', 'in', $uid)->where('status', $status))->sum('extract_price') ?: 0;
    }

    public static function extractStatistics()
    {
        //待提现金额
        $data['price'] = floatval(self::where('status', 0)->sum('extract_price'));
        //总获得
        $data['brokerage_count'] = StoreBill::getBrokerageCount();
        //已提现金额
        $data['priced'] = floatval(self::where('status', 1)->sum('extract_price'));
        //未提现金额
        $data['brokerage_not'] = bcsub(bcsub($data['brokerage_count'], $data['priced'], 2), $data['price'], 2);
        return compact('data');
    }

    /**
     * @param $where
     * @return array
     */
    public static function systemPage($where)
    {
        $model = new self;
        if ($where['date'] != '') {
            list($startTime, $endTime) = explode(' - ', $where['date']);
            $model = $model->where('a.add_time', '>', strtotime($startTime));
            $model = $model->where('a.add_time', '<', (int)bcadd(strtotime($endTime), 86400, 0));
        }
        if ($where['status'] != '') $model = $model->where('a.status', $where['status']);
        if ($where['extract_type'] != '') $model = $model->where('a.extract_type', $where['extract_type']);
        if ($where['nireid'] != '') $model = $model->where('a.real_name|a.id|b.name|a.bank_code|a.alipay_code', 'like', "%$where[nireid]%");
        $model = $model->alias('a');
        $model = $model->field('a.*,b.name as store_name');
        $model = $model->join('system_store b', 'b.id=a.store_id', 'LEFT');
        $model = $model->order('a.id desc');
        return self::page($model, $where);
    }

    public static function changeFail($id, $fail_msg)
    {
        $fail_time = time();
        $data = self::get($id);
        $extract_number = $data['extract_price'];
        $mark = '提现失败,退回' . $extract_number . '元';
        $uid = $data['store_id'];
        $status = -1;
        $User = SystemStore::where('id', $uid)->find()->toArray();
        StoreBill::income('提现失败', $uid, 'extract_fail', $extract_number, $id, bcadd($User['money'], $extract_number, 2), $mark);
        SystemStore::bcInc($uid, 'money', $extract_number, 'id');
        return self::edit(compact('fail_time', 'fail_msg', 'status'), $id);
    }

    public static function changeSuccess($id)
    {
        return self::edit(['status' => 1], $id);
    }
}