<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\admin\controller\bbfxshop\yajin;

use app\admin\controller\bbfxshop\Base;
use think\Db;
use app\common\model\bbfxshop\User;


class Refund extends Base
{

    public $model = null;
    public function _initialize(){
        parent::_initialize();
        $this->model = new \app\common\model\bbfxshop\Yajin;
    }
    
    public function getList(){
        $params = $this->param();
        
        $pindex = max(1, intval($params["page"]));
        $psize = intval($params["limit"])?intval($params["limit"]):10;
        $where = array("a.uniacid"=>UNIACID);
        $status = trim($params['status']);
        $startTime = trim($params['startTime']);
        $endTime = trim($params['endTime']);
        
        $keyword = trim($params['keyword']);
        
        $type = max(1,intval($params['type']));
        if(!empty($keyword)){
            
            if($type == 1){
                $where['b.nickname'] = ['like',"%".$keyword."%"];
            }
            else if($type == 2){
                $where['a.user_id'] = intval($keyword);
            }
        }
         
        if($status != ''){
            $where['a.status'] = intval($status);
        }
        
        $whereTime = [];
        if($startTime){
            $startTime = strtotime($startTime." 00:00:00");
            $where['a.createtime'] = ['>=',$startTime];
        }
        
        if($endTime){
            $whereTime['a.createtime'] = ['<=',$endTime];
        }
        
        $list = Db::name("bbfx_yajin_refund_record")->alias("a")->join("bbfx_user b","a.user_id=b.id")->where($where)->where($whereTime)->field('a.*,b.avatar,b.nickname')->order('a.createtime desc')->limit(($pindex - 1) * $psize,$psize)->select();
        
    	foreach($list as &$val){
    	    $val['avatar'] = cdnurl($val['avatar']);
    	    $val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
    	    if($val['shtime']){
    	        $val['shtime'] = date("Y-m-d H:i:s",$val['shtime']);
    	    }
    	    else{
    	        $val['shtime'] = "";
    	    }
    	}
    	unset($val);
      
    	$total = Db::name("bbfx_yajin_refund_record")->alias("a")->join("bbfx_user b","a.user_id=b.id")->where($where)->where($whereTime)->count();
      	
        __success("操作成功",['total'=>$total,'list'=>$list]);
    }
    
    public function shenhe(){
        global $_W;
        $params = $this->param();
        
        $id = intval($params['id']);
        $status = intval($params['status']);
        $refund_money = round($params['refund_money'],2);
        $reason = $params['reason'];
        $log = Db::name("bbfx_yajin_refund_record")->where(["uniacid"=>UNIACID,"id"=>$id])->find();
        if(empty($log)){
            __error("申请记录不存在"); 
        }
        
        if(!in_array($status,[1,2])){
            __error("审核状态错误");  
        }
        
        if($log['status'] != 0){
            __error("已审核");  
        }
        
        try {
            Db::startTrans();
            
            if(empty($reason)){
                $reason = "";
            }
            
            $res = Db::name("bbfx_yajin_refund_record")->where(['id'=>$log['id'],'status'=>0])->update(["shtime"=>time(),"status"=>$status]);
            if($res){
                if($status == 1){
                    Db::name("bbfx_yajin_refund_record")->where(['id'=>$log['id']])->update(['refund_money'=>$refund_money]);
                    if($log['type'] == 2){
                        $user = User::getUser($log['user_id']);
                        
                        $out_batch_no = $log['out_batch_no'];
                        if(empty($out_batch_no)){
                            $out_batch_no = date("YmdHis").random(8,true);
                            Db::name("bbfx_yajin_refund_record")->where(['id'=>$log['id']])->update(['out_batch_no'=>$out_batch_no]);
                        }
                        
                        if($_W['base']['is_merch_transfer_new'] == 1){
                            $res = \app\common\model\bbfxshop\Wxpay::newTransfer($user['openid'],$log['realmoney'],$out_batch_no,$log['realname'],"押金退还",$user['platform']);
                            if($res['code'] != 1){
                                throw new \Exception($res['message']);
                            }
                            $data = [
                                'batch_id'=>$res['data']['transfer_bill_no']
                            ];
                            if(!empty($res['data']['package_info'])){
                                $data['package_info'] = $res['data']['package_info'];
                            }
                            $data['is_confirm'] = 0;
                        }
                        else{
                            $res = \app\common\model\bbfxshop\Wxpay::transfer($user['openid'],$refund_money,$out_batch_no,$log['refund_no'],$log['realname'],"押金退还",$user['platform']);
                            if(empty($res) || $res['code'] != 1){
                                throw new \Exception($res['message']);
                            }
                            $data = [
                                'batch_id'=>$res['data']['batch_id']
                            ];
                        }
                        
                        Db::name("bbfx_yajin_refund_record")->where(['out_batch_no'=>$out_batch_no,'uniacid'=>UNIACID])->update($data);
                    }
                    
                    Db::name("bbfx_yajin_record")->where(['id'=>$log['pid']])->update(['status'=>2,'refundtime'=>time(),'refund_money'=>$refund_money]);
                }
                else{
                    Db::name("bbfx_yajin_refund_record")->where(['id'=>$log['id']])->update(['reason'=>$reason]);
                    $log['notes'] = $reason;
                }
            }
            else{
                throw new \Exception("审核失败");
            }
            
            Db::commit();
        } 
        catch (\Exception $e) {
            Db::rollback();
            __error(0,$e->getMessage());
        }
        
        $dd = ['id'=>$log['id'],'status'=>$status];
        if($status == 1){
            $dd['refund_money'] = $refund_money;
        }
        else{
            $dd['reason'] = $reason;
        }
        \app\admin\model\AdminLog::record("","",$dd,"bbfx_yajin_refund_record");
        
        __success("操作成功"); 
        
    }

     
    public function delete(){
        $this->commonDelete('bbfx_yajin_refund_record');
    }
}