<?php
/**
 * @package merchant
 *
 * @author xaboy
 * @day 2020-05-06
 *
 *
 */

namespace app\controller\api;

use app\common\repositories\merchant\order\OrderGzcRepository;
use app\common\repositories\merchant\order\OrderMerchantRepository;
use app\common\repositories\user\UserRepository;
use app\controller\api\user\Volunteer;
use app\controller\api\util\Signature;
use app\models\routine\RoutineQrcode;
use app\traits\HaikeApiRequest;
use app\traits\HuiPay;
use app\validate\api\PaymentCreate;
use crmeb\basic\BaseController;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;
use think\facade\Request;

/**
 * Class Auth
 * @package app\controller\api
 * @author xaboy
 * @day 2020-05-06
 */
class Third extends BaseController
{
    use HaikeApiRequest;
    use HuiPay;


    public function thirdRegister(UserRepository $repository)
    {
        $data = $this->request->params(['phone', 'spread', 'sign']);
        Log::channel("gong")->info("三方注册：" . json_encode($data));
        // 校验sign
        $checkSign = Signature::thirdCheckSign($data, Request::header());
        if (!$checkSign) {
            Log::channel("gong")->error('sign校验失败');
            return app('json')->fail('sign校验失败');
        }

        $user = $repository->accountByUser($data['phone']);
        if (!$user) {
            // 注册
            $user = $repository->registr($data['phone'], '', 'THIRD', intval($data['spread']));
            if ($data['spread']) {
                $repository->bindSpread($user, intval($data['spread']));
            }
        }
        $user = $repository->mainUser($user);
        $repository->loginAfter($user);

        $data = Db::name('user')->field('uid,phone,create_time')->where('uid', $user['uid'])->find();
        $data['certification'] = Db::name("user_certification")->field('user_name,mobile,user_card')->where(["uid" => $user['uid'], 'status' => 1])->find();
        $data['unsettled_pension'] = Db::name('gzc_logs')->where('success', 0)->where('uid', $user['uid'])->sum('pension');
        $data['have_already'] = Db::name('gzc_logs')->where('success', 1)->where('uid', $user['uid'])->sum('pension');

        $birth_data = substr($data['certification']["user_card"], 6, 8);
        $birth = strtotime(substr($data['certification']["user_card"], 6, 8));
        $old_age = $this->getSex($data['certification']["user_card"]) ? 60 : 55;
        $age = $this->getAgeByID($birth);
        if ($age < $old_age) {
            $yes = $old_age - $age;
            $data["birthday60"] = date("Y-" . substr($birth_data, 4, 2) . '-' . substr($birth_data, 6, 2), strtotime("+" . $yes . " year"));
        }
        if ($age == $old_age) {
            $data['can_withdraw'] = 1;
            $data["birthday60"] = date("Y-m-d", $birth);
        }
        if ($age > $old_age) {
            $data['can_withdraw'] = 1;
            $yes = $age - $old_age;
            $data["birthday60"] = date("Y-" . substr($birth_data, 4, 2) . '-' . substr($birth_data, 6, 2), strtotime("-" . $yes . " year"));
        }
        return app('json')->success($data);
    }

