<?php

namespace app\api\service\ucenter;

use think\facade\Db;
use think\facade\Request;
use app\common\enum\Terminal;
use app\common\library\utils\Tool;
use app\common\library\utils\Image;
use app\common\exception\BaseException;
use app\common\model\Users as UsersModel;
use app\common\service\Users as UsersService;
use app\common\service\Config as ConfigService;
use app\common\model\Payment as PaymentModel;
use app\common\enum\UsersLog as UsersLogEnum;
use app\common\model\users\UsersLog as UsersLogModel;
use app\common\enum\UsersWithdraw as UsersWithdrawEnum;
use app\api\model\WithdrawTerminal as WithdrawTerminalModel;
use app\api\model\users\UsersWithdraw as UsersWithdrawModel;
use app\common\model\users\UsersWithdrawalBank as UsersWithdrawalBankModel;

/**
 * @package app\api\service\ucenter
 * @class Withdraw
 * @author xzncit 2024/4/14
 */
class Withdraw {

    /**
     * 提现配置
     * @return array
     */
    public static function getConfig(){
        $config            = ConfigService::getColumns("withdrawal",["status","content"]);
        $config["content"] = !empty($config["content"]) ? explode("\n",trim(str_replace(["\r\n", "\r"],"\n",$config["content"]))) : [];
        $config["amount"]  = UsersService::auth("money","0.00");
        return $config;
    }

    /**
     * 获取支付方式
     * @return WithdrawTerminalModel[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getPaymentList(){
        $type = Terminal::getTerminalNo(Request::header("Client-Type","h5"));
        $condition = [];
        $condition[] = ["terminal","=",$type];
        $condition[] = ["withdraw_terminal.status","=",1];
        $condition[] = ["payment.status","=",1];
        $condition[] = ["payment.code","<>","balance"];
        return WithdrawTerminalModel::withJoin("payment")->where($condition)->order('payment.sort','ASC')->select()->map(function ($value){
            $payment = $value["payment"];
            return [
                "id"        => $payment["id"],
                "code"      => $payment["code"],
                "name"      => ($payment["code"] == "wechat" ? "微信零钱" : $payment["alias_name"]),
                "icon"      => Image::thumb($payment["photo"])
            ];
        });
    }

    /**
     * 获取提现配置
     * @param $params
     * @return array|mixed
     */
    public static function getBank($params=[]){
        if(!isset($params["id"])){
            return [];
        }

        $row = UsersWithdrawalBankModel::where(["user_id"=>UsersService::auth("id"),"pay_id"=>$params["id"]])->find();
        if(empty($row["content"])){
            return [];
        }

        $array       = json_decode($row["content"],true);
        $array["id"] = $row["id"];
        return $array;
    }

