<?php
/**
 * Created by PhpStorm.
 * User: blade
 * Date: 2018/1/12
 * Time: 18:42
 */

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request as Req;
use Illuminate\Support\Facades\App;
use Request;

class RedbagController extends Controller{
    //页面
    function Index(Req $req){
        $request['red_type']=isset($req->red_type)?trim($req->red_type):null;
        $request['system_user']=isset($req->system_user)?trim($req->system_user):null;
        $request['input_order']=isset($req->account_name)?trim($req->account_name):null;
        $request['startime']=isset($req->startime)?trim($req->startime):null;
        $request['endtime']=isset($req->endtime)?trim($req->endtime):null;


        $dt = \App\Lib\DataTable\DataTable::init();
        $dt->setDataSource('/admin/Redbag/getList');
        $dt->setLang('redBag');
        $dt->addColsFields('red_type', array('templet' => '#red_type', 'sort' => false,'width'=>120));
        $dt->addColsFields('system_user', array('sort' => false,'width'=>140));
        $dt->addColsFields('create_time', array('sort' => false,'width'=>190));
        $dt->addColsFields('input_order', array('sort' => false,'width'=>240));
        $dt->addColsFields('input_reason', array('sort' => false));
//        $dt->addColsFields('input_rule', array('sort' => false,'templet' => '#input_rule'));//暂时无用，注释
        $dt->addColsFields('sum_money', array('sort' => false,'width'=>100));
        $dt->addColsFields('success_money', array('sort' => false,'width'=>100));
        $dt->addColsFields('sum_user', array('sort' => false));
        $dt->addColsFields('suescc_user', array('sort' => false));//成功人数
        $dt->addColsFields('fail_user', array('sort' => false));//失败人数
        return view('admin.redBag/index', $dt->render($request));

    }
    //数据源
    function getList(Req $req){
        $red_type=isset($req->red_type)?trim($req->red_type):null;
        $system_user=isset($req->system_user)?trim($req->system_user):null;
        $input_order=isset($req->account_name)?trim($req->account_name):null;
        $startime=isset($req->startime)?trim($req->startime):null;
        $endtime=isset($req->endtime)?trim($req->endtime):null;
        $list=isset($req->limit)?trim($req->limit):50;
        $where=array();
        if(!empty($red_type)){
            $where[]=array('red_type',$red_type);
        }
        $db=new \App\Models\MoneyRed;
        $data=$db->getList($list,$where);
        $regType=trans('redBag.redType');
        foreach ($data['data'] as $k=>$v){
            $data['data'][$k]['red_type']=$regType[$v['red_type']];
        }
        return \App\Lib\DataTable\DataTable::init()->toJson($data['data'],$data['total']);
    }

