<?php
namespace App\Http\Models\Api;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

class Common extends Model
{
    // 获取用户信息
    public static function getUserInfo($api_token)
    {
        $find_user_info = DB::table('login_temporary')
            ->where('api_token', '=', $api_token)
            ->select('adm_id', 'adm_cid', 'adm_shop_id', 'shop_superior_id', 'adm_name', 'adm_phone', 'shop_versions')
            ->first();
        if (!empty($find_user_info)) {
            $find_user_info->shop_versions = 2;
        }
        return $find_user_info;
    }

    // 移动端获取用户信息
    public static function webgetUserInfo($api_token)
    {
        $find_user_info = DB::table('login_webapp')
            ->where('api_token', '=', $api_token)
            ->select('adm_id', 'adm_cid', 'adm_shop_id', 'shop_superior_id', 'adm_name', 'adm_phone', 'shop_versions')
            ->first();
        $find_user_info->shop_versions = 2;
        return $find_user_info;
    }

    // 微信小程序获取用户信息
    public static function wechatGetUserInfo($api_token)
    {
        $find_user_info = DB::table('login_wechat_applet')
            ->where('api_token', '=', $api_token)
            ->select('adm_id', 'adm_cid', 'adm_shop_id', 'shop_superior_id', 'adm_name', 'adm_phone', 'shop_versions')
            ->first();
        $find_user_info->shop_versions = 2;
        return $find_user_info;
    }

    /**
     * [addLog 添加操作日志]
     * @param [type] $user_info [用户信息]
     * @param [type] $oplo_ip        [操作ip]
     * @param [type] $oplo_module    [操作模块]
     * @param [type] $oplo_action    [操作功能]
     * @param [type] $oplo_content   [操作内容]
     */
    public static function addLog(
        $user_info,
        $oplo_ip,
        $oplo_module,
        $oplo_action,
        $oplo_content
    ) {
        $add_data = [
            'oplo_cid'=>$user_info->adm_cid,
            'oplo_shop_id'=>$user_info->adm_shop_id,
            'oplo_adm_id'=>$user_info->adm_id,
            'oplo_adm_name'=>$user_info->adm_name,
            'oplo_module'=>$oplo_module,
            'oplo_action'=>$oplo_action,
            'oplo_content'=>$oplo_content,
            'oplo_ip'=>$oplo_ip
        ];
        return DB::table('operation_log')->insert($add_data);
    }

    /**
     * [addRemind 电话提醒表添加数据]
     * @param [type] $user_info   		[用户信息]
     * @param [type] $shop_type   		[门店类型]
     * @param [type] $phone_type   		[类型1工单2售后单]
     * @param [type] $wor_id      		[工单id]
     * @param [type] $wor_order_number  [工单编号]
     * @param [type] $service_adm_id    [技师id]
     * @param [type] $service_adm_phone [技师电话]
     */
    public static function addRemind(
        $user_info,
        $shop_type,
        $phone_type,
        $wor_id,
        $wor_order_number,
        $service_adm_id,
        $service_adm_phone
    ) {
        $add_data = [
            'phre_cid'=>$user_info->adm_cid,
            'phre_superior_id'=>$user_info->shop_superior_id,
            'phre_shop_type'=>$shop_type,
            'phre_shop_id'=>$user_info->adm_shop_id,
            'phre_phone_type'=>$phone_type,
            'phre_wor_id'=>$wor_id,
            'phre_wor_number'=>$wor_order_number,
            'phre_service_adm_id'=>$service_adm_id,
            'phre_service_phone'=>$service_adm_phone,
            'phre_phone_state'=>1,
            'phre_remind_state'=>1,
        ];

        return DB::table('phone_remind')->insert($add_data);
    }

    /**
     * [orderRule 订单编号规则]
     * @param [type] $user_info   		[用户信息]
     */
    public static function orderRule($user_info)
    {
        // 查询当前门店有无生成订单编号
        $rule_data = DB::table('order_rule')
                ->where('orru_type', 1) //类型：1.订单编号规则 2.工单编号规则
                ->where('orru_cid', $user_info->adm_cid)
                ->where('orru_shop_id', $user_info->adm_shop_id)
                ->first(['orru_number','orru_date','orru_id']);
        if ($rule_data) {
            // 有此总店的数据 判断是不是今天的
            if ($rule_data->orru_date == date('Y-m-d')) {
                // 订单总量+1
                $order_rule = DB::table('order_rule')
                        ->where('orru_id', $rule_data->orru_id)
                        ->increment('orru_number');

                $today_order = $rule_data->orru_number + 1; //今天的订单总量
            } else {
                // 修改日期为今天 订单总量从1开始
                $orru_data['orru_date'] = date('Y-m-d');
                $orru_data['orru_number'] = 1;
                $orru_data['orru_update_time'] = date('Y-m-d H:i:s');
                $order_rule = DB::table('order_rule')
                        ->where('orru_id', $rule_data->orru_id)
                        ->update($orru_data);

                $today_order = 1; //今天的订单总量
            }
        } else {
            // 新增一条数据
            $orru_data['orru_cid'] = $user_info->adm_cid;
            $orru_data['orru_superior_id'] = $user_info->shop_superior_id;
            $orru_data['orru_shop_id'] = $user_info->adm_shop_id;
            $orru_data['orru_type'] = 1; //类型：1.订单编号规则 2.工单编号规则
            $orru_data['orru_date'] = date('Y-m-d');
            $orru_data['orru_number'] = 1;
            $order_rule = DB::table('order_rule')->insert($orru_data);

            $today_order = 1; //今天的订单总量
        }
        //根据门店id长度，订单编号插入6位数字
        $shop_length = 6 - strlen($user_info->adm_shop_id);//门店id剩余补足位数
        $rand_start = str_pad(1, $shop_length, 1, STR_PAD_LEFT);//随机数开始
        $rand_end = str_pad(9, $shop_length, 9, STR_PAD_LEFT);//随机数结束
        // 年月日是8位 门店id+随机数是6位 订单编号共20位 所以补零的位数为5位
        $number = 'D'.date('Ymd').str_pad($user_info->adm_shop_id,6,rand($rand_start, $rand_end),STR_PAD_LEFT) . str_pad($today_order, 5, '0', STR_PAD_LEFT);

        return $number;
    }

