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

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\WeChatApplet\Verify\AppletOrderManage\VerifyAppletWorkOrderController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use App\Http\Models\Api\CashierDesk;
use App\Http\Models\Services\Order;
use App\Http\Models\Services\OrderManage\WorkOrders;

// 微信小程序 -- 业务系统 -- 工单列表
class AppletWorkOrderController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

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

        $search_data = $request->all();

        // 实际金额最小钱数
        if (!empty($search_data['min_price'])) {
            if (empty($search_data['wor_plus_minus'])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误']);
            }
            $search_data['min_price'] = $search_data['min_price'] * 100;
            if ($search_data['wor_plus_minus'] == 2) {
                $search_data['min_price'] = -$search_data['min_price'];
            }
        }
        // 实际金额最大钱数
        if (!empty($search_data['max_price'])) {
            if (empty($search_data['wor_plus_minus'])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误']);
            }
            $search_data['max_price'] = $search_data['max_price'] * 100;
            if ($search_data['wor_plus_minus'] == 2) {
                $search_data['max_price'] = -$search_data['max_price'];
                $max_price = $search_data['max_price'];
                $search_data['max_price'] = $search_data['min_price'];
                $search_data['min_price'] = $max_price;
            }
        }

        if (!empty($search_data['goo_goods_encode'])) { //工单列表-检索编码搜索
            $orgt_id = DB::table('order_goods_temporary')
                ->where('orgt_type', 2)
                ->where('orgt_adm_id', $user_info->adm_id)
                ->where('orgt_goods_encode', 'like', '%' . $search_data['goo_goods_encode'] . '%')
                ->value('orgt_id');
            if (empty($orgt_id)) {
                $this->goodsIndex($user_info, $shop_ids, $search_data);
            }
            $list_data = DB::table('work_order as a')
                ->leftJoin('work_client as b', 'b.wocl_wor_id', '=', 'a.wor_id')
                ->leftJoin('order_goods_temporary as orgt', 'orgt.orgt_ord_id', '=', 'a.wor_id')
                ->where('wor_cid', $user_info->adm_cid)
                ->where('wor_superior_shop_id', $shop_ids)
                ->where('wor_delete', 1)
                ->where('wor_collection_bill', 1) //是否代收账单：1正常工单2代收账单
                ->where('orgt_adm_id', $user_info->adm_id)
                ->where('orgt_type', 2)
                ->where(function ($query) use ($search_data) { //订单单号
                    if (!empty($search_data['wor_order_number'])) {
                        $query->where('wor_order_number', 'like', '%' . $search_data['wor_order_number'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //工单单号
                    if (!empty($search_data['wor_number'])) {
                        $query->where('wor_number', 'like', '%' . $search_data['wor_number'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //客户单位
                    if (!empty($search_data['wocl_channel_unit'])) {
                        $query->where('wocl_channel_unit', 'like', '%' . $search_data['wocl_channel_unit'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //客户姓名
                    if (!empty($search_data['wocl_name'])) {
                        $query->where('wocl_name', 'like', '%' . $search_data['wocl_name'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //客户电话
                    if (!empty($search_data['wocl_phone'])) {
                        $query->where('wocl_phone', 'like', '%' . $search_data['wocl_phone'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //车牌号
                    if (!empty($search_data['wocl_car_num'])) {
                        $query->where('wocl_car_num', 'like', '%' . $search_data['wocl_car_num'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //车型
                    if (!empty($search_data['wocl_car_vehicle_type'])) {
                        $query->where('wocl_car_vehicle_type', 'like', '%' . $search_data['wocl_car_vehicle_type'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //订单类型1会员零售2客户单位3速电派单
                    if (!empty($search_data['wor_type'])) {
                        $query->where('wor_type', $search_data['wor_type']);
                    }
                })
                ->where(function ($query) use ($search_data) { //1.新订单 2未派单 3待接单/已派单 4.未出发/已接单 5.预约/已预约 6.出发/已出发 7.抵达/抵达 8.待审核/完成待审核 9驳回/完成已驳回 10完成/完成已通过 11终止 12锁定13.速电撤销回收14工单冲单
                    if (!empty($search_data['wor_state'])) {
                        $query->where('wor_state', $search_data['wor_state']);
                    }
                })
                ->where(function ($query) use ($search_data) { //服务技师id
                    if (!empty($search_data['wor_service_adm_id'])) {
                        $query->where('wor_service_adm_id', $search_data['wor_service_adm_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //派单人
                    if (!empty($search_data['wor_create_id'])) {
                        $query->where('wor_create_id', $search_data['wor_create_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //备注
                    if (!empty($search_data['wor_remark'])) {
                        $query->where('wor_remark', 'like', '%' . $search_data['wor_remark'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //订单类型
                    if (!empty($search_data['wor_service_type'])) {
                        $query->where('wor_service_type', $search_data['wor_service_type']);
                    }
                })
                ->where(function ($query) use ($search_data) { //创建时间/派单时间
                    // 如果选择开始时间并且选择结束时间
                    if (!empty($search_data['create_time_start']) && !empty($search_data['create_time_end'])) {
                        $query->whereBetween('wor_create_time', [$search_data['create_time_start'], $search_data['create_time_end'] . ' 23:59:59']);
                    } else {
                        // 如果选择开始时间
                        if (!empty($search_data['create_time_start'])) {
                            $query->where('wor_create_time', '>=', $search_data['create_time_start']);
                        } else {
                            // 如果选择结束时间
                            if (!empty($search_data['create_time_end'])) {
                                $query->where('wor_create_time', '<=', $search_data['create_time_end'] . ' 23:59:59');
                            }
                        }
                    }
                })
                ->where(function ($query) use ($search_data) { //1系统工单2外派工单
                    if (!empty($search_data['wocl_wor_type']) && $search_data['wocl_wor_type'] == 1) {
                        $query->whereIn('wocl_wor_type', [1, 3]);
                    } elseif (!empty($search_data['wocl_wor_type'])) {
                        $query->whereIn('wocl_wor_type', [2, 4, 5]);
                    }
                })
                ->where(function ($query) use ($search_data) { //1系统工单2外派工单
                    if (!empty($search_data['join_type']) && $search_data['join_type'] == 1) {
                        $query->whereIn('wocl_wor_type', 4);
                    } elseif (!empty($search_data['join_type'])) {
                        $query->where('wocl_wor_type', 2);
                    }
                })
                ->where(function ($query) use ($search_data) { //服务门店id
                    if (!empty($search_data['wor_service_shop_id'])) {
                        $query->where('wor_service_shop_id', $search_data['wor_service_shop_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //实际金额区间搜索
                    // 如果选择最小钱数并且选择最大钱数
                    if (!empty($search_data['min_price']) && !empty($search_data['max_price'])) {
                        $query->whereBetween('wor_actual_price', [$search_data['min_price'], $search_data['max_price']]);
                    } else {
                        // 如果选择最小钱数
                        if (!empty($search_data['min_price'])) {
                            $query->where('wor_actual_price', '>=', $search_data['min_price']);
                        } else {
                            // 如果选择最大钱数
                            if (!empty($search_data['max_price'])) {
                                $query->where('wor_actual_price', '<=', $search_data['max_price']);
                            }
                        }
                    }
                })
                ->where(function ($query) use ($search_data) { //服务项目id
                    if (!empty($search_data['wor_service_sepr_id'])) {
                        $query->where('wor_service_sepr_id', $search_data['wor_service_sepr_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //客户id/会员id
                    if (!empty($search_data['wocl_client_id'])) {
                        $query->where('wocl_client_id', $search_data['wocl_client_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //仓库id
                    if (!empty($search_data['wor_ware_id'])) {
                        $query->where('wor_ware_id', $search_data['wor_ware_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //商品检索编码
                    if (!empty($search_data['goo_goods_encode'])) {
                        $query->where('orgt_goods_encode', 'like', '%' . $search_data['goo_goods_encode'] . '%');
                    }
                })
                ->select('wor_id', 'wor_create_id', 'wor_number', 'wor_order_number', 'wor_service_sepr_id', 'wor_service_adm_id', 'wor_service_type', 'wor_service_state', 'wor_state', 'wor_pass', 'wor_type', 'wor_goo_amount', 'wor_remark', 'wor_shop_id', 'wor_create_time', 'wor_audit_times', 'wocl_channel_unit', 'wocl_name', 'wocl_phone', 'wocl_car_num', 'wor_service_shop_id', 'wor_ware_id', 'wor_collection_price', 'wocl_longitude', 'wocl_latitude', 'wor_actual_price', 'wocl_province', 'wocl_city', 'wocl_county', 'wocl_address', 'wocl_wor_type', 'wocl_join_audit', 'wor_account_state', 'wocl_join_wor_id', 'wocl_consent_state', 'wocl_appoint_remark', 'wocl_assign_price', 'wocl_rescue_service_price', 'wocl_rescue_collection_price', 'wocl_client_id', 'wocl_sd_virtual_type', 'wocl_precise_lock', 'wor_appoint_time', 'wocl_whether_app', 'wor_order_id', 'wocl_car_vehicle_type', 'wocl_before_wor_state')
                ->orderBy('wor_id', 'desc')
                ->paginate($this->show_count);
        } else {
            $list_data = DB::table('work_order as a')
                ->leftJoin('work_client as b', 'b.wocl_wor_id', '=', 'a.wor_id')
                ->where('wor_cid', $user_info->adm_cid)
                ->where('wor_superior_shop_id', $shop_ids)
                ->where('wor_delete', 1)
                ->where('wor_collection_bill', 1) //是否代收账单：1正常工单2代收账单
                ->where(function ($query) use ($search_data) { //订单单号
                    if (!empty($search_data['wor_order_number'])) {
                        $query->where('wor_order_number', 'like', '%' . $search_data['wor_order_number'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //工单单号
                    if (!empty($search_data['wor_number'])) {
                        $query->where('wor_number', 'like', '%' . $search_data['wor_number'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //客户单位
                    if (!empty($search_data['wocl_channel_unit'])) {
                        $query->where('wocl_channel_unit', 'like', '%' . $search_data['wocl_channel_unit'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //客户姓名
                    if (!empty($search_data['wocl_name'])) {
                        $query->where('wocl_name', 'like', '%' . $search_data['wocl_name'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //客户电话
                    if (!empty($search_data['wocl_phone'])) {
                        $query->where('wocl_phone', 'like', '%' . $search_data['wocl_phone'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //车牌号
                    if (!empty($search_data['wocl_car_num'])) {
                        $query->where('wocl_car_num', 'like', '%' . $search_data['wocl_car_num'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //车型
                    if (!empty($search_data['wocl_car_vehicle_type'])) {
                        $query->where('wocl_car_vehicle_type', 'like', '%' . $search_data['wocl_car_vehicle_type'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //订单类型1会员零售2客户单位3速电派单
                    if (!empty($search_data['wor_type'])) {
                        $query->where('wor_type', $search_data['wor_type']);
                    }
                })
                ->where(function ($query) use ($search_data) { //1.新订单 2未派单 3待接单/已派单 4.未出发/已接单 5.预约/已预约 6.出发/已出发 7.抵达/抵达 8.待审核/完成待审核 9驳回/完成已驳回 10完成/完成已通过 11终止 12锁定13.速电撤销回收14工单冲单
                    if (!empty($search_data['wor_state'])) {
                        $query->where('wor_state', $search_data['wor_state']);
                    }
                })
                ->where(function ($query) use ($search_data) { //服务技师id
                    if (!empty($search_data['wor_service_adm_id'])) {
                        $query->where('wor_service_adm_id', $search_data['wor_service_adm_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //派单人
                    if (!empty($search_data['wor_create_id'])) {
                        $query->where('wor_create_id', $search_data['wor_create_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //备注
                    if (!empty($search_data['wor_remark'])) {
                        $query->where('wor_remark', 'like', '%' . $search_data['wor_remark'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //订单类型
                    if (!empty($search_data['wor_service_type'])) {
                        $query->where('wor_service_type', $search_data['wor_service_type']);
                    }
                })
                ->where(function ($query) use ($search_data) { //创建时间/派单时间
                    // 如果选择开始时间并且选择结束时间
                    if (!empty($search_data['create_time_start']) && !empty($search_data['create_time_end'])) {
                        $query->whereBetween('wor_create_time', [$search_data['create_time_start'], $search_data['create_time_end'] . ' 23:59:59']);
                    } else {
                        // 如果选择开始时间
                        if (!empty($search_data['create_time_start'])) {
                            $query->where('wor_create_time', '>=', $search_data['create_time_start']);
                        } else {
                            // 如果选择结束时间
                            if (!empty($search_data['create_time_end'])) {
                                $query->where('wor_create_time', '<=', $search_data['create_time_end'] . ' 23:59:59');
                            }
                        }
                    }
                })
                ->where(function ($query) use ($search_data) { //1系统工单2外派工单
                    if (!empty($search_data['wocl_wor_type']) && $search_data['wocl_wor_type'] == 1) {
                        $query->whereIn('wocl_wor_type', [1, 3]);
                    } elseif (!empty($search_data['wocl_wor_type'])) {
                        $query->whereIn('wocl_wor_type', [2, 4, 5]);
                    }
                })
                ->where(function ($query) use ($search_data) { //1系统工单2外派工单
                    if (!empty($search_data['join_type']) && $search_data['join_type'] == 1) {
                        $query->where('wocl_wor_type', 4);
                    } elseif (!empty($search_data['join_type']) && $search_data['join_type'] == 2) {
                        $query->where('wocl_wor_type', 2);
                    } elseif (!empty($search_data['join_type']) && $search_data['join_type'] == 3) {
                        $query->where('wocl_wor_type', 5);
                    }
                })
                ->where(function ($query) use ($search_data) { //服务门店id
                    if (!empty($search_data['wor_service_shop_id'])) {
                        $query->where('wor_service_shop_id', $search_data['wor_service_shop_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //实际金额区间搜索
                    // 如果选择最小钱数并且选择最大钱数
                    if (!empty($search_data['min_price']) && !empty($search_data['max_price'])) {
                        $query->whereBetween('wor_actual_price', [$search_data['min_price'], $search_data['max_price']]);
                    } else {
                        // 如果选择最小钱数
                        if (!empty($search_data['min_price'])) {
                            $query->where('wor_actual_price', '>=', $search_data['min_price']);
                        } else {
                            // 如果选择最大钱数
                            if (!empty($search_data['max_price'])) {
                                $query->where('wor_actual_price', '<=', $search_data['max_price']);
                            }
                        }
                    }
                })
                ->where(function ($query) use ($search_data) { //服务项目id
                    if (!empty($search_data['wor_service_sepr_id'])) {
                        $query->where('wor_service_sepr_id', $search_data['wor_service_sepr_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //客户id/会员id
                    if (!empty($search_data['wocl_client_id'])) {
                        $query->where('wocl_client_id', $search_data['wocl_client_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //仓库id
                    if (!empty($search_data['wor_ware_id'])) {
                        $query->where('wor_ware_id', $search_data['wor_ware_id']);
                    }
                })
                ->select('wor_id', 'wor_create_id', 'wor_number', 'wor_order_number', 'wor_service_sepr_id', 'wor_service_adm_id', 'wor_service_type', 'wor_service_state', 'wor_state', 'wor_pass', 'wor_type', 'wor_goo_amount', 'wor_remark', 'wor_shop_id', 'wor_create_time', 'wor_audit_times', 'wocl_channel_unit', 'wocl_name', 'wocl_phone', 'wocl_car_num', 'wocl_address', 'wor_service_shop_id', 'wor_ware_id', 'wor_collection_price', 'wocl_longitude', 'wocl_latitude', 'wor_actual_price', 'wor_plus_minus', 'wocl_province', 'wocl_city', 'wocl_county', 'wocl_wor_type', 'wocl_join_audit', 'wor_account_state', 'wocl_join_wor_id', 'wocl_consent_state', 'wocl_appoint_remark', 'wocl_assign_price', 'wocl_rescue_service_price', 'wocl_rescue_collection_price', 'wocl_client_id', 'wocl_sd_virtual_type', 'wocl_precise_lock', 'wor_appoint_time', 'wocl_whether_app', 'wor_order_id', 'wocl_car_vehicle_type', 'wocl_before_wor_state')
                ->orderBy('wor_id', 'desc')
                ->paginate($this->show_count);
        }
        $list_items = $list_data->items();
        $virtual_shop_id = [];
        $shop_id = [];
        $virtual_adm_id = [];
        if ($list_items) {
            $wocl_client_id = array_unique(array_column($list_items, 'wocl_client_id')); //选择的客户id，会员id/单位id
            // 查询客户单位
            $channel = DB::table('channel_unit')
                ->whereIn('chun_id', $wocl_client_id)
                ->where('chun_shop_id', $shop_ids)
                ->where('chun_state', '1')
                ->pluck('chun_unit_name', 'chun_id')
                ->toArray();
            $wor_order_id = array_column($list_items, 'wor_order_id');
            // 查询订单状态
            $find_ord_state = DB::table('order')
                ->whereIn('ord_id', $wor_order_id)
                ->pluck('ord_wor_state', 'ord_id')->toArray();

            $wor_ware_id = array_column($list_items, 'wor_ware_id');
            $find_ware_data = DB::table('warehouse')
                ->whereIn('ware_id', $wor_ware_id)
                ->pluck('ware_name', 'ware_id')
                ->toArray();

            foreach ($list_items as $key => $value) {
                $wor_id[] = $value->wor_id;
                $adm_id[] = $value->wor_create_id;
                $adm_id[] = $value->wor_service_adm_id;
                $service_sepr_id[] = $value->wor_service_sepr_id;
                $shop_id[] = $value->wor_shop_id;
                if ($value->wocl_wor_type != 4) {
                    $shop_id[] = $value->wor_service_shop_id;
                } else {
                    $virtual_shop_id[] = $value->wor_service_shop_id;
                    $virtual_adm_id[] = $value->wor_service_adm_id;
                }
                $shop_id[] = $value->wor_service_shop_id;
                if ($value->wocl_appoint_remark) {
                    $list_items[$key]->wor_remark = $value->wor_remark . '【预约备注】' . $value->wocl_appoint_remark;
                }
                // 客户单位名称
                if (isset($channel[$value->wocl_client_id])) {
                    $list_items[$key]->wocl_channel_unit = $channel[$value->wocl_client_id];
                } else {
                    if ($value->wor_type == 3) {
                        $list_items[$key]->wocl_channel_unit = '速电快保';
                    } else {
                        $list_items[$key]->wocl_channel_unit = $value->wocl_channel_unit;
                    }
                }
                // 门店未发货,APP拒单,速电锁定,速电撤销后,锁定库存没有还回原仓库,需要把锁定库存还回原仓库
                $list_items[$key]->revocation = 1; //速电锁定撤销订单状态值1无取消工单2取消工单
                if ($value->wor_type == 3) { //速电派单
                    if ($value->wor_state == 12 && $value->wor_service_state == 10 && $find_ord_state[$value->wor_order_id] == 9 && $value->wocl_before_wor_state == 2) {
                        $list_items[$key]->revocation = 2;
                    }
                }

                // 仓库名称
                if (isset($find_ware_data[$value->wor_ware_id])) {
                    $list_items[$key]->wor_ware_id = $find_ware_data[$value->wor_ware_id];
                } else {
                    $list_items[$key]->wor_ware_id = '';
                }
            }
            $shop_id = array_unique($shop_id);
            // 查找账号id对应的账号姓名
            $find_shop = DB::table('shop')
                ->whereIn('shop_id', $shop_id)
                ->select('shop_id', 'shop_store_name', 'shop_type')
                ->get()->toArray();

            // 查找虚拟加盟店数据
            $virtual_shop = DB::table('virtual_shop')
                ->whereIn('vish_id', $virtual_shop_id)
                ->select('vish_id', 'vish_store_name')
                ->get()->toArray();

            $adm_id = array_unique($adm_id);
            // 查找账号id对应的账号姓名
            $find_admin = DB::table('admin')
                ->whereIn('adm_id', $adm_id)
                ->select('adm_id', 'adm_name', 'adm_phone')
                ->get()->toArray();
            // 查找工单商品
            $work_goods = DB::table('work_good as wogo')
                ->leftjoin('goods as goo', 'goo.goo_id', '=', 'wogo.wogo_goo_id')
                ->whereIn('wogo_wor_id', $wor_id)
                ->select('wogo_wor_id', 'wogo_goo_id', 'wogo_goo_name', 'wogo_goo_goods_encode', 'wogo_goo_type', 'wogo_goo_price', 'wogo_goo_amount', 'wogo_is_recycle', 'wogo_actual_recycle_number', 'wogo_collection_price', 'wogo_state', 'wogo_recycle_quantity', 'wogo_recycle_price', 'wogo_tem_goo_name as tem_goo_name', 'wogo_assign_price', 'goo_brse_id', 'goo_bra_name', 'goo_class')
                ->get()->toArray();
            // 查询系列数据
            $goo_brse_id = array_column($work_goods, 'goo_brse_id');
            $brse_data = DB::table('brand_serie')
                ->whereIn('brse_id', $goo_brse_id)
                ->pluck('brse_name', 'brse_id')
                ->toArray();
            foreach ($work_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) {
                            $work_goods[$key]->wogo_goo_name = $brse_data[$value->goo_brse_id] . ' ' . $value->wogo_goo_name;
                        } else {
                            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                $work_goods[$key]->wogo_goo_name = $brse_data[$value->goo_brse_id] . ' ' . $value->wogo_goo_name;
                            }
                        }
                    }
                }
                // 显示品牌名称
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                    if ($value->goo_class == 2) {
                        $work_goods[$key]->wogo_goo_name = $value->goo_bra_name . ' ' . $value->wogo_goo_name;
                    } else {
                        if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $work_goods[$key]->wogo_goo_name = $value->goo_bra_name . ' ' . $value->wogo_goo_name;
                        }
                    }
                }
                unset($work_goods[$key]->goo_class);
                unset($work_goods[$key]->goo_brse_id);
            }
            // 查询备注信息
            $wor_reamrks = DB::table('order_remarks')
                ->whereIn('orre_wor_id', $wor_id)
                ->select('orre_create_adm_name', 'orre_content', 'orre_time', 'orre_wor_id', 'orre_module')
                ->orderby('orre_id', 'desc')
                ->get()->toArray();

            // 服务项目
            $service_project = DB::table('service_project')
                ->whereIn('sepr_id', $service_sepr_id)
                ->select('sepr_id', 'sepr_name')
                ->get()->toArray();

            // 查找所有订单回收金额
            $recycle_price = DB::table('junk_recycle')
                ->whereIn('jur_wor_id', $wor_id)
                ->where('jur_price', '!=', 0)
                ->select('jur_wor_id', 'jur_price')
                ->get()->toArray();
            // 查找操作记录
            $work_log = DB::table('order_log')
                ->whereIn('orlo_wor_id', $wor_id)
                ->orderBy('orlo_id', 'desc')
                ->select('orlo_wor_id', 'orlo_time', 'orlo_create_adm_name', 'orlo_content')
                ->get()->toArray();
        } else {
            $find_admin = [];
            $work_goods = [];
            $service_project = [];
            $find_shop = [];
            $work_log = [];
            $recycle_price = 0;
            $wor_reamrks = [];
            $virtual_shop = [];
        }
        $state_count = DB::table('work_order')
            ->where('wor_cid', $user_info->adm_cid)
            ->where('wor_superior_shop_id', $shop_ids)
            ->where('wor_delete', 1)
            ->where('wor_collection_bill', 1) //是否代收账单：1正常工单2代收账单
            ->select(DB::raw('count(*) as count, wor_state'))
            ->groupBy('wor_state')
            ->get();
        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $this->show_count;        //一页显示多少个
        $data_info['data'] = $list_items;                        //返回数据
        $data_info['find_shop'] = $find_shop;                    //返回门店名称
        $data_info['find_admin'] = $find_admin;                  //返回账号姓名
        $data_info['work_goods'] = $work_goods;                  //订单商品数据
        $data_info['service_project'] = $service_project;        //服务项目
        $data_info['state_count'] = $state_count;                //状态数量统计
        $data_info['recycle_price'] = $recycle_price;            //订单回收金额
        $data_info['work_log'] = $work_log;                      //操作记录
        $data_info['wor_reamrks'] = $wor_reamrks;                //工单备注
        $data_info['virtual_shop'] = $virtual_shop;              //虚拟加盟店

        if ($list_data) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data_info]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }

    // 工单列表-检索编码搜索
    public function goodsIndex($user_info, $shop_ids, $search_data)
    {
        set_time_limit(0);

        $list_data = DB::table('work_good')
            ->where('wogo_state', '!=', 2)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_goods_encode'])) {
                    $query->where('wogo_goo_goods_encode', $search_data['goo_goods_encode']);
                }
            }) //商品检索编码
            ->select('wogo_wor_id', 'wogo_goo_name', 'wogo_goo_goods_encode')
            ->groupBy('wogo_wor_id')
            ->get()->toArray();
        foreach ($list_data as $key=>$value) {
            // 查询该单是否存在
            $orgt_id = DB::table('order_goods_temporary')
                ->where('orgt_ord_id', $value->wogo_wor_id)
                ->where('orgt_adm_id', $user_info->adm_id)
                ->where('orgt_type', 2)
                ->value('orgt_id');
            if (empty($orgt_id)) {
                // 查询工单单号
                $wor_number = DB::table('work_order')
                    ->where('wor_id', $value->wogo_wor_id)
                    ->where('wor_cid', $user_info->adm_cid)
                    ->where('wor_shop_id', $shop_ids)
                    ->where('wor_delete', 1)
                    ->where('wor_collection_bill', 1) //是否代收账单：1正常工单2代收账单
                    ->value('wor_number');
                $orgt_data['orgt_ord_id'] = $value->wogo_wor_id; //工单id
                $orgt_data['orgt_order_number'] = $wor_number ?? ''; //工单单号
                $orgt_data['orgt_adm_id'] = $user_info->adm_id; //操作人
                $orgt_data['orgt_goods_encode'] = $value->wogo_goo_goods_encode; //检索编码
                $orgt_data['orgt_type'] = 2; //类型：1订单2工单
                $orgt_data['orgt_update_time'] = date('Y-m-d H:i:s');
                $orgt_id = DB::table('order_goods_temporary')->insert($orgt_data);
            }
        }
    }

    // 详情
    public function info(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyAppletWorkOrderController;
        $error_message = $verify_data->infoValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::wechatGetUserInfo($request['api_token']);

        $select_field = "wor_id, wor_number, wor_service_sepr_id, wor_audit_times, wor_service_adm_id, wor_code, wor_create_id, wor_service_type, wor_service_state, wor_state, wor_type, wor_goo_amount, wor_remark, wor_pass, wor_create_time, wocl_channel_unit, wocl_name, wocl_phone, wocl_car_num, wocl_address, ware_name, ware_type, ware_id, wor_shop_id, wor_service_shop_id, wor_collection_price, wocl_collect_state, wocl_province, wocl_city, wocl_county, wor_actual_price, wocl_rescue_service_price, wocl_join_wor_id, wocl_assign_price, wocl_plus_minus, wor_plus_minus, wocl_car_vehicle_type, wocl_rescue_collection_price, wocl_join_ord_id, wocl_wor_type, wor_order_id, wocl_client_id, wocl_sd_virtual_type, wocl_shit_id, wor_order_number";
        $work_order = new WorkOrders();
        $return_data = $work_order->info($user_info, $request->all(), 1, $select_field);
        return response()->json($return_data);
    }

    // 派单
    public function assign(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyAppletWorkOrderController;
        $error_message = $verify_data->assignShowValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::wechatGetUserInfo($request['api_token']);

        $find_wor = DB::table('work_order as wor')
            ->leftJoin('work_client as wocl', 'wocl.wocl_wor_id', '=', 'wor.wor_id')
            ->where('wor_id', $request['wor_id'])
            ->where('wor_shop_id', $user_info->adm_shop_id)
            ->select('wor_number', 'wor_service_adm_id', 'wor_service_type', 'wor_ware_id', 'wor_goo_amount', 'wor_remark', 'wor_service_shop_id', 'wor_pass', 'wor_order_id', 'wor_create_id', 'wor_type', 'wocl_client_id', 'wocl_wor_type', 'wor_delete', 'wor_state', 'wor_order_number', 'wocl_name', 'wocl_phone', 'wocl_province', 'wocl_city', 'wocl_address', 'wocl_county', 'wocl_whether_app')
            ->first();
        if (empty($find_wor)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单不存在，无法派单！']);
        }
        if ($find_wor->wor_pass == 4) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单已经锁定，无法派单！']);
        }
        if ($find_wor->wor_delete == 2) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单已经取消，无法派单！']);
        }
        if (!in_array($find_wor->wor_state, [2, 3])) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'该状态不是待接单或者未派单状态, 不能改派技师']);
        }

        DB::beginTransaction();

        // 验证数据
        $verify_data = new VerifyAppletWorkOrderController;
        $error_message = $verify_data->assignValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 判断当前技师状态
        $adm_state = DB::table('admin_shop_role')
            ->where('adm_id', $request['wor_service_adm_id'])
            ->where('shop_id', $user_info->adm_shop_id)
            ->value('adm_state');
        if ($adm_state == 1) {
            $work_order = new WorkOrders();
            $return_data = $work_order->sendAssing($user_info, $request->all(), 1, $find_wor);
            if ($return_data['code'] == 200) {
                $adm_phone =  DB::table('admin')
                    ->where('adm_id', $request['wor_service_adm_id'])
                    ->value('adm_phone');
                $push_name['alias'][] = $adm_phone; //发送对象

                Common::addLog($user_info, getRealIp($request), '工单列表', '派单', $find_wor->wor_number . ' 派单成功');

                $find_order = DB::table('order')
                    ->where('ord_id', $find_wor->wor_order_id)
                    ->first(['ord_other_system_number', 'ord_type', 'ord_service_type']);

                if (config('apisystem.SYNC_STATE') && $find_order->ord_type == 3) {
                    $url = config('apisystem.sd_server_name') . '/index.php/sync_receipt_status';
                    $param['serial_number'] = $find_order->ord_other_system_number; //第三方工单号
                    $param['ip'] = getRealIp($request);
                    $param['type'] = 1;
                    $param['install_id'] = $request['wor_service_adm_id'];
                    $param['time'] = date('Y-m-d H:i:s');
                    $param['token'] = md5(md5($param['time'] . config('apisystem.sd_token'))); //token
                    $doPost_res = Common::doPost($param, $url, 2);
                    $doPost_res = json_decode($doPost_res);
                    if ($doPost_res->code == 204) {
                        DB::rollBack();
                        return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'此技师未同步至速电']);
                    }
                    if ($doPost_res->code != 200) {
                        DB::rollBack();
                        return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'失败']);
                    }
                }
                $result_push = pushMessage($push_name, '您有新的工单：' . $find_wor->wor_number . ' 请注意查收');

                if (!empty($request['wor_service_adm_id']) && $find_wor->wocl_whether_app == 1) {
                    $wechat_msg['pushtype'] = 1; //工单推送
                    $wechat_msg['adm_id'] = $request['wor_service_adm_id']; //推送人
                    $wechat_msg['wor_number'] = $find_wor->wor_number; //工单号
                    $wechat_msg['ord_number'] = $find_wor->wor_order_number; //订单号
                    $wechat_msg['order_type'] = ordType($find_order->ord_service_type); //订单类型
                    $wechat_msg['user_name'] = $find_wor->wocl_name; //姓名
                    $wechat_msg['user_phone'] = $find_wor->wocl_phone; //手机号
                    $wechat_msg['user_dress'] = $find_wor->wocl_province . $find_wor->wocl_city . $find_wor->wocl_county . $find_wor->wocl_address; //手机号
                    $wechat_msg['tittle'] = '您有新工单请及时处理'; //手机
                    $wechat_msg['remark'] = $find_wor->wor_remark; //备注
                    $CashierDesk = new CashierDesk;
                    $CashierDesk->inforPush($wechat_msg);
                }
                DB::commit();
                return response()->json($return_data);
            } else {
                DB::rollBack();
                return response()->json($return_data);
            }
        } else {
            return response()->json(['data'=>500, 'msg'=>'error', 'data'=>'当前技师已离职,无法派单']);
        }
    }

    // 取消工单
    public function delete(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyAppletWorkOrderController;
        $error_message = $verify_data->rejectValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::wechatGetUserInfo($request['api_token']);

        // 查询信息
        $find_wor = DB::table('work_order as wor')
            ->leftjoin('work_client as wocl', 'wocl.wocl_wor_id', '=', 'wor.wor_id')
            ->where('wor_id', $request['wor_id'])
            ->where('wor_shop_id', $user_info->adm_shop_id)
            ->select('wor_number', 'wor_state', 'wor_order_id', 'wor_goo_amount', 'wor_type', 'wor_actual_price', 'wor_ware_id', 'wor_remark', 'wor_pass', 'wor_service_type', 'wor_type', 'wocl_client_id', 'wocl_sd_virtual_type', 'wocl_wor_type', 'wor_order_number', 'wor_delete')
            ->first();
        if (empty($find_wor)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单不存在，无法取消工单！']);
        }
        if (!in_array($find_wor->wor_state, [1, 2, 12])) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单不是未派单状态，无法取消工单！']);
        }
        if ($find_wor->wor_pass == 4) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单已经锁定，无法取消工单！']);
        }
        if ($find_wor->wor_delete != 1) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前工单已经取消！']);
        }

        DB::beginTransaction();

        $work_order = new WorkOrders();
        $return_data = $work_order->deletes($user_info, $request->all(), $find_wor);
        if ($return_data['code'] == 200) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '工单列表', '取消工单', $find_wor->wor_number . '工单取消成功');
            return response()->json($return_data);
        } else {
            DB::rollBack();
            return response()->json($return_data);
        }
    }
}