    function  addRedBag(Req $req){

        if(!$req->isMethod('post')){
            $redType_db=new \App\Models\RedBag;
            $type=$redType_db->getRedBagType();
            return view('admin.redBag/addRedBag',['type'=>$type]);
        }else{
            //理由
            $password=$req->password;
            $reason=$req->reason_info?trim($req->reason_info):'';
            $redBag_type=$req->type?intval($req->type):'';
            $input_rule=$req->input_rule?trim($req->input_rule):'';
            $path=$req->path?trim($req->path):'';
            if(empty($reason)){
                return responseToJson(-5023500012);//理由不能为空
            }
            if(empty($redBag_type)){
                return responseToJson(-5023500112);//类型不能为空
            }
            if(empty($password)){
                return responseToJson(-5040022122);//密码不能为空
            }
            if(empty($path)){
                return responseToJson(-5040022222);//文件路径不能为空
            }
            //验证密码
            $admin_info = \App\Models\System_user::where('id', session('adminInfo.admin_id'))->first();
            if (!$admin_info) {
                return responseToJson(-7010100202);
            }
            $admin_info = $admin_info->toArray();
            if (!VerPassword($password, $admin_info['encryption_2'], $admin_info['password_2'])) {
                return responseToJson(-7010001622);
            }
            //初始化错误记录数组
            $error_account_array=array();
            $total_count=0;//总条数
            //计算失败金额
            $fail_money=0;
            //读取文件内容
            $data=$this->readFile($path);
            if($data<0) {
                return responseToJson($data);
            }
            //检查重复数据
            $data=$this->checkDate($data);
            $total_count=count($data);
            foreach ($data as $k=>$v){
                if(empty($v['money'])){
                    $error_account_array[]=$v['account_name'].','.$v['money'].','.$v['reason'];
                    $fail_money+=$v['money'];
                    unset($data[$k]);
                }
            }
            //重排序列
            $data=array_values($data);

            //获取含用户id的数据
            $data_account=$this->getAccountDate($data);
            //获取初始用户名数组
//            $org_name_array=array_column($data,'account_name');
            //获取有效用户名数组
            $real_name_array=array_column($data_account,'account_name');
            //记录无限用户及金额
            foreach ($data as $v){
                if(!in_array(trim($v['account_name']),$real_name_array)){
                    $error_account_array[]=$v['account_name'].','.$v['money'].','.$v['reason'];
                    $fail_money+=$v['money'];
                }
            }
            if(empty($data_account)){
                $report_data=array(
                    'total'=>$total_count,//总条数
                    'fail'=>count($error_account_array),//失败条数
                    'error'=>$error_account_array,
                    'success'=>0,
                );
                return responseToJson($report_data);//文件上用户均不存在
            }
            $out_order_id=OrderID();
            //更新用户余额
            $res=$this->updateCash($data_account);
            if($res<0){
                return responseToJson($res);
            }
            //添加资金记录
            $inset_return=$this->MoneyLog($data_account,$out_order_id,$reason,$redBag_type);
            if(is_array($inset_return['error'])&&count($inset_return['error'])>0){
                foreach ($inset_return['error'] as $v){
                    $error_account_array[]=$v;
                }
            }
            $fail_money+=$inset_return['fail_money'];
            $log = array(
                session('adminInfo.admin_name'),
                $reason,
                $redBag_type,
                $input_rule,
            );
            OperationLog(session('adminInfo.admin_id'), 'Redbag', $log);
            $res_data=array(
                'total'=>$total_count,//总条数
                'fail'=>count($error_account_array),//失败条数
                'error'=>$error_account_array,
            );
            $res_data['success']=$res_data['total']-$res_data['fail'];
            //计算总金额
            $sum_money=0;
            foreach ($data as $k=>$v){
                $sum_money+=$v['money'];
            }
            //红包记录数据
            $data_log=array(
                'red_type'=>$redBag_type,
                'suescc_user'=>$res_data['success'],
                'fail_user'=>$res_data['fail'],
                'input_reason'=>$reason,
                'input_rule'=>$input_rule,
                'sum_user'=>$total_count,
                'sum_money'=>$sum_money,
                'success_money'=>round($sum_money-$fail_money,2),
            );
            $data_log['input_order']=$out_order_id;

            $out_order=$this->baoLog($data_log);
            if($out_order<0){
                return responseToJson($out_order);
            }
            return responseToJson($res_data);
        }
    }
    //文件上传
    function upload(Req $req){
//        print_r($_FILES);
        //判断请求中是否包含name=file的上传文件
        if(!$req->hasFile('file')){
            return responseToJson(-5050010022);
//                exit('上传文件为空！');
        }
        $file = $req->file('file');
        //判断文件上传过程中是否出错
        if(!$file->isValid()){
            return responseToJson(-5050010122);
//                exit('文件上传出错！');
        }
//        $path = $file->path();//文件路径
        $store_result = $file->store('cvs');
        $path=storage_path('app/'.$store_result);
//        $path=str_replace('\\','/',$path);
        $data=array(
            'path'=>$path,
            'name'=>$file->getClientOriginalName()
        );
        return responseToJson($data);
    }
    //读取cvs文件
    function readFile($path){
        $data=array();
        $file = fopen($path,"r");
        while(! feof($file))
        {
            $str=fgetcsv($file);
//            print_r($str);
            $str[2]=!empty($str[2])?iconv('GBK', 'UTF-8',$str[2]):' ';
//            $data[]=fgetcsv($file);
            $data[]=$str;
        }
        fclose($file);
//        print_r($data);
        array_shift ($data);//弹出第一姓名，金额,理由数据
        $data=array_filter($data);
//        print_r($data);die;
        if(count($data)==0){
            return -5050010222;
        }
        $return_array=array();
        foreach ($data as $k=>$v){
            if(isset($v[0])){
                $return_array[$k]['account_name']=trim($v[0]);
                $return_array[$k]['money']=trim($v[1]);
                $return_array[$k]['reason']=$v[2];
            }

//            if(isset($v[2])){
//                $return_array[$k]['reason']=mb_convert_encoding($v[2],'utf-8',mb_detect_encoding($v[2]));
//            }else{
//                $return_array[$k]['reason']='';
//            }

        }
        unset($data);
        return $return_array;

    }
    //数据检测排除重复用户和金额的钱
    private function checkDate($data){
        $len=count($data);
        for($i = 0; $i < $len; $i ++) {
            for($j = $i + 1; $j < $len; $j ++) {
                if ($data[$i]['account_name'] == $data[$j]['account_name']&&$data[$i]['money'] == $data[$j]['money']) {
//                    $repeat_arr [] = $data [$i];
                    unset($data[$i]);
                    break;
                }
            }
        }
        return $data;
    }
    //添加红包记录
    private function baoLog($data){
        $red_db=new \App\Models\MoneyRed;
        return $red_db->insertData($data);
    }

