<?php
namespace App\Http\Controllers\Api\OtherSystemInterfaces\zptz;

use App\Services\CommonService;
use App\Services\ReceivablePay\ReceivablePayService;
use App\Services\SettleIn\SettleInService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\OtherSystemInterfaces\VerifyOtherSystemOrdersController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use App\Http\Controllers\Api\Push\PushMessageController;
use App\Http\Models\Services\Order;
use App\Http\Models\Services\WarehouseLock;
use BlueCity\Core\Inc\ErrorInc;
use App\Models\Business\WashOrder;
use App\Models\Common as MCommon;
use App\Http\Models\Api\CashierDesk;
use Illuminate\Support\Facades\Validator;

// 与智配贴装系统对接功能
class zptzSystemOrdersController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

    // 同步订单，智配贴装系统派单
    public function importOrders(Request $request)
    {
        $get_ip = getRealIp($request); //获取ip
        // 接收数据流
        $request = file_get_contents("php://input");
        // 解析
        Common::write_log($request, 1, 'importOrders');
        $request = json_decode($request, true);
        // $request = $request->all();
        // 验证数据
        // $verify_data = new VerifyOtherSystemOrdersController;
        // $error_message = $verify_data->importOrdersValidator($request);
        // if ($error_message) {
        //     return response()->json(['code'=>202, 'msg'=>$error_message]);
        // }

        try {
            $return_data = $this->addOrder($request);
            return response()->json($return_data);
        } catch (Exception $e) {
            return response()->json(['code'=>201, 'msg'=>'派单失败', 'data'=>'派单失败']);
        }
    }

    // 生成订单
    public function addOrder($request)
    {
        // 查询绑定门店
        $shop_data = DB::table('shop as s')
            ->leftjoin('shop_relevance as sr', 'sr.shre_shop_id', '=', 's.shop_id')
            ->where('shre_relevance_shop_id', $request['ord_service_shop_id'])
            ->where('shre_relevance_type', 1)//关联系统类型1智配贴装
            ->where('shre_state', 2)//状态1已绑定未确定状态2已绑定已确定
            ->where('shre_delete', 1)
            ->first(['shop_id as adm_shop_id', 'shop_cid as adm_cid', 'shop_superior_id', 'shop_store_name']);
        if (empty($shop_data)) {
            return ['code'=>203, 'msg'=>'此门店未绑定', 'data'=>'此门店未绑定'];
        }
        // 查询绑定的服务项目
        $spcs_sepr_id = DB::table('service_project_correlation_system')
            ->where('spcs_system_type', 1)//绑定系统类型1贴装系统
            ->where('spcs_other_sepr_id', $request['sepr_id'])//对接系统服务项目id
            ->where('spcs_state', 2)
            ->value('spcs_sepr_id');
        if (empty($spcs_sepr_id)) {
            return ['code'=>203, 'msg'=>'服务项目未绑定', 'data'=>'服务项目未绑定'];
        }

        DB::beginTransaction();
        // 订单单号
        $ord_order_number = MCommon::numberRule($shop_data, 1);
        $data['ord_cid'] = $shop_data->adm_cid;
        $data['ord_superior_shop_id'] = $shop_data->adm_shop_id;
        $data['ord_shop_id'] = $shop_data->adm_shop_id;
        $find_order_type = DB::table('order_type')
            ->where('orty_shop_id', $shop_data->adm_shop_id)
            ->where('orty_state', 1)
            ->first();
        if (empty($find_order_type)) {
            $add_ord_type['orty_shop_id'] = $shop_data->adm_shop_id;
            $add_ord_type['orty_name'] = '服务单';
            $add_ord_type['orty_state'] = 1;
            $add_ord_type['orty_default'] = 1;
            $res = DB::table('order_type')->insertGetId($add_ord_type);
            $data['ord_new_type'] = $res;
        } else {
            $data['ord_new_type'] = $find_order_type->orty_id;
        }
        $data['ord_other_system_number'] = $request['platform_number'];
        $data['ord_other_order_num'] = $request['order_num'];
        $data['ord_order_number'] = $ord_order_number;
        $data['ord_type'] = 1;//买家类型：1门店零售2企业客户
//        $data['ord_new_type'] = DB::table('order_type')
//            ->where('orty_shop_id', $shop_data->adm_shop_id)
//            ->where('orty_state', 1)
//            ->value('orty_id');//订单类型
        $data['ord_service_type'] = 1; //订单类型：1生成工单类2不生成工单类3商品单4会员卡
        $data['ord_classify'] = 2; //订单分类：1蓄电池2洗美店3易损件
        $data['ord_is_split'] = 1; //订单拆分1正常单服务订单2多服务分订单3多服务总订单
        $data['ord_payment_way'] = 0; //结算方式：1现金2支付宝3微信4银行卡5会员卡
        $data['ord_source'] = 5;  //下单来源：1pc端2车主端(车主小程序)3技师端4合作商5智配贴装
        $data['ord_add_work_state'] = 1;  //是否生成工单1是2否
        $data['ord_wor_state'] = 7;  //订单的工单状态1未派工单2服务中4已完成、待评价7待接单11取消订单20已评价
        if(isset($request['all_price_values'])){
           // $prices = $request['all_price_values']* 100;
            $prices = $request['goo_price'] * 100;
        }else{
            $prices = $request['sepr_quantity']*$request['goo_price'] * 100;
        }
        $data['ord_order_price'] = $prices;//$request['sepr_quantity']*$request['goo_price'] * 100;
        $data['ord_update_time'] = date('Y-m-d H:i:s');
        $ord_unique_string = md5(md5($shop_data->adm_shop_id . date('Y-m-d H:i:s') . rand(10000, 99999)) . rand(10000, 99999));
        $data['ord_unique_string'] = $ord_unique_string;
        $ord_explain = '';
        if(isset($request['orderMsgInfo'])){
            foreach ($request['orderMsgInfo'] as $vv){
                $ord_explain .= $vv['goo_name'].'×'.$vv['goo_quantity'].',';
            }

        }else{
            if (isset($request['goo_name'])) {
                $ord_explain = $request['goo_name'];
            }
        }

        $data['ord_explain'] = $ord_explain;
        $ord_id = WashOrder::insertGetId($data);
        $sdcode['sdoc_sd_order_num'] = $request['order_num'];
        $sdcode['sdoc_order_num'] = $ord_order_number;
        $sdcode['sdoc_order_id'] = $ord_id;
        $sdcode['sdoc_type'] = $request['is_code']??1;
        $sdcode['sdoc_creactime'] = date("Y-m-d H:i:s");
        $addcode = DB::table('sd_order_code')->insertGetId($sdcode);
        /*-------------------------------------------同步生成应收应付------------------------------------------*/
        $receivable['recpay_cid'] = $data['ord_cid'];
        $receivable['recpay_shop_id'] = $data['ord_shop_id'];
        $receivable['recpay_shop_superior_id'] = $data['ord_superior_shop_id'];
        $receivable['recpay_type'] = '1'; //类型：1.销售订单
//$receivable['recr_number_id'] = $recr_number_id; //应收账单id
        $receivable['recpay_original_id'] = $ord_id; //与类型所对应的id
        $receivable['recpay_original_number'] = $data['ord_order_number']; //与类型所对应的单号
        $receivable['recpay_client_type'] = 6; //客户类型：1.会员零售 2.来往单位 3.加盟店 4会员零售(工单代收）
        $receivable['recpay_client_id'] = '0'; //会员id/来往单位id
        $receivable['recpay_client_name'] = ''; //来往单位名称
        $receivable['recpay_receivable_price'] = $data['ord_order_price']; //应收金额
        $receivable['recpay_arrears_price'] = $data['ord_order_price']; //欠收金额
        $receivable['recpay_actual_price'] = '0'; //实收金额
        $receivable['recpay_cost_price'] = '0'; //成本价
        $receivable['recpay_receivable_pay'] = '0'; //应付金额
        $receivable['recpay_actual_pay'] = '0'; //实付金额
        $receivable['recpay_state'] = '1'; //状态：1未确认2已确认
        $receivable['recpay_order_state'] = '1'; //订单状态：1正常2退款3取消
        $receivable['recpay_remark'] = ''; //备注
        $receivable['recpay_plus_minus'] = '1'; //盈利正负：1正值2负值
        $receivable['recpay_profit'] = '0'; //盈利金额

        ReceivablePayService::add($receivable);
        /*-------------------------------------------同步生成应收应付------------------------------------------*/
        $remaek['orre_cid'] = $data['ord_cid'];
        $remaek['orre_superior_shop_id'] = $data['ord_superior_shop_id'];
        $remaek['orre_shop_id'] = $data['ord_shop_id'];
        $remaek['orre_ord_id'] = $ord_id;
        $remaek['orre_wor_id'] = 0;
        $remaek['orre_create_adm_name'] = '系统同步';
        $remaek['orre_create_adm_id'] = 0;
        $remaek['orre_time'] = date("Y-m-d H:i:s");

        // 添加订单客户表数据
        $orcl_data = [
            'orcl_ord_id' => $ord_id,
            // 'orcl_business_name' => isset($request['orcl_business_name']) ? $request['orcl_business_name'] : '',//企业名称
            // 'orcl_business_id' => isset($request['orcl_business_id']) ? $request['orcl_business_id'] : '',//企业id
            'orcl_name' => $request['orcl_name'] ? $request['orcl_name'] : '散户',
            'orcl_phone' => $request['orcl_phone'] ? $request['orcl_phone'] : '',
            'orcl_carowner_name' => $request['orcl_name'] ? $request['orcl_name'] : '',
            'orcl_carowner_phone' => $request['orcl_phone'] ? $request['orcl_phone'] : '',
            'orcl_car_num' => isset($request['orcl_car_num']) ? $request['orcl_car_num'] : '',
            'orcl_car_vin' => isset($request['orcl_car_vin']) ? $request['orcl_car_vin'] : '', //车架号 车辆识别码
            // 'orcl_car_brand_series' => isset($request['orcl_car_brand_series']) ? $request['orcl_car_brand_series'] : '', //品牌车系
            // 'orcl_carbrse_type' => isset($request['orcl_carbrse_type']) ? $request['orcl_carbrse_type'] : 1, //品牌车系分类
            'orcl_mem_source' => isset($request['orcl_mem_source']) ? $request['orcl_mem_source'] : '', //客户来源
            'orcl_province' => isset($request['orcl_province']) ? $request['orcl_province'] : '',
            'orcl_city' => isset($request['orcl_city']) ? $request['orcl_city'] : '',
            'orcl_county' => isset($request['orcl_county']) ? $request['orcl_county'] : '',
            'orcl_address' => isset($request['orcl_address']) ? $request['orcl_address'] : '',
            'orcl_update_time' => date('Y-m-d H:i:s'),
        ];
        // 客户下单备注
        if (isset($request['content']) && !empty($request['content'])) {
            $remaek['orre_content'] = $request['content'];
            $remaek['orre_module'] = '客户留言';
            DB::table('zptz_remarks')->insertGetId($remaek);
            $orcl_data['orcl_cus_msg'] = $request['content'];
        }
        // 客户车型
        if (isset($request['car_infor']) && !empty($request['car_infor'])) {
            $remaek['orre_content'] = $request['car_infor'];
            $remaek['orre_module'] = '客户车型';
            DB::table('zptz_remarks')->insertGetId($remaek);
            $orcl_data['orcl_car_brand_series'] = $request['car_infor'];
        }
        $orcl_id = DB::table('order_client')->insertGetId($orcl_data);
        $edit_data['ord_orcl_id'] = $orcl_id;
        WashOrder::where('ord_id', $ord_id)->update($edit_data);

        // 服务类型单子，传过来的是服务 循环来商品存
        $orgo_data['orgo_ord_id'] = $ord_id;
        $orgo_data['orgo_order_number'] = $ord_order_number;
        $orgo_data['orgo_goo_id'] = $spcs_sepr_id;
        $orgo_data['orgo_goo_type'] = 2;//商品类型 1正常商品2服务3会员卡
        $orgo_data['orgo_goo_inventory'] = 1;
        $orgo_data['orgo_state'] = 1;
        $orgo_data['orgo_goo_unit'] = '次';
        $orgo_data['orgo_update_time'] = date('Y-m-d H:i:s');
        $sepr_names = '';
        $sepr_quantitys = 0;
        if(isset($request['orderMsgInfo'])){
            $sepr_quantitys = array_sum(array_column($request['orderMsgInfo'], 'sepr_quantity'));
            foreach ($request['orderMsgInfo'] as $v){
                $orgo_data['orgo_goo_name'] = $v['goo_name'];//$v['sepr_name'];
                $orgo_data['orgo_goo_quantity'] = $v['sepr_quantity'];
                $orgo_data['orgo_goo_price'] = $v['goo_price'] * 100;
                $orgo_data['orgo_goo_amount'] = $v['goo_price'] * 100;
                $orgo_data['orgo_can_assign_quantity'] = $v['sepr_quantity'];
                $orgo_id = DB::table('order_goods')->insertGetId($orgo_data);

                $sepr_names .= $v['sepr_name'].',';
            }
        }else{
            $orgo_data['orgo_goo_name'] = $request['sepr_name'];
            $orgo_data['orgo_goo_quantity'] = $request['sepr_quantity'];
            $orgo_data['orgo_goo_price'] = $request['goo_price'] * 100;
            $orgo_data['orgo_goo_amount'] = $request['goo_price'] * 100;
            $orgo_data['orgo_can_assign_quantity'] = $request['sepr_quantity'];
            $orgo_id = DB::table('order_goods')->insertGetId($orgo_data);
        }


        // 添加排班计划
        $wopl_data['wopl_shop_id'] = $shop_data->adm_shop_id;
        // $wopl_data['wopl_wor_id'] = $wor_id;
        $wopl_data['wopl_ord_id'] = $ord_id;
        $wopl_data['wopl_sepr_id'] = 0;
        $wopl_data['wopl_sepr_name'] = $request['sepr_quantity']??$sepr_quantitys;
        $wopl_data['wopl_goo_id'] = 0;
        $wopl_data['wopl_goo_name'] = $request['sepr_name']??$sepr_names;//$request['sepr_name'];
        $wopl_data['wopl_address_id'] = $shop_data->adm_shop_id;
        $wopl_data['wopl_address'] = $shop_data->shop_store_name."(本店)";
        $wopl_data['wopl_address_type'] = 1;
        $wopl_data['wopl_sale_name'] = '';
        $wopl_data['wopl_sale_id'] = '';
        $wopl_data['wopl_explain'] = '';
        $wopl_data['wopl_time'] = isset($request['orcl_appoint_time']) ? date('H:i:s', strtotime($request['orcl_appoint_time'])) : '';
        $wopl_data['wopl_date'] = isset($request['orcl_appoint_time']) ? date('Y-m-d', strtotime($request['orcl_appoint_time'])) : '';
        $wopl_data['wopl_create_time'] = date('Y-m-d H:i:s');
        $wopl_id = DB::table('work_plan')->insertGetId($wopl_data);

        // 添加查看商品图片
        if (isset($request['config_img'])) {
            $config_img = $request['config_img'];
            $code = array_column($config_img, 'code');
            if (!empty($config_img)) {
                $all_image = DB::table('image_config')
                    ->where('imco_type', 1)
                    ->get()->toArray();
                foreach ($all_image as $k => $v) {
                    $add_image_data['vaca_shop_id'] = $shop_data->adm_shop_id;
                    $add_image_data['vaca_ord_id'] = $ord_id;
                    $add_image_data['vaca_type'] = 1;
                    $add_image_data['vaca_data_id'] = $v->imco_id;
                    $add_image_data['vaca_name'] = $v->imco_name
                    ;
                    $add_image_data['vaca_create_time'] = date('Y-m-d H:i:s');
                    $add_image_data['vaca_create_id'] = 0;
                    if (in_array($v->imco_sd_number, $code)) {
                        $add_image_data['vaca_must'] = 1;
                    } else {
                        $add_image_data['vaca_must'] = 2;
                    }
                    $add_image_res = DB::table('wash_validate_car')->insert($add_image_data);
                }
                foreach ($config_img as $key => $value) {
                    $image_data = DB::table('image_config')
                        ->where('imco_sd_number', $value['code'])
                        ->first();
                    if ($image_data) {
                        if ($image_data->imco_type == 2) {
                            $add_comdata['coin_shop_id'] = $shop_data->adm_shop_id;
                            $add_comdata['coin_ord_id'] = $ord_id;
                            $add_comdata['coin_type'] = 3;
                            $add_comdata['coin_name'] = $image_data->imco_name;
                            $add_comdata['coin_data_id'] = $image_data->imco_id;
                            $add_comdata['coin_must'] = $value['image_must'];
                            $add_comdata['coin_create_time'] = date('Y-m-d H:i:s');
                            $add_comdata['coin_create_id'] = 0;
                            $co_res = DB::table('completion_info')->insert($add_comdata);
                        }
                    }
                }
            }
        }
        
        if ($ord_id && $orcl_id && $orgo_id && $wopl_id) {
            DB::commit();
            $adm_id = DB::table('admin')
                ->leftJoin('admin_shop_role as asr', 'asr.adm_id', '=', 'admin.adm_id')
                ->where("asr.shop_id",$shop_data->adm_shop_id)
                ->where('admin.adm_get_push',2)
                ->select('admin.adm_id')
                ->get();
            if($adm_id) {
                $adm_id = CommonService::dataToArray($adm_id);
                foreach($adm_id as $k => $v){
                    $wechat_msg['pushtype'] = 4; //工单推送
                    $wechat_msg['adm_id'] = $v['adm_id']; //推送人
                    $wechat_msg['wor_number'] = $request['order_num']; //订单号
                    $wechat_msg['ord_number'] = $request['platform_number']; //工单编号
                    $wechat_msg['goods'] = '贴膜服务'; //商品信息
                    $wechat_msg['ord_id'] = $ord_id; //订单id
                    $wechat_msg['orcl_name'] = $orcl_data['orcl_name']; //客户姓名
                    $wechat_msg['adm_shop_id'] = $shop_data->adm_shop_id;
                    $wechat_msg['tittle'] = '您有新订单请及时处理'; //手机
                    $CashierDesk = new CashierDesk;
                    $CashierDesk->inforPush($wechat_msg);
                }
            }

            $return_data['ord_id'] = $ord_id; //订单id
            $return_data['ord_order_number'] = $ord_order_number; //订单单号
            return ['code'=>200, 'msg'=>'新增成功', 'data'=>$return_data];
        } else {
            DB::rollBack();
            return ['code'=>500, 'msg'=>'新增失败', 'data'=>'新增失败'];
        }
    }

    // 拒单标签
    public function refuseLabel(Request $request)
    {
        // 智配订单
        $url = config('apiconnect.ZPTZ_URL') . '/index.php/api/supplychain/SupplyMz/searchLable';
        $param['time'] = date('Y-m-d H:i:s');
        $param['type'] = 2;
        $param['token'] = md5(md5($param['time'] . config('apiconnect.ZPTZ_TOKEN'))); //token
        $param_return = Common::doPost($param, $url, 2);
        $param_return = json_decode($param_return, true);        
        return response()->json($param_return);
    }

    // 拒单
    public function orderRefuse(Request $request)
    {
        if (empty($request['label_id']) || empty($request['ord_id']) || empty($request['label_name'])) {
            return response()->json(['code'=>500, 'msg'=>'参数错误', 'data'=>'参数错误']);
        }

        $user_info = Common::getUserInfo($request['api_token']);
        $order_data = DB::table('order')
            ->where('ord_id', $request['ord_id'])
            ->first(['ord_other_system_number', 'ord_wor_state', 'ord_order_number', 'ord_type']);
        if (!in_array($order_data->ord_wor_state, [7])) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前订单不是待接单状态，无法拒单']);
        }

        DB::beginTransaction();
        $ord_data['ord_remark'] = $request->input('ord_remark', '');
        $ord_data['ord_wor_state'] = 11;
        $ord_data['ord_update_time'] = date('Y-m-d H:i:s');
        $ord_res = DB::table('order')
            ->where('ord_id', $request['ord_id'])
            ->update($ord_data);
        if ($ord_res) {
            // 智配订单
            $url = config('apisystem.sd_server_name') . '/index.php/api/supplychain/SupplyMz/sync_receipt_status';
            $param['type'] = 2;
            $param['time'] = date('Y-m-d H:i:s'); //收货时间
            $param['ip'] = getRealIp($request);
            $param['sin_bid'] = $request['label_id']; //拒单标签
            $param['sin_bcentent'] = $request['label_name']; //拒单标签名称
            $param['content'] = $request['label_name'].$request['ord_remark']; //拒单备注
            $param['token'] = md5(md5($param['time'] . config('apiconnect.ZPTZ_TOKEN'))); //token
            $param['serial_number'] = $order_data->ord_other_system_number; //第三方工单号
            $param_return = Common::doPost($param, $url, 2);
            $param_return = json_decode($param_return, true);
            if ($param_return['code'] != 200) {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'失败']);
            }
            //取消应收应付
            $find_rece = DB::table('receivable_pay')
                ->where('recpay_original_id', $request['ord_id'])
                ->first();
            if($find_rece){
                $update_qrres = DB::table('receivable_pay')
                    ->where('recpay_original_id', $request['ord_id'])
                    ->update(['recpay_order_state'=>3]);
            }
            // 添加新增订单信息的提示
            // $inhi_data['inhi_original_adm_id'] = 0; //原始单号创建人
            // $inhi_data['inhi_original_id'] = $request['ord_id']; //原始单id
            // $inhi_data['inhi_original_number'] = $order_data->ord_order_number; //原始单号
            // $inhi_data['inhi_original_state'] = 0; //原始单状态
            // $inhi_data['inhi_original_operation'] = '门店拒单'; //操作
            // $inhi_data['inhi_operation_state'] = 19; //操作状态：19门店拒单
            // addInformationHint($user_info, $inhi_data, 3);

            Common::addLog($user_info, getRealIp($request), '订单列表', '拒单', '订单:' . $order_data->ord_order_number . ' 拒单成功');
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'拒单成功', 'data'=>'拒单成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'拒单失败', 'data'=>'拒单失败']);
        }
    }

    // 智配贴装订单锁定、取消锁定
    public function orderLock(Request $request)
    {
        // 接收数据流
        $request = file_get_contents("php://input");
        // 解析
        Common::write_log($request, 2, 'orderLock');
        $request = json_decode($request, true);

        if (empty($request['order_num']) || empty($request['type']) || empty($request['remark'])) {
            return response()->json(['code'=>202, 'msg'=>'参数错误']);
        }

        $order_data = DB::table('order')
            ->where('ord_other_system_number', $request['order_num'])
            ->first(['ord_id', 'ord_wor_state', 'ord_cid', 'ord_superior_shop_id', 'ord_shop_id', 'ord_order_number']);
        if (empty($order_data)) {
            return response()->json(['code'=>203, 'msg'=>'未找到此订单', 'data'=>'未找到此订单']);
        }

        // 查询工单信息
        $find_wor_data = DB::table('work_order')
                ->where('wor_order_id', $order_data->ord_id)
                ->where('wor_delete', 1)
                ->where('wor_state', '<>', 11)
                ->select('wor_id', 'wor_number', 'wor_service_adm_id', 'wor_order_number', 'wor_appoint_time')
                ->first();

        DB::beginTransaction();
        $remark_data['orre_cid'] = $order_data->ord_cid;
        $remark_data['orre_superior_shop_id'] = $order_data->ord_superior_shop_id;
        $remark_data['orre_shop_id'] = $order_data->ord_shop_id;
        $remark_data['orre_ord_id'] = $order_data->ord_id;
        if ($find_wor_data) {
            $remark_data['orre_wor_id'] = $find_wor_data->wor_id;
        }
        $remark_data['orre_create_adm_name'] = '智配贴装';
        if ($request['type'] == 1) {
            $remark_data['orre_content'] = '已锁定：'. $request['remark'];
            $remark_data['orre_module'] = '智配订单-锁定';
        } else {
            $remark_data['orre_content'] = '取消锁定：'.$request['remark'];
            $remark_data['orre_module'] = '智配订单-取消锁定';
        }
        $remark_data['orre_time'] = date('Y-m-d H:i:s');
        $res = DB::table('zptz_remarks')->insert($remark_data);

        if ($find_wor_data && $find_wor_data->wor_service_adm_id) {
            // 查询技师相关信息
            $find_adm_data = DB::table('admin as a')
                    ->leftJoin('wash_grade_level as b', 'b.grle_id', '=', 'a.adm_grle_id')
                    ->leftJoin('wash_grade_professional as c', 'c.grpr_id', '=', 'b.grle_grpr_id')
                    ->where('adm_id', $find_wor_data->wor_service_adm_id)
                    ->select('adm_id', 'adm_name', 'adm_phone', 'grle_id', 'grle_name', 'grpr_id', 'grpr_name')
                    ->first();
            $find_wogo_data = DB::table('work_good as wogo')
                    ->leftJoin('service_project as sp', 'sp.sepr_id', '=', 'wogo.wogo_goo_id')
                    ->where('wogo_wor_id', $find_wor_data->wor_id)
                    ->where('wogo_goo_type', 2)
                    ->select('wogo_goo_id', 'sepr_name', 'sepr_check_car', 'sepr_id', 'wogo_goo_type')
                    ->get()->toArray();
            $sepr_name = '';
            if ($find_wogo_data) {
                foreach ($find_wogo_data as $key => $value) {
                    $sepr_name = $sepr_name.','.$value->sepr_name;
                }
            }
            // 微信消息推送
            $wechat_msg['pushtype'] = 3; //工单推送
            $wechat_msg['wor_state'] = $remark_data['orre_module']; //工单进度
            $wechat_msg['adm_id'] = $find_wor_data->wor_service_adm_id; //推送人
            $wechat_msg['wor_number'] = $find_wor_data->wor_number; //工单号
            $wechat_msg['ord_number'] = $find_wor_data->wor_order_number; //订单号
            $wechat_msg['user_name'] = $find_adm_data->adm_name; //姓名
            $wechat_msg['user_phone'] = $find_adm_data->adm_phone; //手机号
            $wechat_msg['user_data'] = $find_adm_data->adm_name.' '.$find_adm_data->adm_phone; //姓名
            $wechat_msg['orcl_appoint_time'] = $find_wor_data->wor_appoint_time; //预约时间
            $wechat_msg['sepr_name'] = $sepr_name; //服务项目
            if ($request['type'] == 1) {
                $wechat_msg['tittle'] = '您有智配贴装工单被锁定，请注意查看'; //手机
            } else {
                $wechat_msg['tittle'] = '您有智配贴装工单已取消锁定，请注意查看'; //手机
            }
            $wechat_msg['remark'] = $remark_data['orre_content'];
            $CashierDesk = new CashierDesk;
            $wechat_msg_res = $CashierDesk->inforPush($wechat_msg);
        }

        if ($res) {
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'成功', 'data'=>'成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>203, 'msg'=>'失败', 'data'=>'失败']);
        }
    }

    // 撤销订单
    public function recycleOrder(Request $request)
    {
        // 接收数据流
        $request = file_get_contents("php://input");
        // 解析
        Common::write_log($request, 2, 'sdOrderLock');
        $request = json_decode($request, true);

        if (empty($request['ord_order_number']) || empty($request['type'])) {
            return response()->json(['code'=>202, 'msg'=>'参数错误', 'data'=>'参数错误']);
        }

        $order_data = DB::table('order')
            ->where('ord_other_system_number', $request['ord_order_number'])
            ->first(['ord_id', 'ord_wor_state', 'ord_cid', 'ord_superior_shop_id', 'ord_shop_id', 'ord_order_number']);
        if (empty($order_data)) {
            return response()->json(['code'=>203, 'msg'=>'未找到此订单', 'data'=>'未找到此订单']);
        }
        if ($order_data->ord_wor_state == 20) {
            return response()->json(['code'=>203, 'msg'=>'订单已完成，无法撤销', 'data'=>'订单已完成，无法撤销']);
        }

        // 查询工单信息
        $find_wor_data = DB::table('work_order')
                ->where('wor_order_id', $order_data->ord_id)
                ->where('wor_delete', 1)
                ->where('wor_state', '<>', 11)
                ->select('wor_id', 'wor_service_state', 'wor_number', 'wor_service_adm_id')
                ->first();
                
        DB::beginTransaction();
        // 判断是否生成工单，未生成工单的可以把订单改为取消状态
        $wor_res = false;
        if (empty($find_wor_data)) {
            $wor_res = true;
        } else {
            // 已经生成工单的，技师没有接单的，订单可以改为取消状态
            if ($find_wor_data->wor_service_state == 1) {
                $wor_data['wor_delete'] = 2;
                $wor_data['wor_update_time'] = date('Y-m-d H:i:s');
                $wor_res = DB::table('work_order')
                    ->where('wor_id', $find_wor_data->wor_id)
                    ->update($wor_data);
            } else {
                $wor_res = true;
            }
        }
        $ord_data['ord_wor_state'] = 11;
        $ord_data['ord_update_time'] = date('Y-m-d H:i:s');
        $ord_res = DB::table('order')
            ->where('ord_id', $order_data->ord_id)
            ->update($ord_data);

        $remark_data['orre_cid'] = $order_data->ord_cid;
        $remark_data['orre_superior_shop_id'] = $order_data->ord_superior_shop_id;
        $remark_data['orre_shop_id'] = $order_data->ord_shop_id;
        $remark_data['orre_ord_id'] = $order_data->ord_id;
        if ($find_wor_data) {
            $remark_data['orre_wor_id'] = $find_wor_data->wor_id;
        }
        $remark_data['orre_create_adm_name'] = '智配贴装';
        if ($request['type'] == 1) {
            $remark_data['orre_content'] = '已撤销：'.$request['remark'];
            $remark_data['orre_module'] = '智配订单-撤销';
        } else {
            $remark_data['orre_content'] = '已回收：'.$request['remark'];
            $remark_data['orre_module'] = '智配订单-回收';
        }
        $remark_data['orre_time'] = date('Y-m-d H:i:s');
        $res = DB::table('zptz_remarks')->insert($remark_data);
        if ($res && $ord_res && $wor_res) {
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'成功', 'data'=>'成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>203, 'msg'=>'失败', 'data'=>'失败']);
        }
    }

    // 审核订单，通过、驳回
    public function opinionOrder(Request $request)
    {
        // 接收数据流
        $request = file_get_contents("php://input");
        // 解析
        Common::write_log($request, 2, 'opinionOrder');
        $request = json_decode($request, true);

        if (empty($request['ord_order_number']) || empty($request['type'])) {
            return response()->json(['code'=>202, 'msg'=>'参数错误', 'data'=>'参数错误']);
        }

        $order_data = DB::table('order')
            ->where('ord_other_system_number', $request['ord_order_number'])
            ->where('ord_wor_state', '<>', 11)
            ->first(['ord_id', 'ord_wor_state', 'ord_cid', 'ord_superior_shop_id', 'ord_shop_id', 'ord_order_number', 'ord_create_time']);
        if (empty($order_data)) {
            return response()->json(['code'=>203, 'msg'=>'未找到此订单', 'data'=>'未找到此订单']);
        }
        // 查询工单信息
        $find_wor_data = DB::table('work_order')
                ->where('wor_order_id', $order_data->ord_id)
                ->where('wor_delete', 1)
                ->where('wor_state', '<>', 11)
                ->select('wor_id', 'wor_number', 'wor_service_adm_id', 'wor_order_number', 'wor_appoint_time', 'wor_other_audit')
                ->first();
        if (empty($find_wor_data)) {
            return response()->json(['code'=>203, 'msg'=>'未找到此工单', 'data'=>'未找到此工单']);
        }
        if ($find_wor_data->wor_other_audit != 1) {
            return response()->json(['code'=>200, 'msg'=>'当前工单已审核！', 'data'=>'当前工单已审核！']);
        }

        DB::beginTransaction();
        $remark_data['orre_cid'] = $order_data->ord_cid;
        $remark_data['orre_superior_shop_id'] = $order_data->ord_superior_shop_id;
        $remark_data['orre_shop_id'] = $order_data->ord_shop_id;
        $remark_data['orre_ord_id'] = $order_data->ord_id;
        if ($find_wor_data) {
            $remark_data['orre_wor_id'] = $find_wor_data->wor_id;
        }
        $remark_data['orre_create_adm_name'] = '智配贴装';
        if ($request['type'] == 1) {
            $remark_data['orre_content'] = '已通过：'. isset($request['remark']) ? $request['remark'] : '';
            $remark_data['orre_module'] = '智配订单-通过';
            $wor_data['wor_other_audit'] = 2;
        } else {
            $remark_data['orre_content'] = '已驳回：'.$request['remark'];
            $remark_data['orre_module'] = '智配订单-驳回';
            $wor_data['wor_other_audit'] = 3;
            $wor_data['wor_state'] = 7;
            $wor_data['wor_service_state'] = 5;
        }
        $remark_data['orre_time'] = date('Y-m-d H:i:s');
        $res = DB::table('zptz_remarks')->insert($remark_data);
        // 更改工单状态
        $wor_res = DB::table('work_order')
            ->where('wor_id', $find_wor_data->wor_id)
            ->update($wor_data);
        if ($res && $wor_res) {
            if ($request['type'] == 2) {
                // 查询技师相关信息
                $find_adm_data = DB::table('admin as a')
                        ->leftJoin('wash_grade_level as b', 'b.grle_id', '=', 'a.adm_grle_id')
                        ->leftJoin('wash_grade_professional as c', 'c.grpr_id', '=', 'b.grle_grpr_id')
                        ->where('adm_id', $find_wor_data->wor_service_adm_id)
                        ->select('adm_id', 'adm_name', 'adm_phone', 'grle_id', 'grle_name', 'grpr_id', 'grpr_name')
                        ->first();
                $find_wogo_data = DB::table('work_good as wogo')
                        ->leftJoin('service_project as sp', 'sp.sepr_id', '=', 'wogo.wogo_goo_id')
                        ->where('wogo_wor_id', $find_wor_data->wor_id)
                        ->where('wogo_goo_type', 2)
                        ->select('wogo_goo_id', 'sepr_name', 'sepr_check_car', 'sepr_id', 'wogo_goo_type')
                        ->get()->toArray();
                $sepr_name = '';
                if ($find_wogo_data) {
                    foreach ($find_wogo_data as $key => $value) {
                        $sepr_name = $sepr_name.','.$value->sepr_name;
                    }
                }
                // 微信消息推送
                $wechat_msg['pushtype'] = 3; //工单推送
                $wechat_msg['wor_state'] = '审核驳回'; //工单进度
                $wechat_msg['adm_id'] = $find_wor_data->wor_service_adm_id; //推送人
                $wechat_msg['wor_number'] = $find_wor_data->wor_number; //工单号
                $wechat_msg['wor_id'] = $find_wor_data->wor_id; //工单id
                $wechat_msg['ord_number'] = $find_wor_data->wor_order_number; //订单号
                $wechat_msg['user_name'] = $find_adm_data->adm_name; //姓名
                $wechat_msg['user_phone'] = $find_adm_data->adm_phone; //手机号
                $wechat_msg['user_data'] = $find_adm_data->adm_name.' '.$find_adm_data->adm_phone; //姓名
                $wechat_msg['orcl_appoint_time'] = $find_wor_data->wor_appoint_time; //预约时间
                $wechat_msg['sepr_name'] = $sepr_name; //服务项目
                $wechat_msg['tittle'] = '您有智配贴装工单被驳回，请及时处理'; //手机
                $wechat_msg['remark'] = $request['remark'];
                $CashierDesk = new CashierDesk;
                $wechat_msg_res = $CashierDesk->inforPush($wechat_msg);
            }
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'成功', 'data'=>'成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>203, 'msg'=>'失败', 'data'=>'失败']);
        }
    }


    // 速电账单同步
    public function importBillOrders(Request $request)
    {
        // 接收数据流
        $request = file_get_contents("php://input");
        // 解析
        Common::write_log($request, 2, 'importBillOrders');
        $request = json_decode($request, true);

        if (empty($request['bill_bumber']) || empty($request['start_time']) || empty($request['end_time']) || empty($request['bill_price']) || empty($request['order_data']) || empty($request['ord_service_shop_id']) || empty($request['sdob_shop_name'])) {
            return response()->json(['code'=>202, 'msg'=>'参数错误1']);
        }
        foreach ($request['order_data'] as $key => $value) {
            if (empty($value['ord_order_number']) || !is_numeric($value['actual_price']) || !is_numeric($value['relative_price']) || empty($value['details_price']) || empty($value['sobd_car_owner_name'])) {
                return response()->json(['code'=>202, 'msg'=>'参数错误2']);
            }
        }
        DB::connection()->enableQueryLog();
    /*    $user_info = DB::table('shop as s')
            ->leftjoin('shop_correlation as sc', 'sc.shco_shop_id', '=', 's.shop_id')
            ->where('sc.shco_system_shop_id', $request['ord_service_shop_id'])
            ->first(['shop_id as adm_shop_id', 'shop_cid as adm_cid', 'shop_superior_id', 'shop_store_name']);
         print_r(DB::getQueryLog());
        if (empty($user_info)) {
            return response()->json(['code'=>203, 'msg'=>'此门店未绑定','data'=>$user_info]);
        }*/
        // 查询绑定门店
        $user_info = DB::table('shop as s')
            ->leftjoin('shop_relevance as sr', 'sr.shre_shop_id', '=', 's.shop_id')
            ->where('shre_relevance_shop_id', $request['ord_service_shop_id'])
            ->where('shre_relevance_type', 1)//关联系统类型1智配贴装
            ->where('shre_state', 2)//状态1已绑定未确定状态2已绑定已确定
            ->where('shre_delete', 1)
            ->first(['shop_id as adm_shop_id', 'shop_cid as adm_cid', 'shop_superior_id', 'shop_store_name']);
        if (empty($user_info)) {
            return ['code'=>203, 'msg'=>'此门店未绑定', 'data'=>'此门店未绑定'];
        }


        $user_info->adm_id = 0;
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        DB::beginTransaction();
        $order_count = count($request['order_data']);
        $number = 'DZ' . time() . rand(10000000, 99999999);
        // 1.订单账单表新增一条数据
        $add_data['orbi_cid'] = $user_info->adm_cid;
        $add_data['orbi_shop_id'] = $user_info->adm_shop_id;
        $add_data['orbi_superior_shop_id'] = $shop_id;
        $add_data['orbi_number'] = $number;
        $add_data['orbi_order_amount'] = $order_count;
        $add_data['orbi_start_time'] = $request['start_time'];
        $add_data['orbi_end_time'] = $request['end_time'];
        $add_data['orbi_state'] = 3; //待审核
        $add_data['orbi_type'] = 3; //类型：1门店零售2渠道单位
        $add_data['orbi_create_type'] = 2; //账单生成类型1手动生成2速电同步生成
        $order_number = [];
        foreach ($request['order_data'] as $key => $value) {
            $order_number[] = $value['ord_order_number'];
        }

        $res = DB::table('sd_order_bill')
            ->where('sdob_sd_bill_bumber', $request['bill_bumber'])
            ->where('sdob_state', '!=', 2)
            ->value('sdob_id');
        if (!empty($res)) {
            return response()->json(['code'=>203, 'msg'=>'结算单号重复']);
        }

        $order_info = DB::table('order')
            ->whereIn('ord_other_system_number', $order_number)
            ->where('ord_delete', 1)
            ->where('ord_state', 1) //未结算
            ->whereIn('ord_wor_state', [4, 5, 8]) //无工单 已完成  撤销订单
            // ->whereBetween('ord_create_time', [$add_data['orbi_start_time'].' 00:00:00',$add_data['orbi_end_time'].' 23:59:59']) //无工单 已完成
            ->get([
                'ord_goods_quantity', 'ord_collection_price', 'ord_actual_price', 'ord_state',
                'ord_service_type', 'ord_plus_minus', 'ord_id', 'ord_other_system_number', 'ord_order_number'
            ]);
        $order_info = json_decode(json_encode($order_info), true);
        // if(count($order_info) != $order_count){
        //     return response()->json(['code'=>203, 'msg'=>'订单集合中有未派过的订单']);
        // }
        $add_data['orbi_collection_price'] = 0; //代收金额
        $add_data['orbi_goods_sum'] = 0; // 商品总量
        $original_id = []; //原始id，更改应收账款数据使用
        $ord_id = [];
        $sys_order_number = [];
        foreach ($order_info as $key => $value) {
            $ord_id[] = $value['ord_id'];
            $sys_order_number[] = $value['ord_other_system_number'];
            $add_data['orbi_collection_price'] += $value['ord_collection_price']; //代收金额
            $add_data['orbi_goods_sum'] += $value['ord_goods_quantity'];
            // if ($value['ord_state'] == 1) { //只相加未结算的订单结算金额
            //     // ord_service_type 订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单
            //     if ($value['ord_service_type'] == 4) {
            //         $original_id[] = $value['ord_id'];
            //         $goods_price -= $value['ord_actual_price'];
            //     } elseif ($value['ord_plus_minus'] == 2 && $value['ord_service_type'] == 3) {
            //         $goods_price -= $value['ord_actual_price'];
            //     } else {
            //         $goods_price += $value['ord_actual_price'];
            //     }
            // }
            foreach ($request['order_data'] as $k => $v) {
                if ($value['ord_other_system_number'] == $v['ord_order_number']) {
                    $request['order_data'][$k]['order_number'] = $value['ord_order_number']; //本系统的订单单号
                    $request['order_data'][$k]['order_id'] = $value['ord_id']; //本系统的订单id

                }
            }
        }
        // 结算金额
        $goods_price = $request['bill_price'];
        // 如果是正数
        if ($goods_price >= 0) {
            $sys_goods_price = $goods_price;
            $plus_minus = 1;
            $goods_price = $request['bill_price'];
        } else {
            $goods_price = abs($goods_price);
            $sys_goods_price = $goods_price;
            $plus_minus = 2;
        }

        $add_data['orbi_collection_price'] = 0; //代收金额为0
        $add_data['orbi_plus_minus'] = $plus_minus; //正数
        $add_data['orbi_state'] = 1; //账单状态1.未结款2.已结款3.待审核4.已驳回5.部分结款
        $add_data['orbi_merge_state'] = 2; //1是2否
        $add_data['orbi_total_price'] = $goods_price; //合计金额（单位：分）订单的结算
        $add_data['orbi_bill_price'] = $goods_price; //结算金额（单位：分）订单结算金额：商品总金额-回收总金额
        $add_data['orbi_actual_price'] = $goods_price; //实收金额（单位：分）订单结算金额-代收金额，实际应收金额
        // $orbi_id = DB::table('order_bill')->insertGetId($add_data);

        /* if (!empty($order_info)) {
            // 2.修改订单表 账单id
            $sql = 'UPDATE `faster_order` SET ';
            $ord_orbi_id = ''; //账单id
            $ord_state = ''; //更改结算状态
            $update_time = ''; //调货时间
            $ord_id_str = "";
            foreach ($ord_id as $key => $value) {
                // 更改账单id
                $ord_orbi_id = $ord_orbi_id . ' WHEN ' .$value;
                $ord_orbi_id = $ord_orbi_id . ' THEN ' .$orbi_id;
                // 更改结算状态
                $ord_state = $ord_state . ' WHEN ' .$value;
                $ord_state = $ord_state . ' THEN 2';
                // 更改时间
                $update_time = $update_time . ' WHEN ' .$value;
                $update_time = $update_time . ' THEN "' .date('Y-m-d H:i:s').'"';
                //要更改的订单id
                $ord_id_str = $ord_id_str . $value.',';
            }
            $sql = $sql .' `ord_orbi_id`= CASE `ord_id` '.$ord_orbi_id.' END,';
            $sql = $sql .' `ord_state`= CASE `ord_id` '.$ord_state.' END,';
            $sql = $sql .' `ord_update_time`= CASE `ord_id` '.$update_time.' END';
            $sql = $sql .' WHERE `ord_id` IN ('.trim($ord_id_str, ',').')';
            $save_order = DB::update($sql);
        } else {
            $save_order = true;
        }
        // 3. 订单退款类型的生成账单之后，应收账款列表不再显示申请还款的按钮
        // 将应收账款的订单退款类型的收款状态改为 3还款待核对状态
        if (empty($original_id)) {
            $update_recr = true;
        } else {
            $recr_edit_data['recr_leisurely_type'] = 3;
            $recr_edit_data['recr_update_time'] = date('Y-m-d H:i:s');
            $update_recr = DB::table('receivable_credit')
                ->where('recr_cid', $user_info->adm_cid)
                ->where('recr_shop_superior_id', $shop_id)
                ->where('recr_type', 3)
                ->where('recr_account_type', 10)
                ->whereIn('recr_original_id', $original_id)
                ->update($recr_edit_data);
        } */

        //速电同步账单表
        $bill['sdob_cid'] = $user_info->adm_cid;
        $bill['sdob_shop_id'] = $user_info->adm_shop_id;
        $bill['sdob_superior_shop_id'] = $shop_id;
        $bill['sdob_sd_bill_bumber'] = $request['bill_bumber'];
        $bill['sdob_orbi_number'] = $number;
        // $bill['sdob_orbi_id'] = $orbi_id;
        $bill['sdob_start_time'] = $add_data['orbi_start_time'];
        $bill['sdob_end_time'] = $add_data['orbi_end_time'];
        $bill['sdob_sd_bill_price'] = $request['bill_price']; //速电账单金额
        $bill['sdob_bill_price'] = $sys_goods_price; //系统账单金额
        $bill['sdob_service_shop_id'] = $request['ord_service_shop_id'];
        $bill['sdob_create_time'] = date('Y-m-d H:i:s');
        $bill['sdob_shop_name'] = $request['sdob_shop_name']; //速电同步的门店名称
        $bill['sdob_stl_ticket'] = $request['sdob_stl_ticket'];

        $sdob_id = DB::table('sd_order_bill')->insertGetid($bill);

        foreach ($request['order_data'] as $key => $value) {
            $bill_details[$key]['sobd_sdob_id'] = $sdob_id;
            $bill_details[$key]['sobd_order_number'] = $value['ord_order_number'];
            $bill_details[$key]['sobd_ord_order_number'] = isset($value['order_number']) ? $value['order_number'] : '';
            $bill_details[$key]['sobd_ord_id'] = isset($value['order_id']) ? $value['order_id'] : '';
            $bill_details[$key]['sobd_actual_price'] = $value['actual_price'];
            $bill_details[$key]['sobd_relative_price'] = $value['relative_price'];
            $bill_details[$key]['sobd_details_price'] = json_encode($value['details_price']);
            $bill_details[$key]['sobd_car_owner_name'] = $value['sobd_car_owner_name']; //速电同步的车主姓名
            $bill_details[$key]['sobd_create_time'] = date('Y-m-d H:i:s'); //添加时间
            $bill_details[$key]['sobd_goods_name'] = $value['goods_name'];
           // DB::table('order')->where('ord_id',$value['ord_id'])->update(['ord_orbi_id'=>$sdob_id]);

        }
        $sobd_sdob_id = DB::table('sd_order_bill_details')->insert($bill_details);

        // 6. 生成应收账单
        /* $createBill = ReceivableBill::create(
            $user_info, //用户信息
            3, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
            0, //应收账款id
            $orbi_id, //原始id(订单账单id)
            $number, //应收账款单号/原始号(订单账单编号)
            6, //客户类型：1.门店零售 2.来往单位
            0, //会员id/来往单位id
            '', //来往单位名称
            $goods_price, //实收金额
            date('Y-m-d H:i:s'), //结款时间
            0, //会计科目id
            0, //实际金额
            0, //抹零金额
            1, //状态：1.未核销 2.已核销
            2, //应收账单id是否是自己 1.不是 2.是
            '',  //备注
            0,  //已收金额
            '', //截止时间
            $plus_minus,//金额正负
            5,//显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款
            date('Y-m-d H:i:s'),
            2//是否合并代收：1是2否
        );

        //账单下所有的订单为不统计状态
        $statistics_type_update = DB::table('receivable_credit')
            ->where('recr_cid', $user_info->adm_cid)
            ->where('recr_shop_superior_id', $shop_id)
            ->where('recr_type', 3)
            ->where('recr_belongs_id', $orbi_id)
            ->update(['recr_statistics_type'=>2,'recr_update_time'=>date('Y-m-d H:i:s')]);
        if ($statistics_type_update || $statistics_type_update===0) {
        } else {
            DB::rollBack();
            return response()->json(['code'=> 203, 'msg'=>'生成账单失败']);
        }

        //判断是否有本系统不存在的订单
        $diff_number = array_diff($order_number,$sys_order_number);

        if (!empty($diff_number)) {
            foreach ($diff_number as $key => $value) {
                $price  = 0;
                foreach ($request['order_data'] as $k => $v) {
                    if($v['ord_order_number'] == $value){
                        $price = $v['actual_price'];
                    }
                }
                $rece[$key]['recr_cid'] = $user_info->adm_cid;
                $rece[$key]['recr_shop_id'] = $user_info->adm_shop_id;
                $rece[$key]['recr_shop_superior_id'] = $shop_id;
                $rece[$key]['recr_type'] = 3; //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                $rece[$key]['recr_account_type'] = 5;
                $rece[$key]['recr_number_id'] = $createBill; //应收账单id
                $rece[$key]['recr_belongs_id'] = $orbi_id; //应收账单id
                // $rece[$key]['recr_original_id'] = $recr_original_id; //与类型所对应的id
                $rece[$key]['recr_original_number'] = $value; //与类型所对应的单号
                $rece[$key]['recr_client_type'] = 6; //客户类型：1.门店零售 2.来往单位
                $rece[$key]['recr_client_id'] = 0; //会员id/来往单位id
                $rece[$key]['recr_client_name'] = config('apisystem.sd_chan_info')['name']; //来往单位名称
                $rece[$key]['recr_settle_price'] = $price; //结算金额
                $rece[$key]['recr_actual_price'] = $price; //实际金额
                $rece[$key]['recr_state'] = 1; //状态：1.未核销 2.已核销
                $rece[$key]['recr_plus_minus'] = 1; //金额正负值
                $rece[$key]['recr_bill_type'] = 2; //1系统单  2非系统单
            }
            $recr_res = DB::table('receivable_credit')->insert($rece);
        }else{
            $recr_res = true;
        } */

        // // 查询出 该订单下已结算的 订单id
        // $ord_id = DB::table('order')
        //         ->where('ord_state', 2)
        //         ->where('ord_orbi_id', $orbi_id)
        //         ->get(['ord_id']);
        // $ord_id = json_decode(json_encode($ord_id), true);
        // $ord_id = array_column($ord_id, 'ord_id');
        // if ($orbi_id && $save_order && $update_recr && $sdob_id && $sobd_sdob_id && $createBill && $recr_res) {
        if ($sdob_id && $sobd_sdob_id) {
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'生成账单成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>203, 'msg'=>'生成账单失败']);
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 编辑技师信息
     * @param string orcl_name 姓名
     * @param string orcl_phone 电话
     * @param string orcl_province 省份
     * @param string orcl_city 城市
     * @param string orcl_county 区县
     * @param string orcl_address 地址
     * @param string ord_order_number 工单号
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2023-06-08 008 下午 3:15:01
     * |---------------------------------------------------------------------------------
    */
    public function editSd ( Request $request ){
        $get_ip = getRealIp($request); //获取ip
        // 接收数据流
        $request = file_get_contents("php://input");
        // 解析
        Common::write_log($request, 1, 'editSd');
        $request = json_decode($request, true);
        try {
            $ord_orcl_id = WashOrder::where("ord_other_system_number",$request['ord_order_number'])->value('ord_orcl_id');
            if($ord_orcl_id){
                $orcl_data = [
                    'orcl_name' => $request['orcl_name'] ? $request['orcl_name'] : '散户',
                    'orcl_phone' => $request['orcl_phone'] ? $request['orcl_phone'] : '',
                    'orcl_carowner_name' => $request['orcl_name'] ? $request['orcl_name'] : '',
                    'orcl_carowner_phone' => $request['orcl_phone'] ? $request['orcl_phone'] : '',
                    'orcl_car_num' => isset($request['orcl_car_num']) ? $request['orcl_car_num'] : '',
                    'orcl_province' => isset($request['orcl_province']) ? $request['orcl_province'] : '',
                    'orcl_city' => isset($request['orcl_city']) ? $request['orcl_city'] : '',
                    'orcl_county' => isset($request['orcl_county']) ? $request['orcl_county'] : '',
                    'orcl_address' => isset($request['orcl_address']) ? $request['orcl_address'] : '',
                    'orcl_update_time' => date('Y-m-d H:i:s'),
                ];
                $orcl_id = DB::table('order_client')->where('orcl_id',$ord_orcl_id)->update($orcl_data);
                if($orcl_id){
                    return response()->json(['code'=>200, 'msg'=>'操作成功', 'data'=>'操作成功']);
                }else{
                    return response()->json(['code'=>203, 'msg'=>'编辑失败MZ', 'data'=>'编辑失败MZ']);
                }
            }else{
                return response()->json(['code'=>202, 'msg'=>'工单号不存在MZ', 'data'=>'工单号不存在MZ']);
            }
        } catch (Exception $e) {
            return response()->json(['code'=>201, 'msg'=>'编辑失败MZ', 'data'=>'编辑失败MZ']);
        }
    }

    // 速电驳回
    public function reject(Request $request)
    {
        // 接收数据流
        $request = file_get_contents("php://input");
        // 解析
        Common::write_log($request, 2);
        $request = json_decode($request, true);

        $sd_data = DB::table('sd_order_bill')
            ->where('sdob_sd_bill_bumber', $request['sd_bill_bumber'])
            ->where('sdob_state', '!=', 2)
            ->first(['sdob_sd_bill_bumber', 'sdob_orbi_id', 'sdob_id']);
        if (empty($sd_data)) {
            return response()->json(['code'=>203, 'msg'=>'结算单号错误']);
        }

        $more_id = DB::table('money_record')
            ->where('more_orbi_id', $sd_data->sdob_orbi_id)
            ->value('more_id');
        if (!empty($more_id)) {
            return response()->json(['code'=>203, 'msg'=>'此账单已结款不能驳回']);
        }

        $orbi_info = DB::table('order_bill')
            ->where('orbi_id', $sd_data->sdob_orbi_id)
            ->first(['orbi_state', 'orbi_type']);
        if ($sd_data->sdob_orbi_id>0 && $orbi_info->orbi_state != 1) {
            return response()->json(['code'=>203, 'msg'=>'此账单已结款不能驳回']);
        }

        DB::beginTransaction();
        //删除速电账单
        $sdob_res = DB::table('sd_order_bill')
            ->where('sdob_id', $sd_data->sdob_id)
            ->update(['sdob_state' => 2, 'sdob_update_time' => date('Y-m-d H:i:s')]);
        if($sd_data->sdob_orbi_id>0) {
            //删除该账单
            $orbi_res = DB::table('order_bill')
                ->where('orbi_id', $sd_data->sdob_orbi_id)
                ->delete();
            //删除已生成的应收账单
            $rece_res = DB::table('receivable_credit')
                ->where('recr_original_id', $sd_data->sdob_orbi_id)
                ->delete();
            //把所属账单id修改成0
            $rece_two = DB::table('receivable_credit')
                ->where('recr_belongs_id', $sd_data->sdob_orbi_id)
                ->update(['recr_belongs_id' => 0, 'recr_update_time' => date('Y-m-d H:i:s')]);

            $order_data['ord_update_time'] = date('Y-m-d H:i:s');
            $order_data['ord_orbi_id'] = 0;
            $order_data['ord_state'] = 1;
            DB::table('order')
                ->where('ord_orbi_id', $sd_data->sdob_orbi_id)
                ->update($order_data);
        }else{
            $orbi_res = true;
            $rece_res = true;
            $rece_two = true;
        }
        if ($sdob_res && $orbi_res && $rece_res && $rece_two) {
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'账单撤回成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>203, 'msg'=>'账单撤回失败']);
        }
    }


    /**
     * @name 服务商同步到门店
     * @return array|\Illuminate\Http\JsonResponse|mixed
     * @author du
     * @date 2023/6/15 synShopByZptz
     * @Time: 13:46
     */
    public function synShopByZptz(){
        // 接收数据流
        $request = file_get_contents("php://input");
        // 解析
        //Common::write_log($request, 2);

        $input = json_decode($request, true);
        if(!is_array($input)){
            return response()->json(['code'=>500, 'msg'=>'门店数据异常请联系管理员']);
        }
        $sexsit = DB::table('shop_relevance')->where('shre_relevance_shop_id',$input['service_id'])->value('shre_id');
        if($sexsit){
            return response()->json(['code'=>2000, 'msg'=>'已绑定']);
        }

        $message = [
            'shop_name.required'=> '门店不能为空',
            // 'shop_name.unique'=> '门店名已存在',
            'phone.required'=> '电话不能为空',
            // 'phone.unique'=> '电话已存在',
            'phone.regex'=> '电话号码不正确',
            'charge_name.required'=> '姓名不能为空',
            'goods_ids.required'=> '服务项目不能为空',
        ];
        $rules = [
            'shop_name' =>'required',
            //  'shop_name' =>'required|unique:settle_in,shop_name',
            'phone' =>'required',
            'phone' =>['regex:/^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/'],
            'charge_name'=>'required',
            'goods_ids'=>'required',
        ];

        $Validator = Validator::make($input,$rules,$message);
        if($Validator->fails()){
            return response()->json(['data'=>'','code'=>500, 'msg'=>$Validator->errors()->first()]);exit;
        }

        $phone_exist = DB::table('settle_in')->where('phone',$input['phone'])->where('status','!=',7)->value('id');
        if($phone_exist){
            return response()->json(['data'=>'','code'=>500, 'msg'=>'手机号已存在']);exit;
        }
        $shop_exist = DB::table('settle_in')->where('shop_name',$input['shop_name'])->where('status','!=',7)->value('id');
        if($shop_exist){
            return response()->json(['data'=>'','code'=>500, 'msg'=>'门店名称已存在']);exit;
        }

        DB::beginTransaction();
        //添加入驻信息
        $input['bussiness_time'] = '08:00-17:00';
        $input['appointment_phone'] = $input['phone'];
        $ret_settle = SettleInService::add($input);
        $ret_settle = CommonService::dataToArray($ret_settle);
       // $ret_settle = json_decode($ret_settle,true);
        CommonService::addLog('入驻', json_encode($ret_settle), '11111','添加入驻返回');
        if($ret_settle['code']!=200){
            DB::rollBack();
            return $ret_settle;
        }
        //创建账号 shop_store_name  shop_phone id shop_name  shop_province shop_city   shop_county  shop_address  shop_password goods_ids
        $input['id'] = $ret_settle['data'];
        $input['shop_store_name'] = $input['shop_name'];
        $input['shop_phone'] = $input['phone'];
        $input['shop_image'] = config('apisystem.server_name_https') .'/image/pcImg/shop_default_img.png';
        $input['shop_province'] = $input['shop_province']??'';
        $input['shop_city'] = $input['shop_city']??'';
        $input['shop_county'] = $input['shop_county']??'';
        $input['shop_address'] = $input['shop_address']??'';
        $input['shop_password'] = $input['shop_password']??substr(trim($input['phone']),0,6);//'123456';
        $input['shop_adm_name'] = $input['charge_name']??'';
        $ret_create = SettleInService::createAccount($input);

        $shop_id = $ret_create['data'];
        CommonService::addLog('入驻', json_encode($ret_create), $shop_id,'添加创建门店返回11');/*  if($ret_createy['code']!=200){
            DB::rollBack();
            return $ret_createy;
        }*/

        //审核通过　互相绑定账号
        //改变状态
        $data['settle_in_id'] = $ret_settle['data'];
        $data['s_status'] = 2;
        $data['remark'] = '自动通过';
       $ret_s = DB::table('settle_in_schedule')->insertGetId($data);
        $update['info_status'] = 2;
        $se_ret = DB::table('settle_sync_information')->where('settle_in_id',$ret_settle['data'])->where('type',1)->update($update);//更新审核结果
       $ret_sett = DB::table('settle_in')->where('id',$ret_settle['data'])->update(['status'=>2, 'shop_id'=>$shop_id]);
        //绑定智配服务商ID

        if(!$sexsit){
            $sarr['shre_relevance_shop_id'] = $input['service_id'];
            $sarr['shre_shop_id'] = $shop_id;
            $sarr['shre_relevance_type'] = 1;
            $sarr['shre_state'] = 2;
            DB::table('shop_relevance')->insert($sarr);
        }
        if($ret_s&&$ret_sett){
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'操作成功','data'=>$shop_id]);
        } else {
            DB::rollBack();
            return response()->json(['code'=>203, 'msg'=>'操作失败']);
        }

    }

    /**
     * @name 智配同步凭证
     * @return \Illuminate\Http\JsonResponse
     * @author du
     * @date 2023/6/16
     * @Time: 11:03
     */
    public function synVoucher(){
        // 接收数据流
        $request = file_get_contents("php://input");
        // 解析
        //Common::write_log($request, 2);
        $input = json_decode($request, true);
        if(empty($input['wat_num'])){
            return response()->json(['code'=>1003, 'msg'=>'账单号不能为空']);
        }
        if(empty($input['voucher'])){
            return response()->json(['code'=>1003, 'msg'=>'凭证不能为空']);
        }

        $exsit = DB::table('sd_order_bill')->where('sdob_sd_bill_bumber',$input['wat_num'])->value('sdob_id');
        if(!$exsit){
            return response()->json(['code'=>202, 'msg'=>'无此账单']);
        }

        $ret = DB::table('sd_order_bill')->where('sdob_sd_bill_bumber',$input['wat_num'])->update(['sdob_is_voucher'=>2,'sdob_voucher'=>$input['voucher']]);
        if($ret){
            return response()->json(['code'=>200, 'msg'=>'操作成功']);
        } else {
            return response()->json(['code'=>203, 'msg'=>'操作失败']);
        }

    }
    
    /**|---------------------------------------------------------------------------------
     * @name 同步财务结算
     * @param string wat_num 结算单号
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2023/8/3 18:08
     * |---------------------------------------------------------------------------------
    */
    public function sysBillOrderState ( Request $request ){
        // 接收数据流
        $request = file_get_contents("php://input");
        // 解析
        //Common::write_log($request, 2);
        // 解析
        Common::write_log($request, 1, 'sysBillOrderState');
        $input = json_decode($request, true);
        if(empty($input['wat_num'])){
            return response()->json(['code'=>1003, 'msg'=>'账单号不能为空']);
        }
        $exsit = DB::table('sd_order_bill')->where('sdob_sd_bill_bumber',$input['wat_num'])->first();
        if(!$exsit){
            return response()->json(['code'=>202, 'msg'=>'无此账单']);
        }
        $exsit = CommonService::dataToArray($exsit);
        $orbi_number = $exsit['sdob_orbi_number'];
        $sdob_state = $exsit['sdob_state'];
        $orbi_state = DB::table('order_bill')->where('orbi_number',$orbi_number)->value('orbi_state');
        DB::beginTransaction();
        if($sdob_state == 3 ){
            $ret = true;
        }else{
            $ret = DB::table('sd_order_bill')->where('sdob_sd_bill_bumber',$input['wat_num'])->update(['sdob_state'=>3]);
        }
        if($orbi_state == 2 ){
            $rea = true;
        }else{
            $rea = DB::table('order_bill')->where('orbi_number',$orbi_number)->update(['orbi_state'=>2]);
        }
        if($ret && $rea){
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'操作成功','data'=>'']);
        }else{
            DB::rollBack();
            return response()->json(['code'=>203, 'msg'=>'操作失败'.$ret.'--'.$rea,'data'=>'']);
        }
    }

}
