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

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

// 微信小程序 -- 业务系统 -- 订单列表
class AppletOrderController 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_id = $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['ord_plus_minus'])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误']);
            }
            $search_data['min_price'] = $search_data['min_price'] * 100;
            if ($search_data['ord_plus_minus'] == 2) {
                $search_data['min_price'] = -$search_data['min_price'];
            }
        }
        // 实际金额最大钱数
        if (!empty($search_data['max_price'])) {
            if (empty($search_data['ord_plus_minus'])) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误']);
            }
            $search_data['max_price'] = $search_data['max_price'] * 100;
            if ($search_data['ord_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', 1)
                ->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_id, $search_data);
            }
            $list_data = DB::table('order as ord')
                ->leftJoin('order_client as orcl', 'orcl.orcl_ord_id', '=', 'ord.ord_id')
                ->leftJoin('order_goods_temporary as orgt', 'orgt.orgt_ord_id', '=', 'ord.ord_id')
                ->where('ord_cid', $user_info->adm_cid)
                ->where('ord_superior_shop_id', $shop_id)
                ->where('ord_collection_bill', 1) //是否代收账单：1正常订单2代收账单
                ->where('orgt_adm_id', $user_info->adm_id)
                ->where('orgt_type', 1)
                ->where(function ($query) use ($search_data) { //仓库名称
                    if (!empty($search_data['ware_id'])) {
                        $query->where('ord_ware_id', $search_data['ware_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //业务员搜索
                    if (!empty($search_data['orcl_adm_id'])) {
                        $query->where('chun_adm_id', $search_data['orcl_adm_id'])
                            ->where('ord_type', 2);
                    }
                })
                ->where(function ($query) use ($search_data) { //订单单号
                    if (!empty($search_data['ord_order_number'])) {
                        $query->where('ord_order_number', 'like', '%' . $search_data['ord_order_number'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //客户姓名
                    if (!empty($search_data['orcl_name'])) {
                        $query->where('orcl_name', 'like', '%' . $search_data['orcl_name'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //客户电话
                    if (!empty($search_data['orcl_phone'])) {
                        $query->where('orcl_phone', 'like', '%' . $search_data['orcl_phone'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //车牌号
                    if (!empty($search_data['orcl_car_num'])) {
                        $query->where('orcl_car_num', 'like', '%' . $search_data['orcl_car_num'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //车型
                    if (!empty($search_data['orcl_car_vehicle_type'])) {
                        $query->where('orcl_car_vehicle_type', 'like', '%' . $search_data['orcl_car_vehicle_type'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //买家类型：1会员零售2客户单位3速电派单4第三方派单5运营中心给门店派单
                    if (!empty($search_data['ord_type'])) {
                        $query->where('ord_type', $search_data['ord_type']);
                    }
                })
                ->where(function ($query) use ($search_data) { //订单类型：1服务单2销售单3换货单4退货单5发货单6结清单7救援单
                    if (!empty($search_data['ord_service_type'])) {
                        $query->where('ord_service_type', $search_data['ord_service_type']);
                    }
                })
                ->where(function ($query) use ($search_data) { //创建人id
                    if (!empty($search_data['ord_create_id'])) {
                        $query->where('ord_create_id', $search_data['ord_create_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //结算状态1未结算2已结算3已核销4已还款
                    if (!empty($search_data['ord_state'])) {
                        $query->where('ord_state', $search_data['ord_state']);
                    }
                })
                ->where(function ($query) use ($search_data) { //订单的工单状态1未派工单2服务中3售后中4已完成5无工单6审核活动7待接单8锁定9速电撤销回收10终止11取消订单12超出可欠天数待审核
                    if (!empty($search_data['ord_wor_state'])) {
                        $query->where('ord_wor_state', $search_data['ord_wor_state']);
                    }
                })
                ->where(function ($query) use ($search_data) { //结算方式1.账期 2.现结 3微信 4支付宝
                    if (!empty($search_data['ord_payment_way'])) {
                        $query->where('ord_payment_way', $search_data['ord_payment_way']);
                    }
                })
                ->where(function ($query) use ($search_data) { //备注
                    if (!empty($search_data['ord_remark'])) {
                        $query->where('ord_remark', 'like', '%' . $search_data['ord_remark'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //创建时间
                    // 如果选择开始时间并且选择结束时间
                    if (!empty($search_data['create_time_start']) && !empty($search_data['create_time_end'])) {
                        $query->whereBetween('ord_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('ord_create_time', '>=', $search_data['create_time_start']);
                        } else {
                            // 如果选择结束时间
                            if (!empty($search_data['create_time_end'])) {
                                $query->where('ord_create_time', '<=', $search_data['create_time_end'] . ' 23:59:59');
                            }
                        }
                    }
                })
                ->where(function ($query) use ($search_data) { //订单分类 1普通订单 2虚拟加盟店订单 3下级门店订单
                    if (!empty($search_data['ord_form_type'])) {
                        $query->where('ord_form_type', $search_data['ord_form_type']);
                    }
                })
                ->where(function ($query) use ($search_data) { //出库方1仓库2直营店3加盟店4虚拟加盟店5下级门店
                    if (!empty($search_data['orcl_shipment_party'])) {
                        $query->where('orcl_shipment_party', $search_data['orcl_shipment_party']);
                    }
                })
                ->where(function ($query) use ($search_data) { //速电指派门店id
                    if (!empty($search_data['ord_service_shop_id'])) {
                        $query->where('ord_service_shop_id', $search_data['ord_service_shop_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //客户id
                    if (!empty($search_data['ord_client_id'])) {
                        $query->where('ord_client_id', $search_data['ord_client_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //实际金额区间搜索
                    // 如果选择最小钱数并且选择最大钱数
                    if (!empty($search_data['min_price']) && !empty($search_data['max_price'])) {
                        $query->whereBetween('ord_actual_price', [$search_data['min_price'], $search_data['max_price']]);
                    } else {
                        // 如果选择最小钱数
                        if (!empty($search_data['min_price'])) {
                            $query->where('ord_actual_price', '>=', $search_data['min_price']);
                        } else {
                            // 如果选择最大钱数
                            if (!empty($search_data['max_price'])) {
                                $query->where('ord_actual_price', '<=', $search_data['max_price']);
                            }
                        }
                    }
                })
                ->where(function ($query) use ($search_data) { //检索编码
                    if (!empty($search_data['goo_goods_encode'])) {
                        $query->where('orgt_goods_encode', 'like', '%' . $search_data['goo_goods_encode'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //速电单号（第三方系统单号）
                    if (!empty($search_data['ord_other_system_number'])) {
                        $query->where('ord_other_system_number', 'like', '%' . $search_data['ord_other_system_number'] . '%');
                    }
                })
                ->select('ord_id', 'ord_create_id', 'ord_order_number', 'ord_goods_quantity', 'ord_actual_price', 'ord_payment_way', 'ord_state', 'ord_wor_state', 'ord_wor_quantity', 'ord_type', 'ord_service_type', 'orcl_channel_unit', 'orcl_name', 'orcl_phone', 'orcl_car_num', 'orcl_province', 'orcl_city', 'orcl_county', 'orcl_address', 'ord_remark', 'ord_create_time', 'ord_order_price', 'ord_delete', 'ord_collection_price', 'ord_service_shop_id', 'orcl_order_type', 'orcl_consent_state', 'orcl_consent_type', 'orcl_reminder_state', 'ord_order_state', 'orcl_assign_price', 'orcl_shipment_party', 'orcl_rescue_service_price', 'orcl_rescue_collection_price', 'ord_service_sepr_id', 'orcl_client_id', 'orcl_appoint_time', 'orcl_appoint_remark', 'ord_ware_id', 'ord_other_system_number', 'ord_client_id')
                ->orderBy('ord_id', 'desc')
                ->paginate($this->show_count);
        } else {
            $orderby_type = 'desc'; //排序类型，默认倒序查询
            // 当查询待接单状态订单时，按正序查询
            if (!empty($request['ord_wor_state']) && $request['ord_wor_state'] == 7) {
                $orderby_type = 'asc'; //默认排序类型
            }
            $list_data = DB::table('order as ord')
                ->leftJoin('order_client as orcl', 'orcl.orcl_ord_id', '=', 'ord.ord_id')
                ->where('ord_cid', $user_info->adm_cid)
                ->where('ord_superior_shop_id', $shop_id)
                ->where('ord_collection_bill', 1) //是否代收账单：1正常订单2代收账单
                ->where(function ($query) use ($search_data) { //仓库名称
                    if (!empty($search_data['ware_id'])) {
                        $query->where('ord_ware_id', $search_data['ware_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //业务员搜索
                    if (!empty($search_data['orcl_adm_id'])) {
                        $query->where('chun_adm_id', $search_data['orcl_adm_id'])
                            ->where('ord_type', 2);
                    }
                })
                ->where(function ($query) use ($search_data) { //订单单号
                    if (!empty($search_data['ord_order_number'])) {
                        $query->where('ord_order_number', 'like', '%' . $search_data['ord_order_number'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //客户单位
                    if (!empty($search_data['orcl_channel_unit'])) {
                        $query->where('orcl_channel_unit', 'like', '%' . $search_data['orcl_channel_unit'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //客户姓名
                    if (!empty($search_data['orcl_name'])) {
                        $query->where('orcl_name', 'like', '%' . $search_data['orcl_name'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //客户电话
                    if (!empty($search_data['orcl_phone'])) {
                        $query->where('orcl_phone', 'like', '%' . $search_data['orcl_phone'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //车牌号
                    if (!empty($search_data['orcl_car_num'])) {
                        $query->where('orcl_car_num', 'like', '%' . $search_data['orcl_car_num'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //车型
                    if (!empty($search_data['orcl_car_vehicle_type'])) {
                        $query->where('orcl_car_vehicle_type', 'like', '%' . $search_data['orcl_car_vehicle_type'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //买家类型：1会员零售2客户单位3速电派单4第三方派单5运营中心给门店派单
                    if (!empty($search_data['ord_type'])) {
                        $query->where('ord_type', $search_data['ord_type']);
                    }
                })
                ->where(function ($query) use ($search_data) { //订单类型：1服务单2销售单3换货单4退货单5发货单6结清单7救援单
                    if (!empty($search_data['ord_service_type'])) {
                        $query->where('ord_service_type', $search_data['ord_service_type']);
                    }
                })
                ->where(function ($query) use ($search_data) { //创建人id
                    if (!empty($search_data['ord_create_id'])) {
                        $query->where('ord_create_id', $search_data['ord_create_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //结算状态1未结算2已结算3已核销4已还款
                    if (!empty($search_data['ord_state'])) {
                        $query->where('ord_state', $search_data['ord_state']);
                    }
                })
                ->where(function ($query) use ($search_data) { //订单的工单状态1未派工单2服务中3售后中4已完成5无工单6审核活动7待接单8锁定9速电撤销回收10终止11取消订单12超出可欠天数待审核
                    if (!empty($search_data['ord_wor_state'])) {
                        $query->where('ord_wor_state', $search_data['ord_wor_state']);
                    }
                })
                ->where(function ($query) use ($search_data) { //结算方式1.账期 2.现结 3微信 4支付宝
                    if (!empty($search_data['ord_payment_way'])) {
                        $query->where('ord_payment_way', $search_data['ord_payment_way']);
                    }
                })
                ->where(function ($query) use ($search_data) { //备注
                    if (!empty($search_data['ord_remark'])) {
                        $query->where('ord_remark', 'like', '%' . $search_data['ord_remark'] . '%');
                    }
                })
                ->where(function ($query) use ($search_data) { //创建时间
                    // 如果选择开始时间并且选择结束时间
                    if (!empty($search_data['create_time_start']) && !empty($search_data['create_time_end'])) {
                        $query->whereBetween('ord_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('ord_create_time', '>=', $search_data['create_time_start']);
                        } else {
                            // 如果选择结束时间
                            if (!empty($search_data['create_time_end'])) {
                                $query->where('ord_create_time', '<=', $search_data['create_time_end'] . ' 23:59:59');
                            }
                        }
                    }
                })
                ->where(function ($query) use ($search_data) { //订单分类 1普通订单 2虚拟加盟店订单 3下级门店订单
                    if (!empty($search_data['ord_form_type'])) {
                        $query->where('ord_form_type', $search_data['ord_form_type']);
                    }
                })
                ->where(function ($query) use ($search_data) { //出库方1仓库2直营店3加盟店4虚拟加盟店5下级门店
                    if (!empty($search_data['orcl_shipment_party'])) {
                        $query->where('orcl_shipment_party', $search_data['orcl_shipment_party']);
                    }
                })
                ->where(function ($query) use ($search_data) { //速电指派门店id
                    if (!empty($search_data['ord_service_shop_id'])) {
                        $query->where('ord_service_shop_id', $search_data['ord_service_shop_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //客户id
                    if (!empty($search_data['ord_client_id'])) {
                        $query->where('ord_client_id', $search_data['ord_client_id']);
                    }
                })
                ->where(function ($query) use ($search_data) { //实际金额区间搜索
                    // 如果选择最小钱数并且选择最大钱数
                    if (!empty($search_data['min_price']) && !empty($search_data['max_price'])) {
                        $query->whereBetween('ord_actual_price', [$search_data['min_price'], $search_data['max_price']]);
                    } else {
                        // 如果选择最小钱数
                        if (!empty($search_data['min_price'])) {
                            $query->where('ord_actual_price', '>=', $search_data['min_price']);
                        } else {
                            // 如果选择最大钱数
                            if (!empty($search_data['max_price'])) {
                                $query->where('ord_actual_price', '<=', $search_data['max_price']);
                            }
                        }
                    }
                })
                ->where(function ($query) use ($search_data) { //速电单号（第三方系统单号）
                    if (!empty($search_data['ord_other_system_number'])) {
                        $query->where('ord_other_system_number', 'like', '%' . $search_data['ord_other_system_number'] . '%');
                    }
                })
                ->select('ord_id', 'ord_create_id', 'ord_order_number', 'ord_goods_quantity', 'ord_actual_price', 'ord_payment_way', 'ord_state', 'ord_wor_state', 'ord_wor_quantity', 'ord_type', 'ord_service_type', 'orcl_channel_unit', 'orcl_name', 'orcl_phone', 'orcl_car_num', 'orcl_province', 'orcl_city', 'orcl_county', 'orcl_address', 'ord_remark', 'ord_create_time', 'ord_order_price', 'ord_delete', 'ord_collection_price', 'ord_service_shop_id', 'orcl_order_type', 'orcl_consent_state', 'orcl_consent_type', 'orcl_reminder_state', 'ord_order_state', 'orcl_assign_price', 'orcl_shipment_party', 'orcl_rescue_service_price', 'orcl_rescue_collection_price', 'ord_service_sepr_id', 'orcl_client_id', 'orcl_appoint_time', 'orcl_appoint_remark', 'ord_ware_id', 'ord_other_system_number', 'ord_client_id')
                ->orderBy('ord_id', $orderby_type)
                ->paginate($this->show_count);
        }
        $ord_service_shop_id = [];
        $virtual_shop_id = [];
        $list_items = $list_data->items();

        if ($list_items) {
            $ord_id = array_column($list_items, 'ord_id'); //订单id
            $ord_create_id = array_unique(array_column($list_items, 'ord_create_id')); //录单人id
            $ord_service_sepr_id = array_unique(array_column($list_items, 'ord_service_sepr_id')); //服务项目id
            $ord_ware_id = array_unique(array_column($list_items, 'ord_ware_id')); //仓库id
            $ord_client_id = array_unique(array_column($list_items, 'ord_client_id')); //选择的客户id，会员id/单位id

            // 查询商品信息
            $order_goods = DB::table('order_goods as orgo')
                ->leftjoin('goods as goo', 'goo.goo_id', '=', 'orgo.orgo_goo_id')
                ->whereIn('orgo_ord_id', $ord_id)
                ->select('orgo_ord_id', 'orgo_goo_id', 'orgo_goo_name', 'orgo_goo_goods_encode', 'orgo_goo_price', 'orgo_goo_quantity', 'orgo_is_recycle', 'orgo_collection_price', 'orgo_state', 'orgo_can_assign_quantity', 'orgo_goo_type', 'orgo_recycle_price', 'orgo_recycle_quantity', 'orgo_tem_goo_name as tem_goo_name', 'orgo_assign_price', 'goo_brse_id', 'goo_bra_name', 'goo_class')
                ->get()->toArray();
            // 查询系列数据
            $goo_brse_id = array_column($order_goods, 'goo_brse_id');
            $brse_data = DB::table('brand_serie')
                ->whereIn('brse_id', $goo_brse_id)
                ->pluck('brse_name', 'brse_id')
                ->toArray();
            foreach ($order_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) {
                            $order_goods[$key]->orgo_goo_name = $brse_data[$value->goo_brse_id] . ' ' . $value->orgo_goo_name;
                        } else {
                            if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                                $order_goods[$key]->orgo_goo_name = $brse_data[$value->goo_brse_id] . ' ' . $value->orgo_goo_name;
                            }
                        }
                    }
                }
                // 显示品牌名称
                if (!in_array($user_info->adm_shop_id, config('apisystem.NO_BRAND_SHOP'))) {
                    if ($value->goo_class == 2) {
                        $order_goods[$key]->orgo_goo_name = $value->goo_bra_name . ' ' . $value->orgo_goo_name;
                    } else {
                        if (!in_array($user_info->adm_shop_id, config('apisystem.NO_SELF_GOODS_SHOP'))) {
                            $order_goods[$key]->orgo_goo_name = $value->goo_bra_name . ' ' . $value->orgo_goo_name;
                        }
                    }
                }
                unset($order_goods[$key]->goo_class);
                unset($order_goods[$key]->goo_brse_id);
            }
            // 查询备注信息
            $order_reamrks = DB::table('order_remarks')
                ->whereIn('orre_ord_id', $ord_id)
                ->select('orre_create_adm_name', 'orre_content', 'orre_time', 'orre_ord_id', 'orre_module')
                ->orderby('orre_id', 'desc')
                ->get();

            // 查询服务项目信息
            $find_sepr = DB::table('service_project')
                ->whereIn('sepr_id', $ord_service_sepr_id)
                ->select('sepr_id', 'sepr_name')
                ->get();

            // 查询录单人信息
            $find_adm = DB::table('admin')
                ->whereIn('adm_id', $ord_create_id)
                ->pluck('adm_name', 'adm_id')->toArray();

            // 查找操作记录
            $order_log = DB::table('order_log')
                ->whereIn('orlo_ord_id', $ord_id)
                ->orderBy('orlo_id', 'desc')
                ->select('orlo_ord_id', 'orlo_time', 'orlo_create_adm_name', 'orlo_content')
                ->get();

            // 查询客户单位
            $channel = DB::table('channel_unit')
                ->whereIn('chun_id', $ord_client_id)
                ->where('chun_shop_id', $shop_id)
                ->where('chun_state', '1')
                ->pluck('chun_unit_name', 'chun_id')
                ->toArray();
            // 查找仓库id对应的仓库名称
            $find_ware_data = DB::table('warehouse')
                ->whereIn('ware_id', $ord_ware_id)
                ->where('ware_shop_id', $user_info->adm_shop_id)
                ->pluck('ware_name', 'ware_id')
                ->toArray();
            foreach ($list_items as $key => $value) {
                if ($value->ord_wor_state == '7') {
                    $list_items[$key]->orcl_name = substituteCharacter($list_items[$key]->orcl_name);
                    $list_items[$key]->orcl_phone = substr_replace($list_items[$key]->orcl_phone, '****', 3, 8);
                    $list_items[$key]->orcl_car_num = substr_replace($list_items[$key]->orcl_car_num, '****', 3, 9);
                    $list_items[$key]->orcl_city = '***';
                    $list_items[$key]->orcl_county = '***';
                    $list_items[$key]->orcl_address = '***';
                }
                if ($value->orcl_shipment_party == 4) { //出库方1仓库2直营店3加盟店4虚拟加盟店5下级门店
                    $virtual_shop_id[] = $value->ord_service_shop_id;
                } else {
                    $ord_service_shop_id[] = $value->ord_service_shop_id;
                }
                if ($value->ord_create_id) {
                    $list_items[$key]->adm_name = $find_adm[$value->ord_create_id];
                } else {
                    $list_items[$key]->adm_name = '';
                }
                // 客户单位名称
                if (isset($channel[$value->ord_client_id])) {
                    $list_items[$key]->orcl_channel_unit = $channel[$value->ord_client_id];
                } else {
                    if ($value->ord_type == 3) {
                        $list_items[$key]->orcl_channel_unit = '速电快保';
                    } else {
                        $list_items[$key]->orcl_channel_unit = $value->orcl_channel_unit;
                    }
                }
                // 仓库
                if ($value->ord_ware_id == '0') {
                    $list_items[$key]->ware_name = '';
                } else {
                    $list_items[$key]->ware_name = $find_ware_data[$value->ord_ware_id];
                }
                unset($list_items[$key]->ord_ware_id);
                unset($list_items[$key]->ord_client_id);
            }

            // 查找服务门店id
            $shop_name = DB::table('shop')
                ->whereIn('shop_id', $ord_service_shop_id)
                ->select('shop_id', 'shop_store_name', 'shop_type')
                ->get();
            // 查找虚拟加盟店数据
            $virtual_shop = DB::table('virtual_shop')
                ->whereIn('vish_id', $virtual_shop_id)
                ->get(['vish_id', 'vish_store_name']);
        } else {
            $order_goods = [];
            $order_log = [];
            $shop_name = [];
            $order_reamrks = [];
            $virtual_shop = [];
            $find_sepr = [];
        }

        $state_count = DB::table('order')
            ->where('ord_cid', $user_info->adm_cid)
            ->where('ord_superior_shop_id', $shop_id)
            ->where('ord_delete', 1)
            ->select(DB::raw('count(*) as count, ord_wor_state'))
            ->groupBy('ord_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['order_goods'] = $order_goods;                //订单商品数据
        $data_info['state_count'] = $state_count;
        $data_info['order_log'] = $order_log;                    //操作记录
        $data_info['shop_name'] = $shop_name;                //门店名称
        $data_info['order_reamrks'] = $order_reamrks;        //订单备注
        $data_info['virtual_shop'] = $virtual_shop;          //虚拟加盟店
        $data_info['find_sepr'] = $find_sepr;          //服务项目
        $data_info['now_time'] = date('Y-m-d H:i:s');          //当前时间

        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_id, $search_data)
    {
        set_time_limit(0);

        $list_items = DB::table('order_goods')
            ->where('orgo_state', '!=', 2)
            ->where(function ($query) use ($search_data) { //商品检索编码
                if (!empty($search_data['goo_goods_encode'])) {
                    $query->where('orgo_goo_goods_encode', $search_data['goo_goods_encode']);
                }
            })
            ->select('orgo_ord_id', 'orgo_goo_name', 'orgo_goo_goods_encode', 'orgo_order_number')
            ->groupBy('orgo_order_number')
            ->get()->toArray();
        foreach ($list_items as $key => $value) {
            // 查询该单是否存在
            $orgt_id = DB::table('order_goods_temporary')
                ->where('orgt_ord_id', $value->orgo_ord_id)
                ->where('orgt_type', 1)
                ->where('orgt_adm_id', $user_info->adm_id)
                ->value('orgt_id');
            if (empty($orgt_id)) {
                $orgt_data['orgt_ord_id'] = $value->orgo_ord_id; //订单id
                $orgt_data['orgt_order_number'] = $value->orgo_order_number; //订单单号
                $orgt_data['orgt_adm_id'] = $user_info->adm_id; //操作人
                $orgt_data['orgt_goods_encode'] = $value->orgo_goo_goods_encode; //检索编码
                $orgt_data['orgt_type'] = 1; //类型：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 VerifyAppletOrderController;
        $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']);

        // 订单详情
        $order_res = Order::info(
            $user_info,
            $request
        );
        return response()->json($order_res);
    }

    // 取消订单
    public function cancel(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyAppletOrderController;
        $error_message = $verify_data->cancelValidator($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_order = DB::table('order as ord')
            ->leftJoin('order_client as orcl', 'orcl.orcl_ord_id', '=', 'ord.ord_id')
            ->where('ord_id', $request['ord_id'])
            ->where('ord_shop_id', $user_info->adm_shop_id)
            ->select('ord_order_number', 'ord_state', 'ord_delete', 'ord_wor_quantity', 'ord_wor_state', 'ord_service_type', 'ord_type', 'ord_client_id', 'ord_goods_quantity', 'ord_actual_price', 'ord_service_shop_id', 'ord_create_id', 'orcl_shipment_party', 'ord_ware_id', 'ord_create_time')
            ->first();
        if (empty($find_order)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单不存在']);
        }
        if ($find_order->ord_state != 1) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单已结算，无法取消']);
        }
        if ($find_order->ord_delete == 2) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单已经取消']);
        }
        if ($find_order->ord_wor_state == 3) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单正在售后中，无法取消']);
        }
        if ($find_order->ord_service_type == 6) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'结清单无法取消']);
        }

        $create_year_month = substr($find_order->ord_create_time, 0, 7); //创建时间年月
        $now_year_month = date('Y-m'); //当前年月
        if ($now_year_month != $create_year_month && $user_info->adm_id != 46) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'不是本月订单，无法取消']);
        }

        // 查询出该订单下所有的工单
        $find_work = DB::table('work_order')
            ->where('wor_order_id', $request['ord_id'])
            ->select('wor_delete', 'wor_id')
            ->get();
        // 验证当前订单下工单 是否已经全部取消
        foreach ($find_work as $key => $value) {
            if ($value->wor_delete == 1) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单存在未取消的工单']);
            }
            $wor_id[$key] = $value->wor_id;
        }
        if (isset($wor_id)) {
            // 验证订单下的工单的商品是否都已回库
            $find_recycle = DB::table('recede_recycle')
                ->where('rec_source_type', 2) //来源类型1.售后 2.取消工单 3.页面新增
                ->where('rec_state', 1) //回收状态 1.未回收 2.已回收
                ->whereIn('rec_ord_id', $wor_id)
                ->first();
            if ($find_recycle) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单下有工单的商品未回库']);
            }
        }

        DB::beginTransaction();

        // 取消订单
        $order_res = Order::cancel(
            $user_info,
            $request,
            $find_order,
            1
        );

        // 生成操作记录
        $cancel_record = orderLog($user_info, $request['ord_id'], 0, '取消订单');
        // 添加备注
        orderRemark($user_info, $request['ord_id'], '', $request['remark'], '订单列表');

        $ord_data['ord_delete'] = 2; //是否删除：1正常订单2取消订单

        if ($order_res['code'] == 200 && $cancel_record) {
            // 添加新增订单信息的提示
            $inhi_data['inhi_original_adm_id'] = $find_order->ord_create_id; //原始单号创建人
            $inhi_data['inhi_original_id'] = $request['ord_id']; //原始单id
            $inhi_data['inhi_original_number'] = $find_order->ord_order_number; //原始单号
            $inhi_data['inhi_original_state'] = $ord_data['ord_delete']; //原始单状态
            $inhi_data['inhi_original_operation'] = '取消订单'; //操作
            $inhi_data['inhi_operation_state'] = 12; //操作状态：12取消订单
            addInformationHint($user_info, $inhi_data, 1);
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '订单列表', '取消订单', '取消订单：' . $find_order->ord_order_number . '成功');
            return response()->json($order_res);
        } else {
            DB::rollBack();
            return response()->json($order_res);
        }
    }

    // 订单审核
    public function isExceed(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyAppletOrderController;
        $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']);

        $find_ord_data = DB::table('order')
            ->where('ord_id', $request['ord_id'])
            ->where('ord_shop_id', $user_info->adm_shop_id)
            ->select('ord_order_number', 'ord_service_type', 'ord_wor_state')
            ->first();
        if (empty($find_ord_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单不存在！']);
        }
        if ($find_ord_data->ord_wor_state != 12) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单不是待审核状态！']);
        }

        $applet_order = new Order();
        $return_data = $applet_order->isExceed($user_info, $request->all(), $find_ord_data);
        
        if ($return_data['code'] == 200) {
            Common::addLog($user_info, getRealIp($request), '订单列表', '审核', '订单:' . $find_ord_data->ord_order_number);
            return response()->json($return_data);
        } else {
            return response()->json($return_data);
        }
    }
}
