<?php
// +----------------------------------------------------------------------
// | A3Mall
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzncit <158373108@qq.com>
// +----------------------------------------------------------------------

namespace app\adminapi\service;

use app\common\exception\BaseException;
use app\common\model\Payment as PaymentModel;
use app\adminapi\model\PaymentTerminal as PaymentTerminalModel;
use app\common\library\utils\Image;
use think\facade\Request;

/**
 * @package app\adminapi\service
 * @class Payment
 * @author xzncit 2024-02-23
 */
class Payment {

    /**
     * 列表
     * @return PaymentModel[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getList(){
        return PaymentModel::where("code","<>","bank")->order("sort","ASC")->select()->map(function ($res){
            $res["photo"] = Image::thumb($res["photo"]);
            return $res;
        });
    }

    /**
     * 支付方式
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getTerminalList(){
        $result = PaymentTerminalModel::withJoin(["payment"=>["name","photo"]])->where("terminal != 8")->order("sort","ASC")->select()->toArray();
        $array  = [];

        foreach($result as $value){
            $value["photo"] = Image::thumb($value["photo"]);
            $array[$value["terminal"]][] = $value;
        }

        return $array;
    }

    /**
     * 详情
     * @param $id
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function detail($id){
        $row = PaymentModel::where("id",$id)->find();
        if(empty($row)){
            return [];
        }

        $config        = !empty($row["config"]) ? json_decode($row["config"],true) : [];
        $row["photo"]  = Image::thumb($row["photo"]);
        $row["config"] = array_merge(self::getOptions($row["code"]),$config);
        return $row;
    }

    /**
     * 保存
     * @param array $params
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function save($params=[]){
        $row = PaymentModel::where("id",$params["id"]??0)->find();
        if(empty($row)){
            throw new \Exception("您要修改的数据不存在",0);
        }

        if(!empty($params["photo"])){
            $params["photo"] = Image::parseUrl($params["photo"]);
        }

        if($row["code"] == "wechat"){
            $apiclientCert = root_path() . "runtime/payment/wechat/apiclient_cert.pem";
            $apiclientKey  = root_path() . "runtime/payment/wechat/apiclient_key.pem";

            if(!file_exists(dirname($apiclientCert))){
                mkdir(dirname($apiclientCert),0777,true);
            }

            if(empty($params["config"]["mchcert_cert"])){
                file_exists($apiclientCert) && unlink($apiclientCert);
            }else{
                file_put_contents($apiclientCert,$params["config"]["mchcert_cert"]);
            }

            if(empty($params["config"]["mchcert_key"])){
                file_exists($apiclientKey) && unlink($apiclientKey);
            }else{
                file_put_contents($apiclientKey,$params["config"]["mchcert_key"]);
            }
        }

        $params["config"] = !empty($params["config"]) ? json_encode($params["config"],JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK) : [];
        PaymentModel::where("id",$params["id"]??0)->save($params);
        return true;
    }

    /**
     * 修改字段状态
     * @param array $params
     * @return bool
     * @throws BaseException
     */
    public static function status($params=[]){
        if(!in_array($params["type"],["status","is_default"])){
            throw new BaseException("error status",0);
        }

        $data = [ $params["type"]=>intval($params["value"]??0) ];
        if($params["type"] == "status"){
            PaymentTerminalModel::where("id",$params["id"]??0)->update($data);
        }else{
            $row = PaymentTerminalModel::where("id",$params["id"]??0)->find();
            PaymentTerminalModel::where("terminal",$row["terminal"])->update(["is_default"=>0]);
            PaymentTerminalModel::where("id",$params["id"]??0)->update($data);
        }

        return true;
    }

    /**
     * @param string $code
     * @return array|mixed
     */
    public static function getOptions($code=""){
        $array = [
            "balance" =>[],
            "wechat"  =>[
                "version"       => 3,
                "type"          => 1,
                "mchid"         => "",        // 微信支付商户号
                "mchkey"        => "",        // 设置APIv3密钥
                "mchserial"     => "",        // 证书序列号
                "mchcert_key"   => "",        // 证书 KEY
                "mchcert_cert"  => "",        // 证书 CERT
                "domain"        => Request::domain()
            ],
            "alipay"  =>[
                "mode"          => 1,
                "type"          => 1,
                "appid"         => "",        // APPID
                "private_key"   => "",        // 私钥字符
                "public_key"    => ""         // 支付宝公钥
            ]
        ];

        return $array[$code]??[];
    }

}