    public function thirdGzc(UserRepository $repository)
    {
        $data = $this->request->params(['uid', 'pension', 'out_trade_no','sign']);
        Log::channel("gong")->info("三方注册：" . json_encode($data));
        // 校验sign
        $checkSign = Signature::thirdCheckSign($data, Request::header());
        if (!$checkSign) {
            Log::channel("gong")->error('sign校验失败');
            return app('json')->fail('sign校验失败');
        }

        $uid = $data['uid'];
        $pension = $data['pension'];
        $data = Db::name('user')->field('uid,phone,create_time')->where('uid', $uid)->find();
        if (!$data)
            return app('json')->fail('该用户未注册');

        $certification = Db::name("user_certification")->where(["uid" => $uid, 'status' => 1])->find();
        if (!$certification)
            return app('json')->fail('该用户未实名');

        $OrderGzcRepository = app()->make(OrderGzcRepository::class);
        $OrderMerchantRepository = app()->make(OrderMerchantRepository::class);
        Db::transaction(function () use ($uid, $certification, $pension, $OrderGzcRepository, $OrderMerchantRepository,$data) {
            //新增入账明细记录
            $orderId = $OrderMerchantRepository->getNewOrderId('IN10');
            $create = [
                'uid'          => $uid,
                'platform_no'  => $orderId,
                'user_name'    => $certification['user_name'],
                'mobile'       => $certification['mobile'],
                'user_card'    => $certification['user_card'],
                'pension'      => $pension,
                'order_type'   => 10,
                'out_trade_no' => $data['out_trade_no']
            ];
            $test_user = Db::name('user')->where('uid', $uid)->value('test_user');
            if ($test_user == 0) {
                $OrderGzcRepository->create($create);
            }
        });
        return app('json')->success("true");
    }

    public function thirdGzcList(UserRepository $repository)
    {
        $data = $this->request->params(['uid', 'start_time', 'end_time', 'page', 'limit', 'sign']);
        Log::channel("gong")->info("三方注册：" . json_encode($data));
        // 校验sign
        $checkSign = Signature::thirdCheckSign($data, Request::header());
        if (!$checkSign) {
            Log::channel("gong")->error('sign校验失败');
            return app('json')->fail('sign校验失败');
        }

        $data = Db::name('gzc_logs')
            ->field('id,uid,user_name,mobile,user_card,pension,success,create_time')
            ->where('id', '>', 2538)
            ->when($data['uid'], function ($query, $data) {
                $query->where('uid', '=', $data);
            })
            ->when($data['start_time'], function ($query, $data) {
                $query->where('create_time', '>', $data);
            })
            ->when($data['end_time'], function ($query, $data) {
                $query->where('create_time', '<', $data);
            })
            ->page($data['page'], $data['limit'])
            ->select()
            ->toArray();
        return app('json')->success($data);
    }

    public function thirdCertification()
    {
        $data = $this->request->params(['uid', 'mobile', 'user_name', 'user_card', 'sign']);
        Log::channel("gong")->info("三方注册：" . json_encode($data));
        // 校验sign
        $checkSign = Signature::thirdCheckSign($data, Request::header());
        if (!$checkSign) {
            Log::channel("gong")->error('sign校验失败');
            return app('json')->fail('sign校验失败');
        }
        unset($data['sign']);
        $renzeng = Db::name("user_certification")->where("uid", $data['uid'])->find();
        if ($renzeng) {
        } else {
            $res = Db::name('user_certification')->insert($data);
        }

        return app('json')->success([
            'user_name' => $data['user_name'],
            'age'       => $this->getAgeByID($data['user_card']),
            'user_card' => $data['user_card'],
        ]);
    }

    public function payBalance()
    {
        $data = $this->request->params(['money', 'sign']);
        Log::channel("gong")->info("三方支付：" . json_encode($data));
        // 校验sign
        $checkSign = Signature::thirdCheckSign($data, Request::header());
        if (!$checkSign) {
            Log::channel("gong")->error('sign校验失败');
            return app('json')->fail('sign校验失败');
        }
    }

