<?php
/**
 * 文件名称（批量导入订单信息）
 * 文件简单描述（用于批量导入订单信息）
 * @author DouBin
 * @Date: 2021/12/31
 * @Time: 11:56
 * @Email: db@sudianwang.com
 * @version 1.0
 * @copyright BlueCity
 */
namespace App\Http\Controllers\Orders;
use App\Http\Controllers\BaseController;
use App\Models\OrderBimport;
use App\Models\Orders;
use App\Services\BmmcService;
use App\Services\GoodsService;
use App\Services\OrderaddService;
use App\Services\OrderService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Excel;
use App\Services\CommonService;
use BlueCity\Core\Inc\ErrorInc;


class BulkImportController extends BaseController
{
    /**|---------------------------------------------------------------------------------
     * @name 列表页
     * @param string ju_ordernum 订单单号
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/12/31 11:56
     * |---------------------------------------------------------------------------------
    */
    public function index ( Request $request ){
        if (!$request->filled('state')) {
            //数据状态 1未执行，2单号已经存在，3系统异常错误，4商品编号不存在，5操作成功
            return $this->error('参数错误', ErrorInc::FAILED_PARAM);
            exit;
        }
        $input = $request->all();
        $db = DB::table('order_bimport');
        if(in_array($request->input('state'),[1,2,3,4,5])){
            $db = $db->where('state',$request->input('state'));
        }
        if($request->filled('p_id')){
            $db = $db->where('p_id',$request->input('p_id'));
        }
        if($request->filled('order_num')){
            $db = $db->where('order_num',$request->input('order_num'));
        }

        $session = $request->get('session_token');
        if ($session['admin_groupnew'] != 7) {//管理员可以看全部
            $db = $db->where('company_id',$session['company_id']);
        }

        $page_size = (int)$request->input('page_size', 10);
        $page = (int)$request->input('page', 1);
        if ($page < 1) {
            $page = 1;
        }
        $offset = ($page - 1) * $page_size;
        $limit = $offset . "," . $page_size;
        $count = $db->count();
        $list = $db->offset($offset)->limit($page_size)->orderBy('oi_id', 'ASC')->get();
        if ($session['admin_groupnew'] != 7) {//管理员可以看全部
            $wtb = DB::table('order_bimport')->where("state", 1)->where('company_id',$session['company_id'])->count();
        }else{
            $wtb = DB::table('order_bimport')->where("state", 1)->count();
        }
        $showcount = [
            ['showname' => "全部", 'shownum' => '--','status'=>0],
            ['showname' => "未同步", 'shownum' => $wtb??0,'status'=>1],
            ['showname' => "单号存在", 'shownum' => '--','status'=>2],
            ['showname' => "系统异常", 'shownum' => '--','status'=>3],
            ['showname' => "商品编号错误", 'shownum' => '--','status'=>4],
            ['showname' => "添加成功", 'shownum' => '--','status'=>5]
        ];
        $data['showcount'] = $showcount;


        $all_button = BmmcService::whereButton($input['token'],$input['Pri_id']);
        $export = BmmcService::getTopButton('uploadExcelImport,sysDataAll','',$all_button);
        $data['button_top'] = $export['button_top']??[];//顶部按钮
        $data['button_search'] = $export['button_search']??[];//搜索栏按钮


        if (!$list->isEmpty()) {
            $list = $list->toArray();
            $pt = DB::table('pt')->pluck('pt_name','id');
            $state = ['1'=>'未同步','2'=>'单号存在','3'=>'系统异常','4'=>'商品编号错误','5'=>'添加成功'];
            foreach($list as $k => $v){
                $buttonData = [];
                $list[$k]['pt_name'] = $pt[$v['p_id']]??'未知平台';
                $list[$k]['state_name'] = $state[$v['state']]??'未知状态';
                if(in_array($v['state'],[1,3])){

                    $buttonData[] = 'sysData';
                    $button = BmmcService::getListButton($buttonData,$all_button);
                    $list[$k]['button_one'] = $button['button_one']??[];
                    $list[$k]['button_two'] = $button['button_two']??[];
                    $list[$k]['button_three'] = $button['button_three']??[];

                }
            }
            $data['list'] = $list;
            $data['page'] = [
                'page' => $page,
                'allPage' => ceil($count / $page_size),
                'page_size' => $page_size,
                'count' => $count
            ];
            return $this->success('返回成功',$data);
            exit;
        }else{
            $data['list'] = [];
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY,$data);
            exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 上传excel导入
     * @param file 文件名
     * @param p_id 平台id
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/12/31 11:57
     * |---------------------------------------------------------------------------------
    */
    public function uploadExcelImport ( Request $request ){
        try {
            $file = $request->file('file');

            $p_id = $request->input('p_id');//平台id
            $session = $request->get('session_token');
            $admin_acc = $session['admin_acc'];

            if ($session['admin_groupnew'] != 7) {//管理员可以看全部
                $company_id = $session['company_id'];
            }else{
                $company_id = $request->input('company_id')??1;
            }

            if (!$file){
                throw new ApiException("请选择文件");
            }
            $ext = $file->getClientOriginalExtension();// 获取扩展名
            if(!in_array($ext,['xls','xlsx','csv'])){//判断格式
                throw new ApiException("仅支持xls和xlsx结尾的excel文件");
            }
            //上传文件
            $file_name = date('YmdHis').rand(10,99).'.'.$ext;
            $urlname = public_path('excel');
            $file->move($urlname,$file_name);
            $filename = $urlname.'/'.$file_name;
            Excel::load($filename,function($reader)use($admin_acc,$p_id,$company_id){
                $reader = $reader->getSheet(0);

                $data = $reader->toArray();
                if($data[0][0]!='平台编号' && $data[0][1]!='用户姓名' && $data[0][2]!='用户电话' && $data[0][3]!='省份' && $data[0][4]!='城市' && $data[0][5]!='区县' && $data[0][6]!='详细地址' && $data[0][7]!='商品编号' && $data[0][8]!='商品数量' && $data[0][9]!='商品单价' && $data[0][10]!='订单备注' && $data[0][11]!='车型信息'){
                    throw new \Exception("excel格式错误");
                }
                unset($data['0']);
                $sql = "INSERT IGNORE INTO gone_order_bimport (order_num,p_id,shr_name,shr_phone,shr_sheng,shr_shi,shr_xian,shr_dress,good_code,good_num,good_price,creactor,remark,car,company_id) VALUES ";
                foreach ($data as $key => $val){
                    /* $ssx = $data[$key]['3'].$data[$key]['4'].$data[$key]['5'];
                *    echo strpos($data[$key]['6'],$ssx);
                     if(strpos($data[$key]['6'],$ssx)!==false){
                         $length = mb_strlen($ssx);
                         $dress = mb_substr($data[$key]['6'],$length,null,'utf-8');
                     }else{
                         $dress = $data[$key]['6'];
                     }*/
                    $dress = $data[$key]['6'];
                    $sqls[]="('".$this->restrict($data[$key]['0'])."','".$p_id."','".$this->restrict($data[$key]['1'])."','".$this->restrict($data[$key]['2'])."','".$data[$key]['3']."','".$data[$key]['4']."','".$data[$key]['5']."','".$dress."','".$this->restrict($data[$key]['7'])."','".$this->restrict($data[$key]['8'])."','".$data[$key]['9']."','".$admin_acc."','".$data[$key]['10']."','".$data[$key]['11']."','".$company_id."')";
                }
                $sql.=implode(',',$sqls);
                DB::insert($sql);
            });
            if (file_exists($filename)){
                //echo 11;
                unlink($filename);
            }
            unset($data);
            $content = '导入了文件'.$filename;
            $this->insertingLog('添加，','',$content,'订单导入',$request->ip(),$request->get('session_token')['admin_acc']);
            return $this->success('导入成功1');
            //return response()->json(['Data' => '','ErrorCode' => 1, 'ErrorMessage' => '导入成功1']);exit;
            exit;
        }catch(\Exception $e){
            return $this->error($e->getMessage(), ErrorInc::MYSQL_FAILED);
            //return response()->json(['Data' => '', 'ErrorCode' => 3, 'ErrorMessage' => $e->getMessage()]);
            exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 执行订单
     * @param int oi_id 数据id
     * @param int type 操作类型 1：获取可执行数量
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/12/31 13:55
     * |---------------------------------------------------------------------------------
    */
    public function sysData ( Request $request ){
        $session = $request->get('session_token');
        $admin_pt_id = $session['admin_pt_id'];
        $admin_pt_id = trim($admin_pt_id);
        $admin_pt_id = explode(',', $admin_pt_id);
        if($request->filled('type')){
            if($request->input('type')=='1'){
                $num = DB::table('order_bimport')->where('state',1)->whereIn('p_id',$admin_pt_id)->count();
                $num = $num??0;
                if($num == 0){
                    return $this->error('无数据', ErrorInc::DATA_EMPTY,$num);
                    //return response()->json(['Data' => $num, 'ErrorCode' => 2, 'ErrorMessage' => '无数据']);
                    exit;
                }else{
                    return $this->success('成功',$num);
                    //return response()->json(['Data' => $num, 'ErrorCode' => 1, 'ErrorMessage' => '成功']);
                    exit;
                }
            }
        }
        $db = new OrderBimport();
        if($request->filled('oi_id')){
            $data = CommonService::getMysqlData($db, ['oi_id'=>$request->input('oi_id'),'state_searchin'=>[1,3],'p_id_searchin'=>$admin_pt_id],[],[],'first');
        }else{
            $data = CommonService::getMysqlData($db, ['state'=>1,'p_id_searchin'=>$admin_pt_id],[],['oi_id'=>'ASC'],'first');
        }
        if($data) {
            if(in_array($session['company_id'],[12,14])){
                $db = DB::table('jd_bound');
                $good_id = CommonService::getMysqlData($db, ['sku_id' => $data['good_code']], ['goods_id'], [], 'value');
            }else {
                $db = DB::table('pj_goodcode');
                $good_id = CommonService::getMysqlData($db, ['pgc_code' => $data['good_code']], ['pgc_pgid'], [], 'value');
            }
            $poss['update_time'] = time();
            if($good_id){
                $goods = GoodsService::getGoodsByKey('pg_id',$good_id);
                if($good_id) {
                    $order = new Orders();
                    $order_num = OrderService::getOrderBy('order_num', $data['order_num'],['id']);
                    if(!$order_num) {
                        $sys_bh = 'LP' . date("YmdHis") . str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);
                        $input['sys_bh'] = $sys_bh;
                        $input['skb_bh'] = $data['order_num'];
                        $input['pt_id'] = $data['p_id'];
                        $input['ser_type'] = 1;
                        $input['shr_name'] = $data['shr_name'];
                        $input['shr_phone'] = $data['shr_phone'];
                        $input['shr_sheng'] = $data['shr_sheng'];
                        $input['shr_shi'] = $data['shr_shi'];
                        $input['shr_xian'] = $data['shr_xian'];
                        $input['shr_adress'] = $data['shr_dress'];
                        $input['shr_other'] = $data['remark'];
                        $input['car_audit'] = 2;
                        $input['order_type'] = 1;
                        $input['order_time'] = date("Y-m-d H:i:s");
                        $input['pay_type'] = 1;
                        $input['car_infor'] = $data['car'];
                        $input['goods'][0]['goods_price'] = $data['good_price'];
                        $input['goods'][0]['goods_num'] = $data['good_num'];
                        $input['goods'][0]['cd_id'] = $goods['cd_id'];
                        $input['goods'][0]['goods_id'] = $goods['pg_id'];
                        $input['goods'][0]['goods_name'] = $goods['good_name'];
                        $input['goods'][0]['goods_number'] = $goods['goods_number'];
                        $input['goods'][0]['goods_brand'] = $goods['brand_name'];

                        $return = OrderaddService::addOrder($input, $session, $request->ip());
                        if ($return['ErrorCode'] == 1) {
                            $poss['state'] = 5;
                            $rea = OrderBimport::where('oi_id',$data['oi_id'])->update($poss);
                            return $this->success('操作成功');
                        } else {
                            $poss['state'] = 3;
                            $rea = OrderBimport::where('oi_id',$data['oi_id'])->update($poss);
                            return $this->error('操作数据异常',ErrorInc::INVALID_PARAM);
                        }
                    }else{
                        $poss['state'] = 2;
                        $rea = OrderBimport::where('oi_id',$data['oi_id'])->update($poss);
                        return $this->error('单号已存在',ErrorInc::DATA_EXIST);
                    }
                }else{
                    $poss['state'] = 4;
                    $rea = OrderBimport::where('oi_id',$data['oi_id'])->update($poss);
                    return $this->error('商品标号错误',ErrorInc::INVALID_PARAM);
                }
            }else{
                $poss['state'] = 4;
                $rea = OrderBimport::where('oi_id',$data['oi_id'])->update($poss);
                return $this->error('商品标号错误',ErrorInc::INVALID_PARAM);
            }
        }else{
            return $this->error('无数据',ErrorInc::DATA_EMPTY);
            //return response()->json(['Data' => '', 'ErrorCode' => 4, 'ErrorMessage' => '无数据']);
            exit;
        }
    }
    //去除空格
    function restrict($str){
        $is_str=array(" ","　","\t","\n","\r","	");
        $is_str_er=array("","","","","","");
        return str_replace($is_str,$is_str_er,$str);
    }
}
