<?php

namespace Server\payment\web;

use App\Models\CorePaylog;
use App\Services\PayService;
use Server\payment\PaymentService;

class IndexController extends PaymentService {

    public function gencert(){
        $res = $this->WechatGenCert();
        if (is_error($res)) return $res;
        if (is_string($res) && !empty($res)){
            $search = str_replace("\\", "/", SERVICE_PAYMENT);
            $platform_cert = str_replace($search, "", $res);
            $data = $this->configs;
            $data['wechat']['platform_cert'] = $platform_cert;
            $data['wechat']['platform_date'] = TIMESTAMP;
            if (!$this->SettingSave('payment', $data, $this->uniacid)){
                return $this->error("保存失败，请重试");
            }
        }
        return $this->success("配置成功！", referer());
    }

    public function main(){
        global $_GPC;
        $where = "uniacid=:uniacid";
        $params = array(":uniacid"=>$this->uniacid);
        if (!empty($_GPC['keyword'])){
            $where .= " and (tid=:tid or uniontid=:uniontid)";
            $params[':uniontid'] = $params[':tid'] = trim($_GPC['keyword']);
        }
        $page = max(1, intval($_GPC['page']));
        $limit = ($page-1)*15;
        $list = pdo_fetchall("select * from ".tablename($this->tablePayLog)." where $where order by plid desc limit $limit,15", $params);
        $total = pdo_fetchcolumn("select count(*) from ".tablename($this->tablePayLog)." where $where", $params);
        if (!empty($list)){
            $colors = array('orange','green','cyan','red','black');
            foreach ($list as &$value){
                $value['payment'] = $this->payments[$value['type']];
                $value['state'] = $this->states[$value['status']];
                $value['badge'] = $colors[$value['status']];
            }
        }
        return $this->View(array(
            'title'=>"支付记录",
            'list'=>$list,
            'total'=>$total,
            'pager'=>pagination($total, $page)
        ));
    }

    public function setting(){
        $this->Composer();
        if (checksubmit()){
            global $_GPC;
            $data = array();
            $data['credit'] = array(
                'pay_switch'=>intval($_GPC['credit_switch'])
            );
            $alipay = $_GPC['alipay'];
            $alipay['sign_type'] = trim($alipay['sign_type']);
            $alipay['pay_switch'] = intval($alipay['pay_switch']);
            $alipay['recharge_switch'] = intval($alipay['recharge_switch']);
            if (empty($_GPC['alipay_switch'])){
                $alipay['pay_switch'] = $alipay['recharge_switch'] = 0;
            }
            $data['alipay'] = $alipay;
            $wechat = $_GPC['wechat'];
            $wechat['pay_switch'] = intval($wechat['pay_switch']);
            $wechat['recharge_switch'] = intval($wechat['recharge_switch']);
            $wechat['app_switch'] = intval($wechat['app_switch']);
            $wechat['h5_switch'] = intval($wechat['h5_switch']);
            $wechat['use_public_cert'] = intval($wechat['use_public_cert']);
            if (empty($_GPC['wechat_switch'])){
                $wechat['pay_switch'] = $wechat['recharge_switch'] = 0;
            }
            if ($wechat['apiclient_cert']!=$this->configs['wechat']['apiclient_cert']){
                if (!empty($wechat['apiclient_cert'])){
                    //保存新的API证书
                    $cert = $this->saveCert($wechat['apiclient_cert']);
                    if (is_error($cert)) return $cert;
                    $data['wechat_refund']['cert'] = file_get_contents($cert);
                }else{
                    //删除API证书
                    $this->removeCert();
                    $data['wechat_refund']['cert'] = '';
                }
            }
            if ($wechat['apiclient_key']!=$this->configs['wechat']['apiclient_key']){
                if (!empty($wechat['apiclient_key'])){
                    //保存新的API证书
                    $key = $this->saveCert($wechat['apiclient_key'],'key');
                    if (is_error($key)) return $key;
                    $data['wechat_refund']['key'] = file_get_contents($key);
                }else{
                    //删除API证书
                    $this->removeCert('key');
                    $data['wechat_refund']['key'] = '';
                }
            }
            // 处理公钥证书上传
            if ($wechat['public_cert']!=$this->configs['wechat']['public_cert']){
                if (!empty($wechat['public_cert'])){
                    //保存新的公钥证书
                    $publicCert = $this->saveCert($wechat['public_cert'],'public_cert');
                    if (is_error($publicCert)) return $publicCert;
                }else{
                    //删除公钥证书
                    $this->removeCert('public_cert');
                }
            }
            $data['wechat'] = $wechat;
            if (!$this->SettingSave('payment', $data, $this->uniacid)){
                return $this->error("保存失败，请重试");
            }
            return $this->success("保存成功！", $this->url('setting'));
        }
        return $this->View(array(
            'setting'=>$this->configs,
            'title'=>"支付参数"
        ));
    }

    public function upload(){
        $storage = serv('storage', $this->uniacid);
        if (!$storage->enabled) return $this->error("uploadFailed");
        $uploadConfig = $storage->settings['upload']['file']['extentions'];
        if (!in_array("pem", $uploadConfig)){
            $uploadConfig[] = "pem";
            $storage->settings['upload']['file']['extentions'] = $uploadConfig;
        }
        $res = $storage->saveFile("file", "file");
        if (is_error($res)){
            return $res;
        }
        return $this->success($res);
    }

    public function removeCert($name='cert'){
        $filename = md5($this->uniacid.$name.$GLOBALS['_W']['config']['setting']['authkey']);
        return @unlink(SERVICE_PAYMENT."cert/$filename.crt");
    }

    public function saveCert($file, $name='cert'){
        $path = storage_path("app/public/$file");
        if (!file_exists($path)) return $this->error("找不到证书文件");
        $certInfo = file_get_contents($path);
        $res = $this->WechatEecrypt($certInfo, $name);
        if (is_error($res)) return $res;
        if (serv('storage')->removeFile($file)){
            pdo_delete("core_attachment", array('attachment'=>$file, 'uniacid'=>$this->uniacid));
        }
        return $res;
    }

    public function dorefund(){
        global $_GPC;
        $detail = pdo_get($this->tablePayLog, array('plid'=>intval($_GPC['pid'])));
        $result = $this->Refund($detail);
        if (is_error($result)) return $result;
        return $this->success($result['status']=='SUCCESS'?"退款成功！":"已发起退款！", $this->url());
    }

    public function payDemo(){
        global $_W;
        $payment = request()->input("type", "alipay");
        $testfee = 0.1 + (random(1,true) / 100);
        $orderinfo = [
            'openid'=>$_W['uid'],
            'tid'=>random(10),
            'fee'=>$testfee,
            'type'=>$payment,
            'tag'=>"测试充值{$testfee}元",
            'is_usecard'=>0,
            'card_type'=>0,
            'card_id'=>0,
            'card_fee'=>0,
            'encrypt_code'=>random(6,true),
            'is_wish'=>0
        ];
        try {
            //创建系统支付记录
            CorePaylog::create($orderinfo);
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }

        return $this->success(array(
            'url'=>$this->api($payment, ['tid'=>$orderinfo['tid']], 'app'),
            'amount'=>$testfee
        ));
    }

}