    public function payCreate()
    {
        $data = $this->request->params(['pay_type', 'pay_amt', 'order_no', 'goods_title', 'goods_desc', 'notify_url', 'sign']);
        try {
            validate(PaymentCreate::class)->check($data);
        } catch (ValidateException $exception) {
            return app('json')->fail($exception->getMessage());
        }
        Log::channel("gong")->info("三方注册：" . json_encode($data));
        // 校验sign
        $checkSign = Signature::thirdCheckSign($data, Request::header());
        if (!$checkSign) {
            Log::channel("gong")->error('sign校验失败');
            return app('json')->fail('sign校验失败');
        }
        $payType = $data['pay_type'];
        $payMoney = $data['pay_amt'];
        $pay_user_id = 'oGtg_6KAbu-DKWPIruXccOG5VOmw';
        if ($payType == 'WX') {
            $pay_wx = systemConfig('pay_wx');
            //微信
            if ($pay_wx == 3) {
                $member_id = Db::name('merchant_member')->where('mer_id', 324)->where("type", 3)->value('member_id');

                $key = 'api_live_b0a687ec-5450-4ada-a0e4-65bac0f46871';
                $app_id = 'app_383a75dd-c03d-44ab-8f58-92c60fe9b9d0';
            } else {
                $member_id = Db::name('merchant_member')->where('mer_id', 324)->where("type", 2)->value('member_id');

                $key = 'api_live_90ef02e4-54ac-41ee-adf1-e4927d23d58f';
                $app_id = 'app_0827b960-b932-45ec-b800-4e850091b419';
            }

            $type = '2';
            $pay_channel = 'wx_pub';
            $expend = [
                'open_id' => $pay_user_id
            ];
        } elseif ($payType == 'ALI') {
            $member_id = Db::name('merchant_member')->where('mer_id', 324)->where("type", 1)->value('member_id');
            $app_id = 'app_44108546-d27a-48ee-88c1-84b45b75114f';
            $type = '1';
            $pay_channel = 'alipay_pub';
            $expend = [
                'buyer_id'=>$pay_user_id
            ];
            $key = 'api_live_b23537ed-64b8-45d6-832e-fb228aa9e0a9';
        };
        if ($payMoney == '0.00') {
            $div_members = [
                [
                    'member_id' => 0,
                    'amount'    => sprintf("%01.2f",$payMoney),
                    'fee_flag'  => 'Y'
                ]
            ];
        } else {
            $div_members = [
                [
                    'member_id' => $member_id,
                    'amount'    => sprintf("%01.2f",$payMoney* 0.8) ,
                    'fee_flag'  => 'Y'
                ],
                [
                    'member_id' => 0,
                    'amount'    => sprintf("%01.2f",$payMoney * 0.2),
                    'fee_flag'  => 'N'
                ]
            ];
        }

        $params = [
            'order_no'    => $data['order_no'],
            'app_id'      => $app_id,
            'pay_channel' => $pay_channel,
            'pay_amt'     => (string)sprintf("%01.2f",$payMoney),
            'goods_title' => $data['goods_title'],
            'goods_desc'  => $data['goods_desc'],
            'device_info' => [
                'device_ip' => app('request')->ip()
//                    'device_ip'=>'115.171.134.68'
            ],

            'expend'      => json_encode($expend),
            'div_members' => json_encode($div_members),
            'fee_mode'    => 'I',
            'notify_url'  => $data['notify_url']
        ];

        $res = $this->Payment_create_traits($params, $type, $key);
        if (!empty($res['error_code'])) {
            return app('json')->fail($res['error_msg']);
        } else {
            return app('json')->success($res);
        }
    }


    public function getSex($cid)
    {
        //根据身份证号，自动返回性别
        $sexint = (int)substr($cid, 16, 1);
        return $sexint % 2 === 0 ? false : true;
    }

    public function getAgeByID($id)
    {
        //过了这年的生日才算多了1周岁
        if (empty($id)) return '';
        $date = strtotime(substr($id, 6, 8));
        //获得出生年月日的时间戳
        $today = strtotime('today');
        //获得今日的时间戳
        $diff = floor(($today - $date) / 86400 / 365);
        //得到两个日期相差的大体年数
        //strtotime加上这个年数后得到那日的时间戳后与今日的时间戳相比
        $age = strtotime(substr($id, 6, 8) . ' +' . $diff . 'years') > $today ? ($diff + 1) : $diff;
        return $age;
    }


}
