<?php
namespace App\Http\Controllers\WeChatApplet\Technician;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Export;
use App\Http\Models\Services\Prints;
use BlueCity\Core\Controllers\MountingCoreController as Controller;
use BlueCity\Core\Traits\ResourceControllerMethod;
use App\Services\Business\WashRecedeRecycleService;
use BlueCity\Core\Inc\ErrorInc;
use App\Services\LoginUserService;
use App\Models\OperationLog;
use App\Services\CommonService;

// 技师小程序-退换入库
class WashRecedeRecycleController extends Controller
{
    public $dataService = null;

    public function __construct()
    {
        $this->dataService = $service = new WashRecedeRecycleService();
        $this->bootWithService($service);
    }

    // 列表每页显示数据个数
    protected $show_count = 10;

    // 列表
    public function index(Request $request)
    {
        // 记录日志
        $log_record['request'] = $request->all();
        $log_record['time'] = date('Y-m-d H:i:s');
        $log_record['function'] = 'index';
        logFileRecord($log_record, 'wash/WashRecedeRecycle', 2);
        request()->offsetSet('rt', 'wechat');
        $user_info = LoginUserService::getUser();
        $search_data = $this->dataService->searchPage($user_info, $request->all(), 10);
        $list_button = getAppletListButton($request['api_token'], $request['pri_id']);
        if (empty($search_data['data']['data'])) {
            return response()->json($search_data);
        } else {
            if (!empty($search_data)) {
                $recycle = false;
                foreach ($list_button as $key_b => $value_b) {
                    if ($value_b['pri_operate_method'] == 'recycle' && $value_b['have_pri'] == 1) {
                        $recycle = true;
                    }
                }
                foreach ($search_data['data']['data'] as $key => $value) {
                    $buttonData = [];
                    
                    if($value->rec_state == 1 && $recycle){
                        $buttonData[] = 'recycle';
                        $search_data['data']['data'][$key]->is_can_recycle = 1;
                    } else {
                        $buttonData[] = 'recycleInfo';
                        $search_data['data']['data'][$key]->is_can_recycle = 2;
                    }
                    $button = CommonService::getAppletListButton($buttonData,$list_button);
                    $search_data['data']['data'][$key]->button_one = $button['button_one']??[];
                    $search_data['data']['data'][$key]->button_two = $button['button_two']??[];
                    $search_data['data']['data'][$key]->button_three = $button['button_three']??[];
                }
            }
            return response()->json($search_data);
        }
    }

