<?php
namespace app\controller\api\store\order;

use app\common\repositories\merchant\apply\MerchantHaikeApplyRepository;
use app\common\repositories\store\order\StoreGroupOrderRepository;
use app\common\repositories\system\config\ConfigValueRepository;
use crmeb\basic\BaseController;
use app\common\repositories\store\order\StoreCartRepository;
use app\common\repositories\store\order\StoreOrderRepository;
use app\traits\HaikeApiRequest;
use think\App;
use think\facade\Db;
use think\facade\Log;

class MpOrder extends BaseController
{
    use HaikeApiRequest;
    /**
     * @var StoreOrderRepository
     */
    protected $repository;
    /**
     * StoreOrder constructor.
     * @param App $app
     * @param StoreOrderRepository $repository
     */
    public function __construct(App $app, StoreOrderRepository $repository)
    {
        parent::__construct($app);
        $this->repository = $repository;
    }
    //查询商户状态
    public function test(){
        $merch_no = (string)$this->request->param("merch_no", '');
        $res = $this -> merchantInfo(['merch_no' => $merch_no]);
        return app('json')->status('success', $res);
    }
    //配置微信公众号
    public function test1(){
        $merch_no = (string)$this->request->param("merch_no", '');
        $url = env('HAIKE.HOSTNAME')."/api/v1/wx-appid-conf/add";
        $data = [
            "agent_no"=> env('HAIKE.AGENT_NO'),
            "merch_no"=> $merch_no,
            "conf_key"=> "pay_appId",
            "conf_value"=> 'wx10669a2eca032216',
        ];
        $res = $this -> request($data,$url);
        return app('json')->status('success', $res);
    }
    //批量修改商户结算方式申请及变更
    public function merchantWithdrawalSetting(){
        $haikeApplyRepository = app()->make(MerchantHaikeApplyRepository::class);
        $merchant = Db::name("merchant") -> where("withdrawal_setting","D1") -> select();
        foreach ($merchant as $key => $value){
            $response = $haikeApplyRepository->merchantWithdrawalSetting([
                "merch_no"=> $value['merch_no'],
            ]);
            Log::info($response);
        }
    }

    public function notify(){
        try {
            $post = $this->request->post();
            Db::name("log")->insert(array('data'=>'小程序支付回调：'.json_encode($post)));//日志记录
            $bool = $this->doNotify($post);
            if (!$bool)
                return app('json')->success(['result' => 'ERROR']);
            Db::name("log")->insert(array('data'=>'小程序支付回调1：==='));//日志记录
            $store_order = Db::name("store_order") -> where("order_sn",$post['out_trade_no']) -> field('group_order_id,order_id') -> find();
            Db::name("log")->insert(array('data'=>'小程序支付回调2：'.$store_order['group_order_id']));//日志记录
            $groupOrder = app()->make(StoreGroupOrderRepository::class)->getWhere(['group_order_id' => $store_order['group_order_id']]);
            Db::name("log")->insert(array('data'=>'小程序支付回调3：'.json_encode($groupOrder)));//日志记录
            if (!$groupOrder || $groupOrder->paid == 1)
                return app('json')->success(['result' => 'SUCCESS']);
            app()->make(StoreOrderRepository::class)->paySuccess($groupOrder,2);
            app()->make(StoreOrderRepository::class)->takeOrder($store_order['order_id']);

            return app('json')->success(['result' => 'SUCCESS']);
        } catch (\Throwable $e) {
            Log::info($e->getMessage());
            return app('json')->status('error', $e->getMessage());
        }
    }

    /**
     * 聚合公众号支付API
     * @return mixed
     * @author php迷途小书童
     * @created 2021/1/16 10:02
     */
    public function jsapiPay(){

        $id = (string)$this->request->param("id", '');
        $pay_user_id = (string)$this->request->param("pay_user_id", '');

        $order = $this->repository->getDetailByGroupOrderId((int)$id);
        if (!$order)
            return app('json')->fail('订单不存在');

        $orders['trade_type'] = 'WX';
        $orders['merch_no'] = Db::name("merchant")->where("mer_id",$order['mer_id'])->value('merch_no');
        $orders['out_trade_no'] = $order['order_sn'];
        $orders['money'] = $order['pay_price'];
        $orders['pay_user_id'] = $pay_user_id;
        $orders['appid'] = 'wx10669a2eca032216';
        $orders['type'] = 'mp';

        $orders['pension'] = $this -> repository -> ch_rebate($order['mer_id'],$order['pay_price']);

        //商家返佣比例
        $base_commission= merchantConfig($order['mer_id'], 'base_commission');
        if(!$base_commission){
            //若商家返佣比例不存在 则使用平台配置
            $base_commission = systemConfig('extension_one_rate');
        }
        //sat刷卡手续费比例
        $souxufee = systemConfig('yanglao');
        $souxufees = bcmul($order['pay_price'], $souxufee * 0.01, 2);
        $money = bcsub($order['pay_price'], $souxufees, 2);
        $avaiable = bcmul($money,  $base_commission * 0.01, 2);

        //服务商分账的钱
        $service_money = bcsub($avaiable, $orders['pension'], 2);

        $orders['service_money'] = $service_money;

        $notify_url = '/api/mpPay/notify';

        $data = $this->getJsapiPayGateway($orders,$notify_url);

        try {
            if ($data['return_code'] === 10000) {
                $params = [
                    'trade_no' => $data['trade_no'],
                    'channel_trade_no' => $data['channel_trade_no'],
                ];

                Db::name("store_order")->where("order_id",$order['order_id'])->update($params);

                return app('json')->success($data);
            } else {
                return app('json')->fail($data['return_msg']);
            }
        } catch (\Throwable $e) {
            return app('json')->status('error', $e->getMessage(), ['out_trade_no' => $order['order_sn']]);
        }
    }

    public function getOrder(StoreOrderRepository $storeOrderRepository){
        $mer_id = (string)$this->request->param("mer_id", '');
        $status = $this->request->param("status", 1);
        $uid = $this->request->uid();
        [$page, $limit] = $this->getPage();
        $where['mer_id'] = $mer_id;
        $where['uid'] = $uid;
        $where['status'] = $status;
        $where['is_del'] = 0;
        $list = $storeOrderRepository->merchantGetList($where, $page, $limit);
        return app('json')->success($list);
    }


}