<?php

namespace App\Http\Controllers;

use App\Exports\Export;
use App\Imports\OrderIssueExport;
use App\Imports\OrderIssueImport;
use App\Logistic;
use App\Order;
use App\OrderIssue;
use App\OrderIssueProcessLog;
use App\OrderIssueType;
use App\Owner;
use App\RejectedBill;
use App\Services\OrderIssueService;
use App\Services\OrderService;
use App\Services\RejectedService;
use App\Shop;
use App\UserWorkgroup;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;

class OrderIssueController extends Controller
{

    public function __construct()
    {
        app()->singleton("orderIssueService", OrderIssueService::class);
        app()->singleton("orderService", OrderService::class);
        app()->singleton("rejectedService", RejectedService::class);
        app()->singleton('rejectedService',RejectedService::class);
    }

    public function index(Request $request)
    {
        if (!Gate::allows('订单管理-问题件-查询')) {
            return redirect(url('/'));
        }
        $orderIssueService = app('orderIssueService');
        $owners = Owner::all();
        $orderIssues = $orderIssueService->paginate($request);
        return view('order.issue.index', compact('owners', 'orderIssues'));
    }

    public function create()
    {
        if (!Gate::allows('订单管理-订单问题件生成')) {
            return redirect(url('/'));
        }
        $types = OrderIssueType::all();
        $meg = ['success' => true];
        $userWorkGroup = UserWorkgroup::all();
        $logistic = Logistic::all();
        $owners = Owner::all();
        return view('order.issue.create', compact(['types', 'meg', 'userWorkGroup', 'logistic', 'owners']));
    }

    public function store(Request $request)
    {
        if (!Gate::allows('订单管理-订单问题件生成')) {
            return redirect(url('/'));
        }
        $orderIssueService = app('orderIssueService');
        $orderIssueService->validatorCreate($request)->validate();
        $orderIssue = null;
        if ($request->filled('logistic_number_return')) {
            $orderIssue = $orderIssueService->createByLogisticNumber($request);
        } else {
            $orderIssue = $orderIssueService->create($request);
        }
        $msg = '';
        if ($orderIssue == null) {
            $msg = '创建订单问题件失败';
        } else {
            $msg = '创建订单问题件成功';
        }
        $owners = Owner::all();
        $orderIssues = $orderIssueService->paginate($request);
        OrderIssueProcessLog::create(['order_issue_id' => $orderIssue['id'], 'user_id' => Auth::user()['id'], 'content' => '创建订单问题件', 'type' => '创建']);
        return redirect('order/issue/index'); /*view('order.issue.index', compact('owners', 'orderIssues', 'msg'))*/;
    }

    public function edit($id)
    {
        if (!Gate::allows('订单管理-问题件-编辑')) {
            return redirect(url('/'));
        }
        $orderIssue = OrderIssue::where('id', $id)->first();
        $order = Order::with(['packages' => function ($query) {
            return $query->with(['commodities' => function ($query) {
                return $query->with('commodity');
            }]);
        }])->where('id', $orderIssue->order_id)->first();
        $secondOrder = Order::with(['packages'=>function($query){
            return $query->with(['commodities'=>function($query){
                return $query->with(['commodity']);
            }]);
        }])->where('id', $orderIssue->second_order_id)->first();
        $rejectedBill = RejectedBill::where('id', $orderIssue->rejected_bill_id)->first();
        $userWorkgroup = UserWorkgroup::all();
        $orderIssueType = OrderIssueType::all();

        $owners = Owner::all();
        $shops = Shop::all();
        $logistics = Logistic::all();
//        return view('order/issue/edit', compact(['orderIssue', 'owners', 'userWorkgroup', 'shops', 'logistics', 'orderIssueType',]));
        return view('order/issue/edit', compact(['orderIssue', 'owners', 'userWorkgroup', 'shops', 'logistics', 'orderIssueType', 'order', 'secondOrder', 'rejectedBill']));
    }

    public function update(Request $request)
    {
        //
    }

