<?php
namespace App\Http\Controllers\Orders;
use App\Http\Controllers\BaseController;
use App\Services\BmmcService;
use Illuminate\Http\Request;
use BlueCity\Core\Inc\ErrorInc;
use App\Models\User;
use App\Models\Orders;
use App\Models\OrderList;
use App\Models\SettlementList;
use DB;
use Excel;

/**
 * Class SysJdUserDataController 回传京东用户信息
 * @package App\Http\Controllers\Orders
 */
class SysJdUserDataController extends BaseController{
    /**|---------------------------------------------------------------------------------
     * @name 列表页
     * @param string ju_ordernum 订单单号
     * @param  int ju_pid 平台id
     * @param  int state 数据状态
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/8/5 23:07
     * |---------------------------------------------------------------------------------
    */
    public function index ( Request $request ){

        if (!$request->filled('state')) {
            //数据状态 1：未处理  5已修改 10同步成功 15 失败 20 单号不存在 25 订单状态错误
            return $this->error('参数错误', ErrorInc::FAILED_PARAM);
            //return response()->json(['data' => '', 'errorMessage' => '参数错误', 'errorCode' => 3]);
            exit;
        }
        $input = $request->all();
        $db = DB::table('jd_userdata');
        if(in_array($request->input('state'),[1,5,10,15,20,25])){
            $db = $db->where('ju_state',$request->input('state'));
        }
        if($request->filled('ju_pid')){
            $db = $db->where('ju_pid',$request->input('ju_pid'));
        }
        if($request->filled('ju_ordernum')){
            $db = $db->where('ju_ordernum',$request->input('ju_ordernum'));
        }
        $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->select('ju_id','ju_admin','ju_pid','ju_ordernum','ju_shrname','ju_shrphone','ju_shrsheng','ju_shrcity','ju_shrcountry','ju_address','ju_state','ju_time')->offset($offset)->limit($page_size)->orderBy('ju_id', 'ASC')->get();
        $wtb = DB::table('jd_userdata')->where("ju_state",1)->count();
        $tbsb = DB::table('jd_userdata')->where("ju_state",15)->count();
        $bcz = DB::table('jd_userdata')->where("ju_state",20)->count();
        $orderError = DB::table('jd_userdata')->where("ju_state",25)->count();
        $showcount = [
            ['showname' => "全部", 'shownum' => '--','status'=>0],
            ['showname' => "未同步", 'shownum' => $wtb??0,'status'=>1],
            ['showname' => "已变更", 'shownum' => '--','status'=>5],
            ['showname' => "已同步", 'shownum' => '--','status'=>10],
            ['showname' => "失败", 'shownum' => $tbsb??0,'status'=>15],
            ['showname' => "单号不存在", 'shownum' => $bcz??0,'status'=>20],
            ['showname' => "订单状态错误", 'shownum' => $orderError??0,'status'=>25]
        ];
        $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'=>'未同步','5'=>'未同步','10'=>'已同步','15'=>'失败','20'=>'单号不存在','25'=>'订单状态错误'];
            foreach($list as $k => $v){
                $buttonData = [];
                $list[$k]['pt_name'] = $pt[$v['ju_pid']]??'未知平台';
                $list[$k]['state_name'] = $state[$v['ju_state']]??'未知状态';
                if(in_array($v['ju_state'],[1,15])){
                    /*  $button = $this->getButton('sysData',$all_button,2);//同步
                  /*  if ($button != 'none'){
                          $list[$k]['button_one'][] = $button[0];
                          if (count($button) == 1){
                              $list[$k]['button_two']=[];
                              $list[$k]['button_three']=[];
                          }elseif ((count($button)<=3) && (count($button)>1)){
                              $list[$k]['button_two']=array_slice($button,1,2);
                              $list[$k]['button_three'] = [];
                          }else{
                              $list[$k]['button_two'] =array_slice($button,1,2);
                              $list[$k]['button_three'] =array_slice($button,3);
                          }
                          unset($button);
                      }else{
                          $list[$k]['button_one'] = [];
                          $list[$k]['button_two'] = [];
                          $list[$k]['button_three'] = [];
                      }*/

                    $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);
            //return response()->json(['Data' => $data, 'ErrorMessage' => '返回成功', 'ErrorCode' => 1]);
            exit;
        }else{
            $data['list'] = [];
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY,$data);
            //return response()->json(['Data' => $data, 'ErrorMessage' => '暂无数据', 'ErrorCode' => 2]);
            exit;
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 上传excel导入
     * @param file 文件名
     * @param p_id 平台id
     * @return \Illuminate\Http\JsonResponse
     * @author dou 2021/8/6 0:35
     * |---------------------------------------------------------------------------------
    */
    public function uploadExcelImport ( Request $request ){
        try {
            $file = $request->file('file');

            $p_id = $request->input('p_id');//平台id
            $admin_acc = $request->get('session_token')['admin_acc'];
            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){
                $reader = $reader->getSheet(0);

                $data = $reader->toArray();
                if($data[0][0]!='客户订单号' && $data[0][1]!='商品编码' && $data[0][9]!='收货人姓名' && $data[0][10]!='收货人电话'){
                    throw new \Exception("excel格式错误");
                }
                unset($data['0']);
                $sql = "INSERT IGNORE INTO gone_jd_userdata (ju_admin,ju_pid,ju_ordernum,ju_sku,ju_brand,ju_goodname,ju_goodprice,ju_procurement,ju_procurementnum,ju_return,ju_gnum,ju_shrname,ju_shrphone,ju_address,ju_shrsheng,ju_shrcity,ju_shrcountry,ju_prentnum,ju_orderprice,ju_userprice) VALUES ";
                foreach ($data as $key => $val){
                    $ssx = $data[$key]['12'].$data[$key]['13'].$data[$key]['14'];
                    if(strpos($data[$key]['11'],$ssx) !== false){
                        $length = mb_strlen($ssx);
                        $dress = mb_substr($data[$key]['11'],$length,null,'utf-8');
                    }else{
                        $dress = $data[$key]['11'];
                    }
	                $sqls[]="('".$admin_acc."','".$p_id."','".$this->restrict($data[$key]['0'])."','".$this->restrict($data[$key]['1'])."','".$data[$key]['2']."','".$data[$key]['3']."','".$data[$key]['4']."','".$data[$key]['5']."','".$data[$key]['6']."','".$data[$key]['7']."','".$data[$key]['8']."','".$data[$key]['9']."','".$data[$key]['10']."','".$dress."','".$data[$key]['12']."','".$data[$key]['13']."','".$data[$key]['14']."','".$data[$key]['19']."','".$data[$key]['24']."','".$data[$key]['25']."')";
                    //$sarr = [];
                    //$sarr[$key]['ju_admin']  =  $admin_acc;
                    //$sarr[$key]['ju_pid']  =  $p_id;
                    //$sarr[$key]['ju_ordernum']  = $data[$key]['0'];
                    //$sarr[$key]['ju_sku']  = $data[$key]['1'];
                    //$sarr[$key]['ju_brand']  =  $data[$key]['2'];
                    //$sarr[$key]['ju_goodname']  =  $data[$key]['3'];
                    //$sarr[$key]['ju_goodprice']  =  $data[$key]['4'];
                    //$sarr[$key]['ju_procurement']  =  $data[$key]['5'];
                    //$sarr[$key]['ju_procurementnum']  =  $data[$key]['6'];
                    //$sarr[$key]['ju_return']  =  $data[$key]['7'];
                    //$sarr[$key]['ju_gnum']  =  $data[$key]['8'];
                    //$sarr[$key]['ju_shrname']  =  $data[$key]['9'];
                    //$sarr[$key]['ju_shrphone']  =  $data[$key]['10'];
                    //$sarr[$key]['ju_address']  =  $data[$key]['11'];
                    //$sarr[$key]['ju_shrsheng']  =  $data[$key]['12'];
                    //$sarr[$key]['ju_shrcity']  =  $data[$key]['13'];
                    //$sarr[$key]['ju_shrcountry']  =  $data[$key]['14'];
                    //$sarr[$key]['ju_prentnum']  =  $data[$key]['19'];
                    //$sarr[$key]['ju_orderprice']  =  $data[$key]['24'];
                    //$sarr[$key]['ju_userprice']  =  $data[$key]['25'];
                    //$even = Db::table('jd_userdata')->insertGetId($sarr[$key]);
                    //if (!$even) {
                    //    $even = Db::table('jd_userdata')->where('ju_ordernum',$data[$key]['0'])->value('ju_id');
                    //    if (!$even) {
                    //        throw new \Exception("导入失败");
                    //    }
                    //}
                    //unset($sarr);
                }
                $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 ju_id 数据id
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/8/6 1:10
     * |---------------------------------------------------------------------------------
    */
    public function sysData ( Request $request ){
        if($request->filled('type')){
            if($request->input('type')=='1'){
                $num = DB::table('jd_userdata')->where('ju_state',1)->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;
                }
            }
        }
        if($request->filled('ju_id')){
            $data = Db::table('jd_userdata')->where('ju_id',$request->input('ju_id'))->first();
        }else{
            $data = Db::table('jd_userdata')->where('ju_state',1)->orderBy('ju_id','ASC')->first();
        }
        if($data) {
            if ($data['ju_state'] != '1') {
                return $this->error('数据状态错误', ErrorInc::FAILED_PARAM);
                //return response()->json(['Data' => '', 'ErrorCode' => 3, 'ErrorMessage' => '数据状态错误']);
                exit;
            }
            $order = Orders::where("order_num",$data['ju_ordernum'])->select('customer_id','new_customer_id','order_status','sys_num')->first();
            if($order){
                if($order['customer_id']!=$order['new_customer_id']){
                    $poss['ju_state'] = '5';
                }else{
                    DB::beginTransaction();
                    $arr['shr_name'] = $data['ju_shrname'];//姓名
                    $arr['shr_phone'] = $data['ju_shrphone'];//电话
                    $arr['shr_sheng'] = $data['ju_shrsheng'];//省
                    $arr['shr_shi'] = $data['ju_shrcity'];//市
                    $arr['shr_xian'] = $data['ju_shrcountry'];//县
                    $arr['shr_adress'] = $data['ju_address'];//详细地址
                    $list = User::insertGetId($arr);
                    $att['new_customer_id'] = $list;
                    $chos = Orders::where("order_num",$data['ju_ordernum'])->update($att);
                    if (!empty($chos)) {
                        if ($order['order_status'] > 10 && $order['order_status'] < 50) {
                            $olist['customer_phone'] = $arr['shr_phone'];
                            $olist['customer_id'] = $list;
                            $res = OrderList::where('order_num', $data['ju_ordernum'])->update($olist);
                            if (!empty($res)) {
                                if ($order['order_status'] >=30 && $order['order_status'] < 50 ) {
                                    $settm['customer_id'] = $list;
                                    $res = SettlementList::where('order_num', $data['ju_ordernum'])->update($settm);
                                }
                                $poss['ju_state'] = '10';
                            }else{
                                DB::rollBack();
                                $poss['ju_state'] = '15';
                            }
                        }
                        $poss['ju_state'] = '10';
//                        else{
//                            DB::rollBack();
//                            $poss['ju_state'] = '25'; //订单状态错误
//                        }
                    }else{
                        echo 2;
                        DB::rollBack();
                        $poss['ju_state'] = '15';
                    }
                }
            }else{
                $poss['ju_state'] = '20';
            }
            $rea = Db::table('jd_userdata')->where('ju_id',$data['ju_id'])->update($poss);
            if($rea){
                DB::commit();
                $content = $order['order_num'] . "订单，地址";
                $this->insertingLog('编辑，',$order['sys_num'],$content,'京东用户数据回传',$request->ip(),$request->get('session_token')['admin_acc']);
                return $this->success('成功');
                //return response()->json(['Data' => '', 'ErrorCode' => 1, 'ErrorMessage' => '成功']);
                exit;
            }else{
                DB::rollBack();
                return $this->error('失败', ErrorInc::MYSQL_FAILED);
               // return response()->json(['Data' => '', 'ErrorCode' => 2, 'ErrorMessage' => '失败']);
                exit;
            }
        }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);
    }
}
