<?php
namespace App\Http\Controllers\orders;
use App\Http\Controllers\BaseController;
use App\Http\Controllers\Common\CommonController;
use App\Services\BmmcService;
use App\Services\CommonService;
use App\Services\OrderService;
use BlueCity\Core\Inc\ErrorInc;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use DB;
use Excel;

class ImportNotesController extends BaseController{
    public function index ( Request $request ){
        if(!$request->filled('state')) {
            return $this->error('缺少state参数', ErrorInc::FAILED_PARAM);exit;
        }
        $input = $request->all();
        $Db = DB::table('note_import');
        if($input['state']>0){
            $Db = $Db->where('syc_status',$input['state']);
        }
        if(isset($input['order_num'])){
            $Db = $Db->where('order_num',$input['order_num']);
        }
        $page_size = (int)$request->input('page_size',10);
        $page = (int)$request->input('page',1);
        if($page<1){
            $page = 1;
        }
        $offset = ($page-1)*$page_size;
        $count = $Db->count();

        $list = $Db->orderBy('id','DESC')->offset($offset)->limit($page_size)->get();

        $count_menu = DB::table('note_import')->selectRaw("count('id') as num,syc_status")->groupBy('syc_status')->get()->toarray();
        $arr = array_column($count_menu, 'num','syc_status');
        //dd($arr);
        if($count_menu){
            $tonji['new'] = $arr[1]??0;
            $tonji['yet'] = $arr[2]??0;
            $tonji['unusual'] = $arr[3]??0;
            $tonji['noOrder'] = $arr[4]??0;
            $tonji['solved'] = $arr[5]??0;
            $tonji['all'] = array_sum($arr)??0;
        }
        $data['show_Menu'] = [
            ['showname'=>"全部",'status'=>'0','shownum'=>$tonji['all']],
            ['showname'=>"新导入",'status'=>'1','shownum'=>$tonji['new']],
            ['showname'=>"已同步",'status'=>'2','shownum'=>$tonji['yet']],
            ['showname'=>"异常单",'status'=>'3','shownum'=>$tonji['unusual']],
            ['showname'=>"未匹配到订单",'status'=>'4','shownum'=>$tonji['noOrder']],
            ['showname'=>"已解决",'status'=>'5','shownum'=>$tonji['solved']]
        ];

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

        $status_names = $this->getNoteStatusName(true);
        if (!$list->isEmpty()) {
            $list = $list->toArray();
            foreach ($list as $k=>$v){
                $buttonData = [];
                $list[$k]['status_name'] = $status_names[$v['syc_status']];

                if ($v['syc_status'] == 4){
                    $buttonData[] = 'updateNoteSlove';
                }elseif ($v['syc_status'] == 1||$v['syc_status'] == 3){
                    $buttonData[] = 'sysNote';
                }
                $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'] = [
            'count' => $count,
            'page'  => $page,
            'page_size' => $page_size,
            'allPage'  => ceil($count/$page_size)
        ];
        return $this->success('获取成功', $data); exit;
    }else{
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY,$data);exit;
        }
    }

    /**
     * @name 导入备注
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/3/3
     */
public function importNote(Request $request){
    try{
        $file = $request->file('file');
        if (!$file){
            return $this->error('请选择文件', ErrorInc::FAILED_PARAM, []);exit;
        }
        $ext = $file->getClientOriginalExtension();     // 扩展名
        if(!in_array($ext,['xls','xlsx'])){
            throw new \Exception("仅支持xls和xlsx结尾的excel文件");
        }

        $admin_acc = $request->get('session_token')['admin_acc'];
        //上传文件
        $file_name = date('YmdHis').rand(10,99).'.'.$ext;
        $urlname = public_path('excel/upload/'.date('y-m-d'));
        $file->move($urlname,$file_name);
        $filename = $urlname.'/'.$file_name;
        Excel::load($filename,function($reader)use($admin_acc){
            $reader = $reader->getSheet(0);
            $data = $reader->toArray();
            $arr = [];
            $list = $data;
            if($list[0][0]!='单号' || $list[0][1]!='备注内容' ){
                throw new \Exception('excel格式错误');
            }
            $num = 0;
            $time = strtotime(date("H:i:s",strtotime("-5 minute")));
            foreach ($data as $key => $val){
                if($key<1 || $val[0]==''){
                    continue;
                }
                $exis = DB::table('note_import')->where('order_num',$val[0])->orderBy('create_time','DESC')->value('create_time');
                $gtime = strtotime($exis);
                if($time<$gtime){
                    throw new \Exception('单号:'.$val[0].'导入时间小于五分钟');
                }

                $arr[$num]['order_num']  = $val[0];//单号
                $arr[$num]['content']  = $val[1];//备注
                $arr[$num]['create_name']  = $admin_acc;//评价内容
                $arr[$num]['update_name']  = $admin_acc;//评价显示内容
               /* if ($key >0){
                    $a = DB::table('note_import')->insert($arr[$key]);
                }*/
                $num++;
            }
            DB::table('note_import')->insert($arr);

        });
        if (file_exists($filename)){
            unlink($filename);
        }
        unset($data);
        return $this->success('导入成功');exit;
    }catch(\Exception $e){
        return $this->error($e->getMessage(), ErrorInc::MYSQL_FAILED);exit;
    }
}

    /**
     * @name 同步备注
     * syc_status 状态：1新导入；2已同步；3异常单；4未匹配到订单；5已解决
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/3/3
     */