    public function destroy(Request $request)
    {

    }

    public function batchImport(Request $request)
    {
        if (!Gate::allows('订单管理-订单问题件生成')) {
            return redirect(url('/'));
        }
        $file = $request->file('file');
        $fileSuffix = $request->file('file')->getClientOriginalExtension();
        if (in_array($fileSuffix, ['xlsx', 'xlsm', 'xltx', 'xltm', 'xls', 'xlt', 'ods', 'ots', 'slk', 'xml', 'gnumeric', 'htm', 'html', 'csv', 'tsv'])) {
            ini_set('max_execution_time', 2100);
            ini_set('memory_limit', '512M');
            $extension = $request->file()['file']->getClientOriginalExtension();
            $extension[0] = strtoupper($extension[0]);
            Excel::import(new OrderIssueImport(), $request->file()['file']->path(), null, $extension);
            if (Cache::has('error')) {
                return '<h1 class="text-danger">导入Excel失败<br><p style="color: red">' . Cache::pull('error') . '</p></h1>';
            } else {
                $exception = Cache::get('exception');
                $a = '';
                for ($i = 0; $i < count($exception); $i++) {
                    $a .= implode(',', $exception[$i]) . '&#10';
                };
                $this->log(__METHOD__, __FUNCTION__, json_encode($request->toArray()), Auth::user()['id']);
                return '<h1 class="text-danger">导入Excel成功<br><textarea style="width: 50%;height: 50%">' . $a . '</textarea></h1>';
            }
        } else {
            return '<h1 class="text-danger">失败<br><p style="color: red">不支持该文件类型</p></h1>';
        }
    }

