<?php
namespace App\Http\Controllers\orders;
use App\Http\Controllers\BaseController;
use App\Services\BmmcService;
use App\Services\CommonService;
use App\Services\RecycleOrderService;
use BlueCity\Core\Inc\ErrorInc;
use Illuminate\Http\Request;
use DB;
use Excel;

class RecycleJdOrderController extends BaseController{
    /**
     * @name 京仓回收列表
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/3/10
     */
    public function index ( Request $request ){
        if(!$request->filled('state')) {
            return $this->error('缺少state参数', ErrorInc::FAILED_PARAM);exit;
        }
        $input = $request->all();
        $Db = DB::table('recycle_jd');
        if($input['state']>0){
            $Db = $Db->where('syc_status',$input['state']);
        }
        if(isset($input['order_num'])){
            $Db = $Db->where('order_num',$input['order_num']);
        }
        if(isset($input['ex_order_num'])){//出库单号
            $Db = $Db->where('ex_order_num',$input['ex_order_num']);
        }
        if(isset($input['bar_code'])){ //条码
            $Db = $Db->where('bar_code',$input['bar_code']);
        }
        if(isset($input['sku_id'])){ //商品编号
            $Db = $Db->where('sku_id',$input['sku_id']);
        }
        if(isset($input['jd_courier_number'])){ //运单编号
            $Db = $Db->where('jd_courier_number',$input['jd_courier_number']);
        }
        $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('recycle_jd')->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'=>"通知ERP失败",'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('importJdRefundOrder,cynRecycleOrder','',$all_button);
        $data['button_top'] = $export['button_top']??[];//顶部按钮
        $data['button_search'] = $export['button_search']??[];//搜索栏按钮

        $status_names = $this->getStatusName(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'] == 1||$v['syc_status'] == 3){
                    $buttonData[] = 'cynRecycle';
                }
                $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/9
     */
public function importJdRefundOrder(Request $request){
    try{
        $p_id = $request->input('p_id');
        if(!intval($p_id)){
            return $this->error('请选择平台', ErrorInc::FAILED_PARAM, []);exit;
        }
        $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,$p_id){
            $reader = $reader->getSheet(0);
            $data = $reader->toArray();
            $arr = [];
            $list = $data;
            if($list[0][0]!='退货单号' || $list[0][4]!='商品编号' ){
                throw new \Exception('excel格式错误');
            }
            $num = 0;
            foreach ($data as $key => $val){
                $exis = DB::table('recycle_jd')->where('order_num',$val[0])->where('jd_courier_number',$val[12])->value('id');
                if($exis || $key<1 || $val[0]==''){
                    continue;
                }
                $arr[$num]['order_num']  = $val[0];//单号
                $arr[$num]['apply_time']  = $val[1];//申请时间
                $arr[$num]['bar_code']  = $val[2];//备件条码
                $arr[$num]['channel']  = $val[3];//合作渠道
                $arr[$num]['sku_id']  = $val[4];//商品编号
                $arr[$num]['goods_name']  = $val[5];//商品名称
                $arr[$num]['refund_price']  = $val[6];//退货金额
                $arr[$num]['Purchasing']  = $val[7];//采销员
                $arr[$num]['ex_order_num']  = $val[8];//出库单号
                $arr[$num]['ex_type']  = $val[9];//出库类型
                $arr[$num]['company']  = $val[10];//机构
                $arr[$num]['re_warehouse']  = $val[11];//备件库
                $arr[$num]['jd_courier_number']  = $val[12];//运单号
                $arr[$num]['confirm_time']  = $val[13];//确认收货时间
                $arr[$num]['confirm_renson']  = $val[14];//确认收货人
                $arr[$num]['create_name']  = $admin_acc;//创建人
                $arr[$num]['update_name']  = $admin_acc;//更新人
                $arr[$num]['p_id']  = $p_id;//平台ID
                $num++;
/*
                if ($key >0){
                     $a = DB::table('recycle_jd')->insert($arr[$key]);
                }*/
            }
            //dump($arr);exit;
            DB::table('recycle_jd')->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通知ERP失败；4异常单；
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/3/10
     */
public function cynRecycleOrder(Request $request){
    $session_token = $request->get('session_token');
    $ip = $request->ip();
    if($request->filled('id')){
        $id = intval($request->input('id'));
        $info = DB::table('recycle_jd')->where('id',$id)->first();
    }else {
        $info = DB::table('recycle_jd')->where('syc_status',1)->first();
    }
    if(!$info){
        return $this->error('无需同步数据', ErrorInc::MYSQL_FAILED);
    }
    $ret = $this->updateRecycleOrder($info,$session_token,$ip);
    return $ret->original;

}

    /**
     * @param $info
     * syc_status 1新导入；2已同步；3通知ERP失败；4异常单；
     * @param $session_token
     * @return mixed
     * @author du
     * @date 2022/3/10
     */
public function updateRecycleOrder($info,$session_token,$ip){
    $db = DB::table('recycle_jd');
    $list = CommonService::getMysqlData($db, ['jd_courier_number'=>$info['jd_courier_number'],'order_num'=>$info['order_num']],['sku_id','goods_name','bar_code']);
    if($list) {
        $nowdate = date("Y-m-d H:i:s");
        $recycledata['pt_id'] = $info['p_id'];
        $recycledata['bar_code'] = $info['bar_code'];
        $recycledata['Purchasing'] = $info['Purchasing']??$session_token['admin_acc'];

        $recycledata['recycle_type'] = 3;//回收类型1门店回收  2 库房回收 3:京仓回收
        $recycledata['order_num'] = $info['order_num'];
        $recycledata['sys_num'] = $info['ex_order_num'];
        $recycledata['courier_number'] = $info['jd_courier_number'];
        $recycledata['store_id'] = 0;//收货部门编号
        $recycledata['send_type'] = 3;//发货类型1门店发回2客户发货 3:京仓
        $recycledata['after_id'] = 0;//售后id
        $recycledata['ro_reason'] = 3;//回收原因：1换货回收（等于1补发必须填写） 2退款回收（等于2时必须填写退款单） 3只回收
        $goods = [];
        foreach($list as $k => $v){
            $goods[$k]['goods_id'] = $v['sku_id'];
            $goods[$k]['goods_name'] = $v['goods_name'];
            $goods[$k]['bar_code'] = $v['bar_code']??'';
            $goods[$k]['goods_num'] = 1;
            $goods[$k]['msg_id'] = 0;
        }
        //dump($goods);
        $recycledata['goodsArr'] = $goods;
//dump($recycledata);exit;
        //dump($recycledata['goodsArr']);exit;
        $ret = RecycleOrderService::creactRecycle($recycledata, $session_token, $ip);

        if ($ret['ErrorCode'] != '1') {
            if ($ret['ErrorCode'] == '9400') {
                DB::table('recycle_jd')->where('jd_courier_number', $info['jd_courier_number'])->where('order_num', $info['order_num'])->update(['syc_status' => 3, 'update_time' => $nowdate, 'update_name' => $session_token['admin_acc']]);
            } else {
                DB::table('recycle_jd')->where('jd_courier_number', $info['jd_courier_number'])->where('order_num', $info['order_num'])->update(['syc_status' => 4, 'update_time' => $nowdate, 'update_name' => $session_token['admin_acc']]);
            }
            return $this->error($ret['ErrorMessage'], ErrorInc::TRANSFER_FAILED); exit;
        } else {
            DB::table('recycle_jd')->where('id', $info['id'])->update(['syc_status' => 2, 'update_time' => $nowdate, 'update_name' => $session_token['admin_acc']]);
            return $this->success('同步成功');
            exit;
        }
    }else{
        return $this->error('操作失败无商品', ErrorInc::DATA_EMPTY);
    }


}

    /**
     * @name 获取状态名称
     * @param string $type
     * @return array|array[]
     * @author du
     * @date 2022/3/10
     */
public function getStatusName($type=''){
    $arr = [['type'=>1,'name'=>'新导入'],['type'=>2,'name'=>'已同步'],['type'=>3,'name'=>'通知ERP失败'],['type'=>4,'name'=>'异常单']];
    if($type){
        $arr = array_column($arr, 'name','type');
    }
    return $arr;
}

}