    /**
     * 保存提现配置
     * @param $params
     * @return true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function save($params=[]){
        $model = UsersWithdrawalBankModel::where(["user_id"=>UsersService::auth("id"),"pay_id"=>$params["pay_id"]])->find();
        if(empty($model)){
            UsersWithdrawalBankModel::create([
                "user_id"       => UsersService::auth("id"),
                "pay_id"        => $params["pay_id"],
                "content"       => json_encode($params),
                "create_time"   => time()
            ]);
        }else{
            $model->content = json_encode($params);
            $model->save();
        }

        return true;
    }

    public static function order($params=[]){
        $row = UsersWithdrawModel::where(["user_id"=>UsersService::auth("id",0),"status"=>0])->find();
        if(!empty($row)){
            throw new BaseException("您还有提现申请未处理",0);
        }

        if(empty($params["price"])){
            throw new BaseException("",0);
        }

        $config = ConfigService::getArray("withdrawal",0);
        if($params["price"] < $config['amount']){
            throw new BaseException("提现金额不能小于{$config['amount']}元",0);
        }

        if($params["price"] > UsersService::auth("money","0.00")){
            throw new BaseException("您的余额不足",0);
        }

        $payment = PaymentModel::where("id",$params["pay_id"])->find();
        if(empty($payment)){
            throw new BaseException("您选择的汇款方式不存在",0);
        }

        $bankContent = UsersWithdrawalBankModel::where(["user_id"=>UsersService::auth("id"),"pay_id"=>$params["pay_id"]])->value("content");
        if(empty($bankContent)){
            throw new BaseException("请完善提现信息",0);
        }

        $bank = json_decode($bankContent,true);
        if(in_array($payment["code"],["wechat","alipay"])){
            if(empty($bank["real_name"])){
                throw new BaseException("请填写真实姓名",0);
            }

            if(empty($bank["account"])){
                throw new BaseException("请填写绑定帐户",0);
            }
        }else{
            if(empty($bank["real_name"])){
                throw new BaseException("请填写持卡人",0);
            }

            if(empty($bank["bank_name"])){
                throw new BaseException("请填写开户行",0);
            }

            if(empty($bank["bank_code"])){
                throw new BaseException("请填写银行卡号",0);
            }
        }

        $payFee = 0;
        if($config["commission"] > 0){
            $settlementPrice = round(((100 - $config["commission"]) / 100) * $params["price"],2);
            $payFee = round($params["price"] - $settlementPrice,2);
        }else{
            $settlementPrice = $params["price"];
        }

        try{
            UsersWithdrawModel::startTrans();

            UsersModel::where("id",UsersService::auth("id",0))->update([
                "money"=>Db::raw("money-" . $params["price"])
            ]);

            UsersWithdrawModel::create([
                "user_id"           => UsersService::auth("id",0),
                "pay_id"            => $params["pay_id"],
                "order_no"          => orderNo(),
                "pay_fee"           => $payFee,
                "price"             => $params["price"],
                "settlement_price"  => $settlementPrice,
                "status"            => 0,
                "content"           => $bankContent,
                "create_time"       => time()
            ]);
            UsersWithdrawModel::commit();
        }catch (\Exception $ex){
            UsersWithdrawModel::rollback();
        }

        return true;
    }

    public static function wallet($params){
        $array = [
            "total" => 0,
            "list"  => [],
            "size"  => 10
        ];

        $condition   = [];
        $condition[] = ["user_id","=",UsersService::get("id",0)];
        $active      = intval($params["active"]??0);
        if(isset($active) && in_array($active,[1,2])){
            $condition[] = ["operation","=",$active - 1];
        }

        $page          = $params["page"]??1;
        $count         = UsersLogModel::where($condition)->count();
        $array["list"] = UsersLogModel::where($condition)->page($page,$array["size"])->order('id','desc')->select()->map(function ($value){
            return [
                "type"               => UsersLogEnum::getType($value["type"]),
                "operation"          => $value["operation"],
                "value"              => $value["value"],
                "description"        => $value["description"],
                "create_time"        => date("Y-m-d H:i:s",$value["create_time"])
            ];
        });

        $array["total"] = ceil($count / $array["size"]);
        if($array["total"] == $page -1){
            throw new BaseException("没有数据了哦！",-1,$array);
        }

        return $array;
    }

    /**
     * 提现记录
     * @param $params
     * @return array
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getLog($params=[]){
        $array = [
            "total" => 0,
            "list"  => [],
            "size"  => 10
        ];

        $condition   = [];
        $condition[] = ["user_id","=",UsersService::get("id",0)];
        $page  = $params["page"]??1;
        $count = UsersWithdrawModel::withJoin("payment")->where($condition)->count();
        $array["list"] = UsersWithdrawModel::withJoin("payment")->where($condition)->page($page,$array["size"])->order('id','desc')->select()->map(function ($value){
            $payment = $value["payment"];
            $content = json_decode($value["content"],true);
            if(in_array($payment["code"],["wechat","alipay"])){
                $account = Tool::repeat($content["real_name"],1,3) . "|" . Tool::repeat($content["account"],2,3);
            }else{
                $account = Tool::repeat($content["real_name"],1,3) . "|" . Tool::repeat($content["bank_code"],4,3);
            }

            return [
                "account"           => $account,
                "pay_name"          => ($payment["code"] == "wechat" ? "微信零钱" : $payment["alias_name"]),
                "order_no"          => $value["order_no"],
                "pay_fee"           => $value["pay_fee"],
                "price"             => $value["price"],
                "settlement_price"  => $value["settlement_price"],
                "status"            => UsersWithdrawEnum::status($value["status"]),
                "create_time"       => date("Y-m-d H:i:s",$value["create_time"])
            ];
        });

        $array["total"] = ceil($count / $array["size"]);
        if($array["total"] == $page -1){
            throw new BaseException("没有数据了哦！",-1,$array);
        }

        return $array;
    }

}