<?php


namespace App\Servers;

use App\Jobs\AutoWithdrawJob;
use App\Models\ErrorRecord;
use App\Models\Goods;
use App\Models\GoodsBrowse;
use App\Models\GoodsImg;
use App\Models\GoodsSearch;
use App\Models\GoodsSpec;
use App\Models\Member;
use App\Models\MemberAddress;
use App\Models\MemberOpenId;
use App\Models\SearchStr;
use App\Models\Shop;
use App\Models\ShopWithdraw;
use App\Models\SpecClass;
use App\Models\SpecKey;
use App\Models\Withdraw;
use App\Models\WithdrawConfig;
use Illuminate\Support\Facades\DB;


/**
 * Redis数据缓存类
 */
class WithdrawServer
{

    private $status_arr = [
        1 => '待审核',
        2 => '已驳回',
        3 => '已完成',
    ];

    private $withdraw_type = [
        1 => '微信转账',
        2 => '线下转账'
    ];
    static private $server = '';


    private function __construct()
    {

    }

    /**
     * 创建对象
     * @return WithdrawServer
     */
    static function creatServer()
    {
        if (empty(self::$server)) {
            self::$server = new  WithdrawServer();
        }
        return self::$server;
    }

    /**
     * 获取订单状态
     * @param $status
     * @return string
     */
    public function getStatusArr($status)
    {
        return empty($this->status_arr[$status]) ? '' : $this->status_arr[$status];
    }

    /**
     * 获取转账类型
     * @param $type
     * @return string
     */
    function getType($type)
    {
        return empty($this->withdraw_type[$type]) ? '无' : $this->withdraw_type[$type];
    }

    function setWithdraw(Member $member, $money)
    {
        $withdraw_config = WithdrawConfig::where('coin_id', 1)->first();
        if ($withdraw_config->{'type'} == 2) {
            $service_money = $withdraw_config->{'proportion'};
        } else {
            $service_money = round($money * $withdraw_config->{'proportion'} / 100, 6);
        }

        $withdraw_info = [
            'm_id' => $member->{'id'},
            'money' => $money,
            'status' => 1,
            'wx_data' => '',
            'service_money' => $service_money,
            'withdraw_money' => $money - $service_money,
        ];
        DB::beginTransaction();
        $withdraw_info = Withdraw::create($withdraw_info);//记录提现信息
        MoneyDetailServer::creatServer()->write(1, 9, $withdraw_info->{'money'}, 0, $withdraw_info->{'m_id'}, '余额提现', $withdraw_info->{'id'});

        //更新会员余额信息
        $this->setIsAuto($withdraw_config,$withdraw_info,1);
        DB::commit();

        return $withdraw_info;
    }

    /**
     * 店铺提现
     * @param Shop $shop
     * @param $money
     * @param $bank_id
     * @return ShopWithdraw|false|\Illuminate\Database\Eloquent\Model
     * @throws \Exception
     */
    function setShopWithdraw(Shop $shop, $money, $bank_id)
    {
        $withdraw_config = WithdrawConfig::where('coin_id', 2)->first();
        if ($withdraw_config->{'type'} == 2) {
            $service_money = $withdraw_config->{'proportion'};
        } else {
            $service_money = round($money * $withdraw_config->{'proportion'} / 100, 6);
        }

        $withdraw_info = [
            'shop_id' => $shop->{'id'},
            'bank_id' => $bank_id,
            'money' => $money,
            'status' => 1,
            'service_money' => $service_money,
            'withdraw_money' => $money - $service_money,
        ];
        DB::beginTransaction();
        $withdraw_info = ShopWithdraw::create($withdraw_info);//记录提现信息
        $ret = ShopMoneyServer::creatServer()->write(1, 4, $withdraw_info->{'money'}, 0, $withdraw_info->{'shop_id'}, '余额提现', $withdraw_info->{'id'});
        if (empty($ret)) {
            DB::rollBack();
            return false;
        }
        //更新会员余额信息
        $this->setIsAuto($withdraw_config,$withdraw_info,2);
        DB::commit();
        return $withdraw_info;
    }

    /**
     * 验证是否满足自动提现
     * @param WithdrawConfig $config
     * @param $withdraw_info
     * @param $type
     */
    function setIsAuto(WithdrawConfig $config, $withdraw_info, $type)
    {
        if ($config->{'auto_money'} > 0 && $config->{'auto_day'} > 0 && $config->{'auto_num'} > 0) {
            if ($withdraw_info->{'money'} > $config->{'auto_money'}) {
                return;
            }
            $start_date = date('Y-m-d H:i:s', strtotime('-' . $config->{'auto_day'} . ' day'));
            if ($type == 1) {
                $withdraw_num = Withdraw::where('m_id', $withdraw_info->{'m_id'})->where('created_at', '>=', $start_date)->where('status', '<>', 3)->count();
            } else {
                $withdraw_num = ShopWithdraw::where('shop_id', $withdraw_info->{'shop_id'})->where('created_at', '>=', $start_date)->where('status', '<>', 3)->count();
            }
            if ($withdraw_num > $config->{'auto_num'}) {
                return;
            }
            AutoWithdrawJob::dispatch($type,$withdraw_info->{'id'})->onConnection('redis')->onQueue('auto_withdraw');
        }
    }

    /**
     * 自动提现功能
     * @param $type
     * @param $withdraw_id
     */
    function sysAutoWithdraw($type,$withdraw_id){
        if($type==1){
            $withdraw_info = Withdraw::where('id',$withdraw_id)->where('status', 1)->first();
            if(empty($withdraw_info)){
                ErrorRecord::create(['m_id' => 0, 'msg' => '提现信息错误', 'data' => $withdraw_id]);
                return;
            }
            $openid = MemberOpenId::where('m_id', $withdraw_info->{'m_id'})->where('type', 1)->value('openid');
            if (empty($openid)) {
                ErrorRecord::create(['m_id' =>  $withdraw_info->{'m_id'}, 'msg' => '当前用户未绑定微信,无法自动提现', 'data' => $withdraw_id]);
                return;
            }
            //转账到微信零钱
            $request = WeixinServer::creatServer()->setVerified('TX' . $withdraw_info->{'id'} . date('YmdHis'), $withdraw_info->{'withdraw_money'}, $openid, '');
            if (empty($request['code'])) {
                ErrorRecord::create(['m_id' =>  $withdraw_info->{'m_id'}, 'msg' => '微信转账失败:'.$withdraw_info->{'id'}, 'data' => json_encode($request)]);
                return;
            } else {
                $wx_data = json_encode($request);
            }
            $withdraw_info->update(['status' => 2, 'withdraw_type' => 1, 'wx_data' => $wx_data]);
        }else{
            //店铺自动审核暂未功能
        }
    }

    function autoWithdraw()
    {
        $list = Withdraw::where('status', 1)->get();
        foreach ($list as $info) {
            $openid = MemberOpenId::where('m_id', $info->{'m_id'})->where('type', 1)->value('openid');
            if (empty($openid)) {
                continue;
            }
            //转账到微信零钱
            $request = WeixinServer::creatServer()->setVerified('TX' . $info->{'id'} . date('YmdHis'), $info->{'withdraw_money'}, $openid, '');
            if (empty($request['code'])) {
                continue;
            } else {
                $wx_data = json_encode($request);
            }
            $info->update(['status' => 2, 'withdraw_type' => 1, 'wx_data' => $wx_data]);
        }
    }


}