public function synNotes(Request $request){
    $session_token = $request->get('session_token');
    $db = DB::table('note_import');
    if($request->filled('id')){
        $id = intval($request->input('id'));
        $info = CommonService::getMysqlData($db, ['id'=>$id,'syc_status'=>1],['id','order_num','content'],[],'first');
//        $info = DB::table('note_import')->where('id',$id)->where('syc_status',1)->select('id','order_num','content')->first();
    }else {
        $info = CommonService::getMysqlData($db, ['syc_status'=>1],['id','order_num','content'],[],'first');
//        $info = DB::table('note_import')->where('syc_status',1)->select('id','order_num','content')->first();
    }
    if(empty($info)){
        return $this->error('无需同步数据', ErrorInc::MYSQL_FAILED);
    }
    $ret = $this->updateNote($info,$session_token);
    return $ret->original;

}

    /**
     * @name 更新为已解决
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/3/4
     */
    public function updateNoteSlove(Request $request){
        if(!$request->filled('id')){
            return $this->error('参数错误少ID', ErrorInc::FAILED_PARAM);exit;
        }
        $id = intval($request->input('id'));
        $session_token = $request->get('session_token');
        $nowdate = date("Y-m-d H:i:s");
        $info = DB::table('note_import')->where('id',$id)->select('syc_status','order_num')->first();
        if($info['status']!=4){
            return $this->error('状态不正确', ErrorInc::MYSQL_FAILED);exit;
        }
        $ret = DB::table('note_import')->where('id',$id)->where('syc_status',4)->update(['syc_status'=>5,'update_time'=>$nowdate,'update_name'=>$session_token['admin_acc']]);
        if($ret){
            //日志
            $this->insertingLog('更新为解决，',$info['order_num'],'解决：'.$info['order_num'],'备注导入',$request->ip(),$session_token['admin_acc']);
            return $this->success('更新成功');exit;
        }else{
            return $this->error('更新失败', ErrorInc::MYSQL_FAILED);exit;
        }
    }

    /**
     * @param $info
     * @param $session_token
     * @return mixed
     * @author du
     * @date 2022/3/3
     */
public function updateNote($info,$session_token){
    $nowdate = date("Y-m-d H:i:s");
    $sys_num = OrderService::getOrderBy('order_num', $info['order_num'],['sys_num']);
    if(!$sys_num){
        DB::table('note_import')->where('id',$info['id'])->update(['syc_status'=>4,'update_time'=>$nowdate,'update_name'=>$session_token['admin_acc']]);
        return $this->error('未匹配到订单:'.$info['order_num'], 10086);
    }else{
        $ret = CommonService::accMe($sys_num, '导入备注', $info['content'], '', 2, $session_token['admin_groupnew'], $session_token['admin_acc'], $session_token['id']);
        if($ret){
            DB::table('note_import')->where('id',$info['id'])->update(['syc_status'=>2,'update_time'=>$nowdate,'update_name'=>$session_token['admin_acc']]);
            return $this->error('同步成功:'.$info['order_num'], 10086);
//            return $this->success('同步成功'); exit;
        }else{
            DB::table('note_import')->where('id',$info['id'])->update(['syc_status'=>3,'update_time'=>$nowdate,'update_name'=>$session_token['admin_acc']]);
            return $this->error('异常单:'.$info['order_num'], 10086);
        }
    }
}

    /**
     * @name 获取状态名称
     * @param string $type
     * @return array|array[]
     * @author du
     * @date 2022/3/4
     */
public function getNoteStatusName($type=''){
    $arr = [['type'=>1,'name'=>'新导入'],['type'=>2,'name'=>'已同步'],['type'=>3,'name'=>'异常单'],['type'=>4,'name'=>'未匹配到订单'],['type'=>5,'name'=>'已解决']];
    if($type){
        $arr = array_column($arr, 'name','type');
    }
    return $arr;
}

}