    // 退换单详情
    public function info(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->infoValidator($request->all());
        $error_message = json_decode(json_encode($error_message, true),true);
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM,  $error_message);
        }
        request()->offsetSet('rt', 'wechat');
        $user_info = LoginUserService::getUser();

        $return_data = $this->dataService->details($user_info, $request->all());
        
        
        return response()->json($return_data);
    }

    // 退换
    public function recycle(Request $request)
    {   
        // 验证参数
        $error_message = $this->dataService->mainValidator->recycleValidator($request->all());
        $error_message = json_decode(json_encode($error_message, true),true);
        if (!empty($error_message)) {
            return $this->error('请求参数错误！', ErrorInc::INVALID_PARAM,  $error_message);
        }
        request()->offsetSet('rt', 'wechat');
        // 获取用户信息
        $user_info = LoginUserService::getUser();

        // 记录日志
        $log_record['request'] = $request->all();
        $log_record['time'] = date('Y-m-d H:i:s');
        $log_record['function'] = 'recycle';
        logFileRecord($log_record, 'wash/WashRecedeRecycle', 2);
        // 获取回收单数据
        $find_recede = DB::table('recede_recycle as re')
            ->leftjoin('admin as a', 'a.adm_id', '=', 're.rec_create_adm_id')
            ->leftjoin('recede_client as recl', 'recl.recl_rec_id', '=', 're.rec_id')
            ->where('rec_id', $request['rec_id'])
            ->select('rec_number', 'rec_ord_id', 'rec_ord_order_number', 'rec_create_time', 'rec_state', 'rec_amount', 'rec_remark', 'rec_date', 'rec_price', 'rec_mobile_ware_id', 'rec_source_type', 'rec_ware_id', 'adm_name as rec_create_adm_name', 'rec_waon_class', 'rec_id', 'rec_type', 'recl_client_id', 'recl_channel_unit', 'recl_name', 'rec_create_adm_id')
            ->first();
        if (empty($find_recede)) {
            return response()->json(['code'=>500, 'msg'=>'当前退换入库单不存在', 'data'=>'']);
        }
        if ($find_recede->rec_state == 2) {
            return response()->json(['code'=>500, 'msg'=>'当前退货入库单已回收', 'data'=>'']);
        }
        if ($request['type'] == 1) { //获取页面数据
            // 查询出仓库名称
            $find_recede->ware_name = DB::table('warehouse')
                ->where('ware_id', $find_recede->rec_ware_id)
                ->value('ware_name');
            // 创建人-组长
            $find_adm_data = DB::table('admin')
                ->where('adm_id', $find_recede->rec_create_adm_id)
                ->select('adm_id', 'adm_phone', 'adm_name')
                ->first();
            if ($find_adm_data) {
                $find_recede->rec_create_adm_name = $find_adm_data->adm_name;
                $find_recede->rec_create_adm_phone = $find_adm_data->adm_phone;
            } else {
                $find_recede->rec_create_adm_name = '';
                $find_recede->rec_create_adm_phone = '';
            }
            $find_goods = DB::table('recede_goods as rego')
                ->leftjoin('goods as goo', 'goo.goo_id', '=', 'rego.rego_goo_id')
                ->where('rego_rec_id', $request['rec_id'])
                ->select('rego_goo_id as goo_id', 'goo_name', 'rego_goo_goods_encode as goo_goods_encode', 'rego_goo_price as goo_price', 'rego_sell_number as goo_amount', 'rego_recycle_number as goo_recycle_amount', 'rego_fine_quantity', 'rego_priority_quantity', 'rego_unchecked_quantity', 'rego_ware_id', 'rego_waon_class', 'rego_wago_id', 'goo_type', 'goo_bra_name', 'goo_brse_id', 'goo_class', 'rego_wafg_id', 'rego_goo_inventory', 'rego_orgo_id', 'rego_goo_unit', 'rego_goo_unta_id', 'goo_unit_conversion')
                ->get()->toArray();
            // 查询系列数据
            $goo_brse_id = array_column($find_goods, 'goo_brse_id');
            $brse_data = DB::table('brand_serie')
                ->whereIn('brse_id', $goo_brse_id)
                ->pluck('brse_name', 'brse_id')
                ->toArray();
            foreach ($find_goods as $key => $value) {
                // 判断系列id,是否为空,不为空,将系列名称跟商品名称拼接在一起
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRSND_SERIE_SHOP'))) {
                    if (!empty($value->goo_brse_id)) {
                        if ($value->goo_class == 2) {
                            $find_goods[$key]->goo_name = $brse_data[$value->goo_brse_id] . ' ' . $value->goo_name;
                        } else {
                            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                $find_goods[$key]->goo_name = $brse_data[$value->goo_brse_id] . ' ' . $value->goo_name;
                            }
                        }
                    }
                }
                // 显示品牌名称
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                    if ($value->goo_class == 2) {
                        $find_goods[$key]->goo_name = $value->goo_bra_name . ' ' . $value->goo_name;
                    } else {
                        if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $find_goods[$key]->goo_name = $value->goo_bra_name . ' ' . $value->goo_name;
                        }
                    }
                }
                unset($find_goods[$key]->goo_brse_id);
                unset($find_goods[$key]->goo_class);
            }

            // 查询当前账号所拥有的仓库权限
            $adms_ware_id = DB::table('admin_set')
                ->where('adms_adm_id', $user_info->adm_id)
                ->where('adms_shop_id', $user_info->adm_shop_id)
                ->value('adms_ware_id');
            $adms_ware_id = explode(',', $adms_ware_id);

            // // 搜索仓库
            // $find_ware = DB::table('warehouse')
            //     ->where('ware_cid', $user_info->adm_cid)
            //     ->where('ware_superior_shop_id', $user_info->adm_shop_id)
            //     ->where('ware_state', 1)
            //     ->whereIn('ware_id', $adms_ware_id)
            //     ->select('ware_id', 'ware_name')
            //     ->get()->toArray();
            $list_button = getAppletListButton($request['api_token'], $request['pri_id']);
            $recycle = false;
            foreach ($list_button as $key_b => $value_b) {
                if ($value_b['pri_operate_method'] == 'recycle' && $value_b['have_pri'] == 1) {
                    $recycle = true;
                }
            }
            $data['recede_data'] = $find_recede;
            $data['goods_data'] = $find_goods;
            if($find_recede->rec_state == 1 && $recycle){
                $find_recede->is_can_recycle = 1;
            } else {
                $find_recede->is_can_recycle = 2;
            }
            // $data['warehouse_data'] = $find_ware;
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
        }
        DB::beginTransaction();
        $rec_res = WashRecedeRecycleService::recycle($user_info, $request->all(), $find_recede);
        if ($rec_res['code'] == 200) {
            DB::commit();
        } else {
            DB::rollBack();
        }
        return response()->json($rec_res);
    }

    // 搜索勾选过的服务门店
    public function searchShop(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 获取到服务门店信息
        $search_data = $request->all();

        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $list_data = DB::table('shop')
            ->where('shop_superior_id', $shop_id)
            ->where('shop_cid', $user_info->adm_cid)
            ->where('shop_state', 1)
            ->where('shop_type', '<>', 3)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['search_data'])) {
                    $query->where('shop_store_name', 'like', '%' . $search_data['search_data'] . '%');
                }
            })
            ->select('shop_id', 'shop_store_name')
            ->orderBy('shop_id', 'desc')
            ->get();
        if ($list_data) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$list_data]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }

    // 新发货单语音提示
    public function voicePrompt(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $res = DB::table('dispatch_bill')
            ->where([
                'dego_cid' => $user_info->adm_cid,
                'dego_shop_id' => $user_info->adm_shop_id,
                'dego_type' => 1
            ])
            ->get(['dego_id']);
        if (empty($res)) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'暂无发货单']);
        }
        $data = [];
        foreach ($res as $key => $value) {
            $data[] = $value->dego_id;
        }
        //发货单路径
        $url = 'storage/voice/dispatchBill.mp3';
        // $url = $_SERVER['SERVER_NAME'].'/storage/voice/dispatchBill.mp3';
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data]);
    }

    // 导出
    public function export(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $search_data = $request->all();
        $data = DB::table('dispatch_bill as dibi')
            ->leftjoin('work_order as wor', 'wor.wor_id', '=', 'dibi.dego_wor_id')
            ->leftjoin('dispatch_goods as digo', 'digo.digo_dego_id', '=', 'dibi.dego_id')
            ->leftjoin('warehouse as ware', 'ware.ware_id', '=', 'dibi.dego_out_ware_id')
            ->where('dego_cid', $user_info->adm_cid)
            ->where('dego_superior_shop_id', $shop_id)
            ->where('dego_type', '<>', 3)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['dego_type'])) {
                    $query->where('dego_type', $search_data['dego_type']);
                }
            }) //类型：1未出库2已出库
            ->where(function ($query) use ($search_data) {
                //如果选择开始时间并且选择结束时间
                if (!empty($search_data['start_time']) && !empty($search_data['end_time'])) {
                    $query->whereBetween('dego_create_time', [$search_data['start_time'], $search_data['end_time'] . ' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['start_time'])) {
                        $query->where('dego_create_time', '>=', $search_data['start_time']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['end_time'])) {
                            $query->where('dego_create_time', '<=', $search_data['end_time'] . ' 23:59:59');
                        }
                    }
                }
            }) //创建时间
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['dego_service_shop_id'])) {
                    $query->where('dego_service_shop_id', $search_data['dego_service_shop_id']);
                }
            }) //门店id
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['dego_out_ware_id'])) {
                    $query->where('dego_out_ware_id', $search_data['dego_out_ware_id']);
                }
            }) //供货仓库
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['dego_original_number'])) {
                    $query->where('wor_order_number', 'like', '%' . $search_data['dego_original_number'] . '%')
                        ->where('dego_order_type', 2)
                        ->orwhere('dego_original_number', 'like', '%' . $search_data['dego_original_number'] . '%');
                }
            }) //订单号
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['dego_number'])) {
                    $query->where('dego_number', 'like', '%' . $search_data['dego_number'] . '%');
                }
            }) //发货单号
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['dego_service_adm_id'])) {
                    $query->where('dego_service_adm_id', $search_data['dego_service_adm_id']);
                }
            }) //领货人
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['dego_client_id'])) {
                    $query->where('dego_client_id', $search_data['dego_client_id']);
                }
            }) //客户id
            ->select('dego_id', 'dego_number', 'wor_order_number', 'dego_original_number', 'digo_goo_name', 'digo_goo_goods_encode', 'digo_goo_quantity', 'dego_client_type', 'dego_client_id', 'dego_count', 'dego_create_time', 'dego_service_shop_id', 'ware_name', 'ware_leader_id', 'dego_service_adm_id', 'dego_type', 'dego_order_type', 'dego_wor_id')
            ->orderBy('dego_id', 'desc')
            ->get()->toArray();

        if (!empty($data)) {
            // 将对象转化为数组
            $data = json_decode(json_encode($data), true);
            $adm_id = array_unique(array_column($data, 'dego_service_adm_id')); //服务技师id
            $ware_leader_id = array_unique(array_column($data, 'ware_leader_id')); //仓库负责人id
            // 查找技师id对应的账号姓名
            $find_adm_data = DB::table('admin')
                ->whereIn('adm_id', $adm_id)
                ->pluck('adm_name', 'adm_id');
            $shop_id = array_unique(array_column($data, 'dego_service_shop_id')); //服务门店id
            // 查找门店id对应的账号姓名
            $shop = DB::table('shop')
                ->whereIn('shop_id', $shop_id)
                ->pluck('shop_store_name', 'shop_id');
            $find_ware = DB::table('admin')
                ->whereIn('adm_id', $ware_leader_id)
                ->pluck('adm_name', 'adm_id');
            foreach ($data as $key => $value) {
                // 订单发货
                if ($value['dego_order_type'] == 1) {
                    $order_id[] = $value['dego_wor_id'];
                }
                // 工单发货
                if ($value['dego_order_type'] == 2) {
                    $wor_id[] = $value['dego_wor_id'];
                }
                // 售后单发货
                if ($value['dego_order_type'] == '3') {
                    $after_id[] = $value['dego_wor_id'];
                }
                $order_type[] = $value['dego_order_type'];
            }
            foreach ($order_type as $key => $value) {
                if ($value == 1) {
                    if ($order_id) {
                        // 查找订单客户信息
                        $order_client = DB::table('order as ord')
                            ->leftjoin('order_client as orcl', 'orcl.orcl_ord_id', '=', 'ord.ord_id')
                            ->whereIn('orcl_ord_id', $order_id)
                            ->select('orcl_channel_unit', 'orcl_name', 'ord_type', 'ord_client_id')
                            ->get();
                        $order_client = json_decode(json_encode($order_client), true);
                        foreach ($order_client as $k => $v) {
                            if ($v['ord_type'] == 1) {
                                $channel_name[$v['ord_client_id']] = $v['orcl_name'];
                            } elseif ($v['ord_type'] == 2) {
                                $channel_name[$v['ord_client_id']] = $v['orcl_channel_unit'];
                            } elseif ($v['ord_type'] == 3) {
                                $channel_name[$v['ord_client_id']] = $v['orcl_channel_unit'];
                            }
                        }
                    }
                } elseif ($value == 2) {
                    if ($wor_id) {
                        // 查找工单客户信息
                        $work_client = DB::table('work_order as wor')
                            ->leftjoin('work_client as wocl', 'wocl.wocl_wor_id', '=', 'wor.wor_id')
                            ->whereIn('wocl_wor_id', $wor_id)
                            ->select('wocl_channel_unit', 'wocl_name', 'wor_type', 'wocl_client_id')
                            ->get();
                        $work_client = json_decode(json_encode($work_client), true);
                        foreach ($work_client as $k => $v) {
                            if ($v['wor_type'] == 1) {
                                $channel_name[$v['wocl_client_id']] = $v['wocl_name'];
                            } elseif ($v['wor_type'] == 2) {
                                $channel_name[$v['wocl_client_id']] = $v['wocl_channel_unit'];
                            } elseif ($v['wor_type'] == 3) {
                                $channel_name[$v['wocl_client_id']] = $v['wocl_channel_unit'];
                            }
                        }
                    }
                }
            }
            foreach ($data as $key => $value) {
                // 状态
                if ($value['dego_type'] == '1') {
                    $data[$key]['dego_type'] = '未发货';
                } elseif ($value['dego_type'] == '2') {
                    $data[$key]['dego_type'] = '已发货';
                } elseif ($value['dego_type'] == '3') {
                    $data[$key]['dego_type'] = '作废';
                } elseif ($value['dego_type'] == '4') {
                    $data[$key]['dego_type'] = '锁定';
                }
                if ($value['dego_client_type'] == 1) { //买家类型:2.客户单位
                    if (isset($channel_name[$value['dego_client_id']])) {
                        $data[$key]["dego_client_id"] = $channel_name[$value['dego_client_id']];
                    } else {
                        $data[$key]["dego_client_id"] = '';
                    }
                } else {
                    if (isset($channel_name[$value['dego_client_id']])) {
                        $data[$key]["dego_client_id"] = $channel_name[$value['dego_client_id']];
                    } else {
                        $data[$key]["dego_client_id"] = '';
                    }
                }
                // 服务技师id
                if (isset($find_adm_data[$value['dego_service_adm_id']])) {
                    $data[$key]['dego_service_adm_id'] = $find_adm_data[$value['dego_service_adm_id']];
                } else {
                    $data[$key]['dego_service_adm_id'] = '';
                }
                // 服务门店id
                $data[$key]['dego_service_shop_id'] = $shop[$value['dego_service_shop_id']];
                // 仓库负责人
                // if (isset($find_ware[$value['ware_leader_id']])) {
                //     $data[$key]['ware_leader_id'] = $find_ware[$value['ware_leader_id']];
                // } else {
                //     $data[$key]['ware_leader_id'] = '';
                // }
                $adm_id = explode(',',$value['ware_leader_id']);
                $adm_name = DB::table('admin')
                    ->whereIn('adm_id', $adm_id)
                    ->select('adm_name')
                    ->get()->toArray();
                $adm_name = array_column($adm_name, 'adm_name');
                $adm_name =  implode(',', $adm_name);
                $data[$key]->ware_leader_id = $adm_name;
                // 单号
                if ($value['dego_order_type'] == 1) {
                    $data[$key]['wor_order_number'] = $value['dego_original_number'];
                }
                //商品编号
                $data[$key]['digo_goo_goods_encode'] = empty("\t" . $value['digo_goo_goods_encode']) ? '' : "\t" . $value['digo_goo_goods_encode'];
                $data[$key]['digo_goo_name'] = empty($value['digo_goo_name']) ? '' : $value['digo_goo_name'];
                unset($data[$key]['dego_id']);
                unset($data[$key]['dego_client_type']);
                unset($data[$key]['dego_order_type']);
                unset($data[$key]['dego_wor_id']);
            }
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'没有符合条件的数据']);
        }
        $pathName = storage_path() . "/app/public/excel"; //获取上传excel路径
        // 创建文件夹
        if (!file_exists($pathName)) {
            mkdir($pathName, 0775, true);
            chmod($pathName, 0775);
        }

        $streamFileRand = '发货单' . time() . rand(1000, 9999) . '.xls';
        // 产生一个随机文件名（因为你base64上来肯定没有文件名，这里你可以自己设置一个也行）
        $streamFilename = $pathName . '/' . $streamFileRand;

        $where['action_name'] = '发货单列表';
        $where['field_name'] = ['发货单号', '订单单号', '工单单号', '商品名称', '商品编号', '商品数量', '客户单位', '商品总数量', '派单时间', '服务门店', '仓库名称', '仓库负责人', '领货人', '状态'];
        // 调用导出的公共方法
        export::publicExport(
            $streamFilename, //路径
            $where,    //sheet名及其每一行的标题
            $data      //导出数据
        );

        // 判断文件是否存在 存在则成功  不存在则失败
        if (file_exists($streamFilename)) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'storage/excel/' . $streamFileRand]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'导出失败']);
        }
    }

    // 打印
    public function print(Request $request)
    {
        $request['shpt_print_type'] = 1;
        // 验证数据
        $verify_data = new VerifyDispatchController;
        $error_message = $verify_data->printValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $print = Prints::print($user_info, $request);
        if ($print['code'] == 200) {
            Common::addLog($user_info, getRealIp($request), '发货单', '打印', '发货单：' . $print['data_info'][0]['dego_number'] . ' 打印成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$print['data'], 'data_info'=>$print['data_info']]);
        } else {
            return response()->json($print);
        }
    }
}
