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

use Illuminate\Http\Request;
use App\Http\Models\Api\Common;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\AccountControl\VerifySellProjectController;

class SellProjectController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

    // 销售利润
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifySellProjectController;
        $error_message = $verify_data->indexValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

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

        if (!empty($search_data['sede_goo_id']) || !empty($search_data['goo_bra_id']) || !empty($search_data['start_time']) || !empty($search_data['end_time']) || !empty($search_data['sede_shop_id']) || !empty($search_data['chun_id'])) {
            $list_data = DB::table('sell_detail as sede')
                ->leftjoin('goods as goo', 'sede.sede_goo_id', '=', 'goo.goo_id')
                ->leftjoin('channel_unit as chun', 'chun.chun_id', '=', 'sede.sede_client_id')
                ->where('sede_cid', $user_info->adm_cid)
                ->where('sede_superior_shop_id', $shop_id)
                ->where('sede_plus_minus', 1)
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['sede_goo_id'])) {
                        $query->where('sede_goo_id', $search_data['sede_goo_id']);
                    }
                }) //商品名称
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['goo_bra_id'])) {
                        $query->where('goo_bra_id', $search_data['goo_bra_id']);
                    }
                }) //品牌名称
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['sede_shop_id'])) {
                        $query->where('sede_shop_id', $search_data['sede_shop_id']);
                    }
                }) //品牌名称
                ->where(function ($query) use ($search_data) {
                    //如果选择开始时间并且选择结束时间
                    if (!empty($search_data['start_time']) && !empty($search_data['end_time'])) {
                        $query->whereBetween('sede_create_time', [$search_data['start_time'], $search_data['end_time'] . ' 23:59:59']);
                    } else {
                        // 如果选择开始时间
                        if (!empty($search_data['start_time'])) {
                            $query->where('sede_create_time', '>=', $search_data['start_time']);
                        } else {
                            // 如果选择结束时间
                            if (!empty($search_data['end_time'])) {
                                $query->where('sede_create_time', '<=', $search_data['end_time'] . ' 23:59:59');
                            }
                        }
                    }
                }) //创建时间
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['chun_id'])) {
                        $query->where('chun_id', $search_data['chun_id']);
                    }
                }) //客户单位
                ->select(DB::raw('sede_id, goo_name, goo_bra_id, goo_bra_name, goo_goods_encode, sede_order_type, sum(sede_cost_amount_price) as sede_cost_amount_price, sum(sede_amount_price) as sede_amount_price, sum(sede_goo_quantity) as sede_goo_quantity, sede_plus_minus,sede_create_time, sede_order_type, sede_shop_id, sede_superior_shop_id, sede_goo_id, chun_unit_name'))
                ->groupBy('sede_goo_id')
                ->orderBy('sede_id', 'desc')
                ->paginate($this->show_count);
            $list_items = $list_data->items();

            if (!empty($list_items)) {
                $sede_goo_id = array_column($list_items, 'sede_goo_id');
                //退货总金额
                $goods = DB::table('sell_detail as sede')
                    ->leftjoin('goods as goo', 'sede.sede_goo_id', '=', 'goo.goo_id')
                    ->where('sede_plus_minus', 2)
                    ->where('sede_cid', $user_info->adm_cid)
                    ->where('sede_superior_shop_id', $shop_id)
                    ->whereIn('sede_goo_id', $sede_goo_id)
                    ->groupBy('sede_goo_id')
                    ->select(DB::raw('sum(sede_amount_price) as sede_amount_price, sum(sede_cost_amount_price) as sede_cost_amount_price, sum(sede_goo_quantity) as sede_goo_quantity, sede_goo_id'))
                    ->paginate($this->show_count);
                $returned_goods = json_decode(json_encode($goods->items()), true); //退货商品数据
                $returned_goods_price = [];
                if ($returned_goods) {
                    $returned_goods_price = array_column($returned_goods, null, 'sede_goo_id');
                }
                foreach ($list_items as $key => $value) {
                    // 计算公式利润 = (销售单价-成本单价)*销售数量 - (退货单价-成本单价)*退货数量
                    // 等价于 （销售总金额-销售成本总金额） - （退货总金额-退货成本总金额）
                    // 销售金额 = 销售总金额 - 销售成本总金额
                    $sell_price = $value->sede_amount_price - $value->sede_cost_amount_price;

                    $list_items[$key]->sales_return_quantity = 0; //退货总数量
                    $sales_return_price = 0;
                    $sales_sede_amount_price = 0; //退货总金额
                    if (isset($returned_goods_price[$value->sede_goo_id])) {
                        // 退货金额 = 退货总金额-退货成本总金额
                        $sales_return_price = $returned_goods_price[$value->sede_goo_id]['sede_amount_price'] - $returned_goods_price[$value->sede_goo_id]['sede_cost_amount_price'];
                        $sales_sede_amount_price = $returned_goods_price[$value->sede_goo_id]['sede_amount_price']; //退货总金额
                        $list_items[$key]->sales_return_quantity = $returned_goods_price[$value->sede_goo_id]['sede_goo_quantity'];
                    }
                    // 销售总金额-退货总金额
                    $sell_minus_sales = $value->sede_amount_price - $sales_sede_amount_price;
                    // 利润
                    $list_items[$key]->profit = $sell_price - $sales_return_price;

                    // 计算公式利率 = ((销售单价-成本单价)*销售数量 - (退货单价-成本单价)*退货数量)/(销售总金额-退货总金额)*100%
                    if ($sell_minus_sales) {
                        $list_items[$key]->rate = round($list_items[$key]->profit / $sell_minus_sales * 100, 2) . '%';
                    } else {
                        $list_items[$key]->rate = '0%';
                    }
                }
            }
            $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
            $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
            $data_info['total'] = $list_data->total();               //总数据个数
            $data_info['current_number'] = $this->show_count;        //一页显示多少个
            $data_info['data'] = $list_items;                        //返回数据
        } else {
            $data_info['data'] = [];
        }

        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data_info, 'list_button'=>$list_button]);
    }
}
