<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
/**
 * 核销
 */
class Hexiao extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function __construct(){
        parent::__construct();

        if($this->auth->is_hexiao != 1){$this->error('没有核销权限');}
    }

    //首页
    public function index(){

        $wallet = Db::name('user_wallet')->where(['user_id' => $this->auth->id])->find();

        $rs = [
            'hexiaomoney' => $wallet['hexiaomoney'],
            'takecash'    => $wallet['hexiaomoney'],
            'wait'        => '0.00',
        ];

        $this->success(1,$rs);
    }

    //扫核销码获取订单详情
    //code:order_hexiao_no|2024090466d7c9d5abb1c1
    //order_no:2024090466d7c9d5abb1c1
    public function order_info()
    {

        $code = input('code','');
        if(strpos($code,'order_hexiao_no|') !== 0){
            $this->error('识别不到的订单');
        }

        $order_no = substr($code,16);

        $order_info = Db::name('unishop_order')->where('out_trade_no',$order_no)->find();
        if(empty($order_info)){
            $this->error('不存在的订单');
        }
        if($order_info['status'] != 1){
            $this->error('非正常的订单');
        }
        if($order_info['have_paid'] == 0){
            $this->error('未支付的订单');
        }
        if($order_info['have_hexiao'] != 0){
            $this->error('该订单已核销');
        }

        //下面是从unishop/order.php  detail方法里拿过来的
        $order_id = $order_info['id'];
        $orderModel = new \addons\unishop\model\Order();
        $order = $orderModel
            ->with([
                'products' => function ($query) {
                        $query->field('id,order_id,image,number,price,spec,title,product_id');
                    },

            ])
            ->where(['id' => $order_id])->find();

        if ($order) {
            $order = $order->append(['state', 'paidtime'])->toArray();


            foreach ($order['products'] as &$product) {
                $product['image'] = cdnurl($product['image']);
            }

            unset($order['pay_out_trade_no']);



        }

        $this->success(1,$order);
    }

    //完成核销动作
    public function hexiao(){

        $code = input('code','');
        if(strpos($code,'order_hexiao_no|') !== 0){
            $this->error('识别不到的订单');
        }

        $out_trade_no = substr($code,16);

        Db::startTrans();
        $order = Db::name('unishop_order')->where(['out_trade_no' => $out_trade_no])->lock(true)->find();

        if(empty($order)){
            Db::rollback();
            $this->error('不存在的订单');
        }

        if($order['status'] != 1){
            Db::rollback();
            $this->error('非正常的订单');
        }
        if($order['have_paid'] == 0){
            Db::rollback();
            $this->error('未支付的订单');
        }
        if($order['have_hexiao'] != 0){
            Db::rollback();
            $this->error('该订单已核销');
        }


        $update = [
            'have_hexiao' => time(),
            'hexiao_uid'    => $this->auth->id,
        ];
        $order_rs = Db::name('unishop_order')->where('id',$order['id'])->update($update);
        if($order_rs === false){
            Db::rollback();
            $this->error('核销失败');
        }

        //给核销人结算
        $bili = config('site.hexiao_order_money_bili');

        $money = bcdiv(bcmul($order['total_price'],$bili,2),100,2);

        if($money > 0){
            $rs_wallet = model('Wallet')->lockChangeAccountRemain($this->auth->id,'hexiaomoney',$money,201,'核销订单:'.$out_trade_no,'unishop_order',$order['id']);
            if($rs_wallet['status']===false)
            {
                Db::rollback();
                $this->error($rs_wallet['msg']);
            }
        }


        Db::commit();
        $this->success('核销成功');
    }

    //核销统计
    public function order_sum(){
        $startdate = input('startdate',date('Y-m-d'));
        $enddate   = input('enddate'  ,date('Y-m-d'));

        $starttime = strtotime($startdate);
        $endtime   = strtotime($enddate) + 86399;

        $condition = [
            'hexiao_uid' => $this->auth->id,
            'status'     => 1,
            'have_paid'         => ['gt',0],
            'have_delivered'    => ['gt',0],
            'have_hexiao'     => ['gt',0],
        ];
        $count = Db::name('unishop_order')->where($condition)->where('have_hexiao','BETWEEN',[$starttime,$endtime])->count();
        $total_price = Db::name('unishop_order')->where($condition)->where('have_hexiao','BETWEEN',[$starttime,$endtime])->sum('total_price');

        $rs = [
            'count' => $count,
            'total_price' => $total_price,
        ];
        $this->success(1,$rs);
    }

    //核销记录
    public function order_list(){
        $startdate = input('startdate',date('Y-m-d'));
        $enddate   = input('enddate'  ,date('Y-m-d'));

        $starttime = strtotime($startdate);
        $endtime   = strtotime($enddate) + 86399;

        $orderModel = new \addons\unishop\model\Order();

        $condition = [
            'hexiao_uid' => $this->auth->id,
            'status'     => 1,
            'have_paid'         => ['gt',0],
            'have_delivered'    => ['gt',0],
            'have_hexiao'     => ['gt',0],
        ];
        $result = $orderModel
            ->with([
                'products' => function($query) {
                        $query->field('id,title,image,number,price,spec,order_id,product_id');
                    },

            ])
            ->where($condition)
            ->where('have_hexiao','BETWEEN',[$starttime,$endtime])
            ->order(['have_hexiao' => 'desc'])
            ->autopage()
            ->select();



        foreach ($result as &$item) {
            $item->append(['order_id','state']);
            $item = $item->toArray();

            unset($item['pay_out_trade_no']);



            foreach ($item['products'] as &$product) {
                $product['image'] = cdnurl($product['image']);

            }

        }

        $this->success(1,$result);


    }

    //我的核销余额日志
    public function my_intromoney_log(){
        $type = input('type',0);

        $map = [
            'user_id' => $this->auth->id,
        ];

        if($type == 1){
            $map['change_value'] = ['gt',0];
        }
        if($type == 2){
            $map['change_value'] = ['lt',0];
        }

        $list = Db::name('user_intromoney_log')
            ->field('id,log_type,before,change_value,remain,remark,createtime')
            ->where($map)->order('id desc')->autopage()->select();
//        $list = $this->list_appen_logtext($list);

        $this->success('success',$list);
    }

    //提现配置
    public function take_cash_config(){

        $plat_bilv      = config('site.hexiao_takecash_plat_bili');
        $take_cash_days = config('site.hexiao_takecash_days');
        $take_cash_days_str = implode(',',$take_cash_days);

        $data = [
            'hexiaomoney' => model('wallet')->getwallet($this->auth->id,'hexiaomoney'),
            'plat_bilv'   => $plat_bilv,
            'user_bank'   => Db::name('user_bank')->where('user_id',$this->auth->id)->find(),
            'take_cash_days' => $take_cash_days_str,
            'remark'         => '每月'.$take_cash_days_str.'日可以提现',
            'take_cash_button' => in_array(date('d'),$take_cash_days) ? 1 : 0,
        ];

        $this->success('success',$data);
    }

    //提现before
    public function take_cash_before(){
        $freemoney = input('freemoney',0);
        if(!$freemoney){
            $this->error('请填写金额');
        }

        $money = floatval($freemoney);

        if($money<=0)
        {
            $this->error('金额必须大于0');
        }

        $min = config('site.hexiao_takecash_min_money');
        $max = config('site.hexiao_takecash_max_money');
        if($money < $min){
            $this->error('提现金额不能小于'.$min);
        }
        if($money > $max){
            $this->error('提现金额不能大于'.$max);
        }

        $user_money = model('wallet')->getwallet($this->auth->id,'hexiaomoney');
        if($money > $user_money){
            $this->error('提现金额不能大于可提现余额');
        }

        //平台手续费
        $plat_bilv = config('site.hexiao_takecash_plat_bili');
        $plat_money = bcdiv(bcmul($money,$plat_bilv,2),100,2);

        //减去手续费，得实得金额
        $get_money = bcsub($money,$plat_money,2);

        $data = [
            'money'      => $money,
            'plat_bilv'  => $plat_bilv,
            'plat_money' => $plat_money,
            'get_money'  => $get_money,
        ];
        $this->success(1,$data);
    }

    //提现
    public function take_cash(){
        $freemoney = input('freemoney',0);
//        $type = input('type',1);
        $type = 2;

        if(!$freemoney){
            $this->error('请填写金额');
        }

        if (!in_array($type,[1,2,3])) {
            $this->error('未知的提现类型');
        }

        //提现日期限制
        $take_cash_days = config('site.hexiao_takecash_days');
        if(!in_array(date('d'),$take_cash_days)){
            $take_cash_days_str = implode(',',$take_cash_days);
            $this->error('每月'.$take_cash_days_str.'日才可以提现');
        }


        //赋值money
        /*if($rc_id){
            $recharge_config = Db::name('take_cash_config')->where('id',$rc_id)->find();
            $money = $recharge_config['money'] ?: 0;
        }*/

        //自由输入覆盖
        if(!empty($freemoney)){
            $rc_id = 0;
            $money = floatval($freemoney);
        }

        //
        if($money<=0)
        {
            $this->error('金额必须大于0');
        }

        $min = config('site.hexiao_takecash_min_money');
        $max = config('site.hexiao_takecash_max_money');
        if($money < $min){
            $this->error('提现金额不能小于'.$min);
        }
        if($money > $max){
            $this->error('提现金额不能大于'.$max);
        }

        $check = Db::name('hexiao_user_take_cash')->where(['user_id'=>$this->auth->id,'status'=>0])->find();
        if($check){
            $this->error('您已经申请了提现,请等待审核');
        }

        $user_money = model('wallet')->getwallet($this->auth->id,'hexiaomoney');
        if($money > $user_money){
            $this->error('提现金额不能大于可提现余额');
        }

        if($type == 1){
            $table_name = 'user_alipay';
            $account_json = Db::name($table_name)->where('user_id',$this->auth->id)->find();
            if(empty($account_json)){
                $this->error('未绑定对应的提现账号');
            }
        }elseif($type == 2){
            $table_name = 'user_bank';
            $account_json = Db::name($table_name)->where('user_id',$this->auth->id)->find();
            if(empty($account_json)){
                $this->error('未绑定对应的提现账号');
            }
        }elseif($type == 3){
            //微信支付
            $table_name = 'user_wechat';
            $account_json = Db::name($table_name)->where('user_id',$this->auth->id)->find();
            if(empty($account_json)){
                $this->error('未绑定对应的提现账号');
            }
        }

        //平台手续费
        $plat_bilv = config('site.hexiao_takecash_plat_bili');
        $plat_money = bcdiv(bcmul($money,$plat_bilv,2),100,2);

        //减去手续费，得实得金额
        $get_money = bcsub($money,$plat_money,2);

        $data = [
            'user_id' => $this->auth->id,
            'money' => $money,
            'plat_bilv'  => $plat_bilv,
            'plat_money' => $plat_money,
            'get_money'  => $get_money,
            'type' => $type,
            'acount_json' => json_encode($account_json),
            'createtime' => time(),
            'updatetime' => time(),
            'status' => 0,
        ];
        Db::startTrans();

        $log_id = Db::name('hexiao_user_take_cash')->insertGetId($data);
        if(!$log_id){
            Db::rollback();
            $this->error('提现失败');
        }

        //扣除money
        $rs_wallet = model('Wallet')->lockChangeAccountRemain($this->auth->id,'hexiaomoney',-$money,221,'提现(审核中)','hexiao_user_take_cash',$log_id);
        if($rs_wallet['status']===false)
        {
            Db::rollback();
            $this->error($rs_wallet['msg']);
        }

        Db::commit();
        $this->success('申请成功请等待审核');
    }

    //提现记录
    public function take_cash_log(){
        $list = Db::name('hexiao_user_take_cash')->field('id,money,get_money,type,createtime,status')->where(['user_id'=>$this->auth->id])->autopage()->select();
        foreach($list as $key => &$val){
            $val['remark'] = '';

            if($val['type'] == 1){
                $val['remark'] = '支付宝提现';
            }elseif($val['type'] == 2){
                $val['remark'] = '银行卡提现';
            }else{
                $val['remark'] = '微信提现';
            }
        }

        $this->success('success',$list);
    }

}