    /**
     * [orderRule 工单编号规则]
     * @param [type] $user_info   		[用户信息]
     */
    public static function workRule($user_info)
    {
        // 查询当前门店有无生成工单编号
        $rule_data = DB::table('order_rule')
                ->where('orru_type', 2) //类型：1.订单编号规则 2.工单编号规则
                ->where('orru_shop_id', $user_info->adm_shop_id) //门店id
                ->first(['orru_number','orru_date','orru_id']);
        if ($rule_data) {
            // 有此总店的数据 判断是不是今天的
            if ($rule_data->orru_date == date('Y-m-d')) {
                // 工单总量+1
                $order_rule = DB::table('order_rule')
                        ->where('orru_id', $rule_data->orru_id)
                        ->increment('orru_number');

                $today_order = $rule_data->orru_number + 1; //今天的工单总量
            } else {
                // 修改日期为今天 工单总量从1开始
                $orru_data['orru_date'] = date('Y-m-d');
                $orru_data['orru_number'] = 1;
                $orru_data['orru_update_time'] = date('Y-m-d H:i:s');
                $order_rule = DB::table('order_rule')
                        ->where('orru_id', $rule_data->orru_id)
                        ->update($orru_data);

                $today_order = 1; //今天的工单总量
            }
        } else {
            // 新增一条数据
            $orru_data['orru_cid'] = $user_info->adm_cid;
            $orru_data['orru_superior_id'] = $user_info->shop_superior_id;
            $orru_data['orru_shop_id'] = $user_info->adm_shop_id;
            $orru_data['orru_type'] = 2; //类型：1.订单编号规则 2.工单编号规则
            $orru_data['orru_date'] = date('Y-m-d');
            $orru_data['orru_number'] = 1;
            $order_rule = DB::table('order_rule')->insert($orru_data);

            $today_order = 1; //今天的工单总量
        }
        //根据门店id长度，订单编号插入6位数字
        $shop_length = 6 - strlen($user_info->adm_shop_id);//门店id剩余补足位数
        $rand_start = str_pad(1, $shop_length, 1, STR_PAD_LEFT);//随机数开始
        $rand_end = str_pad(9, $shop_length, 9, STR_PAD_LEFT);//随机数结束
        // 年月日是8位 门店id+随机数是6位 工单单编号共20位 所以补零的位数为5位
        // 年月日时分秒是14位 工单编号共20位 所以补零的位数为6位
        $number = 'G'.date('Ymd').str_pad($user_info->adm_shop_id,6,rand($rand_start, $rand_end),STR_PAD_LEFT) . str_pad($today_order, 5, '0', STR_PAD_LEFT);
        return $number;
    }

    /**
     * updateAnalyze 应收账款分析
     * @param [type] $user_info                 [用户信息]
     * @param [type] $rean_chun_id              [客户单位id]
     * @param [type] $rean_bill_number          [单量]
     * @param [type] $rean_settle_price         [应收账款结算金额]
     * @param [type] $rean_type                 [类型1.编辑+ 2.编辑-]
     */
    public static function updateAnalyze(
        $user_info,
        $rean_chun_id,
        $rean_bill_number,
        $rean_settle_price,
        $rean_type
    ) {
        // 查询出当前客户单位是否有数据
        $analyze_data = DB::table('receivable_analyze')
                    ->where('rean_chun_id', $rean_chun_id)
                    ->first();

        if (!empty($analyze_data)) {
            // 编辑
            if ($rean_type == 1) {
                // +
                // 查订单表下当前客户单位 为账期的未核销订单的最早时间
                $early_time = DB::table('order')
                    ->where('ord_state', '!=', 3)
                    ->where('ord_client_id', $rean_chun_id)
                    ->where('ord_payment_way', 1)
                    ->orderBy('ord_create_time', 'asc')
                    ->value('ord_create_time');
                if (empty($early_time)) {
                    $analyze_sql = 'UPDATE `faster_receivable_analyze` SET  `rean_bill_number`= `rean_bill_number`+ ' . $rean_bill_number .' , `rean_settle_price`= `rean_settle_price` + '.$rean_settle_price.', `rean_update_time`= "'.date('Y-m-d H:i:s').'" WHERE  `rean_chun_id` ='.$rean_chun_id;
                } else {
                    $analyze_sql = 'UPDATE `faster_receivable_analyze` SET  `rean_bill_number`= `rean_bill_number`+ ' . $rean_bill_number .' , `rean_settle_price`= `rean_settle_price` + '.$rean_settle_price.', `rean_owe_time`= "'.$early_time.'", `rean_update_time`= "'.date('Y-m-d H:i:s').'" WHERE  `rean_chun_id` ='.$rean_chun_id;
                }
            } else {
                // -
                // 查订单表下当前客户单位 为账期的订单的最早时间
                $early_time = DB::table('order')
                    ->where('ord_client_id', $rean_chun_id)
                    ->where('ord_payment_way', 1)
                    ->orderBy('ord_create_time', 'asc')
                    ->value('ord_create_time');
                if (empty($early_time)) {
                    $analyze_sql = 'UPDATE `faster_receivable_analyze` SET  `rean_bill_number`= `rean_bill_number`-' . $rean_bill_number .' , `rean_settle_price`= `rean_settle_price` - '.$rean_settle_price.', `rean_update_time`= "'.date('Y-m-d H:i:s').'" WHERE  `rean_chun_id` ='.$rean_chun_id;
                } else {
                    $analyze_sql = 'UPDATE `faster_receivable_analyze` SET  `rean_bill_number`= `rean_bill_number`-' . $rean_bill_number .' , `rean_settle_price`= `rean_settle_price` - '.$rean_settle_price.', `rean_owe_time`= "'.$early_time.'", `rean_update_time`= "'.date('Y-m-d H:i:s').'" WHERE  `rean_chun_id` ='.$rean_chun_id;
                }
            }
            $rean_data = DB::update($analyze_sql);
        } else {
            // 新增

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

            // 查订单表下当前客户单位 为账期的未核销订单的最早时间
            $early_time = DB::table('order')
                    ->where('ord_state', '!=', 3)
                    ->where('ord_client_id', $rean_chun_id)
                    ->where('ord_payment_way', 1)
                    ->orderBy('ord_create_time', 'asc')
                    ->value('ord_create_time');
            
            $rean['rean_cid'] = $user_info->adm_cid;
            $rean['rean_shop_id'] = $user_info->adm_shop_id;
            $rean['rean_shop_superior_id'] = $shop_id;
            $rean['rean_chun_id'] = $rean_chun_id; //客户单位id
            $rean['rean_owe_time'] = $early_time ? $early_time :  ''; //首笔欠收订单创建时间
            $rean['rean_bill_number'] = $rean_bill_number; //单量
            $rean['rean_settle_price'] = $rean_settle_price; //应收账款结算金额
            $rean_data = DB::table('receivable_analyze')->insertGetId($rean);
        }
        
        return $rean_data;
    }

    /**
     * 改动门店销量表
     * @param [type] $user_info                 [用户信息]
     * @param [type] $shoa_ord_number           [订单数量]
     * @param [type] $shoa_sales_number         [销售数量]
     * @param [type] $shoa_total_price          [合计：(结算金额)]
     * @param [type] $shoa_type                 [类型1.加 2.减]
     */
    public static function shopSales(
        $user_info,
        $shoa_ord_number,
        $shoa_sales_number,
        $shoa_total_price,
        $shoa_type
    ) {
        // 查询出当前门店是否有数据
        $sales_data = DB::table('shop_sales')
                    ->where('shoa_id', $user_info->adm_cid)
                    ->where('shoa_shop_id', $user_info->adm_shop_id)
                    ->first();
        if (!empty($sales_data)) {
            // 编辑
            if ($shoa_type == 1) {
                $sales_sql = 'UPDATE `faster_shop_sales` SET  `shoa_ord_number`= `shoa_ord_number`+ ' . $shoa_ord_number .' , `shoa_sales_number`= `shoa_sales_number` + '.$shoa_sales_number.' , `shoa_total_price`= `shoa_total_price` + '.$shoa_total_price.' WHERE `shoa_id` ='.$sales_data->shoa_id;
            } else {
                $sales_sql = 'UPDATE `faster_shop_sales` SET  `shoa_ord_number`= `shoa_ord_number`- ' . $shoa_ord_number .' , `shoa_sales_number`= `shoa_sales_number` - '.$shoa_sales_number.' , `shoa_total_price`= `shoa_total_price` - '.$shoa_total_price.' WHERE `shoa_id` ='.$sales_data->shoa_id;
            }
            $shop_sales = DB::update($sales_sql);
        } else {
            // 新增
            // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
            $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
            // 查询出当前门店的类型
            $shop_type = DB::table('shop')
                    ->where('shop_id', $user_info->adm_shop_id)
                    ->value('shop_type');

            $add_data['shoa_cid'] = $user_info->adm_cid;
            $add_data['shoa_superior_shop_id'] = $shop_id;
            $add_data['shoa_shop_id'] = $user_info->adm_shop_id;
            $add_data['shoa_type'] = $shop_type; //类型：1总店2直营店3加盟店
            $add_data['shoa_ord_number'] = $shoa_ord_number; //订单数量
            $add_data['shoa_sales_number'] = $shoa_sales_number; //销售数量
            $add_data['shoa_total_price'] = $shoa_total_price; //合计
            $shop_sales = DB::table('shop_sales')->insertGetId($add_data);
        }
        
        return $shop_sales;
    }