    public function exportOrderIssue(Request $request)
    {
        $orderIssueService = app('orderIssueService');
        $resultdata = $orderIssueService->exportExcel($request);

        $row = [[
            'id' => 'ID', 'created_at' => '状态', 'order_created_at' => '登记日期', 'owner' => '客户', 'shop' => '店铺', 'order_no' => '原始订单号',
            'logistic' => '原始承运商', 'consignee_name' => '收货人', 'consignee_phone' => '收货电话',
            'province' => '省', 'city' => '市', 'district' => '区', 'address' => '收货人地址',
// 原始商品信息order -> package -> commodity
            'commodity_code' => '商品条码', 'commodity_name' => '商品名称', 'amount' => '数量',
// 退回商品信息 rejectedBill -> items
            'barcode_goods' => '商品条码', 'name_goods' => '商品名称', 'goods_amount' => '数量', 'is_checked' => '是否正品', 'remark' => '备注',
            'rejecting_status'=>'退单状态',
            'logtype'=>'操作类型','logremark'=>'说明','user'=>'操作者',
            'order_issue_type' => '问题类别',
            'second_order' => '二次订单', 'second_logistic' => '二次承运商', 'second_logistic_number' => '二次运单号',
// 二次商品信息 order -> package -> commodity
            's_commodity_code' => '条码', 's_commodity_name' => '商品名', 's_amount' => '数量', /*'s_is_checked' => '是否正品', 's_remark' => '备注',*/
            'final_status' => '最终状态', 'logistic_indemnity_money' => '承运商赔偿金额', 'logistic_express_remission' => '承运商快递减免',
            'baoshi_indemnity_money' => '宝时赔偿金额', 'baoshi_express_remission' => '宝时快递减免', 'user_workgroup' => '事故责任方']];

        $list = [];
        $mergeCell = [];
        $i = 0;
        foreach ($resultdata as $result) {
            $count = 0;
            $list[$i] = [
                'id' => $result->id,
                'created_at' => $result->created_at,    // 登记日期
                'order_created_at' => isset($result->order) ? $result->order->created_at : '', // 订单创建日期
                'owner' => isset($result->owner) ? $result->owner->name : '',   // 货主
                'shop' => isset($result->shop) ? $result->shop->name : '',      // 店铺
                'final_status' => $result->final_status,                        // 最终处理结果
                'order_issue_type' => isset($result->type) ? $result->type->name : '',
                'logistic_indemnity_money' => $result->logistic_indemnity_money,
                'logistic_express_remission' => $result->logistic_express_remission,
                'baoshi_indemnity_money' => $result->baoshi_indemnity_money,
                'baoshi_express_remission' => $result->baoshi_express_remission,
                'user_workgroup' => isset($result->userWorkGroup) ? $result->userWorkGroup->name : '',
                'rejecting_status' => isset($result->rejecting_status) ? $result->rejecting_status : '',
            ];
            $sign=$i+2;
            if (isset($result->order)) {
                $list[$i]['logistic'] = $result->order->logistic ? $result->order->logistic->name : '';
                $list[$i]['consignee_name'] = $result->order->consignee_name;
                $list[$i]['consignee_phone'] = $result->order->consignee_phone;
                $list[$i]['province'] = $result->order->province;
                $list[$i]['city'] = $result->order->city;
                $list[$i]['district'] = $result->order->district;
                $list[$i]['address'] = $result->order->address;
                $list[$i]['order_no'] = $result->order->code;
                $cell = $i;
                if (isset($result->order->packages)) {
                    $packages = $result->order->packages;
                    foreach ($packages as $key => $value) {
                        if(isset($value->commodities)){
                            $commodities = $value->commodities;
                            foreach($commodities as $commodity){
                                $list[$cell]['commodity_code'] = isset($commodity->commodity)? $commodity->commodity->sku:'';
                                $list[$cell]['commodity_name'] = isset($commodity->commodity)?$commodity->commodity->name :'';
                                $list[$cell]['amount'] = $commodity->amount;
                            }
                        }
                        $cell++;
                    }
                    $count = $cell - $i;
                }
            }
            if(isset($result->logs)){
                $logs = $result->logs;
                $cell = $i;
                foreach ($logs as $log){
                    $list[$cell]['logtype'] = $log->type;
                    $list[$cell]['logremark'] =$log->content;
                    $list[$cell]['user'] = isset($log->user) ? $log->user->name:"";
                    $cell++;
                }
                $count = $cell - $i > $count ?  $cell - $i : $count;
            }
            if (isset($result->secondOrder)) {
                $list[$i]['second_order'] = $result->secondOrder->code;
                $list[$i]['second_logistic'] = $result->secondOrder->logistic->name;
                $list[$i]['second_logistic_number'] = $result->secondOrder->code;
                $secondOrder = $result->secondOrder;
                if (isset($secondOrder->secondOrder->packages)) {
                    $spackages = $result->order->packages;
                    $cell = $i;
                    foreach ($spackages as $key => $value) {
                        if(isset($value->commodities)){
                            $commodities = $value->commodities;
                            foreach($commodities as $commodity){
                                $list[$cell]['s_commodity_code'] = isset($commodity->commodity)? $commodity->commodity->sku:'';
                                $list[$cell]['s_commodity_name'] = isset($commodity->commodity)?$commodity->commodity->name :'';
                                $list[$cell]['s_amount'] = $commodity->amount;
                            }
                        }
                        $cell++;
                    }
                    $count = $cell - $i > $count ?  $cell - $i : $count;
                }
            }
            if (isset($result->rejectedBill)) {
                $items = $result->rejectedBill->items ?? [];
                $cell = $i;
                foreach ($items as $key => $value) {
                    $list[$cell]['barcode_goods'] = $value['barcode_goods'];
                    $list[$cell]['name_goods'] = $value['name_goods'];
                    $list[$cell]['goods_amount'] = $value['amount'];
                    $list[$cell]['is_checked'] = $value['is_checked'];
                    $list[$cell]['remark'] = $value['remark'];
                    $cell ++;
                }
                $count = $cell - $i > $count ?  $cell - $i : $count;
            }
            $i += $count;
            $mergeCell[$sign] = $i+1;
        }
        $columnName = [
            "A", "B", "C", "D", "E", "F",
            "G", "H", "I",
            "J", "K", "L", "M",
            /*"N", "O", "P",*/
            /*"Q", "R", "S", "T", "U",*/
            "V",
            /*"W", "X", "Y",*/
            "Z",
            "AA", "AB", "AC",
            /*"AD", "AF", "AG",*/
            "AH", "AI", "AJ",
            "AK", "AL" , "AM"];
        if(Gate::has('客户不可见')){
            unset($row[0]['baoshi_indemnity_money']);
            unset($columnName['AK']);

        }
        foreach ($list as $key=>&$value){
            foreach ($row[0] as $rowKey=>$rowValue){
                if(!isset($value[$rowKey])){
                    $value[$rowKey] = '';
                }
            }
        }
        return Excel::download(new Export($row, $list, $mergeCell, $columnName), date('YmdHis', time()) . '-订单问题件.xlsx');
    }

