<?php

/**
 * Created by PhpStorm.
 * User: pc
 * Date: 2021/11/24
 * Time: 16:23
 */

namespace app\api\model;

use app\api\controller\shopro\Commission;
use app\admin\model\Addr;
use app\admin\model\device\Chargedevice;
use app\admin\model\device\Chargegroup;
use app\admin\model\device\Site;
use app\admin\model\order\Order;
use app\admin\model\order\Usercontract;
use app\admin\model\shopro\goods\Goods;
use app\admin\model\shopro\order\Goodsorder;
use app\admin\model\shopro\order\Rechargeorder;
use app\admin\model\users\Agent;
use app\admin\model\users\Users;
use think\Config;
use think\Db;
use think\Exception;
use think\Model;
use think\exception\HttpResponseException;
use think\Request;
use think\Response;

class PaymentLogModel extends Model
{
    // 表名
    protected $name = 'payment_logs';

    /**
     * 判断支付金额
     */
    public static function checkPayMoney($pay_log, $amount)
    {
        if (strpos($pay_log['order_sn'], 'D') === 0) {
            $orderinfo = Order::where(['id' => $pay_log['order_id']])->find();
            $chargedevice = Chargedevice::where(['group_id' => $orderinfo['group_id']])->find();
            $need_pay = sprintf("%.2f",$chargedevice['price']*$orderinfo['num']);
        }else if(strpos($pay_log['order_sn'], 'R') === 0){
            $need_pay = Config::get('site.recharge_gift_pack');
        }else if(strpos($pay_log['order_sn'], 'G') === 0){
            $orderinfo = Goodsorder::where(['id' => $pay_log['order_id']])->find();
            $need_pay = sprintf("%.2f",$orderinfo['pay_fee']);
        }

        if ($amount != $need_pay) {
            return false;
        } else {
            return true;
        }

    }

    /**
     * 支付回调
     */
    public static function dealCallBack($message)
    {
        $pay_log = self::where(['order_sn' => $message['out_trade_no']])->find();
        if (!$pay_log || $pay_log['status'] == 2) {
            return false;
        }
        Db::startTrans();
        try {
            self::where(['order_sn' => $pay_log['order_sn']])->update(['status' => 2]); //支付完成
            Users::where(['id' => $pay_log['user_id']])->update(['type' => 2]);
            $orderinfo = Order::where(['id' => $pay_log['order_id']])->find();
            Order::where(['id' => $pay_log['order_id']])->update(['sale_status' => 2]); //订单状态变为已支付
            Usercontract::where(['order_id' =>$pay_log['order_id']])->update(['status' =>1]);//合同显示
            $agentupdate = ['status' => 1];
            if($orderinfo['share_id']){
                $agentupdate['parent_user_id'] = $orderinfo['share_id'];
            }
            Agent::where(['agent_user_id' => $pay_log['user_id'], 'status' => 2])->update($agentupdate); //变为桩主（合伙人）
//            $chargedevice = Chargedevice::where(['charge_device_sn' => $orderinfo['device_sign']])->find();
//            $chargegroup = Chargegroup::where(['id' => $chargedevice['group_id']])->find();
            $chargegroup = Chargegroup::where(['id' => $orderinfo['group_id']])->find();
            $province_id = Addr::where(['ID' => $chargegroup['city_id']])->value('ParentId');
            $site = Site::where(['agent_user_id' => $pay_log['user_id'], 'group_id' => $orderinfo['group_id']])->find();
            if ($site) {
                $site_id = $site['id'];
            } else {
                $site_arr = [
                    'agent_user_id' => $pay_log['user_id'],
                    'province_id' => $province_id,
                    'city_id' => $chargegroup['city_id'],
                    'area_id' => $chargegroup['area_id'],
                    'area_name' => $chargegroup['group_name'],
                    'createtime' => time(),
                    'group_id' => $orderinfo['group_id'],
                ];
                $site = Site::create($site_arr); //新增个人所属站点
                $site_id = $site->id;
            }
            $authorizetime = strtotime(date('Y-m-d', strtotime('+1 day')));
            $update = [
//                'authorizestatus' => 2,
                'user_id' => $pay_log['user_id'],
                'site_id' => $site_id,
//                'authorizetime' => $authorizetime
            ];
            Chargedevice::where(['group_id' =>$orderinfo['group_id'],'user_id' =>0])->order('id asc')->limit($orderinfo['num'])->update($update);
//            Chargedevice::where(['charge_device_sn' => $orderinfo['device_sign']])->update($update);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
        return true;
    }

    /**
     * @param $message
     * 充值支付回调
     */
    public static function dealRechargeBack($message){
        $pay_log = self::where(['order_sn' => $message['out_trade_no']])->find();
        if (!$pay_log || $pay_log['status'] == 2) {
            return false;
        }
        try{
            Db::startTrans();
            self::where(['order_sn' => $pay_log['order_sn']])->update(['status' => 2]); //支付完成
            Rechargeorder::where(['order_sn' =>$message['out_trade_no']])->update(['status' =>'paid']);//已支付
            $userinfo = Users::where(['id' => $pay_log['user_id']])->find();
            $intro = '充值大礼包赠送购物金';
            $before = $userinfo['shopping_money'];
            $after = $before+$pay_log['need_pay'];
            Users::addShoppingmoney($pay_log['user_id'], $pay_log['need_pay'],9,$intro,$pay_log['id'],$pay_log['order_id'],$before,$after);//赠送购物金

            $goodsinfo = Goods::where(['activity_list' =>1])->find();//找出充值大礼包商品
            if($goodsinfo){
                //生成大礼包商品订单
                $goods_data = [
                    'order_sn' =>getOrdersn('goods'),
                    'user_id' =>$pay_log['user_id'],
                    'goods_id' =>$goodsinfo['goods_id'],
                    'activity_list' =>1,
                    'phone' =>$userinfo['mobile'],
                    'consignee' =>$pay_log['user_id'],
//                'province_name' =>$pay_log['user_id'],
//                'city_name' =>$pay_log['user_id'],
//                'area_name' =>$pay_log['user_id'],
//                'address' =>$pay_log['user_id'],
//                'province_id' =>$pay_log['user_id'],
//                'city_id' =>$pay_log['user_id'],
//                'area_id' =>$pay_log['user_id'],
                    'status' =>2,
                    'total_amount' =>$pay_log['need_pay'],
                    'pay_fee' =>$pay_log['need_pay'],
                    'paytime' =>$pay_log['createtime'],
                    'verification_code' =>rand(100000,999999),
                    'createtime' =>time(),
                ];
                Goodsorder::create($goods_data);
            }

            //执行分佣
            Commission::divideCommission($pay_log['order_sn']);
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
        return true;
    }


    /**
     * 商品购买回调
     */
    public static function dealGoodsBack($message){
        $pay_log = self::where(['order_sn' => $message['out_trade_no']])->find();
        if (!$pay_log || $pay_log['status'] == 2) {
            return false;
        }
        try{
            Db::startTrans();
            self::where(['order_sn' => $pay_log['order_sn']])->update(['status' => 2]); //支付完成
            Goodsorder::where(['order_sn' =>$message['out_trade_no']])->update(['status' =>'1','paytime'=>time()]);//已支付
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
        return true;
    }


}