    /**
     * 改动客户销量表
     * @param [type] $user_info                 [用户信息]
     * @param [type] $chsa_chty_id              [客户单位类型id]
     * @param [type] $chsa_client_id            [客户单位id]
     * @param [type] $chsa_ord_number           [订单数量]
     * @param [type] $chsa_sales_number         [销售数量]
     * @param [type] $chsa_total_price          [合计：(结算金额)]
     * @param [type] $chsa_type                 [类型1.加 2.减]
     */
    public static function channelSales(
        $user_info,
        $chsa_chty_id,
        $chsa_client_id,
        $chsa_ord_number,
        $chsa_sales_number,
        $chsa_total_price,
        $chsa_type
    ) {
        // 查询出当前客户单位是否有数据
        $sales_data = DB::table('channel_sales')
                    ->where('chsa_cid', $user_info->adm_cid)
                    ->where('chsa_shop_id', $user_info->adm_shop_id)
                    ->where('chsa_client_id', $chsa_client_id)
                    ->first();
        if (!empty($sales_data)) {
            // 编辑
            if ($chsa_type == 1) {
                $sales_sql = 'UPDATE `faster_channel_sales` SET  `chsa_ord_number`= `chsa_ord_number`+ ' . $chsa_ord_number .' , `chsa_sales_number`= `chsa_sales_number` + '.$chsa_sales_number.' , `chsa_total_price`= `chsa_total_price` + '.$chsa_total_price.' WHERE `chsa_id` ='.$sales_data->chsa_id;
            } else {
                $sales_sql = 'UPDATE `faster_channel_sales` SET  `chsa_ord_number`= `chsa_ord_number`- ' . $chsa_ord_number .' , `chsa_sales_number`= `chsa_sales_number` - '.$chsa_sales_number.' , `chsa_total_price`= `chsa_total_price` - '.$chsa_total_price.' WHERE `chsa_id` ='.$sales_data->chsa_id;
            }
            $channel_sales = DB::update($sales_sql);
        } else {
            // 新增
            // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
            $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

            $add_data['chsa_cid'] = $user_info->adm_cid;
            $add_data['chsa_superior_shop_id'] = $shop_id;
            $add_data['chsa_shop_id'] = $user_info->adm_shop_id;
            $add_data['chsa_type'] = 2; //买家类型：1门店零售2渠道单位
            $add_data['chsa_chty_id'] = $chsa_chty_id; //客户单位类型id
            $add_data['chsa_client_id'] = $chsa_client_id; //选择的客户id，会员id/单位id
            $add_data['chsa_ord_number'] = $chsa_ord_number; //订单数量
            $add_data['chsa_sales_number'] = $chsa_sales_number; //销售数量
            $add_data['chsa_total_price'] = $chsa_total_price; //合计
            $channel_sales = DB::table('channel_sales')->insertGetId($add_data);
        }
        
        return $channel_sales;
    }