    public function excelImport(Request $request)
    {
        if (!Gate::allows('订单管理-订单问题件生成')) {
            return redirect(url('/'));
        }
        return view('order.issue.import');
    }

    public function apiOrderIssueTag(Request $request)
    {
        if (!Gate::allows('订单管理-订单问题件生成')) {
            return ['success' => false, 'fail_info' => '没有对应权限'];
        }
        if (!$request->input('orderNos')) {
            return ['success' => false, 'fail_info' => '没有传入的订单编号'];
        }
        $orderIssueService = app('orderIssueService');
        return $orderIssueService->orderIssueTag($request);
    }

    public function apiDestroy(Request $request)
    {
        if (!Gate::allows('订单管理-问题件-删除')) {
            return ['success' => false, 'fail_info' => '没有对应权限'];
        }
        if (!($request->has('id'))) {
            return ['success' => 'false', 'fail_info' => '没有问题题件相关的参数'];
        }
        $orderIssue = OrderIssue::where('id', $request->input('id'))->first();
        $bool = $orderIssue->delete();
        if ($bool) {
            $this->log(__METHOD__, __FUNCTION__, json_encode($request->toArray()), Auth::user()['id']);
            return ['success' => 'true'];
        } else {
            return ['success' => 'false', 'fail_info' => '删除问题单出现异常,请联系管理员'];
        }
    }

    public function apiUpdate(Request $request)
    {
        if (!Gate::allows('订单管理-问题件-编辑')) {
            return ['success' => false, 'fail_info' => '没有对应权限'];
        }
        $validator =  $this->apiUpdateValidator($request);
        if ($validator->fails()){
            $arr = [];
            foreach ($validator->getMessageBag()->toArray() as $k=>$error){
                array_push($arr, $error[0]);
            }
            return [
                'success' => false,
                'errors' => $arr
            ];
        }
        $orderIssue = OrderIssue::where('id', $request->input('id'))->first();
        if (!$orderIssue) {
            return ['success' => false, 'fail_info' => '数据库没有相应记录,请到查询页面刷新重试'];
        }
        $orderIssue->fill($request->all());
        $orderIssue->update();
        $this->log(__METHOD__, __FUNCTION__, json_encode($request->toArray()), Auth::user()['id']);
        return ['success' => true, 'id' => $orderIssue['id']];
    }

    public function apiEndOrderIssue(Request $request)
    {
        if (!Gate::allows('订单管理-问题件-编辑')) {
            return ['success' => false, 'fail_info' => '没有对应的权限'];
        }
        if (!$request->has('ids')) {
            return ['success' => false, 'fail_info' => '没有传入对应的参数'];
        }
        $count = OrderIssue::whereIn('id', $request->input('ids'))->where('handle_status', 2)->count();
        if ($count > 0) {
            return ['success' => false, 'fail_info' => '勾选的内容中已有完结的订单问题件,取消勾选后重试'];
        } else {
            $count = OrderIssue::whereIn('id', $request->input('ids'))->update(['handle_status' => 2]);
            foreach ($request->input('ids') as $id) {
                OrderIssueProcessLog::create(['order_issue_id' => $id, 'user_id' => Auth::user()['id'], 'type' => '结束', 'content' => '完结订单']);
            }
            $this->log(__METHOD__, __FUNCTION__, json_encode($request->toArray()), Auth::user()['id']);
            return ['success' => true];
        }
    }