    //更新用户余额
    private function updateCash($data){
        if(!is_array($data)){
            return -5050010322;
        }
        $account_db=new \App\Models\Account_detailed;
        foreach ($data as $k=>$v){
            if($v['money']>0){
                $res=$account_db->addMoney($v['account_identity'],$v['money']);
                if($res<0){
                    break;
                }
            }else if($v['money']<0){
                $res=$account_db->costMoney($v['account_identity'],$v['money']);
                if($res<0){
                    break;
                }
            }
        }
        return $res;
    }
    //用户数据组装成含有用户余额及用户id的数组
    private function getAccountDate($data){
        $account_db=new \App\Models\Account_list;
        //获取用户名的以为数组
        $account_name_array=array_column($data,'account_name');

        //获取用户余额，及id
        $account_data=$account_db->getAccountCash($account_name_array);


        foreach ($account_data as $k=>$v){
            foreach ($data as $ka=>$va){
                if($v['account_name']==$va['account_name']){
                    $account_data[$k]['money']=$va['money'];
//                    if(isset($va['reason'])){
                    $account_data[$k]['reason']=$va['reason'];
//                    }
                }
            }
        }
        return $account_data;
    }
    //添加用户资金记录
    private function MoneyLog($data,$out_order_id,$reson,$red_type){
        $money_db=new \App\Models\Money_details;
        $insert_data=array();
        $money_time=date('Y-m-d H:i:s');
        $order_f=date('Ym');
        $system=session('adminInfo.admin_name');
        $order_f_red=trans('redBag.redoder');
        $error_account_array=array();
        $fail_money=0;
        foreach ($data as $k=>$v){
            $end_order=$v['money']*100;
            $money_cash=$v['cash']+$v['money'];
            $insert_data['trade_id']=$order_f.'_'.$v['account_name'].'_'.$end_order.$order_f_red[$red_type];
            $insert_data['info_identity']=UUID();
            $insert_data['money_time']=$money_time;
            $insert_data['account_name']=$v['account_name'];
            $insert_data['account_identity']=$v['account_identity'];
            $insert_data['money']=abs($v['money']);
            if($v['money']>0){
                $insert_data['money_type']=1;
            }else{
                $insert_data['money_type']=2;
            }
            $insert_data['money_cash']=$money_cash;
            $insert_data['trade_type']=12;
            $insert_data['reason']=trans('redBag.redType')[$red_type].':'.$reson.$v['reason'];
            $insert_data['trade_desc']=$system.'发放红包给：'.$v["account_name"].'金额'.$v['money'];
            $insert_data['sysetem_user']=session('adminInfo.admin_name');
            $insert_data['out_order_id']=$out_order_id;
            //插入数据
            $res=$money_db->insertData($insert_data);
            if($res<0){
                $error_account_array[]=$v["account_name"].','.$v['money'].','.$v['reason'];
                $fail_money+=$v['money'];
            }
        }
//        return $money_db->insertAllData($insert_data);
        return array('error'=>$error_account_array,'fail_money'=>$fail_money);
    }

    //添加红包记录
    function addLog(Req $req){
        $reason=$req->reason?trim($req->reason):'';
        $redBag_type=$req->red_type?intval($req->red_type):'';
        $input_order=$req->input_order?trim($req->input_order):'';
        $input_rule=$req->input_rule?trim($req->input_rule):'';
        if(empty($reason)){
            return responseToJson(-5023500012);//理由不能为空
        }
        if(empty($redBag_type)){
            return responseToJson(-5023500112);//类型不能为空
        }
        $data=array(
            'red_type'=>$redBag_type,
            'input_order'=>$input_order,
            'input_reason'=>$reason,
            'input_rule'=>$input_rule,
        );


    }

    //导出红包文件返利
    function giveDemo(){
        $head = '用户名, 金额, 理由';
        $str = iconv('utf-8', 'gbk',  $head) . chr(10) . chr(9);
        $data=array(
            'test1',
            100,
            '红包'
        );
        $str .= iconv('utf-8', 'gbk', trim(implode(',', $data))) . chr(10) . chr(9);
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="demo.csv"');
        header('Cache-Control: max-age=0');

        echo $str;
    }

}