    /**
     * 改动销售利润表
     * @param [type] $user_info             [用户信息]
     * @param [type] $sepr_year             [年]
     * @param [type] $sepr_month            [月]
     * @param [type] $sepr_goo_id           [数组, 商品id]
     * @param [type] $sepr_sales_number     [数组, 销售数量(正常订单) / 退货数量(退货单) / 平均成本单价(采购单)]
     * @param [type] $sepr_price            [数组, 销售价格]
     * @param [type] $sepr_return_price     [数组, 退货单价]
     * @param [type] $sepr_type             [1.正常订单 2.退货单 3.采购单]
     * @param [type] $sepr_calculate        [1.+ 2.-]
     * @param [type] $sepr_return_cost      [数组, 退货成本](先不管)
     */
    public static function sellProfit(
        $user_info,
        $sepr_year,
        $sepr_month,
        $sepr_goo_id,
        $sepr_sales_number,
        $sepr_price,
        $sepr_return_price,
        $sepr_type,
        $sepr_calculate
        // $sepr_return_cost,
    ) {
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
        
        // 将数据与商品id一一对应
        foreach ($sepr_goo_id as $key => $value) {
            if (!empty($sepr_sales_number)) {
                // 商品id和所对应的销售数量/退货数量/平均成本单价
                $sales_number[$value] = $sepr_sales_number[$key];
            }
            if (!empty($sepr_price)) {
                // 商品id和所对应的销售价格
                $price[$value] = $sepr_price[$key];
            }
            if (!empty($sepr_return_price)) {
                // 商品id和所对应的退货单价
                $return_price[$value] = $sepr_return_price[$key];
            }
            // 商品id和所对应的退货成本
            // $return_cost[$value] = $sepr_return_cost[$key];
        }
                
        // 加
        if ($sepr_calculate == 1) {

            // 查询出当前销售利润中是否存在此商品
            $profit_data = DB::table('sell_profit')
                    ->where('sepr_cid', $user_info->adm_cid)
                    ->where('sepr_shop_id', $user_info->adm_shop_id)
                    ->where('sepr_year', $sepr_year)
                    ->where('sepr_month', $sepr_month)
                    ->whereIn('sepr_goo_id', $sepr_goo_id)
                    ->get()->toArray();
            if (!empty($profit_data)) {
                // 编辑
                $sql = 'UPDATE `faster_sell_profit` SET ';
                $accumulation = '';
                $renewal = '';
                $sum_renewal = '';
                // $costing = '';
                $update_time = '';
                $ids = '';

                foreach ($profit_data as $key => $value) {
                    if ($sepr_type == 1) {//正常订单 1.销售数量累加 2.平均单品售价更新 3.总的单品售价
                        //销售数量
                        $sum_amount = $value->sepr_sales_number + $sales_number[$value->sepr_goo_id];

                        //总的单品售价
                        $sum_money = $value->sepr_sum_price + ($sales_number[$value->sepr_goo_id] * $price[$value->sepr_goo_id] * 100);
                        //平均单品售价
                        $avg_money = $sum_money / $sum_amount;

                        // 销售数量累加
                        $accumulation = $accumulation . ' WHEN ' .$value->sepr_id;
                        $accumulation = $accumulation . ' THEN ' .$sum_amount;

                        // 总的单品售价
                        $sum_renewal = $sum_renewal . ' WHEN ' .$value->sepr_id;
                        $sum_renewal = $sum_renewal . ' THEN ' .$sum_money;

                        // 平均单品售价更新
                        $renewal = $renewal . ' WHEN ' .$value->sepr_id;
                        $renewal = $renewal . ' THEN ' .$avg_money;
                    } elseif ($sepr_type == 2) { //退货单 1.退货数量累加 2.退货单价更新 3.总的退货单价更新
                        //退货数量
                        $sum_amount = $value->sepr_return_number + $sales_number[$value->sepr_goo_id];
                        //总的退货单价
                        $sum_money = $value->sepr_sum_return_price + ($sales_number[$value->sepr_goo_id] * $return_price[$key] * 100);
                        //平均退货单价
                        $avg_money = $sum_money / $sum_amount;

                        // 退货数量累加
                        $accumulation = $accumulation . ' WHEN ' .$value->sepr_id;
                        $accumulation = $accumulation . ' THEN ' .$sum_amount;

                        // 平均退货单价更新
                        $renewal = $renewal . ' WHEN ' .$value->sepr_id;
                        $renewal = $renewal . ' THEN ' .$avg_money;

                        // 总的退货单价更新
                        $sum_renewal = $sum_renewal . ' WHEN ' .$value->sepr_id;
                        $sum_renewal = $sum_renewal . ' THEN ' .$sum_money;

                    // 退货成本更新
                        // $costing = $costing . ' WHEN ' .$value->sepr_id;
                        // $costing = $costing . ' THEN ' .$return_cost[$value->sepr_goo_id];
                    } else { //采购单 1.平均采购单价更新

                        // 平均成本单价更新
                        $renewal = $renewal . ' WHEN ' .$value->sepr_id;
                        $renewal = $renewal . ' THEN ' .$sales_number[$value->sepr_goo_id];
                    }

                    // 更改时间
                    $update_time = $update_time . ' WHEN ' .$value->sepr_id;
                    $update_time = $update_time . ' THEN "' .date('Y-m-d H:i:s').'"';

                    // 删除已更改的商品数据
                    unset($sales_number[$value->sepr_goo_id]);

                    $ids = $ids . $value->sepr_id.',';
                }

                if ($sepr_type == 1) { //正常订单
                    $sql = $sql .' `sepr_sales_number`=  CASE `sepr_id` '.$accumulation.' END,';
                    $sql = $sql .' `sepr_avg_price`=  CASE `sepr_id` '.$renewal.' END,';
                    $sql = $sql .' `sepr_sum_price`=  CASE `sepr_id` '.$sum_renewal.' END,';
                } elseif ($sepr_type == 2) { //退货单
                    $sql = $sql .' `sepr_return_number`=  CASE `sepr_id` '.$accumulation.' END,';
                    $sql = $sql .' `sepr_return_price`=  CASE `sepr_id` '.$renewal.' END,';
                    $sql = $sql .' `sepr_sum_return_price`=  CASE `sepr_id` '.$sum_renewal.' END,';
                // $sql = $sql .' `sepr_return_cost`=  CASE `sepr_id` '.$costing.' END,';
                } else { //采购单
                    $sql = $sql .' `sepr_avg_pro_price`=  CASE `sepr_id` '.$renewal.' END,';
                }
                $sql = $sql .' `sepr_update_time`=  CASE `sepr_id` '.$update_time.' END'; //修改时间
                $sql = $sql . ' WHERE `sepr_id` IN ('.trim($ids, ',').')';
                $sell_profit = DB::update($sql);

                // 查询出修改后的数据  计算利率利润
                $sepr_id = array_column(json_decode(json_encode($profit_data), true), 'sepr_id');
                $behind_profit_data = DB::table('sell_profit')
                        ->whereIn('sepr_id', $sepr_id)
                        ->get();

                $sell_profit_sql = 'UPDATE `faster_sell_profit` SET ';
                $return_rate = '';
                $return_profit = '';
                $save_time = '';
                $id = '';
                foreach ($behind_profit_data as $key => $value) {
                    // 计算利率 ((销售单价-成本单价)×销售数量-(退货单价-成本单价)×退货数量)/(销售总金额-退货总金额)
                    if ($value->sepr_sum_price-$value->sepr_sum_return_price == 0) {
                        $calculate_rate = 0;
                    } else {
                        $calculate_rate = (($value->sepr_avg_price-$value->sepr_avg_pro_price)
                                        *$value->sepr_sales_number-
                                        ($value->sepr_return_price-$value->sepr_avg_pro_price)
                                        *$value->sepr_return_number)
                                        /($value->sepr_sum_price-$value->sepr_sum_return_price);
                        $calculate_rate = $calculate_rate * 100;
                        $calculate_rate = round(str_replace("-", "", $calculate_rate)); //负数变正整数
                    }
                                       

                    $return_rate = $return_rate . ' WHEN ' .$value->sepr_id;
                    $return_rate = $return_rate . ' THEN ' .$calculate_rate;
                    
                    // 计算利润 (销售单价-成本单价)×销售数量-(退货单价-成本单价)×退货数量
                    $calculate_profit = ($value->sepr_avg_price-$value->sepr_avg_pro_price)*$value->sepr_sales_number
                                    - ($value->sepr_return_price-$value->sepr_avg_pro_price)*$value->sepr_return_number;
                    $calculate_profit = str_replace("-", "", $calculate_profit);

                    $return_profit = $return_profit . ' WHEN ' .$value->sepr_id;
                    $return_profit = $return_profit . ' THEN ' .$calculate_profit;
                    
                    // 更改时间
                    $save_time = $save_time . ' WHEN ' .$value->sepr_id;
                    $save_time = $save_time . ' THEN "' .date('Y-m-d H:i:s').'"';

                    $id = $id . $value->sepr_id.',';
                }
                $sell_profit_sql = $sell_profit_sql .' `sepr_return_rate`=  CASE `sepr_id` '.$return_rate.' END,';
                $sell_profit_sql = $sell_profit_sql .' `sepr_return_profit`=  CASE `sepr_id` '.$return_profit.' END,';
                $sell_profit_sql = $sell_profit_sql .' `sepr_update_time`=  CASE `sepr_id` '.$save_time.' END'; //修改时间
                $sell_profit_sql = $sell_profit_sql . ' WHERE `sepr_id` IN ('.trim($id, ',').')';
                $save_sell_profit = DB::update($sell_profit_sql);
                return $save_sell_profit;

                // 是否存在新增的数据
                if (!empty($sales_number)) {
                    foreach ($sales_number as $key => $value) {
                        $add_data[$key]['sepr_cid'] = $user_info->adm_cid;
                        $add_data[$key]['sepr_shop_id'] = $user_info->adm_shop_id;
                        $add_data[$key]['sepr_superior_shop_id'] = $shop_id;
                        $add_data[$key]['sepr_year'] = $sepr_year; //年
                        $add_data[$key]['sepr_month'] = $sepr_month; //月
                        $add_data[$key]['sepr_goo_id'] = $key; //商品id
                        $add_data[$key]['sepr_return_rate'] = 0; //利率
                        $add_data[$key]['sepr_return_profit'] = 0; //利润

                        if ($sepr_type == 1) {//正常订单
                            //总的单品售价
                            $sum_money = $value * $price[$key] * 100;
                            //平均单品售价
                            $avg_money = $sum_money / $value;

                            $add_data[$key]['sepr_sales_number'] = $value; //销售数量
                            $add_data[$key]['sepr_avg_price'] = $avg_money; //平均单品售价
                            $add_data[$key]['sepr_sum_price'] = $sum_money; //总的单品售价
                        } elseif ($sepr_type == 2) { //退货单
                            //总的退货单价
                            $sum_money = $sales_number[$key] * $return_price[$key] * 100;
                            //平均退货单价
                            $avg_money = $sum_money / $sales_number[$key];

                            $add_data[$key]['sepr_return_number'] = $sales_number[$key]; //退货数量
                            $add_data[$key]['sepr_return_price'] = $avg_money; //平均退货单价
                            $add_data[$key]['sepr_sum_return_price'] = $sum_money; //总的退货单价
                            // $add_data[$key]['sepr_return_cost'] = $return_cost[$key]; //退货成本
                        } else {
                            $add_data[$key]['sepr_avg_pro_price'] = $sales_number[$key]; //平均成本单价
                        }
                    }


                    $add_sql = DB::table('sell_profit')->insert($add_data);
                } else {
                    $add_sql = true;
                }
            } else {
                // 新增
                foreach ($sales_number as $key => $value) {
                    $add_data[$key]['sepr_cid'] = $user_info->adm_cid;
                    $add_data[$key]['sepr_shop_id'] = $user_info->adm_shop_id;
                    $add_data[$key]['sepr_superior_shop_id'] = $shop_id;
                    $add_data[$key]['sepr_year'] = $sepr_year; //年
                    $add_data[$key]['sepr_month'] = $sepr_month; //月
                    $add_data[$key]['sepr_goo_id'] = $key; //商品id
                    $add_data[$key]['sepr_return_rate'] = 0; //利率
                    $add_data[$key]['sepr_return_profit'] = 0; //利润

                    if ($sepr_type == 1) {//正常订单
                        //总的单品售价
                        $sum_money = $value * $price[$key] * 100;
                        //平均单品售价
                        $avg_money = $sum_money / $value;

                        $add_data[$key]['sepr_sales_number'] = $value; //销售数量
                        $add_data[$key]['sepr_avg_price'] = $avg_money; //平均单品售价
                        $add_data[$key]['sepr_sum_price'] = $sum_money; //总的单品售价
                    } elseif ($sepr_type == 2) { //退货单
                        //总的退货单价
                        $sum_money = $sales_number[$key] * $return_price[$key] * 100;
                        //平均退货单价
                        $avg_money = $sum_money / $sales_number[$key];

                        $add_data[$key]['sepr_return_number'] = $sales_number[$key]; //退货数量
                        $add_data[$key]['sepr_return_price'] = $avg_money; //平均退货单价
                        $add_data[$key]['sepr_sum_return_price'] = $sum_money; //总的退货单价
                        // $add_data[$key]['sepr_return_cost'] = $return_cost[$key]; //退货成本
                    } else {
                        $add_data[$key]['sepr_avg_pro_price'] = $sales_number[$key]; //平均成本单价
                    }
                }
                
                $sell_profit = DB::table('sell_profit')->insert($add_data);
                $add_sql = true;
                $save_sell_profit = true;
            }
        } else {
            // 减

            $sql = 'UPDATE `faster_sell_profit` SET ';
            $accumulation = '';
            $renewal = '';
            $sum_renewal = '';
            // $costing = '';
            $update_time = '';
            $ids = '';
            foreach ($profit_data as $key => $value) {
                if ($sepr_type == 1) {//正常订单 1.销售数量减 2.平均单品售价更新 3.总的单品售价
                    //销售数量
                    $sum_amount = $value->sepr_sales_number + $sales_number[$value->sepr_goo_id];
                    //总的单品售价
                    $sum_money = $value->sepr_sum_price + ($sales_number[$value->sepr_goo_id] * $sepr_price[$key]);
                    //平均单品售价
                    $avg_money = $sum_money / $sum_amount;

                    // 销售数量累加
                    $accumulation = $accumulation . ' WHEN ' .$value->sepr_id;
                    $accumulation = $accumulation . ' THEN ' .$sum_amount;

                    // 总的单品售价
                    $sum_renewal = $renewal . ' WHEN ' .$value->sepr_id;
                    $sum_renewal = $renewal . ' THEN ' .$sum_money;

                    // 平均单品售价更新
                    $renewal = $renewal . ' WHEN ' .$value->sepr_id;
                    $renewal = $renewal . ' THEN ' .$avg_money;
                } elseif ($sepr_type == 2) { //退货单 1.退货数量减 2.退货单价更新 3.总的退货单价更新
                    //退货数量
                    $sum_amount = $value->sepr_return_number + $sales_number[$value->sepr_goo_id];
                    //总的退货单价
                    $sum_money = $value->sepr_sum_return_price + ($sales_number[$value->sepr_goo_id] * $sepr_return_price[$key]);
                    //平均退货单价
                    $avg_money = $sum_money / $sum_amount;

                    // 退货数量累加
                    $accumulation = $accumulation . ' WHEN ' .$value->sepr_id;
                    $accumulation = $accumulation . ' THEN ' .$sum_amount;

                    // 平均退货单价更新
                    $renewal = $renewal . ' WHEN ' .$value->sepr_id;
                    $renewal = $renewal . ' THEN ' .$avg_money;

                    // 总的退货单价更新
                    $sum_renewal = $sum_renewal . ' WHEN ' .$value->sepr_id;
                    $sum_renewal = $sum_renewal . ' THEN ' .$sum_money;

                // 退货成本更新
                    // $costing = $costing . ' WHEN ' .$value->sepr_id;
                    // $costing = $costing . ' THEN ' .$return_cost[$value->sepr_goo_id];
                } else { //采购单 1.平均采购单价更新

                    // 平均成本单价更新
                    $renewal = $renewal . ' WHEN ' .$value->sepr_id;
                    $renewal = $renewal . ' THEN ' .$sales_number[$value->sepr_goo_id];
                }

                // 更改时间
                $update_time = $update_time . ' WHEN ' .$value->sepr_id;
                $update_time = $update_time . ' THEN "' .date('Y-m-d H:i:s').'"';

                $ids = $ids . $value->sepr_id.',';
            }
            if ($sepr_type == 1) { //正常订单
                $sql = $sql .' `sepr_sales_number`=  CASE `sepr_id` '.$accumulation.' END,';
                $sql = $sql .' `sepr_avg_price`=  CASE `sepr_id` '.$renewal.' END,';
                $sql = $sql .' `sepr_sum_price`=  CASE `sepr_id` '.$sum_renewal.' END,';
            } elseif ($sepr_type == 2) { //退货单
                $sql = $sql .' `sepr_return_number`=  CASE `sepr_id` '.$accumulation.' END,';
                $sql = $sql .' `sepr_return_price`=  CASE `sepr_id` '.$renewal.' END,';
                $sql = $sql .' `sepr_sum_return_price`=  CASE `sepr_id` '.$sum_renewal.' END,';
            // $sql = $sql .' `sepr_return_cost`=  CASE `sepr_id` '.$costing.' END,';
            } else { //采购单
                $sql = $sql .' `sepr_avg_pro_price`=  CASE `sepr_id` '.$renewal.' END,';
            }
            $sql = $sql .' `sepr_update_time`=  CASE `sepr_id` '.$update_time.' END'; //修改时间
            $sql = $sql . ' WHERE `sepr_id` IN ('.trim($ids, ',').')';
            $sell_profit = DB::update($sql);

            // 查询出修改后的数据  计算利率利润
            $sepr_id = array_column(json_decode(json_encode($profit_data), true), 'sepr_id');
            $behind_profit_data = DB::table('sell_profit')
                    ->whereIn('sepr_id', $sepr_id)
                    ->get();

            $sell_profit_sql = 'UPDATE `faster_sell_profit` SET ';
            $return_rate = '';
            $return_profit = '';
            $save_time = '';
            $id = '';
            foreach ($behind_profit_data as $key => $value) {
                // 计算利率 ((销售单价-成本单价)×销售数量-(退货单价-成本单价)×退货数量)/(销售总金额-退货总金额)
                if ($value->sepr_sum_price-$value->sepr_sum_return_price == 0) {
                    $calculate_rate = 0;
                } else {
                    $calculate_rate = (($value->sepr_avg_price-$value->sepr_avg_pro_price)
                                    *$value->sepr_sales_number-
                                    ($value->sepr_return_price-$value->sepr_avg_pro_price)
                                    *$value->sepr_return_number)
                                    /($value->sepr_sum_price-$value->sepr_sum_return_price);
                    $calculate_rate = $calculate_rate * 100;
                    $calculate_rate = round(str_replace("-", "", $calculate_rate)); //负数变正整数
                }


                $return_rate = $return_rate . ' WHEN ' .$value->sepr_id;
                $return_rate = $return_rate . ' THEN ' .$calculate_rate;
                
                // 计算利润 (销售单价-成本单价)×销售数量-(退货单价-成本单价)×退货数量
                $calculate_profit = ($value->sepr_avg_price-$value->sepr_avg_pro_price)*$value->sepr_sales_number-($value->sepr_return_price-$value->sepr_avg_pro_price)*$value->sepr_return_number;
                $return_profit = $return_profit . ' WHEN ' .$value->sepr_id;
                $return_profit = $return_profit . ' THEN ' .$calculate_profit;
                
                // 更改时间
                $save_time = $save_time . ' WHEN ' .$value->sepr_id;
                $save_time = $save_time . ' THEN "' .date('Y-m-d H:i:s').'"';

                $id = $id . $value->sepr_id.',';
            }
            $sell_profit_sql = $sell_profit_sql .' `sepr_return_rate`=  CASE `sepr_id` '.$return_rate.' END,';
            $sell_profit_sql = $sell_profit_sql .' `sepr_return_profit`=  CASE `sepr_id` '.$return_profit.' END,';
            $sell_profit_sql = $sell_profit_sql .' `sepr_update_time`=  CASE `sepr_id` '.$save_time.' END'; //修改时间
            $sell_profit_sql = $sell_profit_sql . ' WHERE `sepr_id` IN ('.trim($id, ',').')';
            $save_sell_profit = DB::update($sell_profit_sql);
            $add_sql = true;
        }
        // return $sell_profit .'---'. $add_sql .'---'. $save_sell_profit;

        if ($sell_profit && $add_sql && $save_sell_profit) {
            return true;
        } else {
            return false;
        }
    }
    