    public function apiDisposeOrderIssue(Request $request)
    {
        if (!Gate::allows('订单管理-问题件-编辑')) {
            return ['success' => false, 'fail_info' => '没有对应权限'];
        }
        if (!$request->has('id')) {
            return ['success' => false, 'fail_info' => '没有传入对应参数'];
        }
        $bool = OrderIssue::where('id', $request->input('id'))->update(['is_new_rejecting' => '已处理']);
        if ($bool) {
            OrderIssueProcessLog::create(['order_issue_id' => $request->input('id'), 'user_id' => Auth::user()['id'], 'content' => '订单已处理', 'type' => '处理']);
            return ['success' => true];
        }
        return ['success' => false, 'fail_info' => '修改失败'];
    }

    public function apiGetOrderInfoByWMSOrderNo(Request $request)
    {
        if (!$request->filled('WMSOrderNo')) {
            return ['success' => false, 'fail_info' => '缺失WMS订单号参数无法查询'];
        }
        $orderService = app('orderService');
        $orderInfo = $orderService->createOrderByWMSOrderNo($request->input('WMSOrderNo'));
        if (!$orderInfo) {
            return ['success' => false, 'fina_info' => '没有对应的WMS订单号'];
        }
        return ['success' => true, 'data' => $orderInfo];
    }

    public function apiOrderIssueHasCreate(Request $request)
    {
        if (!$request->filled(['type', 'id'])) {
            return ['success' => false, 'fail_info' => '缺少对应的参数或条件'];
        }
        $orderService = app('orderService');
        $rejectedService = app('rejectedService');
        if ($request->input('type') == 'WMSOrderNo') {
            $order = $orderService->createOrderByWMSOrderNo($request->input('id'));
            $bool = OrderIssue::where('order_id', $order['id'])->count() > 0;
            if ($bool) {
                return ['success' => false, 'fail_info' => '该订单号已有问题订单件'];
            } else {
                $order = $orderService->createOrderByWMSOrderNo($request->input('id'));
                $rejectedBill = $rejectedService->getRejectedByWMSOrderNo($request->input('id'));
                return ['success' => true, 'data' => compact(['order', 'rejectedBill'])];
            }
        } else if ($request->input('type') == 'RejectedBill') {
            $bool = OrderIssue::where('rejected_bill_id', $request->input('id'))->count() > 0;
            if ($bool) {
                return ['success' => false, 'fail_info' => '退回单号已有对应的问题单'];
            } else {
                $order = $orderService->getOrderInfoByLogisticNumberReturn($request->input('id'));
                $rejectedBill = RejectedBill::with('items')->where('logistic_number_return', $request->input('id'))->first();
                return ['success' => true, 'data' => compact(['order', 'rejectedBill'])];
            }
        }
    }

    public function apiUpdateValidator(Request $request){
        return Validator::make($request->input(), [
            'order_issue_type_id' => ['required'],
            'handle_status' => ['nullable'],
            'result_explain' => ['nullable'],
            'logistic_indemnity_money' => ['nullable','numeric'],
            'logistic_express_remission' => ['nullable'],
            'baoshi_indemnity_money' => ['nullable','numeric'],
            'baoshi_express_remission' => ['nullable'],
        ],[
            'required' => [':attribute 为必填项',':attribute'] ,
            'numeric' => [':attribute  为可确认的数值',':attribute']
        ],[
            'order_issue_type_id'=>'问题类别',
            'handle_status' => '处理状态',
            'result_explain' => '处理结果说明',
            'logistic_indemnity_money' => '承运商赔偿金额',
            'logistic_express_remission' => '承运商快递减免',
            'baoshi_indemnity_money' => '宝时赔偿金额',
            'baoshi_express_remission' => '宝时快递减免',
        ]);
    }
}
