<?php

namespace app\adminapi\service\finance;

use app\common\exception\BaseException;
use app\common\service\Users as UsersService;
use think\facade\Db;
use think\facade\Request;
use app\adminapi\controller\Controller;
use app\common\service\Config as ConfigService;
use app\common\model\Users as UsersModel;
use app\adminapi\model\users\UsersWithdraw as UsersWithdrawModel;

/**
 * @package app\adminapi\service\finance
 * @class Setting
 * @author xzncit 2024/4/13
 */
class Finance extends Controller {

    /**
     * 列表
     * @param $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getList($params=[]){
        $array           = [];
        $fields          = [
            ["active"], [ "active"    => $params["active"]??0 ]
        ];
        $array["total"]  = UsersWithdrawModel::withSearch(...$fields)->withJoin(["payment","users"])->count();
        $array["list"]   = UsersWithdrawModel::withSearch(...$fields)->withJoin(["payment","users"])->order("users_withdraw.id","desc")->page($params["current"]??1,$params["size"]??10)->select()->map(function ($value){
            $payment = $value["payment"];
            $users   = $value["users"];
            $content = json_decode($value["content"],true);
            if(in_array($payment["code"],["wechat","alipay"])){
                $account = $content["real_name"] . "|" . $content["account"];
            }else{
                $account = $content["real_name"] . "|" . $content["bank_name"] . "|" . $content["bank_code"];
            }

            return [
                "id"                => $value["id"],
                "username"          => $users["username"],
                "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"            => $value["status"],
                "create_time"       => $value["create_time"]
            ];
        });

        $array["count"] = [
            "0" => UsersWithdrawModel::count(),
            "1" => UsersWithdrawModel::where(["status"=>0])->count(),
            "2" => UsersWithdrawModel::where(["status"=>1])->count(),
            "3" => UsersWithdrawModel::where(["status"=>2])->count()
        ];

        return $array;
    }

    /**
     * 详情
     * @param $id
     * @return array
     * @throws BaseException
     */
    public static function detail($id){
        $value = UsersWithdrawModel::withJoin(["payment","users"])->where("users_withdraw.id",$id)->findOrEmpty()->toArray();
        if(empty($value)){
            throw new BaseException("内容不存在",0);
        }

        $payment = $value["payment"];
        $users   = $value["users"];
        $content = json_decode($value["content"],true);

        return [
            "id"                => $value["id"],
            "users"             => $users,
            "content"           => $content,
            "payment"           => $payment,
            "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"            => $value["status"],
            "create_time"       => $value["create_time"]
        ];
    }

    /**
     * 保存
     * @param $params
     * @return true
     * @throws BaseException
     */
    public static function save($params=[]){
        $row = UsersWithdrawModel::where("id",$params["id"]??0)->findOrEmpty()->toArray();
        if(empty($row)){
            throw new BaseException("内容不存在",0);
        }

        try{
            UsersWithdrawModel::startTrans();

            if($params["status"] == 2){
                UsersModel::where("id",$row["user_id"])->update([
                    "money"=>Db::raw("money+" . $row["price"])
                ]);
            }

            UsersWithdrawModel::where("id",$params["id"]??0)->save([
                "status"        => $params["status"]??0,
                "mark"          => $params["mark"]??"",
                "update_time"   => time()
            ]);

            UsersWithdrawModel::commit();
        }catch (\Exception $ex){
            UsersWithdrawModel::rollback();
            throw new BaseException($ex->getMessage(),0);
        }
        return true;
    }

    /**
     * 删除
     * @param $id
     * @return bool
     */
    public static function delete($id){
        return UsersWithdrawModel::where("id",$id)->delete();
    }

    /**
     * 汇款设置
     * @param $data
     * @return array|bool|mixed|null
     * @throws \think\db\exception\DbException
     */
    public static function setting($data){
        if(Request::isGet()){
            $array = ConfigService::getArray("withdrawal",[]);
            return $array;
        }

        return ConfigService::save("withdrawal",$data);
    }

}