<?php
namespace App\Http\Controllers\Api\DataStatistical;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use App\Http\Models\Api\Common;
use App\Http\Models\Api\Export;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use App\Http\Models\Services\DataStatistical\DataStatistical;

// 财务系统 -- 销售统计
class DataStatisticalController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

    // 返回头部类型数据
    public function headData(Request $request)
    {
        $user_info = Common::getUserInfo($request['api_token']);
        if (!$user_info) {
            throw new Exception('获取用户信息失败');
        } else {
            $user_info = $this->objectToArray($user_info);
        }

        // 查询设置的销售查询权限
        $list_button_data = DB::table('admin_set')
            ->where('adms_adm_id', $user_info['adm_id'])
            ->where('adms_shop_id', $user_info['adm_shop_id'])
            ->select('adms_id', 'adms_statistical_data')
            ->first();
        $list_button_data = json_decode($list_button_data->adms_statistical_data, true);
        if (empty($list_button_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'请联系系统管理员，设置销售统计权限！']);
        }
        
        $return_list_button = $list_button_data;
        if ($return_list_button[0]['id'] == '6') {//id=6是查看明细的，不在页面展示按钮
            foreach ($return_list_button as $list_key => $list_value) {
                $return_list_button[1]['checked'] = true;
                $list_button_data[1]['checked'] = true;//第一个默认选择
                $return_list_button[$list_key]['result'] = '销量';
                if ($list_value['id'] == '6') {
                    unset($return_list_button[$list_key]);
                }
            }
            unset($return_list_button[$list_key]['count_field']);
            unset($return_list_button[$list_key]['list_field']);
            unset($return_list_button[$list_key]['childCountCheck']);
            unset($return_list_button[$list_key]['childListCheck']);
            unset($return_list_button[$list_key]['childCountAlltype']);
            unset($return_list_button[$list_key]['childListAlltype']);
            unset($return_list_button[$list_key]['childListCheckAll']);
            unset($return_list_button[$list_key]['childCountCheckAll']);
            unset($return_list_button[$list_key]['result']);
        } else {
            foreach ($return_list_button as $list_key => $list_value) {
                $return_list_button[0]['checked'] = true;
                $list_button_data[0]['checked'] = true;//第一个默认选择
                $return_list_button[$list_key]['result'] = '销量';
                if ($list_value['id'] == '6') {
                    unset($return_list_button[$list_key]);
                }
                unset($return_list_button[$list_key]['count_field']);
                unset($return_list_button[$list_key]['list_field']);
                unset($return_list_button[$list_key]['childCountCheck']);
                unset($return_list_button[$list_key]['childListCheck']);
                unset($return_list_button[$list_key]['childCountAlltype']);
                unset($return_list_button[$list_key]['childListAlltype']);
                unset($return_list_button[$list_key]['childListCheckAll']);
                unset($return_list_button[$list_key]['childCountCheckAll']);
                unset($return_list_button[$list_key]['result']);
            }
        }
        
        return response()->json(['code'=>200, 'msg'=>'success', 'list_button_data'=>$return_list_button]);
    }

    // 列表
    public function index(Request $request)
    {
        $user_info = Common::getUserInfo($request['api_token']);
        if (!$user_info) {
            throw new Exception('获取用户信息失败');
        } else {
            $user_info = $this->objectToArray($user_info);
        }

        $input = $request->all();
        // dump($input);die;
        // 查询设置的销售查询权限
        $list_button_data = DB::table('admin_set')
            ->where('adms_adm_id', $user_info['adm_id'])
            ->where('adms_shop_id', $user_info['adm_shop_id'])
            ->select('adms_id', 'adms_statistical_data')
            ->first();
        $list_button_data = json_decode($list_button_data->adms_statistical_data, true);
        if (empty($list_button_data)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'请联系系统管理员，设置销售统计权限！']);
        }
        $select_count_field = [];// 已选择的总计字段权限
        $select_list_field = [];// 已选择的列表字段权限
        $list_title = [];// 返回前端的有权限的列表表头
        $new_data = [];// 返回的总计数据
        $priceshow = [];
        $return_data = [];
        $return_list_button = $list_button_data;
        if ($return_list_button[0]['id'] == '6') {//id=6是查看明细的，不在页面展示按钮
            foreach ($return_list_button as $list_key => $list_value) {
                $return_list_button[1]['checked'] = true;
                $list_button_data[1]['checked'] = true;//第一个默认选择
                $return_list_button[$list_key]['result'] = '销量';
                if ($list_value['id'] == '6') {
                    unset($return_list_button[$list_key]);
                }
            }
        } else {
            foreach ($return_list_button as $list_key => $list_value) {
                $return_list_button[0]['checked'] = true;
                $list_button_data[0]['checked'] = true;//第一个默认选择
                $return_list_button[$list_key]['result'] = '销量';
                if ($list_value['id'] == '6') {
                    unset($return_list_button[$list_key]);
                }
            }
        }
        
        foreach ($list_button_data as $key => $value) {// 遍历设置的按钮
            $list_button_data[$key]['result'] = '销量';
            if (!empty($input['searchtype'])) {// 前端选择了要查询的按钮，查找对应按钮的权限
                if ($value['id'] == $input['searchtype']) {
                    foreach ($value['count_field'] as $co_key => $co_value) {// 总计字段权限
                        if (in_array($co_value['id'], $value['childCountCheck'])) {
                            $select_count_field['field_title'][] = $co_value['field_title'];
                            $select_count_field['field_name'][] = $co_value['field_name'];
                            if (isset($co_value['is_price'])) {// 是否为金额字段
                                $select_count_field['field_price'][] = 1;
                            } else {
                                $select_count_field['field_price'][] = 0;
                            }
                        }
                    }
                    foreach ($value['list_field'] as $li_key => $li_value) {// 列表字段权限
                        if (in_array($li_value['id'], $value['childListCheck'])) {
                            $select_list_field['field_title'][] = $li_value['field_title'];
                            $select_list_field['field_name'][] = $li_value['field_name'];
                            if (isset($li_value['is_price'])) {// 是否为金额字段
                                $select_list_field['field_price'][] = 1;
                            } else {
                                $select_list_field['field_price'][] = 0;
                            }
                        }
                    }
                }
            }
            if (empty($input['searchtype'])) {//第一次进入没有传searchtype值
                if ($value['id'] != '6') {
                    $input['searchtype'] = $value['id'];
                    foreach ($value['count_field'] as $co_key => $co_value) {
                        if (in_array($co_value['id'], $value['childCountCheck'])) {// 总计字段
                            $select_count_field['field_title'][] = $co_value['field_title'];
                            $select_count_field['field_name'][] = $co_value['field_name'];
                            if (isset($co_value['is_price'])) {// 是否为金额字段
                                $select_count_field['field_price'][] = 1;
                            } else {
                                $select_count_field['field_price'][] = 0;
                            }
                        }
                    }
                    foreach ($value['list_field'] as $li_key => $li_value) {
                        if (in_array($li_value['id'], $value['childListCheck'])) {// 列表字段
                            $select_list_field['field_title'][] = $li_value['field_title'];
                            $select_list_field['field_name'][] = $li_value['field_name'];
                            if (isset($li_value['is_price'])) {// 是否为金额字段
                                $select_list_field['field_price'][] = 1;
                            } else {
                                $select_list_field['field_price'][] = 0;
                            }
                        }
                    }
                    break;
                }
            }
        }
        if (empty($input['searchtype'])) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'请求参数错误']);
        }
        $request['searchtype'] = $input['searchtype'];
        $goods_inventory = new DataStatistical();
        if ($input['searchtype'] == '1') { //查询品牌
            $select_field = "goo_bra_id,sum(`dast_goo_quantity`) as quantity, sum(`dast_goo_price`*`dast_goo_quantitys`) as price, sum(`dast_goo_cost`*`dast_goo_quantitys`) as cost, dast_order_type";

            $return_datas = $goods_inventory->goodsIndex($user_info, $request->all(), $this->show_count, $select_field);
            if (count($return_datas) > 0) {
                $direct_accounting_price = $this->brandDirectAccountingPrice($user_info, $input);
                $allnums = 0; //实际销售数量
                $sale_num = 0; //销售数量
                $return_num = 0; //退货数量
                $allprice = 0; //实际销售金额
                $sale_sprice = 0; //销售金额
                $return_sprice = 0; //退款金额
                $sale_cost = 0; //销售成本
                $return_cost = 0; //退款成本
                $allcost = 0; //总成本
                foreach ($return_datas as $key => $value) {
                    if ($value['goo_bra_id'] > 0) {
                        if (empty($data[$value['goo_bra_id']])) {
                            $data[$value['goo_bra_id']]['allnum'] = 0;
                            $data[$value['goo_bra_id']]['sale_num'] = 0;
                            $data[$value['goo_bra_id']]['return_num'] = 0;
                            $data[$value['goo_bra_id']]['sale_sprice'] = 0;
                            $data[$value['goo_bra_id']]['return_sprice'] = 0;
                            $data[$value['goo_bra_id']]['profits'] = 0;
                            $data[$value['goo_bra_id']]['sale_cost'] = 0;
                            $data[$value['goo_bra_id']]['return_cost'] = 0;
                        }
                        if ($value['dast_order_type'] == '1') {
                            $data[$value['goo_bra_id']]['allnum'] = $data[$value['goo_bra_id']]['allnum'] + $value['quantity'];
                            $data[$value['goo_bra_id']]['sale_num'] = $value['quantity'];
                            $data[$value['goo_bra_id']]['sale_sprice'] = $value['price'];
                            $data[$value['goo_bra_id']]['sale_cost'] = $value['cost'];
                            $allnums = $allnums + $value['quantity'];
                            $sale_num = $sale_num + $value['quantity'];
                            $allprice = $allprice + $value['price'];
                            $sale_sprice = $sale_sprice + $value['price'];
                            $sale_cost = $sale_cost + $value['cost'];
                            $allcost = $allcost + $value['cost'];
                        }
                        if ($value['dast_order_type'] == '2') {
                            $data[$value['goo_bra_id']]['allnum'] = $data[$value['goo_bra_id']]['allnum'] + $value['quantity'];
                            $data[$value['goo_bra_id']]['return_num'] = $value['quantity'];
                            $data[$value['goo_bra_id']]['return_sprice'] = $value['price'];
                            $data[$value['goo_bra_id']]['return_cost'] = $value['cost'];
                            $allnums = $allnums + $value['quantity']; //实际销售数量可在循环外使用销售和退货数量相加
                            $return_num = $return_num + $value['quantity'];
                            $allprice = $allprice + $value['price'];
                            $return_sprice = $return_sprice + $value['price'];
                            $return_cost = $return_cost + $value['cost'];
                            $allcost = $allcost - $value['cost'];
                        }
                    }
                }
                $priceshow['allnum'] = $allnums;
                $priceshow['return_num'] = $return_num;
                $priceshow['return_sprice'] = $return_sprice;
                $priceshow['profits'] = $allprice;
                $priceshow['allcost'] = $allcost;
                $priceshow['sale_cost'] = $sale_cost;
                $priceshow['return_cost'] = $return_cost;
                $priceshow['profit'] = $allprice - $allcost;
                $brand = DB::table("brand")
                    ->where(function ($query) use ($user_info) {
                        $query->where('bra_shop_id', 0) //门店id为0的是系统数据
                            ->Orwhere('bra_shop_id', $user_info['adm_shop_id']); //账号所属门店id
                    })
                    ->where(function ($query) use ($user_info) {
                        $query->where('bra_cid', 0) //门店id为0的是系统数据
                            ->Orwhere('bra_cid', $user_info['adm_cid']); //账号所属门店id
                    })
                    ->pluck('bra_name', 'bra_id')->toArray();
                $return_data = [];
                $num = 0;
                $allnum = [];
                foreach ($brand as $key => $value) {
                    if (empty($data[$key])) {
                        $return_data[$num]['brand_name'] = $value;
                        $return_data[$num]['allnum'] = 0;
                        $return_data[$num]['sale_sprice'] = 0;
                        $return_data[$num]['return_sprice'] = 0;
                        $return_data[$num]['profits'] = 0; //营业额
                        $return_data[$num]['allcost'] = 0;
                        $return_data[$num]['profit'] = 0; //营业利润
                        $return_data[$num]['profit_margin'] = 0; //利润率=营业利润/营业额
                    } else {
                        $return_data[$num] = $data[$key];
                        $return_data[$num]['brand_name'] = $value;
                        $return_data[$num]['profits'] = $return_data[$num]['sale_sprice'] + $return_data[$num]['return_sprice']; //营业额(单位:分)
                        $return_data[$num]['allcost'] = $return_data[$num]['sale_cost'] - $return_data[$num]['return_cost']; //总成本（单位：分）
                        $return_data[$num]['profit'] = $return_data[$num]['profits'] - $return_data[$num]['allcost']; //营业利润（单位：分）
                        if ($return_data[$num]['profits'] != '0') {
                            $return_data[$num]['profit_margin'] = sprintf("%.2f", sprintf("%.2f", $return_data[$num]['profit'] / $return_data[$num]['profits']) * 100); //利润率
                        } else {
                            $return_data[$num]['profit_margin'] = 0; //利润率
                        }
                    }
                    if (empty($direct_accounting_price[$key])) {
                        $return_data[$num]['direct_accounting_price'] = 0; //直营核算价（单位：分）
                    } else {
                        $return_data[$num]['direct_accounting_price'] = $direct_accounting_price[$key]['sell_price'] - $direct_accounting_price[$key]['back_price']; //直营核算价（单位：分）
                    }

                    $allnum[] = $return_data[$num]['allnum']; //实售数量
                    $num++;
                }

                // 获取当前列表下的按钮
                $list_button = getListButton($request['api_token'], $request['pri_id']);
                // return response()->json(['code'=>200, 'msg'=>'success', 'allshow'=>$priceshow, 'data'=>$return_data, 'list_button'=>$list_button, 'list_button_data'=>$list_button_data, 'new_data'=>$new_data, 'list_title'=>$list_title]);
            }
        } elseif ($input['searchtype'] == '3') { //销量排行
            $select_field = "dast_actual_goo_id,goo_goods_encode,goo_name,goo_cate_name,goo_ampere_hour,sum(`dast_goo_quantity`) as quantity,sum(`dast_goo_price`*`dast_goo_quantitys`) as price, goo_brse_id, goo_class, goo_unit, goo_bra_name";

            $return_data = $goods_inventory->goodsIndex($user_info, $request->all(), $this->show_count, $select_field);
            if ($return_data) {
                $allnums = 0; //数量合计
                $allprice = 0; //销售合计
                foreach ($return_data as $key => $value) {
                    $allnums = $allnums + $value->quantity;
                    $allprice = $allprice + $value->price;
                }
                $priceshow['allnum'] = $allnums;
                $priceshow['profits'] = $allprice;
                // 获取当前列表下的按钮
                $list_button = getListButton($request['api_token'], $request['pri_id']);
                $return_data = $this->objectToArray($return_data);
            }
        } elseif ($input['searchtype'] == '4') { //开单员销量
            $select_field = "dast_create_id,dast_creacor,sum(`dast_goo_quantity`) as quantity,sum(`dast_goo_price`*`dast_goo_quantitys`) as price,dast_order_type";

            $return_data = $goods_inventory->goodsIndex($user_info, $request->all(), $this->show_count, $select_field);
            if ($return_data) {
                $sale_num = 0;
                $return_num = 0; //退货数量
                $allprice = 0; //销售合计
                $sale_sprice = 0;
                $return_sprice = 0; //退款金额
                $allnums = 0; //数量合计
                foreach ($return_data as $key => $value) {
                    if ($value['dast_create_id'] > 0) {
                        if (empty($data[$value['dast_create_id']])) {
                            $data[$value['dast_create_id']]['dast_creacor'] = $value['dast_creacor'];
                            $data[$value['dast_create_id']]['sale_num'] = 0;
                            $data[$value['dast_create_id']]['return_num'] = 0;
                            $data[$value['dast_create_id']]['sale_sprice'] = 0;
                            $data[$value['dast_create_id']]['return_sprice'] = 0;
                            $data[$value['dast_create_id']]['profits'] = 0;
                        }
                        if ($value['dast_order_type'] == '1') {
                            $data[$value['dast_create_id']]['sale_num'] = $value['quantity'];
                            $data[$value['dast_create_id']]['sale_sprice'] = $value['price'];
                            $sale_num = $sale_num + $value['quantity'];
                            $allprice = $allprice + $value['price'];
                            $sale_sprice = $sale_sprice + $value['price'];
                            $allnums = $allnums + $value['quantity'];
                        }
                        if ($value['dast_order_type'] == '2') {
                            $data[$value['dast_create_id']]['return_num'] = $value['quantity'];
                            $data[$value['dast_create_id']]['return_sprice'] = $value['price'];
                            $return_num = $return_num + $value['quantity'];
                            $allprice = $allprice + $value['price'];
                            $return_sprice = $return_sprice + $value['price'];
                            $allnums = $allnums + $value['quantity'];
                        }
                    }
                }
                $num = 0;
                foreach ($data as $key => $value) {
                    $return_data[$num] = $value;
                    $return_data[$num]['profits'] = $value['sale_sprice'] + $value['return_sprice'];
                    $num++;
                }
                $priceshow['allnum'] = $allnums; //数量合计
                $priceshow['return_num'] = $return_num; //退货数量
                $priceshow['return_sprice'] = $return_sprice; //退款金额
                $priceshow['profits'] = $allprice; //销售合计
                // 获取当前列表下的按钮
                $list_button = getListButton($request['api_token'], $request['pri_id']);
            }
        } elseif ($input['searchtype'] == '5') { //业务员销量
            $select_field = "dast_adm_id,dast_adm_name,sum(`dast_goo_quantity`) as quantity,sum(`dast_goo_price`*`dast_goo_quantitys`) as price,dast_order_type";

            $return_datas = $goods_inventory->goodsIndex($user_info, $request->all(), $this->show_count, $select_field);
            if (count($return_datas) > 0) {
                $sale_num = 0;
                $return_num = 0; //退货数量
                $allprice = 0;
                $sale_sprice = 0;
                $return_sprice = 0;
                foreach ($return_datas as $key => $value) {
                    if ($value['dast_adm_id'] > 0) {
                        if (empty($data[$value['dast_adm_id']])) {
                            $data[$value['dast_adm_id']]['dast_adm_name'] = $value['dast_adm_name'];
                            $data[$value['dast_adm_id']]['sale_num'] = 0;
                            $data[$value['dast_adm_id']]['return_num'] = 0;
                            $data[$value['dast_adm_id']]['sale_sprice'] = 0;
                            $data[$value['dast_adm_id']]['return_sprice'] = 0;
                            $data[$value['dast_adm_id']]['profits'] = 0;
                        }
                        if ($value['dast_order_type'] == '1') {
                            $data[$value['dast_adm_id']]['sale_num'] = $value['quantity'];
                            $data[$value['dast_adm_id']]['sale_sprice'] = $value['price'];
                            $sale_num = $sale_num + $value['quantity'];
                            $allprice = $allprice + $value['price'];
                            $sale_sprice = $sale_sprice + $value['price'];
                        }
                        if ($value['dast_order_type'] == '2') {
                            $data[$value['dast_adm_id']]['return_num'] = $value['quantity'];
                            $data[$value['dast_adm_id']]['return_sprice'] = $value['price'];
                            $return_num = $return_num + $value['quantity'];
                            $allprice = $allprice + $value['price'];
                            $return_sprice = $return_sprice + $value['price'];
                        }
                    }
                }
                $num = 0;
                foreach ($data as $key => $value) {
                    $return_data[$num] = $value;
                    $return_data[$num]['profits'] = $value['sale_sprice'] + $value['return_sprice'];
                    $return_data[$num]['allnum'] = $value['sale_num'] + $value['return_num'];
                    $num++;
                }
                $priceshow['return_num'] = $return_num; //退货数量
                $priceshow['allnum'] = $sale_num + $return_num; //数量合计
                $priceshow['return_sprice'] = $return_sprice; //退款金额
                $priceshow['profits'] = $allprice; //销售合计
                // 获取当前列表下的按钮
                $list_button = getListButton($request['api_token'], $request['pri_id']);
            }
        } elseif ($input['searchtype'] == '7') { //客户汇总
            $select_field = "dast_client_ids,chun_unit_name as dast_client_name,chun_chty_id,dast_type,sum(`dast_goo_quantity`) as quantity,sum(`dast_goo_price`*`dast_goo_quantitys`) as price,sum(`dast_goo_cost`*`dast_goo_quantity`) as cost";

            $return_data = $goods_inventory->goodsIndex($user_info, $request->all(), $this->show_count, $select_field);
            if ($return_data) {
                $chun_chty_id = [];
                $allnum = 0;
                $allprice = 0;
                $allcost = 0;
                foreach ($return_data as $key => $value) {
                    $allnum = $allnum + $value['quantity'];
                    $allprice = $allprice + $value['price'];
                    $allcost = $allcost + $value['cost'];
                    if ($value['dast_type'] == 2) {
                        $chun_chty_id[] = $value['chun_chty_id'];
                        if ($value['dast_client_name'] == '') {
                            $return_data[$key]['dast_client_name'] = '未定义' . $value['dast_client_ids'];
                        }
                    } elseif ($value['dast_type'] == 1) {
                        $return_data[$key]['dast_client_name'] = '零散客户';
                    } elseif ($value['dast_type'] == 3) {
                        $return_data[$key]['dast_client_name'] = '速电客单';
                    } elseif ($value['dast_type'] == 4) {
                        $return_data[$key]['dast_client_name'] = '第三方客单';
                    } else {
                        $return_data[$key]['dast_client_name'] = '未定义';
                    }
                    $return_data[$key]['type_name'] = "未定义";
                    $return_data[$key]['profit'] = $value['price'] - $value['cost'];
                    $return_data[$key]['profit'] = $value['price'] - $value['cost'];
                }
                $priceshow['allnum'] = $allnum; //数量合计
                $priceshow['profits'] = $allprice; //销售合计
                $priceshow['allcost'] = $allcost; //成本合计
                $priceshow['profit'] = $allprice - $allcost; //利润
                if ($chun_chty_id) {
                    $channel_type = DB::table('channel_type')
                        ->whereIn("chty_id", $chun_chty_id)
                        ->pluck('chty_name', 'chty_id')
                        ->toArray();
                    if ($channel_type) {
                        foreach ($return_data as $key => $value) {
                            if ($value['dast_type'] == 2) {
                                $return_data[$key]['type_name'] = $channel_type[$value['chun_chty_id']] ?? '未定义' . $value['chun_chty_id'];
                            }
                        }
                    }
                }
                // 获取当前列表下的按钮
                $list_button = getListButton($request['api_token'], $request['pri_id']);
            }
        } elseif ($input['searchtype'] == '2' || $input['searchtype'] == '6') { //销售明细
            $select_field = "dast_order_number,goo_cate_name,chun_unit_name as unit_name,chun_chty_id,dast_ord_id,dast_id,dast_create_time,goo_name,goo_ampere_hour,dast_goo_quantity,dast_goo_quantitys,dast_goo_price,dast_goo_quantitys*dast_goo_price as allprice,dast_client_id,dast_type,ware_freight_space,dast_service_type,dast_creacor,goo_goods_encode,dast_goo_cost as cost, goo_brse_id, goo_id, goo_class, goo_direct_accounting_price, goo_bra_name, goo_unit";

            $return_data = $goods_inventory->goodsIndex($user_info, $request->all(), $this->show_count, $select_field);
            if ($return_data['data']) {
                $priceshow = [];
                if (!$request->filled('page')) { //页码
                    $input['page'] = 1;
                }
                if ($input['page'] < 2) {
                    $Dbs = $goods_inventory->searchIndex($user_info, $input);
                    $cost_db = $goods_inventory->searchIndex($user_info, $input);
                    $alldata = $Dbs->where('dast_service_project_type', 1)->selectRaw('sum(dast_goo_quantitys*dast_goo_price) as allprice,sum(dast_goo_quantitys*dast_goo_cost) as allcost,sum(dast_goo_quantity) as allnum')->first();
                    // 订单为退货单的总成本
                    $order_return = $cost_db->where('dast_order_type', 2)->selectRaw('sum(dast_goo_quantitys*dast_goo_cost) as allcost')->first();

                    $alldata = $this->objectToArray($alldata);
                    $priceshow['profits'] = $alldata['allprice'];
                    $priceshow['allnum'] = $alldata['allnum'];
                    $priceshow['allcost'] = abs($alldata['allcost']) - abs($order_return->allcost * 2);
                }
                // 获取当前列表下的按钮
                $list_button = getListButton($request['api_token'], $request['pri_id']);
            }
        } elseif ($input['searchtype'] == '8') { //实时数据
            $select_field = "ord_order_number,goo_goods_encode,goo_name,goo_ampere_hour,orgo_goo_quantity,goo_unit,chun_unit_name as unit_name,chun_chty_id,ware_freight_space,ord_create_time,ord_id,ord_type,orgo_goo_price,ord_service_type,orgo_state, goo_bra_name, goo_brse_id, goo_class";

            $count_select_field = "count(ord_id) as num,sum(orgo_goo_quantity*orgo_goo_price) as allprice,sum(orgo_goo_quantity) as allnum,ord_service_type,orgo_state";
            $requests = $request->all();
            if (!empty($requests['creatData'])) {
                $time=date("Y-m-d", strtotime($requests['creatData'][1] . " -2 month"));
                if ($time>$requests['creatData'][0]) {
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'时间范围不可大于两个月']);
                }
            }
            $return_data = $goods_inventory->goodsIndex($user_info, $request->all(), $this->show_count, $select_field, $count_select_field);
            if ($return_data['data']) {
                $priceshow = [];
                $find_ord_datas = $goods_inventory->searchRealIndexs($user_info, $input);
                if (!$request->filled('page')) { //页码
                    $input['page'] = 1;
                }
                if ($input['page'] < 2) {
                    $alldata = $find_ord_datas
                        ->select(DB::raw($count_select_field))
                        ->groupBy('ord_service_type', 'orgo_state')
                        ->get()->toArray();
                    $alldata = $this->objectToArray($alldata);
                    $allprice = 0;
                    $allnum = 0;
                    foreach ($alldata as $key => $value) {
                        // 退货单类型商品金额不统计
                        if ($value['ord_service_type'] == '4' || $value['orgo_state'] == '4') {
                            $allprice -= $value['allprice'];
                            $allnum -= $value['allnum'];
                        } else {
                            $allprice += $value['allprice'];
                            $allnum += $value['allnum'];
                        }
                    }
                    $priceshow['profits'] = $allprice;
                    $priceshow['allnum'] = $allnum;
                }

                // 获取当前列表下的按钮
                $list_button = getListButton($request['api_token'], $request['pri_id']);
            }
        } elseif ($input['searchtype'] == '9') { //服务数据
            $select_field = "dast_order_number, dast_service_sepr_id, dast_ord_id,dast_id, dast_create_time, dast_goo_price, dast_client_id, dast_type, dast_creacor, chun_chty_id, chun_unit_name, dast_service_type";

            $return_data = $goods_inventory->goodsIndex($user_info, $request->all(), $this->show_count, $select_field);
            if ($return_data['data']) {
                $Dbs = $goods_inventory->searchIndex($user_info, $input);
                $priceshow = [];
                if (!$request->filled('page')) { //页码
                    $input['page'] = 1;
                }
                if ($input['page'] < 2) {
                    $cost_db = $Dbs;
                    $alldata = $Dbs->where('dast_service_project_type', 2)->selectRaw('sum(dast_goo_quantitys*dast_goo_price) as allprice, sum(dast_goo_quantity) as allnum')->first(); //

                    $alldata = $this->objectToArray($alldata);
                    $priceshow['profits'] = $alldata['allprice'];
                    $priceshow['allnum'] = $alldata['allnum'];
                }
                // 获取当前列表下的按钮
                $list_button = getListButton($request['api_token'], $request['pri_id']);
            }
        } elseif ($input['searchtype'] == '10') { //拿货占比
            $list_data = DB::table('data_statistical')
                ->where('dast_cid', $user_info['adm_cid'])
                ->where('dast_shop_id', $user_info['adm_shop_id'])
                ->where('dast_service_project_type', 1)
                ->where('dast_order_type', '!=', 3)
                ->where('dast_ord_delete', 1)
                ->where('dast_type', 2)//客户单位类型
                ->where(function ($query) use ($input) { //客户单位id
                    if (!empty($input['dast_client_id'])) {
                        $query->where('dast_client_id', $input['dast_client_id']);
                    }
                })
                ->where(function ($query) use ($input) { //日期范围
                    // 如果选择开始时间并且选择结束时间
                    if (!empty($input['creatData'])) {
                        $input['creatData'][1] = date("Y-m-d", strtotime($input['creatData'][1] . " +1 day"));
                        $query->whereBetween('dast_create_time', $input['creatData']);
                    }
                })
                ->select('dast_client_id')
                ->orderBy('dast_id', 'asc')
                ->groupBy('dast_client_id')
                ->paginate($this->show_count);
            $list_items = $list_data->items();
            $list_client_id = array_column($list_items, 'dast_client_id');

            // 查询客户单位名称
            $find_chun_data = DB::table('channel_unit')
                ->whereIn('chun_id', $list_client_id)
                ->pluck('chun_unit_name', 'chun_id')->toArray();

            // 查询销售统计数据
            $find_dast_data = DB::table('data_statistical as dast')
                ->where('dast_cid', $user_info['adm_cid'])
                ->where('dast_shop_id', $user_info['adm_shop_id'])
                ->where('dast_service_project_type', 1)
                ->where('dast_order_type', '!=', 3)
                ->where('dast_ord_delete', 1)
                ->where('dast_type', 2)//客户单位类型
                ->whereIn('dast_client_id', $list_client_id)
                ->select('dast_client_id', 'dast_service_type', 'dast_goo_quantity')
                ->get()->toArray();

            $deliver_amount = [];//发货单数量
            $service_amount = [];//服务单数量
            $rescue_amount = [];//救援单数量
            $sales_return_amount = [];//退货单数量
            foreach ($find_dast_data as $key => $value) {
                // dast_service_type 订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单 7救援单
                if ($value->dast_service_type == 1) {
                    if (isset($service_amount[$value->dast_client_id])) {
                        $service_amount[$value->dast_client_id] += $value->dast_goo_quantity;
                    } else {
                        $service_amount[$value->dast_client_id] = $value->dast_goo_quantity;
                    }
                } elseif ($value->dast_service_type == 4) {
                    if (isset($sales_return_amount[$value->dast_client_id])) {
                        $sales_return_amount[$value->dast_client_id] += abs($value->dast_goo_quantity);
                    } else {
                        $sales_return_amount[$value->dast_client_id] = abs($value->dast_goo_quantity);
                    }
                } elseif ($value->dast_service_type == 5) {
                    if (isset($deliver_amount[$value->dast_client_id])) {
                        $deliver_amount[$value->dast_client_id] += $value->dast_goo_quantity;
                    } else {
                        $deliver_amount[$value->dast_client_id] = $value->dast_goo_quantity;
                    }
                } elseif ($value->dast_service_type == 7) {
                    if (isset($rescue_amount[$value->dast_client_id])) {
                        $rescue_amount[$value->dast_client_id] += $value->dast_goo_quantity;
                    } else {
                        $rescue_amount[$value->dast_client_id] = $value->dast_goo_quantity;
                    }
                }
            }

            $return_data = [];//返回数据
            $data_info = [];//返回数据
            foreach ($list_client_id as $key => $value) {
                $temp_data['chun_unit_name'] = $find_chun_data[$value];
                if (isset($deliver_amount[$value])) {
                    $temp_deliver_amount = $deliver_amount[$value];
                } else {
                    $temp_deliver_amount = 0;
                }

                if (isset($service_amount[$value])) {
                    $temp_service_amount = $service_amount[$value];
                } else {
                    $temp_service_amount = 0;
                }
                if (isset($rescue_amount[$value])) {
                    $temp_rescue_amount = $rescue_amount[$value];
                } else {
                    $temp_rescue_amount = 0;
                }
                if (isset($sales_return_amount[$value])) {
                    $temp_sales_return_amount = $sales_return_amount[$value];
                } else {
                    $temp_sales_return_amount = 0;
                }
                // 销售数量 = 总的售出商品数量（发货单、服务单、救援单） -  退货商品数量（退货单）
                $temp_data['sell_amount'] = ($temp_deliver_amount + $temp_service_amount + $temp_rescue_amount) - $temp_sales_return_amount;
                // 更换数量 = 救援单售出商品数量
                $temp_data['renewal_amount'] = $temp_rescue_amount;
                // 更换占比 = 救援单售出商品数量 /  销售数量
                if ($temp_data['sell_amount']) {
                    $temp_data['renewal_ratio'] = (round(($temp_rescue_amount / $temp_data['sell_amount']), 2) * 100).'%';
                } else {
                    $temp_data['renewal_ratio'] = '0%';
                }

                // 送货数量 = （发货单、服务单）售出商品数量 - 退货商品数量（退货单）
                $temp_data['deliver_amount'] = ($temp_deliver_amount + $temp_service_amount) - $temp_sales_return_amount;
                if ($temp_data['sell_amount']) {
                    $temp_data['deliver_ratio'] = (round(($temp_data['deliver_amount'] / $temp_data['sell_amount']), 2) * 100).'%';
                } else {
                    $temp_data['deliver_ratio'] = '0%';
                }
                $data_info[$key] = $temp_data;
                unset($temp_data);
            }

            $return_data['current_page'] = $list_data->currentPage();  //当前页面页码
            $return_data['last_page'] = $list_data->lastPage();        //表示最后一页的页码
            $return_data['total'] = $list_data->total();               //总数据个数
            $return_data['current_number'] = $this->show_count;        //一页显示多少个
            $return_data['data'] = $data_info;
            // 获取当前列表下的按钮
            $list_button = getListButton($request['api_token'], $request['pri_id']);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'查询类型错误！']);
        }

        if (isset($select_count_field['field_title'])) {
            $i = 0;
            foreach ($priceshow as $key1 => $value1) {// 遍历总计数据
                foreach ($select_count_field['field_title'] as $keys => $values) {// 遍历选择的字段
                    if ($key1 == $values) {// 把对应的字段和显示名称及数据返回前端
                        $new_data[$i]['field_name'] = $select_count_field['field_name'][$keys];
                        $new_data[$i]['field_value'] = $value1;
                        if ($select_count_field['field_price'][$keys] == 1) {// 字段为金额的数据
                            $new_data[$i]['field_price'] = $select_count_field['field_price'][$keys];
                        }
                        $i++;
                    }
                }
            }
        }
        if (isset($select_list_field['field_title'])) {
            $j = 0;
            foreach ($select_list_field['field_title'] as $key2 => $value2) {//返回有权限的表头
                $list_title[$j]['field_name'] = $select_list_field['field_name'][$key2];
                $list_title[$j]['field_list'] = $value2;
                if ($select_list_field['field_price'][$key2] == 1) {// 字段为金额的数据
                    $list_title[$j]['field_price'] = $select_list_field['field_price'][$key2];
                }
                $j++;
            }
            if (in_array($input['searchtype'], [2,6,8,9,10])) {//遍历列表数据
                if (isset($return_data['data'])) {
                    foreach ($return_data['data'] as $key3 => $value3) {
                        foreach ($value3 as $rd_key => $rd_value) {// 查询出来的所有字段
                            if (!in_array($rd_key, $select_list_field['field_title'])) {// 没有字段的权限就清空
                                unset($return_data[$key3][$rd_key]);
                            }
                        }
                    }
                }
            } else {
                if (isset($return_data)) {
                    foreach ($return_data as $key3 => $value3) {
                        foreach ($value3 as $rd_key => $rd_value) {
                            $new_field  = ['dast_client_ids', 'chun_chty_id', 'dast_type'];
                            if (!in_array($rd_key, $select_list_field['field_title']) && !in_array($rd_key, $new_field)) {// 没有字段的权限就清空
                                unset($return_data[$key3][$rd_key]);
                            }
                        }
                    }
                }
            }
        }
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        return response()->json(['code'=>200, 'msg'=>'success', 'allshow'=>$priceshow, 'data'=>$return_data, 'list_button'=>$list_button, 'list_button_data'=>$return_list_button, 'new_data'=>$new_data, 'list_title'=>$list_title]);
    }

    /**
     * [brandDirectAccountingPrice 品牌直营核算价]
     * @param  [type] $user_info [用户信息]
     * @param  [type] $input     [前端传值]
     * @return [type]            [description]
     */
    private function brandDirectAccountingPrice($user_info, $input)
    {
        /*
            同一品牌的直营核算价
            a1 同一个商品的销售的直营核算价=实售商品数量*商品的直营核算价
            b1 同一个商品的退货直营核算价=退货商品数量*商品的直营核算价
            c1 同一个品牌的销售的直营核算价=这个品牌下所有商品的销售直营核算价的和 a1+a2+...
            c2 同一个品牌的退货的直营核算价=这个品牌下所有商品的退货直营核算价的和 b1+b2+...
            直营核算价 =  c1 - c2;这个价格是页面显示的价格
         */
        $Db = DB::table("data_statistical as a")
            ->leftJoin('goods as b', 'b.goo_id', '=', 'a.dast_goo_id')
            ->leftJoin('warehouse as c', 'c.ware_id', '=', 'a.dast_ware_id')
            ->where('dast_cid', $user_info['adm_cid'])
            ->where('dast_shop_id', $user_info['adm_shop_id'])
            ->where('dast_order_type', '!=', '3')
            ->where('dast_goo_id', '>', 0)
            ->where('dast_ord_delete', '1');
        if (isset($input['creatData']) && !empty($input['creatData'])) { //时间
            $input['creatData'][1] = date("Y-m-d", strtotime($input['creatData'][1] . " +1 day"));
            $Db = $Db->whereBetween('a.dast_create_time', $input['creatData']);
        }
        if (isset($input['dast_type']) && !empty($input['dast_type'])) { //买家类型：1门店零售2渠道单位3速电派单4第三方派单
            $Db = $Db->where('dast_type', $input['dast_type']);
        }
        if (isset($input['dast_client_id']) && !empty($input['dast_client_id'])) { //往来单位
            // 有客户单位id，默认搜索买家类型为客户单位的
            $Db = $Db->where('dast_type', 2); //买家类型
            $Db = $Db->where('dast_client_id', $input['dast_client_id']);
        }
        if (isset($input['goo_bra_id']) && !empty($input['goo_bra_id'])) { //品牌id
            $Db = $Db->where('goo_bra_id', $input['goo_bra_id']);
        }
        if (isset($input['goo_cate_id']) && !empty($input['goo_cate_id'])) { //商品类型
            $Db = $Db->where('goo_cate_id', $input['goo_cate_id']);
        }
        if (isset($input['dast_orcl_chin_type']) && !empty($input['dast_orcl_chin_type'])) { //铺货类型1是铺货2不是铺货
            $Db = $Db->where('dast_orcl_chin_type', $input['dast_orcl_chin_type']);
        }
        if (isset($input['ware_type']) && !empty($input['ware_type'])) { //仓库类型
            $Db = $Db->where('ware_type', $input['ware_type']);
        }
        if (isset($input['dast_ware_id']) && !empty($input['dast_ware_id'])) { //仓库id
            $Db = $Db->where('dast_ware_id', $input['dast_ware_id']);
        }
        if (isset($input['dast_create_id']) && !empty($input['dast_create_id'])) { //开单员id
            $Db = $Db->where('dast_create_id', $input['dast_create_id']);
        }
        if (isset($input['dast_adm_id']) && !empty($input['dast_adm_id'])) { //业务员id
            $Db = $Db->where('dast_adm_id', $input['dast_adm_id']);
        }
        if (isset($input['chun_chty_id']) && !empty($input['chun_chty_id'])) { //客户类型
            $Db = $Db->where('dast_chty_id', $input['chun_chty_id']);
        }
        if (isset($input['dast_orcl_shipment_party']) && !empty($input['dast_orcl_shipment_party'])) { //出库方1仓库2直营店3加盟店4虚拟加盟店
            $Db = $Db->where('dast_orcl_shipment_party', $input['dast_orcl_shipment_party']);
        }
        $list = $Db->selectRaw('goo_bra_id, dast_goo_id, goo_class,  goo_direct_accounting_price, sum(`dast_goo_quantity`) as quantity, dast_order_type')
            ->groupBy('goo_id', 'dast_order_type')->get()->toArray();
        $brand_goo_price = [];
        foreach ($list as $key => $value) {
            if ($value->goo_bra_id) {
                // goo_class 类型：1自营商品2系统商品
                $goo_direct_accounting_price = $value->goo_direct_accounting_price;
                if ($value->goo_class == 2) {
                    // 查询系统商品的直营核算价
                    $goo_direct_accounting_price = DB::table('goods_system_affiliate')
                        ->where('gosa_shop_id', $user_info['adm_shop_id'])
                        ->where('gosa_goo_id', $value->dast_goo_id)
                        ->value('gosa_direct_accounting_price');
                }
                if (isset($brand_goo_price[$value->goo_bra_id])) {
                    // dast_order_type 订单类型1销售单2退款单
                    if ($value->dast_order_type == 1) {
                        $brand_goo_price[$value->goo_bra_id]['sell_price'] += $value->quantity * $goo_direct_accounting_price; //销售金额
                    } else {
                        $brand_goo_price[$value->goo_bra_id]['back_price'] += $value->quantity * $goo_direct_accounting_price; //退回金额
                    }
                } else {
                    // dast_order_type 订单类型1销售单2退款单
                    if ($value->dast_order_type == 1) {
                        $brand_goo_price[$value->goo_bra_id]['sell_price'] = $value->quantity * $goo_direct_accounting_price; //销售金额
                        $brand_goo_price[$value->goo_bra_id]['back_price'] = 0; //退回金额
                    } else {
                        $brand_goo_price[$value->goo_bra_id]['sell_price'] = 0; //销售金额
                        $brand_goo_price[$value->goo_bra_id]['back_price'] = $value->quantity * $goo_direct_accounting_price; //退回金额
                    }
                }
            }
        }
        return $brand_goo_price;
    }

    // 导出
    public function export(Request $request)
    {
        $user_info = Common::getUserInfo($request['api_token']);
        if (!$user_info) {
            throw new Exception('获取用户信息失败');
        } else {
            $user_info = $this->objectToArray($user_info);
        }
        $input = $request->all();
        set_time_limit(0);

        $goods_inventory = new DataStatistical();
       
        // 查询设置的销售查询权限
        $list_button_data = DB::table('admin_set')
            ->where('adms_adm_id', $user_info['adm_id'])
            ->where('adms_shop_id', $user_info['adm_shop_id'])
            ->select('adms_id', 'adms_statistical_data')
            ->first();
        $list_button_data = json_decode($list_button_data->adms_statistical_data, true);
        $select_count_field = [];// 总计字段权限
        $select_list_field = [];// 列表字段权限
        $list_title = [];// 列表表头数据
        $new_data = [];// 总计字段数据
        $list = [];// 导出数据
        foreach ($list_button_data as $key => $value) {
            $list_button_data[0]['checked'] = true;//第一个默认选择
            $list_button_data[$key]['result'] = '销量';
            if (!empty($input['searchtype'])) {
                if ($value['id'] == $input['searchtype']) {
                    foreach ($value['count_field'] as $co_key => $co_value) {
                        if (in_array($co_value['id'], $value['childCountCheck'])) {
                            $select_count_field['field_title'][] = $co_value['field_title'];
                            $select_count_field['field_name'][] = $co_value['field_name'];
                        }
                    }
                    foreach ($value['list_field'] as $li_key => $li_value) {
                        if (in_array($li_value['id'], $value['childListCheck'])) {
                            $select_list_field['field_title'][] = $li_value['field_title'];
                            $select_list_field['field_name'][] = $li_value['field_name'];
                        }
                    }
                }
            }
            if (empty($input['searchtype'])) {//第一次进入没有传searchtype值
                $input['searchtype'] = $value['id'];
                foreach ($value['count_field'] as $co_key => $co_value) {
                    if (in_array($co_value['id'], $value['childCountCheck'])) {// 总计字段
                        $select_count_field['field_title'][] = $co_value['field_title'];
                        $select_count_field['field_name'][] = $co_value['field_name'];
                        if (isset($co_value['is_price'])) {// 是否为金额字段
                            $select_count_field['field_price'][] = 1;
                        } else {
                            $select_count_field['field_price'][] = 0;
                        }
                    }
                }
                foreach ($value['list_field'] as $li_key => $li_value) {
                    if (in_array($li_value['id'], $value['childListCheck'])) {// 列表字段
                        $select_list_field['field_title'][] = $li_value['field_title'];
                        $select_list_field['field_name'][] = $li_value['field_name'];
                        if (isset($li_value['is_price'])) {// 是否为金额字段
                            $select_list_field['field_price'][] = 1;
                        } else {
                            $select_list_field['field_price'][] = 0;
                        }
                    }
                }
                break;
            }
        }
        $request['searchtype'] = $input['searchtype'];
        if ($input['searchtype'] == '1') { //查询品牌
            $select_field = "goo_bra_id,sum(`dast_goo_quantity`) as quantity,sum(`dast_goo_price`*`dast_goo_quantitys`) as price,sum(`dast_goo_cost`*`dast_goo_quantitys`) as cost,dast_order_type";

            $return_data = $goods_inventory->goodsIndex($user_info, $request->all(), $this->show_count, $select_field);
            if (count($return_data) > 0) {
                $direct_accounting_price = $this->brandDirectAccountingPrice($user_info, $input);
                $allnums = 0; //实际销售数量
                $sale_num = 0; //销售数量
                $return_num = 0; //退货数量
                $allprice = 0; //实际销售金额
                $sale_sprice = 0; //销售金额
                $return_sprice = 0; //退款金额
                $sale_cost = 0; //销售成本
                $return_cost = 0; //退款成本
                $allcost = 0; //总成本
                $brand = DB::table("brand")
                    ->where(function ($query) use ($user_info) {
                        $query->where('bra_shop_id', 0) //门店id为0的是系统数据
                            ->Orwhere('bra_shop_id', $user_info['adm_shop_id']); //账号所属门店id
                    })
                    ->where(function ($query) use ($user_info) {
                        $query->where('bra_cid', 0) //门店id为0的是系统数据
                            ->Orwhere('bra_cid', $user_info['adm_cid']); //账号所属门店id
                    })
                    ->pluck('bra_name', 'bra_id')->toArray();
                foreach ($return_data as $key => $value) {
                    if ($value['goo_bra_id'] > 0) {
                        if (empty($data[$value['goo_bra_id']])) {
                            $data[$value['goo_bra_id']]['brand_name'] = '';
                            $data[$value['goo_bra_id']]['sale_num'] = 0;
                            $data[$value['goo_bra_id']]['sale_sprice'] = 0;
                            $data[$value['goo_bra_id']]['sale_cost'] = 0;
                            $data[$value['goo_bra_id']]['return_num'] = 0;
                            $data[$value['goo_bra_id']]['return_sprice'] = 0;
                            $data[$value['goo_bra_id']]['return_cost'] = 0;
                            $data[$value['goo_bra_id']]['allnum'] = 0;
                            $data[$value['goo_bra_id']]['profits'] = 0;
                        }
                        if ($value['dast_order_type'] == '1') {
                            $data[$value['goo_bra_id']]['brand_name'] = '';
                            $data[$value['goo_bra_id']]['sale_num'] = $value['quantity'];
                            $data[$value['goo_bra_id']]['sale_sprice'] = $value['price']/100;
                            $data[$value['goo_bra_id']]['sale_cost'] = $value['cost']/100;
                            $data[$value['goo_bra_id']]['allnum'] = $data[$value['goo_bra_id']]['allnum'] + $value['quantity'];
                            $allnums = $allnums + $value['quantity'];
                            $sale_num = $sale_num + $value['quantity'];
                            $allprice = $allprice + $value['price'];
                            $sale_sprice = $sale_sprice + $value['price'];
                            $sale_cost = $sale_cost + $value['cost'];
                            $allcost = $allcost + $value['cost'];
                        }
                        if ($value['dast_order_type'] == '2') {
                            $data[$value['goo_bra_id']]['brand_name'] = '';
                            $data[$value['goo_bra_id']]['return_num'] = $value['quantity'];
                            $data[$value['goo_bra_id']]['return_sprice'] = $value['price']/100;
                            $data[$value['goo_bra_id']]['return_cost'] = $value['cost']/100;
                            $data[$value['goo_bra_id']]['allnum'] = $data[$value['goo_bra_id']]['allnum'] + $value['quantity'];
                            $allnums = $allnums + $value['quantity']; //实际销售数量可在循环外使用销售和退货数量相加
                            $return_num = $return_num + $value['quantity'];
                            $allprice = $allprice + $value['price'];
                            $return_sprice = $return_sprice + $value['price'];
                            $return_cost = $return_cost + $value['cost'];
                            $allcost = $allcost - $value['cost'];
                        }
                    }
                }
                $priceshow['allnum'] = $allnums;
                $priceshow['return_num'] = $return_num;
                $priceshow['return_sprice'] = $return_sprice;
                $priceshow['profits'] = $allprice;
                $priceshow['allcost'] = $allcost;
                $priceshow['sale_cost'] = $sale_cost;
                $priceshow['return_cost'] = $return_cost;
                $priceshow['profit'] = $allprice - $allcost;
                $list = [];
                $num = 0;
                $allnum = [];
                $list['info']['sale_num'] = ''; //销售数量
                $list['info']['sale_sprice'] = '销售合计:' . $priceshow['profits'] / 100; //销售金额
                $list['info']['sale_cost'] = '销售成本:' . $sale_cost / 100; //销售成本
                $list['info']['return_num'] = '退货数量:' . $return_num; //退货数量
                $list['info']['return_sprice'] = '退款金额:' . $return_sprice / 100; //退款金额
                $list['info']['return_cost'] = '退货成本'.$return_cost/100; //退货成本
                $list['info']['allnum'] = '数量合计:' . $allnums; //实售数量
                $list['info']['allprice'] = '营业额:' . $allprice / 100; //营业额
                $list['info']['allprice'] = ''; //营业成本
                $list['info']['profit'] = '利润:' . $priceshow['profit'] / 100; //营业利润
                $list['info']['profit_margin'] = ''; //利润率
                $list['info']['brand_name'] = ''; //品牌名称
                $list['info']['allcost'] = '成本合计:'.$allcost/100; //成本合计
                foreach ($brand as $keys => $values) {
                    if (empty($data[$keys])) {
                        $list[$num]['brand_name'] = $values;
                        $list[$num]['sale_num'] = 0;
                        $list[$num]['sale_sprice'] = 0;
                        $list[$num]['sale_cost'] = 0;
                        $list[$num]['return_num'] = 0;
                        $list[$num]['return_sprice'] = 0;
                        $list[$num]['return_cost'] = 0;
                        $list[$num]['allnum'] = 0;
                        $list[$num]['profits'] = 0; //营业额
                        $list[$num]['allcost'] = 0;//营业成本
                        if (empty($direct_accounting_price[$keys])) {
                            $list[$num]['direct_accounting_price'] = 0; //直营核算价（单位：分）
                        } else {
                            $list[$num]['direct_accounting_price'] = ($direct_accounting_price[$keys]['sell_price'] - $direct_accounting_price[$keys]['back_price'])/100; //直营核算价（单位：分）
                        }
                        $list[$num]['profit'] = 0; //营业利润
                        $list[$num]['profit_margin'] = 0; //利润率=营业利润/营业额
                    } else {
                        $list[$num] = $data[$keys];
                        $list[$num]['brand_name'] = $values;
                        $list[$num]['profits'] = $list[$num]['sale_sprice'] + $list[$num]['return_sprice']; //营业额(单位:分)
                        $list[$num]['allcost'] = $list[$num]['sale_cost'] - $list[$num]['return_cost']; //营业成本（单位：分）
                        if (empty($direct_accounting_price[$keys])) {
                            $list[$num]['direct_accounting_price'] = 0; //直营核算价（单位：分）
                        } else {
                            $list[$num]['direct_accounting_price'] = ($direct_accounting_price[$keys]['sell_price'] - $direct_accounting_price[$keys]['back_price'])/100; //直营核算价（单位：分）
                        }
                        $list[$num]['profit'] = $list[$num]['profits'] - $list[$num]['allcost']; //营业利润（单位：分）
                        if ($list[$num]['profits'] != '0') {
                            $list[$num]['profit_margin'] = sprintf("%.2f", sprintf("%.2f", $list[$num]['profit'] / $list[$num]['profits']) * 100); //利润率
                        } else {
                            $list[$num]['profit_margin'] = 0; //利润率
                        }
                    }

                    $allnum[] = $list[$num]['allnum']; //实售数量
                    $num++;
                }
                $pathName = storage_path() . "/app/public/excel"; //获取上传excel路径
                // 创建文件夹
                if (!file_exists($pathName)) {
                    mkdir($pathName, 0775, true);
                    chmod($pathName, 0775);
                }
                $streamFileRand = '品牌查询' . time() . rand(1000, 9999) . '.xls';
                // 产生一个随机文件名（因为你base64上来肯定没有文件名，这里你可以自己设置一个也行）
                $streamFilename = $pathName . '/' . $streamFileRand;

                $where['action_name'] = '品牌查询';
                $where['field_name'] = ['品牌名称', '销售数量', '销售金额', '销售成本', '退货数量', '退货金额', '退货成本', '实售数量', '营业额', '营业成本', '直营核算价', '营业利润', '利润率'];
            } else {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
            }
        } elseif ($input['searchtype'] == '2') { //销售明细
            $select_field = "dast_order_number, goo_cate_name, chun_unit_name as unit_name, chun_chty_id, dast_ord_id, dast_id, dast_create_time, goo_name, goo_ampere_hour, dast_goo_quantity, dast_goo_quantitys, dast_goo_price, dast_goo_quantitys*dast_goo_price as allprice, dast_client_id, dast_type, ware_freight_space, dast_service_type, dast_creacor, goo_goods_encode, dast_goo_cost as cost, goo_brse_id, goo_id, goo_class, goo_direct_accounting_price, goo_bra_name, goo_unit";

            $return_data = $goods_inventory->goodsIndex($user_info, $request->all(), $this->show_count, $select_field, '', 2);
            if ($return_data['data']) {
                $Dbs = $goods_inventory->searchIndex($user_info, $input);
                $cost_db = $goods_inventory->searchIndex($user_info, $input);
                $alldata = $Dbs->where('dast_service_project_type', 1)->selectRaw('sum(dast_goo_quantitys*dast_goo_price) as allprice,sum(dast_goo_quantitys*dast_goo_cost) as allcost,sum(dast_goo_quantity) as allnum')->first();
                // 订单为退货单的总成本
                $order_return = $cost_db->where('dast_order_type', 2)->selectRaw('sum(dast_goo_quantitys*dast_goo_cost) as allcost')->first();
                $alldata = $Dbs->where('dast_service_project_type', 1)->selectRaw('sum(dast_goo_quantitys*dast_goo_price) as allprice,sum(dast_goo_quantity) as allnum')->first();
                $alldata = $this->objectToArray($alldata);
                $allshow['profits'] = $alldata['allprice'];
                $allshow['allnum'] = $alldata['allnum'];
                $allshow['allcost'] = $alldata['allcost'];
                $list['info']['dast_order_number'] = '';
                $list['info']['goo_goods_encode'] = '';
                $list['info']['goo_name'] = '';
                $list['info']['goo_ampere_hour'] = '';
                $list['info']['dast_goo_quantity'] = $allshow['allnum'];
                $list['info']['allnum'] = '数量合计:'.$allshow['allnum'];
                // $list['info']['allcost'] = '成本合计'.$allshow['allcost']/100;
                $allcost = abs($alldata['allcost']) - abs($order_return->allcost * 2);
                $list['info']['allcost'] = '成本合计:'.$allcost/100;
                $list['info']['profits'] = '销售合计:'.$allshow['profits']/100;
                $list['info']['attribute'] = '';
                $list['info']['allprice'] = $allshow['profits'] / 100;
                $list['info']['unit_name'] = '';
                $list['info']['type_name'] = '';
                $list['info']['ware_freight_space'] = '';
                $list['info']['dast_create_time'] = '';
                $list['info']['dast_service_type'] = '';
                $list['info']['dast_creacor'] = '';
                $chun_chty_id = [];
                $system_goo_id = []; //系统商品id
                foreach ($return_data['data'] as $key => $value) {
                    if ($value['chun_chty_id'] > 0) {
                        $chun_chty_id[] = $value['chun_chty_id'];
                    }
                    if ($value['goo_class'] == 2) {
                        $system_goo_id[] = $value['goo_id'];
                    }
                }

                $channel_type = [];
                if ($chun_chty_id) {
                    $channel_type = DB::table('channel_type')
                        ->whereIn("chty_id", $chun_chty_id)
                        ->pluck('chty_name', 'chty_id');
                }
                $system_goo_price = []; //系统商品金额
                if ($system_goo_id) {
                    $system_goo_price = DB::table('goods_system_affiliate')
                        ->where('gosa_shop_id', $user_info['adm_shop_id'])
                        ->whereIn('gosa_goo_id', $system_goo_id)
                        ->pluck('gosa_direct_accounting_price', 'gosa_goo_id')
                        ->toArray();
                }
                foreach ($return_data['data'] as $key => $value) {
                    unset($value['order_reamrks']);
                    $list[$key]['dast_order_number'] = $value['dast_order_number']; //订单编号
                    $list[$key]['goo_goods_encode'] = $value['goo_goods_encode']; //商品编码
                    $list[$key]['goo_cate_name'] = $value['goo_cate_name']; //商品品类
                    $list[$key]['goo_name'] = $value['goo_name']; //商品名称
                    $list[$key]['goo_ampere_hour'] = $value['goo_ampere_hour']; //规格
                    $list[$key]['dast_goo_quantity'] = $value['dast_goo_quantity']; //数量
                    $list[$key]['goo_unit'] = $value['goo_unit'];
                    $list[$key]['dast_goo_price'] = $value['dast_goo_price'] / 100; //商品单价
                    $list[$key]['allprice'] = $value['allprice'] / 100; //总额
                    $list[$key]['cost'] = $value['cost'] / 100; //成本
                    $list[$key]['total_cost'] = $value['cost'] / 100 * $value['dast_goo_quantity']; //商品总成本
                    $list[$key]['profit'] = $value['allprice'] / 100 - $value['cost'] / 100 * $value['dast_goo_quantity']; //利润
                    $list[$key]['goo_direct_accounting_price'] = $value['goo_direct_accounting_price'] / 100; //商品的直营核算价

                    if ($value['goo_class'] == 2) {
                        $goo_direct_accounting_price = isset($system_goo_price[$value['goo_id']]) ? $system_goo_price[$value['goo_id']] : 0; //系统商品的直营核算价
                        $list[$key]['goo_direct_accounting_price'] = $goo_direct_accounting_price / 100; //系统商品的直营核算价
                    }
                    $list[$key]['unit_name'] = $value['unit_name']; //来往单位
                    $list[$key]['type_name'] = $value['type_name']; //客户类型
                    $list[$key]['ware_freight_space'] = $value['ware_freight_space']; //仓库编码
                    $list[$key]['dast_create_time'] = $value['dast_create_time']; //创建时间
                    $list[$key]['service_name'] = $value['service_name'];
                    $list[$key]['dast_creacor'] = $value['dast_creacor']; //开单员
                }
                $pathName = storage_path() . "/app/public/excel"; //获取上传excel路径
                // 创建文件夹
                if (!file_exists($pathName)) {
                    mkdir($pathName, 0775, true);
                    chmod($pathName, 0775);
                }
                $streamFileRand = '销售明细' . time() . rand(100, 999) . '.xls';
                // 产生一个随机文件名（因为你base64上来肯定没有文件名，这里你可以自己设置一个也行）
                $streamFilename = $pathName . '/' . $streamFileRand;

                $where['action_name'] = '销售明细';
                $where['field_name'] = ['订单编号', '商品编码', '商品品类', '商品名称', '规格', '数量', '单位', '单价', '总额', '成本', '总成本', '利润', '直营核算价', '客户单位', '客户类型', '仓库编码', '创建时间', '订单类型', '开单员'];
            } else {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
            }
        } elseif ($input['searchtype'] == '3') { //销量排行
            $select_field = "dast_actual_goo_id,goo_goods_encode,goo_name,goo_cate_name,goo_ampere_hour,goo_unit,sum(`dast_goo_quantity`) as quantity,sum(`dast_goo_price`*`dast_goo_quantitys`) as price, goo_class, goo_brse_id, goo_bra_name";

            $return_data = $goods_inventory->goodsIndex($user_info, $request->all(), $this->show_count, $select_field);
            if ($return_data) {
                $allnums = 0; //数量合计
                $allprice = 0; //销售合计
                foreach ($return_data as $key => $value) {
                    $allnums = $allnums + $value->quantity;
                    $allprice = $allprice + $value->price;
                }
                $list['info']['goo_goods_encode'] = '';
                $list['info']['goo_name'] = '';
                $list['info']['goo_cate_name'] = '';
                $list['info']['goo_ampere_hour'] = '';
                $list['info']['attribute'] = '';
                $list['info']['quantity'] = '实售数量:' . $allnums;
                $list['info']['allprice'] = '营业额:' . $allprice / 100;

                $list['info']['allnum'] = '数量合计:' . $allnums;
                $list['info']['profits'] = '销售合计:' . $allprice / 100;
                foreach ($return_data as $key => $value) {
                    $list[$key]['goo_goods_encode'] = $value->goo_goods_encode;
                    $list[$key]['goo_name'] = $value->goo_name;
                    $list[$key]['goo_cate_name'] = $value->goo_cate_name;
                    $list[$key]['goo_ampere_hour'] = $value->goo_ampere_hour;
                    $list[$key]['attribute'] = $value->goo_unit;
                    $list[$key]['quantity'] = $value->quantity;
                    $list[$key]['price'] = $value->price / 100;
                }
                $priceshow['allnum'] = $allnums;
                $priceshow['profits'] = $allprice;
                $pathName = storage_path() . "/app/public/excel"; //获取上传excel路径
                // 创建文件夹
                if (!file_exists($pathName)) {
                    mkdir($pathName, 0775, true);
                    chmod($pathName, 0775);
                }

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

                $where['action_name'] = '销量排行';
                $where['field_name'] = ['商品编码', '商品名称', '商品分类', '规格', '单位', '数量', '总额'];
            } else {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
            }
        } elseif ($input['searchtype'] == '4') { //开单员销量
            $select_field = "dast_create_id,dast_creacor,sum(`dast_goo_quantity`) as quantity,sum(`dast_goo_price`*`dast_goo_quantitys`) as price,dast_order_type";

            $return_data = $goods_inventory->goodsIndex($user_info, $request->all(), $this->show_count, $select_field);
            if ($return_data) {
                $sale_num = 0;
                $return_num = 0; //退货数量
                $allprice = 0; //销售合计
                $sale_sprice = 0;
                $return_sprice = 0; //退款金额
                $allnums = 0; //数量合计
                foreach ($return_data as $key => $value) {
                    if ($value['dast_create_id'] > 0) {
                        if (empty($data[$value['dast_create_id']])) {
                            $data[$value['dast_create_id']]['dast_creacor'] = $value['dast_creacor'];
                            $data[$value['dast_create_id']]['sale_num'] = 0;
                            $data[$value['dast_create_id']]['sale_sprice'] = 0;
                            $data[$value['dast_create_id']]['return_num'] = 0;
                            $data[$value['dast_create_id']]['return_sprice'] = 0;
                            $data[$value['dast_create_id']]['profits'] = 0;
                        }
                        if ($value['dast_order_type'] == '1') {
                            $data[$value['dast_create_id']]['sale_num'] = $value['quantity'];
                            $data[$value['dast_create_id']]['sale_sprice'] = $value['price']/100;
                            $sale_num = $sale_num + $value['quantity'];
                            $allprice = $allprice + $value['price'];
                            $sale_sprice = $sale_sprice + $value['price'];
                            $allnums = $allnums + $value['quantity'];
                        }
                        if ($value['dast_order_type'] == '2') {
                            $data[$value['dast_create_id']]['return_num'] = $value['quantity'];
                            $data[$value['dast_create_id']]['return_sprice'] = $value['price']/100;
                            $return_num = $return_num + $value['quantity'];
                            $allprice = $allprice + $value['price'];
                            $return_sprice = $return_sprice + $value['price'];
                            $allnums = $allnums + $value['quantity'];
                        }
                    }
                }
                $priceshow['allnum'] = $allnums; //数量合计
                $priceshow['return_num'] = $return_num; //退货数量
                $priceshow['return_sprice'] = $return_sprice; //退款金额
                $priceshow['profits'] = $allprice; //销售合计
                $list['info']['dast_creacor'] = '';
                $list['info']['sale_num'] = '实售数量:' . $allnums;
                $list['info']['sale_sprice'] = '';
                $list['info']['return_num'] = '退货数量:' . $return_num;
                $list['info']['return_sprice'] = '退款金额:' . $return_sprice / 100;
                $list['info']['profits'] = '销售合计:' . $allprice / 100;
                $list['info']['allnum'] = '数量合计:' . $allnums;
                $num = 0;
                foreach ($data as $key => $value) {
                    $list[$num] = $value;
                    $list[$num]['profits'] = $value['sale_sprice'] + $value['return_sprice'];
                    $num++;
                }
                $pathName = storage_path() . "/app/public/excel"; //获取上传excel路径
                // 创建文件夹
                if (!file_exists($pathName)) {
                    mkdir($pathName, 0775, true);
                    chmod($pathName, 0775);
                }

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

                $where['action_name'] = '开单员销量';
                $where['field_name'] = ['开单员', '销售数量', '销售金额', '退款数量', '退款金额', '纯营业额'];
            } else {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
            }
        } elseif ($input['searchtype'] == '5') { //业务员销量
            $select_field = "dast_adm_id,dast_adm_name,sum(`dast_goo_quantity`) as quantity,sum(`dast_goo_price`*`dast_goo_quantitys`) as price,dast_order_type";

            $return_data = $goods_inventory->goodsIndex($user_info, $request->all(), $this->show_count, $select_field);
            if (count($return_data) > 0) {
                $sale_num = 0;
                $return_num = 0; //退货数量
                $allprice = 0;
                $sale_sprice = 0;
                $return_sprice = 0;
                foreach ($return_data as $key => $value) {
                    if ($value['dast_adm_id'] > 0) {
                        if (empty($data[$value['dast_adm_id']])) {
                            $data[$value['dast_adm_id']]['dast_adm_name'] = $value['dast_adm_name'];
                            $data[$value['dast_adm_id']]['sale_num'] = 0;
                            $data[$value['dast_adm_id']]['return_num'] = 0;
                            $data[$value['dast_adm_id']]['sale_sprice'] = 0;
                            $data[$value['dast_adm_id']]['return_sprice'] = 0;
                            $data[$value['dast_adm_id']]['profits'] = 0;
                        }
                        if ($value['dast_order_type'] == '1') {
                            $data[$value['dast_adm_id']]['sale_num'] = $value['quantity'];
                            $data[$value['dast_adm_id']]['sale_sprice'] = $value['price']/100;
                            $sale_num = $sale_num + $value['quantity'];
                            $allprice = $allprice + $value['price'];
                            $sale_sprice = $sale_sprice + $value['price'];
                        }
                        if ($value['dast_order_type'] == '2') {
                            $data[$value['dast_adm_id']]['return_num'] = $value['quantity'];
                            $data[$value['dast_adm_id']]['return_sprice'] = $value['price']/100;
                            $return_num = $return_num + $value['quantity'];
                            $allprice = $allprice + $value['price'];
                            $return_sprice = $return_sprice + $value['price'];
                        }
                    }
                }
                $priceshow['return_num'] = $return_num; //退货数量
                $priceshow['allnum'] = $sale_num + $return_num; //数量合计
                $priceshow['return_sprice'] = $return_sprice; //退款金额
                $priceshow['profits'] = $allprice; //销售合计
                $list['info']['dast_adm_name'] = '';
                $list['info']['allnum'] = '数量合计:' . ($sale_num + $return_num);
                $list['info']['sale_sprice'] = '';
                $list['info']['return_num'] = '退货数量:' . $return_num;
                $list['info']['return_sprice'] = '退款金额:' . $return_sprice / 100;
                $list['info']['allprice'] = '营业额:' . $allprice / 100;
                $list['info']['profits'] = '销售合计:' . $allprice / 100;
                $num = 0;
                foreach ($data as $key => $value) {
                    $list[$num] = $value;
                    $list[$num]['profits'] = $value['sale_sprice'] + $value['return_sprice'];
                    $list[$num]['allnum'] = $value['sale_num'] + $value['return_num'];
                    $num++;
                }
                
                $pathName = storage_path() . "/app/public/excel"; //获取上传excel路径
                // 创建文件夹
                if (!file_exists($pathName)) {
                    mkdir($pathName, 0775, true);
                    chmod($pathName, 0775);
                }

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

                $where['action_name'] = '业务员销量';
                $where['field_name'] = ['业务员', '销售数量', '退款数量', '销售金额', '退款金额', '纯营业额', '实售数量'];
            } else {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
            }
        } elseif ($input['searchtype'] == '7') { //客户汇总
            $select_field = "dast_client_ids,chun_unit_name as dast_client_name,chun_chty_id,dast_type,sum(`dast_goo_quantity`) as quantity,sum(`dast_goo_price`*`dast_goo_quantitys`) as price,sum(`dast_goo_cost`*`dast_goo_quantity`) as cost";

            $return_data = $goods_inventory->goodsIndex($user_info, $request->all(), $this->show_count, $select_field);
            if ($return_data) {
                $chun_chty_id = [];
                $allnum = 0;
                $allprice = 0;
                $allcost = 0;
                foreach ($return_data as $rd_key => $rd_value) {
                    $allnum = $allnum + $rd_value['quantity'];
                    $allprice = $allprice + $rd_value['price'];
                    $allcost = $allcost + $rd_value['cost'];
                    if ($rd_value['dast_type'] == 2) {
                        $chun_chty_id[] = $rd_value['chun_chty_id'];
                        if ($rd_value['dast_client_name'] == '') {
                            $return_data[$rd_key]['dast_client_name'] = '未定义' . $rd_value['dast_client_ids'];
                        }
                    } elseif ($rd_value['dast_type'] == 1) {
                        $return_data[$rd_key]['dast_client_name'] = '零散客户';
                    } elseif ($rd_value['dast_type'] == 3) {
                        $return_data[$rd_key]['dast_client_name'] = '速电客单';
                    } elseif ($rd_value['dast_type'] == 4) {
                        $return_data[$rd_key]['dast_client_name'] = '第三方客单';
                    } else {
                        $return_data[$rd_key]['dast_client_name'] = '未定义';
                    }
                }
                $priceshow['allnum'] = $allnum; //数量合计
                $priceshow['profits'] = $allprice; //销售合计
                $priceshow['allcost'] = $allcost; //成本合计
                $priceshow['profit'] = $allprice - $allcost; //利润
                $list['info']['allnum'] = '数量合计:' . $allnum;
                $list['info']['profits'] = '销售合计:' . $allprice / 100;
                $list['info']['allcost'] = '成本合计:' . $allcost / 100;
                $list['info']['profit'] = '利润:' . ($allprice - $allcost) / 100;
                if ($chun_chty_id) {
                    $channel_type = DB::table('channel_type')
                        ->whereIn("chty_id", $chun_chty_id)
                        ->pluck('chty_name', 'chty_id')
                        ->toArray();
                    if ($channel_type) {
                        foreach ($return_data as $key1 => $value1) {
                            if ($value1['dast_type'] == 2) {
                                $return_data[$key1]['type_name'] = $channel_type[$value1['chun_chty_id']] ?? '未定义' . $value1['chun_chty_id'];
                            }
                        }
                    }
                }
                foreach ($return_data as $key => $value) {
                    $list[$key]['type_name'] = isset($value['type_name'])?$value['type_name']:'未定义';
                    $list[$key]['dast_client_name'] = $value['dast_client_name'];
                    $list[$key]['quantity'] = $value['quantity'];
                    $list[$key]['dast_client_name'] = $value['dast_client_name'];
                    $list[$key]['dast_client_name'] = $value['dast_client_name'];
                    $list[$key]['price'] = $value['price']/100;
                    $list[$key]['cost'] = $value['cost']/100;
                    $list[$key]['profit'] = $value['price']/100 - $value['cost']/100;
                }
                
                $pathName = storage_path() . "/app/public/excel"; //获取上传excel路径
                // 创建文件夹
                if (!file_exists($pathName)) {
                    mkdir($pathName, 0775, true);
                    chmod($pathName, 0775);
                }
                $streamFileRand = '客户汇总' . time() . rand(100, 999) . '.xls';
                // 产生一个随机文件名（因为你base64上来肯定没有文件名，这里你可以自己设置一个也行）
                $streamFilename = $pathName . '/' . $streamFileRand;

                $where['action_name'] = '客户汇总';
                $where['field_name'] = ['客户类型', '客户名称', '数量', '销售金额', '销售成本', '销售利润'];
            } else {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
            }
        } elseif ($input['searchtype'] == '6') { //客户汇总--查看明细
            $select_field = "dast_order_number,goo_cate_name,chun_unit_name as unit_name,chun_chty_id,dast_ord_id,dast_id,dast_create_time,goo_name,goo_ampere_hour,dast_goo_quantity,dast_goo_quantitys,dast_goo_price,dast_goo_quantitys*dast_goo_price as allprice,dast_client_id,dast_type,ware_freight_space,dast_service_type,dast_creacor,goo_goods_encode,dast_goo_cost as cost, goo_brse_id, goo_id, goo_class, goo_direct_accounting_price, goo_bra_name, goo_unit";

            $return_data = $goods_inventory->goodsIndex($user_info, $request->all(), $this->show_count, $select_field, '', 2);
            if ($return_data['data']) {
                $Dbs = $goods_inventory->searchIndex($user_info, $input);
                $cost_db = $goods_inventory->searchIndex($user_info, $input);
                $alldata = $Dbs->where('dast_service_project_type', 1)->selectRaw('sum(dast_goo_quantitys*dast_goo_price) as allprice,sum(dast_goo_quantitys*dast_goo_cost) as allcost,sum(dast_goo_quantity) as allnum')->first();

                $alldata = $Dbs->where('dast_service_project_type', 1)->selectRaw('sum(dast_goo_quantitys*dast_goo_price) as allprice,sum(dast_goo_quantity) as allnum')->first();
                $order_return = $cost_db->where('dast_order_type', 2)->selectRaw('sum(dast_goo_quantitys*dast_goo_cost) as allcost')->first();
                $alldata = $this->objectToArray($alldata);
                $allshow['profits'] = $alldata['allprice'];
                $allshow['allnum'] = $alldata['allnum'];
                $list['info']['dast_order_number'] = '';
                $list['info']['goo_goods_encode'] = '';
                $list['info']['goo_name'] = '';
                $list['info']['goo_ampere_hour'] = '';
                $list['info']['dast_goo_quantity'] = $allshow['allnum'];
                $list['info']['attribute'] = '';
                $list['info']['allprice'] = $allshow['profits'] / 100;
                $list['info']['unit_name'] = '';
                $list['info']['type_name'] = '';
                $list['info']['ware_freight_space'] = '';
                $list['info']['dast_create_time'] = '';
                $list['info']['dast_service_type'] = '';
                $list['info']['dast_creacor'] = '';
                $list['info']['allnum'] = '数量合计:'.$allshow['allnum'];
                $allcost = abs($alldata['allcost']) - abs($order_return->allcost * 2);
                $list['info']['allcost'] = '成本合计:'.$allcost/100;
                $list['info']['profits'] = '销售合计:'.$allshow['profits']/100;
                // foreach ($return_data['data'] as $key => $value) {
                //     unset($value['order_reamrks']);
                //     $list[$key]['dast_create_time'] = $value['dast_create_time']; //创建时间
                //     $list[$key]['dast_order_number'] = $value['dast_order_number']; //订单编号
                //     $list[$key]['goo_goods_encode'] = $value['goo_goods_encode']; //商品编码
                //     $list[$key]['goo_name'] = $value['goo_name']; //商品名称
                //     $list[$key]['goo_cate_name'] = $value['goo_cate_name']; //商品分类
                //     $list[$key]['goo_ampere_hour'] = $value['goo_ampere_hour']; //规格
                //     $list[$key]['attribute'] = $value['goo_unit']; //单位
                //     $list[$key]['dast_goo_quantity'] = $value['dast_goo_quantity']; //数量
                //     $list[$key]['dast_goo_price'] = $value['dast_goo_price'] / 100; //商品单价
                //     $list[$key]['allprice'] = $value['allprice'] / 100; //总额
                //     $list[$key]['cost'] = $value['cost'] / 100; //成本
                // }
                foreach ($return_data['data'] as $key => $value) {
                    unset($value['order_reamrks']);
                    $list[$key]['dast_order_number'] = $value['dast_order_number']; //订单编号
                    $list[$key]['goo_goods_encode'] = $value['goo_goods_encode']; //商品编码
                    $list[$key]['goo_cate_name'] = $value['goo_cate_name']; //商品品类
                    $list[$key]['goo_name'] = $value['goo_name']; //商品名称
                    $list[$key]['goo_ampere_hour'] = $value['goo_ampere_hour']; //规格
                    $list[$key]['dast_goo_quantity'] = $value['dast_goo_quantity']; //数量
                    $list[$key]['goo_unit'] = $value['goo_unit'];
                    $list[$key]['dast_goo_price'] = $value['dast_goo_price'] / 100; //商品单价
                    $list[$key]['allprice'] = $value['allprice'] / 100; //总额
                    $list[$key]['cost'] = $value['cost'] / 100; //成本
                    $list[$key]['total_cost'] = $value['cost'] / 100 * $value['dast_goo_quantity']; //商品总成本
                    $list[$key]['profit'] = $value['allprice'] / 100 - $value['cost'] / 100 * $value['dast_goo_quantity']; //利润
                    $list[$key]['goo_direct_accounting_price'] = $value['goo_direct_accounting_price'] / 100; //商品的直营核算价

                    if ($value['goo_class'] == 2) {
                        $goo_direct_accounting_price = isset($system_goo_price[$value['goo_id']]) ? $system_goo_price[$value['goo_id']] : 0; //系统商品的直营核算价
                        $list[$key]['goo_direct_accounting_price'] = $goo_direct_accounting_price / 100; //系统商品的直营核算价
                    }
                    $list[$key]['unit_name'] = $value['unit_name']; //来往单位
                    $list[$key]['type_name'] = $value['type_name']; //客户类型
                    $list[$key]['ware_freight_space'] = $value['ware_freight_space']; //仓库编码
                    $list[$key]['dast_create_time'] = $value['dast_create_time']; //创建时间
                    $list[$key]['service_name'] = $value['service_name'];
                    $list[$key]['dast_creacor'] = $value['dast_creacor']; //开单员
                }
                $pathName = storage_path() . "/app/public/excel"; //获取上传excel路径
                // 创建文件夹
                if (!file_exists($pathName)) {
                    mkdir($pathName, 0775, true);
                    chmod($pathName, 0775);
                }
                $streamFileRand = '销售明细' . time() . rand(100, 999) . '.xls';
                // 产生一个随机文件名（因为你base64上来肯定没有文件名，这里你可以自己设置一个也行）
                $streamFilename = $pathName . '/' . $streamFileRand;

                $where['action_name'] = '客户汇总-查看明细';
                // $where['field_name'] = ['创建时间', '订单编号', '商品编码', '商品名称', '商品品类', '规格', '单位', '数量', '单价', '总额', '成本'];
                $where['field_name'] = ['订单编号', '商品编码', '商品品类', '商品名称', '规格', '数量', '单位', '单价', '总额', '成本', '总成本', '利润', '直营核算价', '客户单位', '客户类型', '仓库编码', '创建时间', '订单类型', '开单员'];
            } else {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
            }
        } elseif ($input['searchtype'] == '8') { //实时数据
            $select_field = "ord_order_number,goo_goods_encode,goo_name,goo_ampere_hour,orgo_goo_quantity,goo_unit,chun_unit_name as unit_name,chun_chty_id,chun_adm_id,ware_freight_space,ord_create_time,ord_id,ord_type,orgo_goo_price,ord_service_type,orgo_state, goo_bra_name, goo_brse_id, goo_class";

            $count_select_field = "count(ord_id) as num,sum(orgo_goo_quantity*orgo_goo_price) as allprice,sum(orgo_goo_quantity) as allnum,ord_service_type,orgo_state";

            $return_data = $goods_inventory->goodsIndex($user_info, $request->all(), $this->show_count, $select_field, $count_select_field, 2);
            if ($return_data['data']) {
                $find_ord_datas = $goods_inventory->searchRealIndexs($user_info, $input);
                $alldata = $find_ord_datas->selectRaw('count(ord_id) as num,sum(orgo_goo_quantity*orgo_goo_price) as allprice,sum(orgo_goo_quantity) as allnum,ord_service_type,orgo_state')->groupBy('ord_service_type', 'orgo_state')->get();
                $alldata = $this->objectToArray($alldata);
                $allprice = 0;
                $allnum = 0;
                foreach ($alldata as $key => $value) {
                    // 退货单类型商品金额不统计
                    if ($value['ord_service_type'] == '4' || $value['orgo_state'] == '4') {
                        $allprice -= $value['allprice'];
                        $allnum -= $value['allnum'];
                    } else {
                        $allprice += $value['allprice'];
                        $allnum += $value['allnum'];
                    }
                }
                $allshow['profits'] = $allprice;
                $allshow['allnum'] = $allnum;
                
                $list['info']['allnum'] = '数量合计:'.$allnum;
                $list['info']['profits'] = '销售合计:'.$allprice/100;

                // 客户单位的业务员id，去重复值，去除空值
                $chun_adm_id = array_filter(array_unique(array_column($return_data['data'], 'chun_adm_id')));
                $find_adm_data = DB::table('admin')
                    ->whereIn('adm_id', $chun_adm_id)
                    ->pluck('adm_name', 'adm_id')
                    ->toArray();
                // 数据在model里已经处理好，这个地方赋值导出的变量就可以
                foreach ($return_data['data'] as $key => $value) {
                    $list[$key]['ord_order_number'] = $value['ord_order_number']; //订单编号
                    $list[$key]['ord_service_type'] = $value['ord_service_type'];//订单类型
                    $list[$key]['goo_goods_encode'] = $value['goo_goods_encode']; //商品编码
                    $list[$key]['goo_name'] = $value['goo_name']; //商品名称
                    $list[$key]['goo_ampere_hour'] = $value['goo_ampere_hour']; //规格
                    $list[$key]['orgo_goo_quantity'] = $value['orgo_goo_quantity']; //数量
                    $list[$key]['goo_unit'] = $value['goo_unit'];
                    $list[$key]['allprice'] = $value['allprice'] / 100; //总额
                    $list[$key]['unit_name'] = $value['unit_name']; //来往单位
                    $list[$key]['type_name'] = $value['type_name']; //客户类型
                    // 客户单位的业务员
                    if (isset($find_adm_data[$value['chun_adm_id']])) {
                        $list[$key]['chun_adm_id'] = $find_adm_data[$value['chun_adm_id']];
                    } else {
                        $list[$key]['chun_adm_id'] = '';
                    }
                    $list[$key]['ware_freight_space'] = $value['ware_freight_space']; //仓库编码
                    $list[$key]['ord_create_time'] = $value['ord_create_time']; //创建时间
                }
                $pathName = storage_path() . "/app/public/excel"; //获取上传excel路径
                // 创建文件夹
                if (!file_exists($pathName)) {
                    mkdir($pathName, 0775, true);
                    chmod($pathName, 0775);
                }

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

                $where['action_name'] = '实时数据';
                $where['field_name'] = ['订单编号', '订单类型', '商品编码', '商品名称', '规格', '数量', '单位', '总额', '客户单位', '客户类型', '业务员', '仓库编码', '创建时间'];
            } else {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
            }
        } elseif ($input['searchtype'] == '9') { //服务数据
            $select_field = "dast_order_number, dast_service_sepr_id, dast_ord_id,dast_id, dast_create_time, dast_goo_price, dast_client_id, dast_type, dast_creacor, chun_chty_id, chun_unit_name, dast_service_type";

            $return_data = $goods_inventory->goodsIndex($user_info, $request->all(), $this->show_count, $select_field, '', 2);
            if ($return_data['data']) {
                $Dbs = $goods_inventory->searchIndex($user_info, $input);
                $cost_db = $goods_inventory->searchIndex($user_info, $input);
                $alldata = $Dbs->where('dast_service_project_type', 2)->selectRaw('sum(dast_goo_quantitys*dast_goo_price) as allprice,sum(dast_goo_quantitys*dast_goo_cost) as allcost,sum(dast_goo_quantity) as allnum')->first();

                $alldata = $Dbs->where('dast_service_project_type', 2)->selectRaw('sum(dast_goo_quantitys*dast_goo_price) as allprice,sum(dast_goo_quantity) as allnum')->first();
                $alldata = $this->objectToArray($alldata);
                $allshow['profits'] = $alldata['allprice'];
                $allshow['allnum'] = $alldata['allnum'];
                $list['info']['allnum'] = '数量合计:'.$allshow['allnum'];
                $list['info']['profits'] = '销售合计:'.$allshow['profits'] / 100;
                foreach ($return_data['data'] as $key => $value) {
                    unset($value['order_reamrks']);
                    $list[$key]['dast_order_number'] = $value['dast_order_number']; //订单编号
                    $list[$key]['service_name'] = $value['service_name'];
                    $list[$key]['dast_sepr_name'] = $value['dast_sepr_name']; //服务项目
                    $list[$key]['dast_goo_price'] = $value['dast_goo_price'] / 100; //服务金额
                    $list[$key]['dast_unit_name'] = $value['dast_unit_name']; //客户单位
                    $list[$key]['chty_name'] = $value['chty_name']; //客户类型
                    $list[$key]['dast_create_time'] = $value['dast_create_time']; //创建时间
                    $list[$key]['dast_creacor'] = $value['dast_creacor']; //开单员
                }
                $pathName = storage_path() . "/app/public/excel"; //获取上传excel路径
                // 创建文件夹
                if (!file_exists($pathName)) {
                    mkdir($pathName, 0775, true);
                    chmod($pathName, 0775);
                }
                $streamFileRand = '服务数据' . time() . rand(100, 999) . '.xls';
                // 产生一个随机文件名（因为你base64上来肯定没有文件名，这里你可以自己设置一个也行）
                $streamFilename = $pathName . '/' . $streamFileRand;

                $where['action_name'] = '服务数据';
                $where['field_name'] = ['订单编号', '订单类型', '服务项目', '服务金额', '客户单位', '客户类型', '创建日期', '开单员'];
            } else {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
            }
        } elseif ($input['searchtype'] == '10') { //拿货占比
            $list_data = DB::table('data_statistical')
                ->where('dast_cid', $user_info['adm_cid'])
                ->where('dast_shop_id', $user_info['adm_shop_id'])
                ->where('dast_service_project_type', 1)
                ->where('dast_order_type', '!=', 3)
                ->where('dast_ord_delete', 1)
                ->where('dast_type', 2)//客户单位类型
                ->where(function ($query) use ($input) { //客户单位id
                    if (!empty($input['dast_client_id'])) {
                        $query->where('dast_client_id', $input['dast_client_id']);
                    }
                })
                ->where(function ($query) use ($input) { //日期范围
                    // 如果选择开始时间并且选择结束时间
                    if (!empty($input['creatData'])) {
                        $input['creatData'][1] = date("Y-m-d", strtotime($input['creatData'][1] . " +1 day"));
                        $query->whereBetween('dast_create_time', $input['creatData']);
                    }
                })
                ->select('dast_client_id')
                ->orderBy('dast_id', 'asc')
                ->groupBy('dast_client_id')
                ->get()->toArray();
            if ($list_data) {
                $list_items = $list_data;
                $list_client_id = array_column($list_items, 'dast_client_id');

                // 查询客户单位名称
                $find_chun_data = DB::table('channel_unit')
                    ->whereIn('chun_id', $list_client_id)
                    ->pluck('chun_unit_name', 'chun_id')->toArray();

                // 查询销售统计数据
                $find_dast_data = DB::table('data_statistical as dast')
                    ->where('dast_cid', $user_info['adm_cid'])
                    ->where('dast_shop_id', $user_info['adm_shop_id'])
                    ->where('dast_service_project_type', 1)
                    ->where('dast_order_type', '!=', 3)
                    ->where('dast_ord_delete', 1)
                    ->where('dast_type', 2)//客户单位类型
                    ->whereIn('dast_client_id', $list_client_id)
                    ->select('dast_client_id', 'dast_service_type', 'dast_goo_quantity')
                    ->get()->toArray();

                $deliver_amount = [];//发货单数量
                $service_amount = [];//服务单数量
                $rescue_amount = [];//救援单数量
                $sales_return_amount = [];//退货单数量
                foreach ($find_dast_data as $key => $value) {
                    // dast_service_type 订单类型：1服务单 2销售单 3换货单 4退货单 5发货单 6结清单 7救援单
                    if ($value->dast_service_type == 1) {
                        if (isset($service_amount[$value->dast_client_id])) {
                            $service_amount[$value->dast_client_id] += $value->dast_goo_quantity;
                        } else {
                            $service_amount[$value->dast_client_id] = $value->dast_goo_quantity;
                        }
                    } elseif ($value->dast_service_type == 4) {
                        if (isset($sales_return_amount[$value->dast_client_id])) {
                            $sales_return_amount[$value->dast_client_id] += abs($value->dast_goo_quantity);
                        } else {
                            $sales_return_amount[$value->dast_client_id] = abs($value->dast_goo_quantity);
                        }
                    } elseif ($value->dast_service_type == 5) {
                        if (isset($deliver_amount[$value->dast_client_id])) {
                            $deliver_amount[$value->dast_client_id] += $value->dast_goo_quantity;
                        } else {
                            $deliver_amount[$value->dast_client_id] = $value->dast_goo_quantity;
                        }
                    } elseif ($value->dast_service_type == 7) {
                        if (isset($rescue_amount[$value->dast_client_id])) {
                            $rescue_amount[$value->dast_client_id] += $value->dast_goo_quantity;
                        } else {
                            $rescue_amount[$value->dast_client_id] = $value->dast_goo_quantity;
                        }
                    }
                }

                $return_data = [];//返回数据
                $data_info = [];//返回数据
                foreach ($list_client_id as $key => $value) {
                    $temp_data['chun_unit_name'] = $find_chun_data[$value];
                    if (isset($deliver_amount[$value])) {
                        $temp_deliver_amount = $deliver_amount[$value];
                    } else {
                        $temp_deliver_amount = 0;
                    }

                    if (isset($service_amount[$value])) {
                        $temp_service_amount = $service_amount[$value];
                    } else {
                        $temp_service_amount = 0;
                    }
                    if (isset($rescue_amount[$value])) {
                        $temp_rescue_amount = $rescue_amount[$value];
                    } else {
                        $temp_rescue_amount = 0;
                    }
                    if (isset($sales_return_amount[$value])) {
                        $temp_sales_return_amount = $sales_return_amount[$value];
                    } else {
                        $temp_sales_return_amount = 0;
                    }
                    // 销售数量 = 总的售出商品数量（发货单、服务单、救援单） -  退货商品数量（退货单）
                    $temp_data['sell_amount'] = ($temp_deliver_amount + $temp_service_amount + $temp_rescue_amount) - $temp_sales_return_amount;
                    // 更换数量 = 救援单售出商品数量
                    $temp_data['renewal_amount'] = $temp_rescue_amount;
                    // 更换占比 = 救援单售出商品数量 /  销售数量
                    if ($temp_data['sell_amount']) {
                        $temp_data['renewal_ratio'] = (round(($temp_rescue_amount / $temp_data['sell_amount']), 2) * 100).'%';
                    } else {
                        $temp_data['renewal_ratio'] = '0%';
                    }
                    // 送货数量 = （发货单、服务单）售出商品数量 - 退货商品数量（退货单）
                    $temp_data['deliver_amount'] = ($temp_deliver_amount + $temp_service_amount) - $temp_sales_return_amount;
                    if ($temp_data['sell_amount']) {
                        $temp_data['deliver_ratio'] = (round(($temp_data['deliver_amount'] / $temp_data['sell_amount']), 2) * 100).'%';
                    } else {
                        $temp_data['deliver_ratio'] = '0%';
                    }
                    $data_info[$key] = $temp_data;
                    unset($temp_data);
                }
                $list = $data_info;

                $pathName = storage_path() . "/app/public/excel"; //获取上传excel路径
                // 创建文件夹
                if (!file_exists($pathName)) {
                    mkdir($pathName, 0775, true);
                    chmod($pathName, 0775);
                }
                $streamFileRand = '拿货占比' . time() . rand(100, 999) . '.xls';
                // 产生一个随机文件名（因为你base64上来肯定没有文件名，这里你可以自己设置一个也行）
                $streamFilename = $pathName . '/' . $streamFileRand;

                $where['action_name'] = '拿货占比';
                $where['field_name'] = ['客户单位', '销售数量', '更换数量', '更换占比', '送货数量', '送货占比'];
            } else {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
            }
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'查询类型错误！']);
        }

        if (isset($select_count_field['field_title'])) {//有设置总计数据权限
            foreach ($list['info'] as $key1 => $value1) {//遍历总计数据
                if (!in_array($key1, $select_count_field['field_title'])) {
                    unset($list['info'][$key1]);
                }
            }
        } else {
            $list['info'] = [];
        }

        $new_where['action_name'] = $where['action_name'];//Excel导出的字段
        if (isset($select_list_field['field_name'])) {
            // 列表显示项名称权限判断，遍历表头数据
            foreach ($where['field_name'] as $key2 => $value2) {
                // 实时数据没有列表业务员显示项，导出有这个，跳过判断
                if ($request['searchtype'] == 8 && $value2 == '业务员') {
                    $new_where['field_name'][] = '业务员';//Excel导出加上这个显示项
                    continue;
                }
                if (!in_array($value2, $select_list_field['field_name'])) {// 没有权限的表头字段清空
                    unset($where['field_name'][$key2]);
                } else {
                    $new_where['field_name'][] = $value2;
                }
            }
        } else {
            $new_where['field_name'] = [];
        }

        // 列表显示数据的字段判断
        if (isset($select_list_field['field_title'])) {
            foreach ($list as $key3 => $value3) {
                if (is_numeric($key3)) {
                    foreach ($value3 as $rd_key => $rd_value) {
                        // 实时数据没有列表业务员显示项，导出有这个，跳过判断
                        if ($request['searchtype'] == 8 && $rd_key == 'chun_adm_id') {
                            continue;
                        }
                        if (!in_array($rd_key, $select_list_field['field_title'])) {
                            unset($list[$key3][$rd_key]);
                        }
                    }
                }
            }
        } else {//没有列表权限就清空列表数据
            foreach ($list as $key3 => $value3) {
                if (is_numeric($key3)) {
                    unset($list[$key3]);
                }
            }
        }
        if (!isset($select_count_field['field_title']) && !isset($select_list_field['field_title'])) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据！']);
        }

        // 调用导出的公共方法
        $this->headExport(
            $streamFilename, //路径
            $new_where,    //sheet名及其每一行的标题
            $list      //导出数据
        );
        // 判断文件是否存在 存在则成功  不存在则失败
        if (file_exists($pathName)) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'storage/excel/' . $streamFileRand]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', '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;
            if (!empty($data['info'])) {
                foreach ($data['info'] as $key => $value) {
                    $sheet->setCellValue($letter[$i] . '2', $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);

            // $spreadsheet->getActiveSheet()->mergeCells('A2:G2');


            $title = $where['field_name'];
            foreach ($title as $key => $value) {
                $sheet->setCellValue($letter[$key] . '1', $value . "\t");
                $spreadsheet->getActiveSheet()->getColumnDimension($letter[$key])->setAutoSize(true);
            }
        }
        $i = $highest_row ? $highest_row : 1; //开始行数
        foreach ($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);
    }

    // 同步订单数据
    public function syncOrderData($id)
    {
        $num = 10;
        $time1 = date("Y-m-d");
        $time2 = date("Y-m-d", strtotime("-1 day", strtotime($time1)));

        // $time2='2019-05-21';
        // $time1='2020-10-01';

        // $time2='2020-10-01';
        // $time1='2021-01-01';

        // $time2='2021-01-02';
        // $time2='2021-01-01';
        // $time1='2021-02-01';

        // $time2='2021-02-01';
        // $time1='2021-02-16';

        // $time2='2021-02-16';
        // $time1='2021-03-01';

        // $time2='2021-03-01';
        // $time1='2021-03-16';

        // $time2='2021-03-16';
        // $time1='2021-03-17';

        // $time2 = '2021-07-01';
        // $time1 = '2021-07-13';
        // dump($id);
        // dump($time1);
        // dump($time2);
        // die;
        // 保存日志
        $data['date_time'] = date('Y-m-d H:i:s');
        $data['time1'] = $time1;
        $data['time2'] = $time2;
        $data['num'] = $num;
        logRecord($data, 'data_statistical_log_new', 2);

        $list = DB::table("order as o")
            ->leftJoin('order_client as oc', 'oc.orcl_ord_id', '=', 'o.ord_id')
            ->where('ord_id', '>', $id)
            ->where('ord_collection_bill', 1)
            ->whereBetween('ord_update_time', array($time2, $time1))
            ->offset(0)
            ->limit($num)
            ->select('ord_wor_state', "ord_id", "ord_cid", "ord_superior_shop_id", "ord_shop_id", "ord_order_number", "ord_create_id", "ord_orcl_id", "ord_client_id", "ord_type", "ord_service_type", "ord_service_sepr_id", "ord_service_adm_id", "ord_service_shop_id", "ord_orla_id", "ord_ware_id", "ord_payment_way", "ord_state", "ord_create_time", "ord_update_time", "ord_delete", "ord_order_price", 'orcl_shipment_party', 'ord_form_type', 'orcl_chin_type', 'orcl_rescue_service_price', 'orcl_rescue_assign_price')
            ->orderBy("ord_id", "ASC")
            ->get()->toArray();
        if (count($list) == 0) {
            return "同步完成";
        } else {
            $list = $this->objectToArray($list);
            $search_ord_order_number = array_column($list, 'ord_order_number');
            // 查询根据订单号销售统计表数据
            $find_dast_data = DB::table("data_statistical")
                ->whereIn("dast_order_number", $search_ord_order_number)
                ->where('dast_add_time', '>', $time1)
                ->select('dast_order_number')
                ->get()->toArray();
            if (count($find_dast_data) > 0) {
                $data_ord_order_number = array_unique(array_column($find_dast_data, 'dast_order_number'));
                // 判断订单是否全部同步，查询出的两个订单号数组数据一样，说明全部同步
                if (count($search_ord_order_number) == count($data_ord_order_number)) {
                    // 订单数据全部同步，获取最后一个订单id，进行下一次数据同步
                    $search_ord_id = array_column($list, 'ord_id');
                    $list_ord_id = $search_ord_id[count($search_ord_id) - 1]; //最后一个订单id
                    // 保存日志
                    $data['date_time'] = date('Y-m-d H:i:s');
                    $data['id'] = $list_ord_id;
                    logRecord($data, 'data_statistical_log_new', 2);
                    return $this->syncOrderData($list_ord_id);
                } else {
                    // 没有全部同步，有一部分已经同步了
                    // 筛选出已经同步的订单，没有同步的订单继续同步
                    $new_list = [];
                    $new_key = 0;
                    foreach ($list as $key => $value) {
                        if (!in_array($value['ord_order_number'], $data_ord_order_number)) {
                            $new_list[$new_key] = $value;
                            $new_key++;
                        }
                    }
                    $list = $new_list;
                }
            }
            $adm_id = [];
            $chun_id = [];
            $chty_id = [];
            $ord_id = [];
            $virtual_ord_id = [];
            $id = 0;
            $ord_order_number_service = [];
            $ord_create_id = array_column($list, 'ord_create_id'); //创建人id
            $ord_service_adm_id = array_column($list, 'ord_service_adm_id'); //服务技师id
            $adm_id = array_unique(array_merge($ord_create_id, $ord_service_adm_id));
            $chun_id = array_column($list, 'ord_client_id'); //客户单位id
            // 查询客户单位数据
            if (!empty($chun_id)) {
                $channel_unit = DB::table("channel_unit")
                    ->whereIn("chun_id", $chun_id)
                    ->select("chun_id", "chun_adm_id", "chun_unit_name", "chun_chty_id")
                    ->get();
                $channel_unit = $this->objectToArray($channel_unit);
                $channel_unit = array_column($channel_unit, null, 'chun_id');
                foreach ($channel_unit as $k => $v) {
                    if ($v['chun_adm_id'] != 0) {
                        $adm_id[] = $v['chun_adm_id'];
                    }
                }
            }
            // 查询创建人、服务技师数据
            if (!empty($adm_id)) {
                $adm_id = array_unique($adm_id);
                $admin = DB::table("admin")
                    ->whereIn("adm_id", $adm_id)
                    ->pluck("adm_name", "adm_id")->toArray();
            }
            $add_dast_data=[];
            $service_key = 0;
            foreach ($list as $keys => $values) {
                $id = $values['ord_id'];
                $ord_id[] = $values['ord_id'];
                $adm_id[] = $values['ord_create_id'];
                if ($values['ord_service_adm_id'] > 0) {
                    $adm_id[] = $values['ord_service_adm_id'];
                }
                if ($values['ord_type'] == '2' && $values['ord_client_id'] != 0) {
                    $chun_id[] = $values['ord_client_id'];
                }
                // 出库方1仓库2直营店3加盟店4虚拟加盟店
                if ($values['orcl_shipment_party'] == 4) {
                    $virtual_ord_id[] = $values['ord_id'];
                    // 查询虚拟加盟店工单的服务项目金额
                    $find_wocl_data = DB::table('work_client as wocl')
                        ->leftjoin('work_order as wor', 'wor.wor_id', '=', 'wocl.wocl_wor_id')
                        ->where('wor_order_id', $values['ord_id'])
                        ->where('wor_order_number', $values['ord_order_number'])
                        ->where('wor_delete', 1)
                        ->where('wor_collection_bill', 1)
                        ->where('wor_state', '!=', 11)
                        ->select('wocl_rescue_service_price')
                        ->first();
                    $values['orcl_rescue_assign_price'] = empty($find_wocl_data->wocl_rescue_service_price) ? 0 : $find_wocl_data->wocl_rescue_service_price;
                }

                // 销售统计金额 = 服务项目金额-派单金额
                $service_project_price = $values['orcl_rescue_service_price'] - $values['orcl_rescue_assign_price'];
                if ($service_project_price != 0) {//金额不为0统计数据
                    $ord_order_number_service[] = $values['ord_order_number'];
                    $add_dast_data[$service_key]['dast_ord_id'] = $values['ord_id'];
                    $add_dast_data[$service_key]['dast_cid'] = $values['ord_cid'];
                    $add_dast_data[$service_key]['dast_superior_shop_id'] = $values['ord_superior_shop_id'];
                    $add_dast_data[$service_key]['dast_shop_id'] = $values['ord_shop_id'];
                    $add_dast_data[$service_key]['dast_order_number'] = $values['ord_order_number'];
                    $add_dast_data[$service_key]['dast_create_id'] = $values['ord_create_id'];
                    $add_dast_data[$service_key]['dast_creacor'] = $admin[$values['ord_create_id']] ?? '无';
                    $add_dast_data[$service_key]['dast_orcl_id'] = $values['ord_orcl_id'];
                    $add_dast_data[$service_key]['dast_client_id'] = $values['ord_client_id'];
                    // ord_type 买家类型：1门店零售2客户单位3速电派单4第三方派单
                    if ($values['ord_type'] == 2) {
                        $add_dast_data[$service_key]['dast_client_ids'] = $values['ord_client_id'];
                        $add_dast_data[$service_key]['dast_adm_id'] = $channel_unit[$values['ord_client_id']]['chun_adm_id'] ?? 0;
                        $add_dast_data[$service_key]['dast_adm_name'] = $admin[$add_dast_data[$service_key]['dast_adm_id']] ?? '无'; //业务员姓名
                        $add_dast_data[$service_key]['dast_chty_id'] = $channel_unit[$values['ord_client_id']]['chun_chty_id'] ?? 0; //客户单位类型id
                    } else {
                        $add_dast_data[$service_key]['dast_client_ids'] = 0;
                        $add_dast_data[$service_key]['dast_adm_id'] = 0;
                        $add_dast_data[$service_key]['dast_adm_name'] = '无';
                        $add_dast_data[$service_key]['dast_chty_id'] = 0;
                    }

                    $add_dast_data[$service_key]['dast_type'] = $values['ord_type'];
                    $add_dast_data[$service_key]['dast_service_type'] = $values['ord_service_type'];
                    $add_dast_data[$service_key]['dast_service_sepr_id'] = $values['ord_service_sepr_id'];
                    $add_dast_data[$service_key]['dast_service_adm_id'] = $values['ord_service_adm_id'];
                    $add_dast_data[$service_key]['dast_service_admor'] = $admin[$values['ord_service_adm_id']] ?? '无';
                    $add_dast_data[$service_key]['dast_service_shop_id'] = $values['ord_service_shop_id'];
                    $add_dast_data[$service_key]['dast_ware_id'] = $values['ord_ware_id'];
                    $add_dast_data[$service_key]['dast_waon_class'] = '';
                    $add_dast_data[$service_key]['dast_payment_way'] = $values['ord_payment_way'];
                    $add_dast_data[$service_key]['dast_state'] = $values['ord_state'];
                    $add_dast_data[$service_key]['dast_create_time'] = $values['ord_create_time'];
                    $add_dast_data[$service_key]['dast_actual_goo_id'] = 0;
                    $add_dast_data[$service_key]['dast_wago_id'] = 0;
                    $add_dast_data[$service_key]['dast_goo_id'] = 0;
                    $add_dast_data[$service_key]['dast_goo_type'] = 0;
                    $add_dast_data[$service_key]['dast_goo_price'] = $service_project_price;
                    $add_dast_data[$service_key]['dast_good_state'] = '';
                    if ($values['ord_service_type'] == '4') {
                        $add_dast_data[$service_key]['dast_goo_quantity'] = 0;
                        $add_dast_data[$service_key]['dast_goo_quantitys'] = 0;
                    } else {
                        $add_dast_data[$service_key]['dast_goo_quantity'] = 1;
                        $add_dast_data[$service_key]['dast_goo_quantitys'] = 1;
                    }
                    $add_dast_data[$service_key]['dast_updata_time'] = $values['ord_update_time'];
                    $add_dast_data[$service_key]['dast_ord_delete'] = $values['ord_delete'];
                    $add_dast_data[$service_key]['dast_add_time'] = date("Y-m-d H:i:s");
                    if ($values['ord_wor_state'] == 9 || $values['ord_delete'] == 2) {
                        $add_dast_data[$service_key]['dast_order_type'] = 3;
                    } else {
                        $add_dast_data[$service_key]['dast_order_type'] = 1;
                    }
                    $add_dast_data[$service_key]['dast_orgo_id'] = 0;
                    $add_dast_data[$service_key]['dast_goo_cost'] = 0;
                    $add_dast_data[$service_key]['dast_orcl_shipment_party'] = $values['orcl_shipment_party'];
                    $add_dast_data[$service_key]['dast_ord_form_type'] = $values['ord_form_type'];
                    $add_dast_data[$service_key]['dast_orcl_chin_type'] = $values['orcl_chin_type'];
                    // ord_wor_state 订单的工单状态1未派工单2服务中3售后中4已完成5无工单6审核活动7待接单8锁定9速电撤销回收10终止11取消订单12待审核
                    $add_dast_data[$service_key]['dast_service_project_type'] = 2; //服务
                    $service_key++;
                }
            }
            if (!empty($add_dast_data)) {
                // 删除订单服务项目数据
                $service_del_res = DB::table("data_statistical")
                    ->where('dast_service_project_type', 2)
                    ->whereIn("dast_order_number", $ord_order_number_service)
                    ->delete();
                $service_dast_res = DB::table('data_statistical')->insert($add_dast_data);
                unset($add_dast_data);
            }
            $list_ord_data = array_column($list, null, 'ord_id'); //订单id
            unset($list);
            
            // 查询订单商品数据
            $find_order_goods = DB::table("order_goods")
                ->whereIn("orgo_ord_id", $ord_id)
                //->where('orgo_state', '!=', 2)
                ->select("orgo_id", "orgo_ord_id", "orgo_actual_goo_id", "orgo_wago_id", "orgo_goo_id", "orgo_goo_type", "orgo_goo_price", "orgo_state", "orgo_goo_quantity", "orgo_waon_class", "orgo_goo_cost", 'orgo_assign_price')
                ->orderBy("orgo_ord_id", "ASC")
                ->get();
            $find_order_goods = $this->objectToArray($find_order_goods);
            // 没有查到订单商品数据，就进行下一次数据同步
            if (empty($find_order_goods)) {
                return $this->syncOrderData($id);
            }
            $list = [];
            // 将订单商品数据与订单数据合并
            foreach ($find_order_goods as $key => $value) {
                $list[$key] = array_merge($list_ord_data[$value['orgo_ord_id']], $value);
            }

            $ord_order_number = [];
            foreach ($list as $key => $value) {
                if (empty($value['orgo_id'])) { //没有订单商品主键id就跳过
                    continue;
                }
                $ord_create_time = explode(' ', $value['ord_create_time'])[0];
                $ord_update_time = explode(' ', $value['ord_update_time'])[0];
                //if ($ord_create_time!=$ord_update_time) {
                $ord_order_number[] = $value['ord_order_number'];
                //}
                $poss[$key]['dast_cid'] = $value['ord_cid'];
                $poss[$key]['dast_superior_shop_id'] = $value['ord_superior_shop_id'];
                $poss[$key]['dast_shop_id'] = $value['ord_shop_id'];
                $poss[$key]['dast_order_number'] = $value['ord_order_number'];
                $poss[$key]['dast_create_id'] = $value['ord_create_id'];
                $poss[$key]['dast_creacor'] = $admin[$value['ord_create_id']] ?? '无';
                $poss[$key]['dast_orcl_id'] = $value['ord_orcl_id'];
                $poss[$key]['dast_client_id'] = $value['ord_client_id'];
                // ord_type 买家类型：1门店零售2客户单位3速电派单4第三方派单
                if ($value['ord_type'] == 2) {
                    $poss[$key]['dast_client_ids'] = $value['ord_client_id'];

                    $poss[$key]['dast_adm_id'] = $channel_unit[$value['ord_client_id']]['chun_adm_id'] ?? 0;
                    $poss[$key]['dast_adm_name'] = $admin[$poss[$key]['dast_adm_id']] ?? '无'; //业务员姓名
                    $poss[$key]['dast_chty_id'] = $channel_unit[$value['ord_client_id']]['chun_chty_id'] ?? 0; //客户单位类型id
                } else {
                    $poss[$key]['dast_client_ids'] = 0;

                    $poss[$key]['dast_adm_id'] = 0;
                    $poss[$key]['dast_adm_name'] = '无';
                    $poss[$key]['dast_chty_id'] = 0;
                }

                $poss[$key]['dast_type'] = $value['ord_type'];
                $poss[$key]['dast_service_type'] = $value['ord_service_type'];
                $poss[$key]['dast_service_sepr_id'] = $value['ord_service_sepr_id'];
                $poss[$key]['dast_service_adm_id'] = $value['ord_service_adm_id'];
                $poss[$key]['dast_service_admor'] = $admin[$value['ord_service_adm_id']] ?? '无';
                $poss[$key]['dast_service_shop_id'] = $value['ord_service_shop_id'];
                $poss[$key]['dast_ware_id'] = $value['ord_ware_id'];
                $poss[$key]['dast_waon_class'] = $value['orgo_waon_class'];
                $poss[$key]['dast_ord_delete'] = $value['ord_delete'];
                $poss[$key]['dast_payment_way'] = $value['ord_payment_way'];
                $poss[$key]['dast_state'] = $value['ord_state'];
                $poss[$key]['dast_orgo_id'] = $value['orgo_id'];
                if ($value['orgo_actual_goo_id'] == 0) {
                    $poss[$key]['dast_actual_goo_id'] = $value['orgo_goo_id'];
                } else {
                    $poss[$key]['dast_actual_goo_id'] = $value['orgo_actual_goo_id'];
                }
                $poss[$key]['dast_wago_id'] = $value['orgo_wago_id'];
                $poss[$key]['dast_goo_id'] = $value['orgo_goo_id'];
                $poss[$key]['dast_goo_type'] = $value['orgo_goo_type'];
                $poss[$key]['dast_good_state'] = $value['orgo_state'];
                $poss[$key]['dast_create_time'] = $value['ord_create_time'];
                $poss[$key]['dast_updata_time'] = $value['ord_update_time'];
                $poss[$key]['dast_add_time'] = date("Y-m-d H:i:s");
                $poss[$key]['dast_goo_quantitys'] = $value['orgo_goo_quantity'];
                // orgo_state 商品状态1正常2删除3回收的商品4换货商品5赠品商品6备用电池7临时商品8旧货商品
                if ($value['orgo_state'] == 3) {
                    $poss[$key]['dast_order_type'] = 3; //类型：1销售单2退款单3忽略
                    $poss[$key]['dast_goo_price'] = $value['orgo_goo_price'];
                    $poss[$key]['dast_goo_quantity'] = $value['orgo_goo_quantity'];
                } elseif ($value['orgo_state'] == 2) {
                    $poss[$key]['dast_order_type'] = 3;
                    $poss[$key]['dast_goo_price'] = $value['orgo_goo_price'];
                    $poss[$key]['dast_goo_quantity'] = $value['orgo_goo_quantity'];
                } elseif ($value['orgo_state'] == 4) {
                    $poss[$key]['dast_order_type'] = 2;
                    $poss[$key]['dast_goo_price'] = "-" . $value['orgo_goo_price'];
                    $poss[$key]['dast_goo_quantity'] = "-" . $value['orgo_goo_quantity'];
                } elseif ($value['ord_service_type'] == 4) { //订单类型：1服务单2销售单3换货单4退货单5发货单6结清单7救援单
                    // 工作总台开退货单，退回旧货商品类型的，不需要统计成本利润
                    if ($value['orgo_waon_class'] == 3) { //仓库类别：3旧货仓
                        $poss[$key]['dast_order_type'] = 3; //类型：1销售单2退款单3忽略
                    } else {
                        $poss[$key]['dast_order_type'] = 2; //类型：1销售单2退款单3忽略
                    }
                    $poss[$key]['dast_goo_price'] = "-" . $value['orgo_goo_price'];
                    $poss[$key]['dast_goo_quantity'] = "-" . $value['orgo_goo_quantity'];
                } else {
                    $poss[$key]['dast_order_type'] = 1; //类型：1销售单2退款单3忽略
                    $poss[$key]['dast_goo_price'] = $value['orgo_goo_price'];
                    $poss[$key]['dast_goo_quantity'] = $value['orgo_goo_quantity'];
                }
                // 临时仓类型商品，不统计成本利润
                if ($value['orgo_waon_class'] == 4) { //仓库类别：4临时仓
                    $poss[$key]['dast_order_type'] = 3; //类型：1销售单2退款单3忽略
                }

                // 不是退货单，选择旧货仓类型商品，商品订单金额为0的不统计成本利润，其他情况统计
                if ($value['ord_service_type'] != 4 && $value['orgo_waon_class'] == 3 && $value['orgo_goo_price'] == 0) {
                    $poss[$key]['dast_order_type'] = 3; //类型：1销售单2退款单3忽略
                }
                $poss[$key]['dast_goo_cost'] = $value['orgo_goo_cost'];
                $poss[$key]['dast_ord_id'] = $value['ord_id'];
                if ($value['orcl_shipment_party'] == 4) { //出库方1仓库2直营店3加盟店4虚拟加盟店
                    $find_ord_data = DB::table('work_good as wogo')
                        ->leftjoin('work_order as wor', 'wor.wor_id', '=', 'wogo.wogo_wor_id')
                        ->where('wor_order_id', $value['ord_id'])
                        ->where('wor_order_number', $value['ord_order_number'])
                        ->where('wor_delete', 1)
                        ->where('wor_collection_bill', 1)
                        ->where('wogo_orgo_id', $value['orgo_id'])
                        ->where('wogo_waon_class', $value['orgo_waon_class'])
                        ->where('wogo_goo_id', $value['orgo_goo_id'])
                        ->where('wogo_goo_type', $value['orgo_goo_type'])
                        ->where('wor_state', '!=', 11)
                        ->select('wogo_goo_price')
                        ->first();
                    $poss[$key]['dast_goo_cost'] = $find_ord_data ? $find_ord_data->wogo_goo_price : 0;
                }
                $poss[$key]['dast_orcl_shipment_party'] = $value['orcl_shipment_party'];
                $poss[$key]['dast_ord_form_type'] = $value['ord_form_type'];
                $poss[$key]['dast_orcl_chin_type'] = $value['orcl_chin_type'];
                // ord_wor_state 订单的工单状态1未派工单2服务中3售后中4已完成5无工单6审核活动7待接单8锁定9速电撤销回收10终止11取消订单12待审核
                if ($value['ord_wor_state'] == 9) {
                    $poss[$key]['dast_order_type'] = 3;
                }
            }
            // 删除订单商品数据
            $del_res = DB::table("data_statistical")
                ->where('dast_service_project_type', 1)
                ->whereIn("dast_order_number", $ord_order_number)
                ->delete();
            $add_res = DB::table("data_statistical")->insert($poss);

            unset($poss);
            unset($list);
            unset($adm_id);
            unset($orgo_ord_id);
            // 保存日志
            $data['date_time'] = date('Y-m-d H:i:s');
            $data['del_res'] = $del_res;
            $data['add_res'] = $add_res;
            $data['id'] = $id;
            logRecord($data, 'data_statistical_log_new', 2);
            return $this->syncOrderData($id);
        }
    }

    public function sysData(Request $request)
    {
        set_time_limit(0);
        $res = $this->syncOrderData(0);
        // $res = $this->syncOrderServiceData(0);
        return $res;
    }

    // 同步订单服务项目数据
    public function syncOrderServiceData($id)
    {
        $num = 10;
        $time1 = date("Y-m-d");
        $time2 = date("Y-m-d", strtotime("-1 day", strtotime($time1)));

        // $time2='2019-05-21';
        // $time1='2020-10-01';

        // $time2='2020-10-01';
        // $time1='2021-01-01';

        // $time2='2021-01-02';
        // $time2='2021-01-01';
        // $time1='2021-02-01';

        // $time2='2021-02-01';
        // $time1='2021-02-16';

        // $time2='2021-02-16';
        // $time1='2021-03-01';

        // $time2='2021-03-01';
        // $time1='2021-03-16';

        // $time2='2021-01-01';
        // $time1='2021-03-01';

        $time2 = '2021-07-13';
        $time1 = '2021-07-15';
        // dump($id);
        // dump($time1);
        // dump($time2);
        // die;
        // 保存日志
        $data['date_time'] = date('Y-m-d H:i:s');
        $data['time1'] = $time1;
        $data['time2'] = $time2;
        $data['num'] = $num;
        logRecord($data, 'data_statistical_log_new', 2);

        $list = DB::table("order as o")
            ->leftJoin('order_client as oc', 'oc.orcl_ord_id', '=', 'o.ord_id')
            ->where('ord_id', '>', $id)
            ->whereNotIn('ord_service_type', [4,5])
            ->where('ord_collection_bill', 1)
            ->whereBetween('ord_update_time', array($time2, $time1))
            ->offset(0)
            ->limit($num)
            ->select('ord_wor_state', "ord_id", "ord_cid", "ord_superior_shop_id", "ord_shop_id", "ord_order_number", "ord_create_id", "ord_orcl_id", "ord_client_id", "ord_type", "ord_service_type", "ord_service_sepr_id", "ord_service_adm_id", "ord_service_shop_id", "ord_orla_id", "ord_ware_id", "ord_payment_way", "ord_state", "ord_create_time", "ord_update_time", "ord_delete", "ord_order_price", 'orcl_shipment_party', 'ord_form_type', 'orcl_chin_type', 'orcl_rescue_service_price', 'orcl_rescue_assign_price')
            ->orderBy("ord_id", "ASC")
            ->get()->toArray();
        // dump($list);die;
        if (count($list) == 0) {
            return "同步完成";
        } else {
            $list = $this->objectToArray($list);
            $search_ord_order_number = array_column($list, 'ord_order_number');
            // 查询根据订单号销售统计表数据
            $find_dast_data = DB::table("data_statistical")
                ->whereIn("dast_order_number", $search_ord_order_number)
                // ->where('dast_add_time', '>', $time1)
                ->where('dast_service_project_type', 2)
                ->where('dast_order_type', 3)
                ->select('dast_order_number')
                ->get()->toArray();
            // dump($find_dast_data);
            // die;
            if (count($find_dast_data) > 0) {
                $data_ord_order_number = array_unique(array_column($find_dast_data, 'dast_order_number'));
                // 判断订单是否全部同步，查询出的两个订单号数组数据一样，说明全部同步
                if (count($search_ord_order_number) == count($data_ord_order_number)) {
                    // 订单数据全部同步，获取最后一个订单id，进行下一次数据同步
                    $search_ord_id = array_column($list, 'ord_id');
                    $list_ord_id = $search_ord_id[count($search_ord_id) - 1]; //最后一个订单id
                    // 保存日志
                    $data['date_time'] = date('Y-m-d H:i:s');
                    $data['id'] = $list_ord_id;
                    logRecord($data, 'data_statistical_log_new', 2);
                    return $this->syncOrderServiceData($list_ord_id);
                } else {
                    // 没有全部同步，有一部分已经同步了
                    // 筛选出已经同步的订单，没有同步的订单继续同步
                    $new_list = [];
                    $new_key = 0;
                    foreach ($list as $key => $value) {
                        if (!in_array($value['ord_order_number'], $data_ord_order_number)) {
                            $new_list[$new_key] = $value;
                            $new_key++;
                        }
                    }
                    $list = $new_list;
                }
            }
            $adm_id = [];
            $chun_id = [];
            $chty_id = [];
            $ord_id = [];
            $virtual_ord_id = [];
            $id = 0;
            $ord_order_numbers = [];
            $ord_create_id = array_column($list, 'ord_create_id'); //创建人id
            $ord_service_adm_id = array_column($list, 'ord_service_adm_id'); //服务技师id
            $adm_id = array_unique(array_merge($ord_create_id, $ord_service_adm_id));
            $chun_id = array_column($list, 'ord_client_id'); //客户单位id
            // 查询客户单位数据
            if (!empty($chun_id)) {
                $channel_unit = DB::table("channel_unit")
                    ->whereIn("chun_id", $chun_id)
                    ->select("chun_id", "chun_adm_id", "chun_unit_name", "chun_chty_id")
                    ->get();
                $channel_unit = $this->objectToArray($channel_unit);
                $channel_unit = array_column($channel_unit, null, 'chun_id');
                foreach ($channel_unit as $k => $v) {
                    if ($v['chun_adm_id'] != 0) {
                        $adm_id[] = $v['chun_adm_id'];
                    }
                }
            }
            // 查询创建人、服务技师数据
            if (!empty($adm_id)) {
                $adm_id = array_unique($adm_id);
                $admin = DB::table("admin")
                    ->whereIn("adm_id", $adm_id)
                    ->pluck("adm_name", "adm_id")->toArray();
            }
            $add_dast_data=[];
            $service_key = 0;
            foreach ($list as $keys => $values) {
                $id = $values['ord_id'];
                $ord_id[] = $values['ord_id'];
                $adm_id[] = $values['ord_create_id'];
                if ($values['ord_service_adm_id'] > 0) {
                    $adm_id[] = $values['ord_service_adm_id'];
                }
                if ($values['ord_type'] == '2' && $values['ord_client_id'] != 0) {
                    $chun_id[] = $values['ord_client_id'];
                }
                // 出库方1仓库2直营店3加盟店4虚拟加盟店
                if ($values['orcl_shipment_party'] == 4) {
                    $virtual_ord_id[] = $values['ord_id'];
                    // 查询虚拟加盟店工单的服务项目金额
                    $find_wocl_data = DB::table('work_client as wocl')
                        ->leftjoin('work_order as wor', 'wor.wor_id', '=', 'wocl.wocl_wor_id')
                        ->where('wor_order_id', $values['ord_id'])
                        ->where('wor_order_number', $values['ord_order_number'])
                        ->where('wor_delete', 1)
                        ->where('wor_collection_bill', 1)
                        ->where('wor_state', '!=', 11)
                        ->select('wocl_rescue_service_price')
                        ->first();
                    $values['orcl_rescue_assign_price'] = empty($find_wocl_data->wocl_rescue_service_price) ? 0 : $find_wocl_data->wocl_rescue_service_price;
                }
                // 销售统计金额 = 服务项目金额-派单金额
                $service_project_price = $values['orcl_rescue_service_price'] - $values['orcl_rescue_assign_price'];
                if ($service_project_price != 0) {//金额不为0统计数据
                    $ord_order_numbers[] = $values['ord_order_number'];
                    $add_dast_data[$service_key]['dast_ord_id'] = $values['ord_id'];
                    $add_dast_data[$service_key]['dast_cid'] = $values['ord_cid'];
                    $add_dast_data[$service_key]['dast_superior_shop_id'] = $values['ord_superior_shop_id'];
                    $add_dast_data[$service_key]['dast_shop_id'] = $values['ord_shop_id'];
                    $add_dast_data[$service_key]['dast_order_number'] = $values['ord_order_number'];
                    $add_dast_data[$service_key]['dast_create_id'] = $values['ord_create_id'];
                    $add_dast_data[$service_key]['dast_creacor'] = $admin[$values['ord_create_id']] ?? '无';
                    $add_dast_data[$service_key]['dast_orcl_id'] = $values['ord_orcl_id'];
                    $add_dast_data[$service_key]['dast_client_id'] = $values['ord_client_id'];
                    // ord_type 买家类型：1门店零售2客户单位3速电派单4第三方派单
                    if ($values['ord_type'] == 2) {
                        $add_dast_data[$service_key]['dast_client_ids'] = $values['ord_client_id'];
                        $add_dast_data[$service_key]['dast_adm_id'] = $channel_unit[$values['ord_client_id']]['chun_adm_id'] ?? 0;
                        $add_dast_data[$service_key]['dast_adm_name'] = $admin[$add_dast_data[$service_key]['dast_adm_id']] ?? '无'; //业务员姓名
                        $add_dast_data[$service_key]['dast_chty_id'] = $channel_unit[$values['ord_client_id']]['chun_chty_id'] ?? 0; //客户单位类型id
                    } else {
                        $add_dast_data[$service_key]['dast_client_ids'] = 0;
                        $add_dast_data[$service_key]['dast_adm_id'] = 0;
                        $add_dast_data[$service_key]['dast_adm_name'] = '无';
                        $add_dast_data[$service_key]['dast_chty_id'] = 0;
                    }

                    $add_dast_data[$service_key]['dast_type'] = $values['ord_type'];
                    $add_dast_data[$service_key]['dast_service_type'] = $values['ord_service_type'];
                    $add_dast_data[$service_key]['dast_service_sepr_id'] = $values['ord_service_sepr_id'];
                    $add_dast_data[$service_key]['dast_service_adm_id'] = $values['ord_service_adm_id'];
                    $add_dast_data[$service_key]['dast_service_admor'] = $admin[$values['ord_service_adm_id']] ?? '无';
                    $add_dast_data[$service_key]['dast_service_shop_id'] = $values['ord_service_shop_id'];
                    $add_dast_data[$service_key]['dast_ware_id'] = $values['ord_ware_id'];
                    $add_dast_data[$service_key]['dast_waon_class'] = '';
                    $add_dast_data[$service_key]['dast_payment_way'] = $values['ord_payment_way'];
                    $add_dast_data[$service_key]['dast_state'] = $values['ord_state'];
                    $add_dast_data[$service_key]['dast_create_time'] = $values['ord_create_time'];
                    $add_dast_data[$service_key]['dast_actual_goo_id'] = 0;
                    $add_dast_data[$service_key]['dast_wago_id'] = 0;
                    $add_dast_data[$service_key]['dast_goo_id'] = 0;
                    $add_dast_data[$service_key]['dast_goo_type'] = 0;
                    $add_dast_data[$service_key]['dast_goo_price'] = $service_project_price;
                    $add_dast_data[$service_key]['dast_good_state'] = '';
                    if ($values['ord_service_type'] == '4') {
                        $add_dast_data[$service_key]['dast_goo_quantity'] = 0;
                        $add_dast_data[$service_key]['dast_goo_quantitys'] = 0;
                    } else {
                        $add_dast_data[$service_key]['dast_goo_quantity'] = 1;
                        $add_dast_data[$service_key]['dast_goo_quantitys'] = 1;
                    }
                    $add_dast_data[$service_key]['dast_updata_time'] = $values['ord_update_time'];
                    $add_dast_data[$service_key]['dast_ord_delete'] = $values['ord_delete'];
                    $add_dast_data[$service_key]['dast_add_time'] = date("Y-m-d H:i:s");
                    if ($values['ord_wor_state'] == 9 || $values['ord_delete'] == 2) {
                        $add_dast_data[$service_key]['dast_order_type'] = 3;
                    } else {
                        $add_dast_data[$service_key]['dast_order_type'] = 1;
                    }
                    $add_dast_data[$service_key]['dast_orgo_id'] = 0;
                    $add_dast_data[$service_key]['dast_goo_cost'] = 0;
                    $add_dast_data[$service_key]['dast_orcl_shipment_party'] = $values['orcl_shipment_party'];
                    $add_dast_data[$service_key]['dast_ord_form_type'] = $values['ord_form_type'];
                    $add_dast_data[$service_key]['dast_orcl_chin_type'] = $values['orcl_chin_type'];
                    // ord_wor_state 订单的工单状态1未派工单2服务中3售后中4已完成5无工单6审核活动7待接单8锁定9速电撤销回收10终止11取消订单12待审核
                    $add_dast_data[$service_key]['dast_service_project_type'] = 2; //服务
                    $service_key++;
                }
            }
            
            if (empty($add_dast_data)) {
                $add_res = true;
                $del_res = true;
            } else {
                // dump($ord_order_numbers);
                $del_res = DB::table("data_statistical")
                    ->where("dast_service_project_type", 2)
                    ->whereIn("dast_order_number", $ord_order_numbers)
                    ->delete();
                $add_res = DB::table('data_statistical')->insert($add_dast_data);
                unset($add_dast_data);
            }
            unset($poss);
            unset($list);
            unset($adm_id);
            unset($orgo_ord_id);
            // 保存日志
            $data['date_time'] = date('Y-m-d H:i:s');
            $data['del_res'] = $del_res;
            $data['add_res'] = $add_res;
            $data['id'] = $id;
            logRecord($data, 'data_statistical_log_new', 2);
            return $this->syncOrderServiceData($id);
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name  生成商品数据数组
     * @param $data 商品表数据组
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/9/30 16:35>
     * |---------------------------------------------------------------------------------
     */
    public function creatGoodata($data)
    {
        $poss = [];
        foreach ($data as $k => $v) {
            $poss[$k] = '';
        }
        return $poss;
    }

    /**|---------------------------------------------------------------------------------
     * @name  合并数组
     * @param $orderdata 订单数据
     * @param $gooddata 商品数据
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/9/30 16:35>
     * |---------------------------------------------------------------------------------
     */
    public function mergeArray($orderdata, $gooddata)
    {
        $data = [];
        foreach ($orderdata as $k => $v) {
            $data[$k] = $v;
        }
        foreach ($gooddata as $k => $v) {
            $data[$k] = $v;
        }
        return $data;
    }

    /**|---------------------------------------------------------------------------------
     * @name  对象转数组
     * @param $object 对象数据
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/9/30 16:35>
     * |---------------------------------------------------------------------------------
     */
    public function objectToArray($object)
    {
        //先编码成json字符串，再解码成数组
        return json_decode(json_encode($object), true);
    }
}