    /**
     * 百度---->高德
     * @param double $lat 纬度
     * @param double $lng 经度
     */
    public static function convert($lat, $lng)
    {
        $x_pi = 3.14159265358979324 * 3000.0 / 180.0;
        $x = $lng - 0.0065;
        $y = $lat - 0.006;
        $z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $x_pi);
        $theta = atan2($y, $x) - 0.000003 * cos($x * $x_pi);
        $lng = $z * cos($theta);
        $lat = $z * sin($theta);
        return array('lng'=>$lng,'lat'=>$lat);
    }

    /**
     * [uploadBase64Img 上传base64图片]
     * @param  [type] $stream [base64数据]
     * @param  [type] $url    路径 存放哪一个文件夹下
     * @param  string $folder [文件夹]
     * @return [type]         [上传成功返回图片路径，失败返回false]
     */
    public static function uploadBase64Img($stream, $url)
    {
        if (stristr($stream, 'data:image')) {
            $stream  = $stream;
        } else {
            $stream="data:image/png;base64,".$stream;
        }
        //获取扩展名和文件名
        if (preg_match('/(?<=\/)[^\/]+(?=\;)/', $stream, $pregR)) {
            $streamFileType = '.' . $pregR[0];
        }

        $streamFileRand = time() . rand(11, 99);//产生一个随机文件名（因为你base64上来肯定没有文件名，这里你可以自己设置一个也行）
        // $pathName = "/public/image/" ;
        $pathName = storage_path()."/".$url."/";//获取上传图片路径
        // 创建文件夹
        if (!file_exists($pathName)) {
            mkdir($pathName, 0775, true);
            chmod($pathName, 0775);
        }
        $streamFilename = $pathName . $streamFileRand . $streamFileType;//上传到服务器图片路径

        //处理base64文本，用正则把第一个base64,之前的部分砍掉
        preg_match('/(?<=base64,)[\S|\s]+/', $stream, $streamForW);
        if (file_put_contents($streamFilename, base64_decode($streamForW[0])) === false) {
            throw new Exception("上传文件失败");
        } else {
            // 返回路径
            $filePath = "storage/".$url."/". $streamFileRand . $streamFileType;
            return $filePath;
        }
    }

    /**
     * [uploadBase64Img 上传base64图片]
     * @param  [string] $url       [base64数据]
     * @param  [array]  $param    路径 存放哪一个文件夹下
     * @return [bool]   成功返回true
     */
    public static function doPost($param, $url, $type=1)
    {
        // 模拟提交数据函数
        $post_data = Common::ToUrlencode($param);
        $post_data=urldecode(json_encode($post_data));
        Common::write_log($param, $type);
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据，json格式
    }

    /**
     * [write_log 写入日志]
     * @param  [type]  $data          [写入的数据]
     * @param  integer $type          [1供应链补货日志2速电派单日志]
     * @param  string  $call_function [调用的方法名]
     * @return [type]                 [description]
     */
    public static function write_log($data, $type=1, $call_function='')
    {
        //设置路径目录信息
        if ($type == 1) {
            $url = storage_path().'/logs/gyl_log.txt';
        } else {
            $url = storage_path().'/logs/mk_order_log.txt';
        }
        $dir_name=dirname($url);
        //目录不存在就创建
        if (!file_exists($dir_name)) {
            //iconv防止中文名乱码
            mkdir(iconv("UTF-8", "GBK", $dir_name));
            chmod($dir_name, 0777);
        }
        $fp = fopen($url, "a");//打开文件资源通道 不存在则自动创建
        date_default_timezone_set('PRC');
        flock($fp, LOCK_EX);
        if (is_array($data)) {
            $data = json_encode($data);
        }
        if (!empty($call_function)) {
            $data = json_decode($data, true);
            $data['call_function'] = $call_function;
            $data = json_encode($data, JSON_UNESCAPED_UNICODE);
        }
        fwrite($fp, date("Y-m-d H:i:s").' '.var_export($data, true)."\r\n\r\n");//写入文件
        flock($fp, LOCK_UN);
        fclose($fp);//关闭资源通道
    }

    /**
     * write_record_log 记录日志
     *
     * @param [type] $data   写入数据
     * @param [type] $path_name  日志文件名
     * @param [type] $call_function  调用的方法
     * @return void
     */
    public static function write_record_log($data, $path_name, $call_function)
    {
        //设置路径目录信息
        $url = storage_path().'/logs/record/'.$path_name;
        $dir_name=dirname($url);
        //目录不存在就创建
        if (!file_exists($dir_name)) {
            //iconv防止中文名乱码
            mkdir(iconv("UTF-8", "GBK", $dir_name));
            chmod($dir_name, 0777);
        }
        $fp = fopen($url, "a");//打开文件资源通道 不存在则自动创建
        date_default_timezone_set('PRC');
        flock($fp, LOCK_EX);
        if (is_array($data)) {
            $data = json_encode($data);
        }
        if (!empty($call_function)) {
            $data = json_decode($data, true);
            $data['call_function'] = $call_function;
            $data = json_encode($data, JSON_UNESCAPED_UNICODE);
        }
        fwrite($fp, date("Y-m-d H:i:s").' '.var_export($data, true)."\r\n\r\n");//写入文件
        flock($fp, LOCK_UN);
        fclose($fp);//关闭资源通道
    }

    public static function ToUrlencode($arr)
    {
        $temp = array();
        if (is_array($arr)) {
            foreach ($arr as $key => $row) {
                $temp[$key] = $row;
                if (is_array($temp[$key])) {
                    $temp[$key] = Common::ToUrlencode($temp[$key]);
                } else {
                    $temp[$key] = urlencode($row);
                }
            }
        } else {
            $temp = $arr;
        }
        return $temp;
    }

    /**
     * [publicOrderLock 改单锁定，取消锁单；改单的时候需要把跟订单相关的数据都锁单]
     * @param  [int] $type          [类型：1锁定 2取消锁单]
     * @param  [int] $state         [类型：1系统锁定 2第三方锁单 3总店 4加盟店]
     * @param  [int] $ord_id        [订单id]
     * @param  [int] $ord_wor_state [订单状态]
     * @return [Boolean]            [description]
     */
    public static function publicOrderLock($type, $state, $ord_id, $ord_wor_state = 0)
    {
        //判断是否有正常工单，不是取消、终止状态的工单
        $wor_data = DB::table('work_order')
            ->where('wor_order_id', $ord_id)
            ->where('wor_delete', 1)
            ->where('wor_state', '<>', 11)
            ->first(['wor_id','wor_state']);
        #速电锁单
        if ($type == 1 && $state == 2) {
            $hint = '速电锁单';
            $order_edit_data['ord_order_state'] = 3; //订单锁定状态1正常2系统锁定3第三方系统锁定
            $order_edit_data['ord_wor_state'] = 8; //8锁定

            $orci['orcl_update_time'] = date('Y-m-d H:i:s');
            $orci['orcl_before_wor_state'] = $ord_wor_state;
            $before_state = DB::table('order_client')
                ->where('orcl_ord_id', $ord_id)
                ->update($orci);
            //如果有工单
            if (!empty($wor_data)) {
                $wor['wor_service_state'] = 10;
                $wor['wor_state'] = 12;
                $wor['wor_pass'] = 5;//1.待审核 2.合格 3.不合格 4系统锁定 5第三方锁定
                $wor_res = DB::table('work_order')
                    ->where('wor_id', $wor_data->wor_id)
                    ->update($wor);
                $wocl['wocl_before_wor_state'] = $wor_data->wor_state;
                $wocl['wocl_update_time'] = date('Y-m-d H:i:s');
                $wocl_state = DB::table('work_client')
                    ->where('wocl_wor_id', $wor_data->wor_id)
                    ->update($wocl);
            } else {
                $wor_res = true;
                $wocl_state = true;
            }
            #速电取消锁单
        } elseif ($type == 2 && $state == 2) {
            $hint = '速电取消锁单';
            $order_edit_data['ord_order_state'] = 1; //订单锁定状态1正常2系统锁定3第三方系统锁定
            $before_state = DB::table('order_client')
                ->where('orcl_ord_id', $ord_id)
                ->value('orcl_before_wor_state');
            $order_edit_data['ord_wor_state'] = $before_state; //还原到锁定之前的状态
            //如果有工单
            if (!empty($wor_data)) {
                $wocl_state = DB::table('work_client')
                    ->where('wocl_wor_id', $wor_data->wor_id)
                    ->value('wocl_before_wor_state');
                if (in_array($wocl_state, [1,2,3])) {
                    $wor['wor_service_state'] = 1;
                } else {
                    $wor['wor_service_state'] = stateSetting($wocl_state);
                }
                $wor['wor_state'] = $wocl_state;
                $wor['wor_pass'] = 1;//待审核
                $wor['wor_update_time'] = date('Y-m-d H:i:s');
                $wor_res = DB::table('work_order')
                    ->where('wor_id', $wor_data->wor_id)
                    ->update($wor);
            } else {
                $wor_res = true;
                $wocl_state = true;
            }
            #系统锁单
        } elseif ($type == 1 && $state == 1) {
            $hint = '系统锁单';
            $order_edit_data['ord_order_state'] = 2; //订单锁单状态1正常2系统锁定3第三方系统锁定
            $order_edit_data['ord_wor_state'] = 8; //8锁定
            $orci['orcl_update_time'] = date('Y-m-d H:i:s');
            $orci['orcl_before_wor_state'] = $ord_wor_state;
            $before_state = DB::table('order_client')
                ->where('orcl_ord_id', $ord_id)
                ->update($orci);

            //如果有工单
            if (!empty($wor_data)) {
                $wor['wor_service_state'] = 10;
                $wor['wor_state'] = 12;
                $wor['wor_pass'] = 4;//1.待审核 2.合格 3.不合格 4系统锁定 5第三方锁定
                $wor_res = DB::table('work_order')
                    ->where('wor_id', $wor_data->wor_id)
                    ->update($wor);
                $wocl['wocl_before_wor_state'] = $wor_data->wor_state;
                $wocl['wocl_update_time'] = date('Y-m-d H:i:s');
                $wocl_state = DB::table('work_client')
                    ->where('wocl_wor_id', $wor_data->wor_id)
                    ->update($wocl);
            } else {
                $wor_res = true;
                $wocl_state = true;
            }
            #系统取消锁单
        } elseif ($type == 2 && $state == 1) {
            $hint = '系统取消锁单';
            $order_edit_data['ord_order_state'] = 1; //订单锁单状态1正常2系统锁定3第三方系统锁单

            $before_state = DB::table('order_client')
                ->where('orcl_ord_id', $ord_id)
                ->value('orcl_before_wor_state');
            $order_edit_data['ord_wor_state'] = $before_state; //还原到锁定之前的状态
            //如果有工单
            if (!empty($wor_data)) {
                $wocl_state = DB::table('work_client')
                    ->where('wocl_wor_id', $wor_data->wor_id)
                    ->value('wocl_before_wor_state');
                if (in_array($wocl_state, [1,2,3])) {
                    $wor['wor_service_state'] = 1;
                } else {
                    $wor['wor_service_state'] = stateSetting($wocl_state);
                }
                $wor['wor_pass'] = 1;//待审核
                $wor['wor_state'] = $wocl_state;
                $wor['wor_update_time'] = date('Y-m-d H:i:s');
                $wor_res = DB::table('work_order')
                    ->where('wor_id', $wor_data->wor_id)
                    ->update($wor);
                if ($wor_res || $wor_res===0) {
                    $wor_res = true;
                } else {
                    DB::rollBack();
                    return response()->json(['code'=> 500,'msg'=>'error','data'=>'失败']);
                }
            } else {
                $wor_res = true;
                $wocl_state = true;
            }
            //加盟店取消锁定
        } elseif ($type == 2 && $state == 4) {
            // 加盟店订单数据
            $join_order_info = DB::table('order_client')
                ->where('orcl_ord_id', $ord_id)
                ->first(['orcl_before_wor_state','orcl_join_wor_id']);
            $order_edit_data['ord_wor_state'] = $join_order_info->orcl_before_wor_state;
            $order_edit_data['ord_order_state'] = 1;

            //总店工单数据
            $head_wor_info = DB::table('work_client')
                ->where('wocl_wor_id', $join_order_info->orcl_join_wor_id)
                ->first(['wocl_wor_id','wocl_before_wor_state as wor_state']);
            if (in_array($head_wor_info->wor_state, [1,2,3])) {
                $join_wor_data['wor_service_state'] = 1;
            } else {
                $join_wor_data['wor_service_state'] = stateSetting($wocl_state);
            }
            $join_wor_data['wor_state'] = $head_wor_info->wor_state;
            ;
            $wor_res = DB::table('work_order')
                ->where('wor_id', $head_wor_info->wocl_wor_id)
                ->update($join_wor_data);
            if ($wor_res || $wor_res===0) {
                $wor_res = true;
            } else {
                DB::rollBack();
                return response()->json(['code'=> 500,'msg'=>'error','data'=>'失败']);
            }
            //总店订单数据
            $head_order_info = DB::table('work_order')
                ->where('wor_id', $join_order_info->orcl_join_wor_id)
                ->first(['wor_order_id']);

            $state = DB::table('order_client')
                ->where('orcl_ord_id', $head_order_info->wor_order_id)
                ->first(['orcl_before_wor_state']);
            $head_order_data['ord_order_state'] = 1;//总店加盟店锁单
            $head_order_data['ord_wor_state'] = $state->orcl_before_wor_state;//锁定
            $wocl_state = DB::table('order')
                ->where('ord_id', $head_order_info->wor_order_id)
                ->update($head_order_data);
            if ($wocl_state || $wocl_state===0) {
                $wocl_state = true;
            } else {
                DB::rollBack();
                return response()->json(['code'=> 500,'msg'=>'error','data'=>'失败']);
            }
        }
        $order_edit_data['ord_update_time'] = date('Y-m-d H:i:s');
        $ord_res = DB::table('order')
            ->where('ord_id', $ord_id)
            ->update($order_edit_data);

        //派工单锁单工单状态(如果有工单)
        if ($wor_data) {
            // 2.1 查询当前工单的发货单的状态，已发货的发货单不需要更改
            $dego_type = $type == 2 ? 4 : 1;
            $find_dego =  DB::table('dispatch_bill')
                ->where('dego_order_type', 2) //类型：1.订单发货 2.工单发货
                ->where('dego_type', $dego_type) //类型：1未出库2已出库3作废4锁定
                ->where('dego_wor_id', $wor_data->wor_id)
                ->select('dego_id')
                ->orderBy('dego_id', 'desc')
                ->first();
            if (empty($find_dego)) {
                $dego_res = true;
            } else {
                $type = $type == 2 ? 1 : 4;
                // 2.2 把还未发货的发货单改成锁定状态
                $dego_edit_data['dego_type'] = $type;
                $dego_edit_data['dego_update_time'] = date('Y-m-d H:i:s');
                $dego_res = DB::table('dispatch_bill')
                    ->where('dego_id', $find_dego->dego_id)
                    ->update($dego_edit_data);
            }
        } else {
            $dego_res = true;
        }
        if ($dego_res && $ord_res && $wor_res && $wocl_state) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * [给速电同步技师数据]
     * @param  [int] $order_id      [订单id]
     * @param  [int] $service_adm_id[技师id]
     * @return [Boolean]            [description]
     */
    public static function technician($order_id, $service_adm_id)
    {
        $system_number = DB::table('order')
            ->where('ord_id', $order_id)
            ->where('ord_type', 3)
            ->value('ord_other_system_number');

        $param['id'] = $service_adm_id;//技师id
        $param['system_number'] = $system_number;//工单号
        $param['token'] = config('apisystem.sd_token');
        $url = config('apisystem.sd_server_name').'/index.php/sync_install_persion';
        $doPost_res = Common::doPost($param, $url);
        $doPost_res = json_decode($doPost_res);
        if ($doPost_res->code != 200) {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'失败']);
        }
        return true;
    }

    /**
     * [addNote 添加备注]
     * @param [type] $user_info [用户信息]
     * @param [type] $note_number    [单号]
     * @param [type] $note_content   [备注内容]
     * @param [type] $oplo_action    [操作功能]
     * @param [type] $oplo_content   [操作内容]
     */
    public static function addNote(
        $user_info,
        $shop_id,
        $number,
        $note_content,
        $note_type
    ) {
        $add_data = [
            'note_adm_cid'=>$user_info->adm_cid,
            'note_superior_shop_id'=>$shop_id,
            'note_shop_id'=>$user_info->adm_shop_id,
            'note_number'=>$number,
            'note_adm_id'=>$user_info->adm_id,
            'note_name'=>$user_info->adm_name,
            'note_content'=>$note_content,
            'note_type'=>$note_type
        ];
        return DB::table('note')->insert($add_data);
    }

    //导出共用方法 添加头部数据
    public static function headExport($path, $where, $data)
    {
        $letter = [];
        $data = json_decode(json_encode($data), true);
        $num=20;
        for ($i=0; $i < $num; $i++) {
            if ($i < 26) {
                $letter[] = chr(65 + $i);
            } else {
                $letter[] = chr(64 + ($i / 26)) . chr(65 + $i % 26);
            }
        }
        $highest_row = '';
        if (is_file($path)){
            $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($path);//如果文件存在则直接载入
            $sheet = $spreadsheet->getActiveSheet();//获取活动的工作sheet
            $highest_row = $sheet->getHighestRow(); // 取得总行数
        } else {
            $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();//文件不存在则实例化一个新的文件
            $sheet = $spreadsheet->getActiveSheet();//获取工作表
            $sheet->setTitle($where['action_name']);  //设置当前sheet的标题
            // $i = 0;
            // foreach ($data['info'] as $key => $value) {
            //     $sheet->setCellValue($letter[$i].'1',$value."   ");
            //     $spreadsheet->getActiveSheet()->getColumnDimension($letter[$i])->setWidth(20);
            //     $spreadsheet->getDefaultStyle()->getFont()->setSize(10);
            //     $i++;
            // }

            // $spreadsheet->getActiveSheet()->getStyle('A3:G3')->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_RED);
            // $spreadsheet->getActiveSheet()->getStyle('A1:G1')->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_RED);

            $title = $where['field_name'];
            foreach ($title as $key => $value) {
                $sheet->setCellValue($letter[$key].'1',$value."\t");
                //$spreadsheet->getActiveSheet()->getColumnDimension($letter[$key])->setAutoSize(true);
                $spreadsheet->getActiveSheet()->getColumnDimension($letter[$key])->setWidth(25);
                
            }
        }
        $i = $highest_row ? $highest_row : 1;//开始行数
        foreach ($data['data'] as $key => $value) {
            $j = 0;
            foreach ($value as $k => $v) {
                $sheet->setCellValue($letter[$j].($i+1), $v."\t");
                $j++;
            }
            $i++;
        }

        $obj_Writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet,'Xls');
        header("Content-type: application/vnd.ms-excel; charset=UTF-8");
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="'.$path.'"');
        header("Content-Transfer-Encoding: binary");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");
        $obj_Writer->save($path);
    }
}
