<?php

namespace App\Services\Shop;

use Illuminate\Database\Eloquent\Model;
use BlueCity\Core\Service\Service;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\Validators\Shop\ProPerformaceValidator;
use BlueCity\Core\Inc\ErrorInc;
use Illuminate\Support\Facades\Request;
use App\Models\Common;
use App\Services\Business\WashOrderService;
use App\Services\CommonService;
use App\Http\Enum\Business\OrderEnum;

class ProPerformaceService extends Service
{
    public static $instance;
    public $modelMain = null;
    public $mainValidator = null;

    public function __construct()
    {
        $this->mainValidator = new ProPerformaceValidator();
    }

    /**
     * @return mixed
     */
    public static function getInstance()
    {
        if (is_null(static::$instance)) {
            static::$instance = new static;
        }
        return static::$instance;
    }

    /**
     * 根据条件搜索数据内容
     *
     * @param array $param 条件
     * @param array $columns 内容
     * @param int $page 页码
     * @param int $pageSize 页容量
     * @return mixed
     */
    public function searchPage($user_info, $search_data, $show_count = 10)
    {
        // 商品列表
        $list_data = DB::table('goods_performance as gp')
            ->where('gppe_cid', $user_info->adm_cid)
            ->where('gppe_shop_id', $user_info->adm_shop_id)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['gppe_goo_name'])) {
                    $query->where('gppe_goo_name', 'like', '%' . $search_data['gppe_goo_name'] . '%');
                }
                if (!empty($search_data['gppe_sale_id'])) {
                    $query->where('gppe_sale_id', $search_data['gppe_sale_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['gppe_type'])) {
                    $query->where('gppe_type', $search_data['gppe_type']);
                }
            })
            ->orderBy('gppe_create_time', 'desc')
            ->paginate($show_count);
        $list_items = $list_data->items();
        // 获取当前列表下的按钮
        $list_button = getListButton($search_data['api_token'], $search_data['pri_id']);
        foreach ($list_items as $key => $value) {
            if ($value->gppe_type == 1) {
                $goo_unit = DB::table('goods')
                    ->where('goo_id', $value->gppe_goo_id)
                    ->value('goo_unit');
            } elseif($value->gppe_type == 2) {
                $goo_unit = '次';
            } else {
                $goo_unit = '';
            }
            if ($goo_unit) {
                $list_items[$key]->gppe_goo_name = $value->gppe_goo_name.'('.$goo_unit.')';
            } else {
                $list_items[$key]->gppe_goo_name = $value->gppe_goo_name;
            }
            $buttonData = [];
            $buttonData[] = 'edit';
            $button = CommonService::getListButton($buttonData,$list_button);
            $list_items[$key]->button_one = $button['button_one']??[];
            $list_items[$key]->button_two = $button['button_two']??[];
            $list_items[$key]->button_three = $button['button_three']??[];
        }
        $data['pages']['current_page'] = $list_data->currentPage();  //当前页面页码
        $data['pages']['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data['pages']['total'] = $list_data->total();               //总数据个数
        $data['pages']['current_number'] = $show_count;        //一页显示多少个
        $data['list'] = $list_items;                        //返回数据
        return $data;
    }

    // 新增
    public static function add($user_info, $request)
    {
        $exist = DB::table('goods_performance')
            ->where('gppe_shop_id', $user_info->adm_shop_id)
            ->where('gppe_sale_id', $request['gppe_sale_id'])
            ->where('gppe_type', $request['gppe_type'])
            ->where('gppe_goo_id', $request['gppe_goo_id'])
            ->exists();
        if ($request['gppe_type'] == 3) {//按订单分类
            $del = DB::table('goods_performance')
                ->where('gppe_shop_id', $user_info->adm_shop_id)
                ->where('gppe_sale_id', $request['gppe_sale_id'])
                ->where('gppe_type', $request['gppe_type'])
                ->update(['gppe_performance'=>0]);
            if ($exist) {
                 $gppe_res = DB::table('goods_performance')
                    ->where('gppe_shop_id', $user_info->adm_shop_id)
                    ->where('gppe_sale_id', $request['gppe_sale_id'])
                    ->where('gppe_type', $request['gppe_type'])
                    ->where('gppe_goo_id', $request['gppe_goo_id'])
                    ->update(['gppe_performance'=>$request['gppe_performance']]);
            }
        }
        if ($exist) {
            if ($request['gppe_type'] != 3) {
                $gppe_res = DB::table('goods_performance')
                    ->where('gppe_shop_id', $user_info->adm_shop_id)
                    ->where('gppe_sale_id', $request['gppe_sale_id'])
                    ->where('gppe_type', $request['gppe_type'])
                    ->where('gppe_goo_id', $request['gppe_goo_id'])
                    ->update(['gppe_performance'=>($request['gppe_performance']*100)]);
            }
            return ['code' => 200, 'msg' => '新增成功', 'data' => $gppe_res];
        }
        $data['gppe_cid'] = $user_info->adm_cid;
        $data['gppe_shop_id'] = $user_info->adm_shop_id;
        $data['gppe_type'] = $request['gppe_type']; //类型1商品2服务3按订单
        $data['gppe_sale_id'] = $request['gppe_sale_id']; //销售员id
        $data['gppe_sale_name'] = $request['gppe_sale_name']; //销售员名称
        $data['gppe_goo_id'] = $request['gppe_goo_id']; //商品id
        $data['gppe_goo_name'] = $request['gppe_goo_name']; //商品名称
        if ($request['gppe_type'] == 3) {
            $data['gppe_performance'] = $request['gppe_performance'];//绩效
        } else {
            $data['gppe_performance'] = $request['gppe_performance']*100;//绩效
        }
        $data['gppe_create_id'] = $user_info->adm_id;
        $data['gppe_create_name'] = $user_info->adm_name;
        $data['gppe_create_time'] = date('Y-m-d H:i:s');
        $gppe_res = DB::table('goods_performance')->insert($data);
        if ($gppe_res) {
            return ['code' => 200, 'msg' => '新增成功', 'data' => $gppe_res];
        } else {
            return ['code' => 500, 'msg' => '新增失败', 'data' => '新增失败'];
        }
    }

    // 编辑绩效
    public static function edit($user_info, $request)
    {
        if ($request['gppe_type'] == 3) {//按订单分类
            $del = DB::table('goods_performance')
                ->where('gppe_shop_id', $user_info->adm_shop_id)
                ->where('gppe_sale_id', $request['gppe_sale_id'])
                ->where('gppe_type', $request['gppe_type'])
                ->update(['gppe_performance'=>0]);
            $gppe_res = DB::table('goods_performance')
                ->where('gppe_id', $request['gppe_id'])
                ->update(['gppe_performance'=>$request['gppe_performance']]);
        } else {
            $data['gppe_performance'] = $request['gppe_performance']*100; //绩效
            $gppe_res = DB::table('goods_performance')->where('gppe_id', $request['gppe_id'])->update($data);
        }
        if ($gppe_res) {
            return ['code' => 200, 'msg' => '编辑成功', 'data' => '编辑成功'];
        } else {
            return ['code' => 500, 'msg' => '编辑失败', 'data' => '编辑失败'];
        }
    }

    /**
     * 订单销售绩效
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2025-02-21
     * @param  [type]           $user_info [description]
     * @param  [type]           $request   [description]
     * @return [type]                      [description]
     */
    public static function orderSalePerformance($user_info, $request, $show_count)
    {
        $list_data = DB::table('order')
            ->leftJoin('order_client', 'orcl_ord_id', '=', 'ord_id')
            ->leftJoin('order_goods', 'orgo_ord_id', '=', 'ord_id')
            ->where('orcl_sales_adm_id', '!=', '')
            ->where(function ($query) use ($request) {
                if (!empty($request['orcl_sales_adm_id'])) {
                    $query->where('orcl_sales_adm_id', $request['orcl_sales_adm_id']);
                }
                if (!empty($request['ord_state'])) {
                    $query->where('ord_state', $request['ord_state']);
                }
                if (!empty($request['ord_source'])) {
                    $query->where('ord_source', $request['ord_source']);
                }
                if (!empty($request['ord_wor_state'])) {
                    $query->where('ord_wor_state', $request['ord_wor_state']);
                }
            })
            ->where(function ($query) use ($request) {
                $query->where('orgo_sale_performance', '>', '0')
                    ->orWhere('ord_saleman_performance', '>', 0);
            })
            ->select('ord_id', 'ord_order_number', 'orcl_sales_adm_id', 'orcl_sales_adm_name', 'ord_order_price', 'ord_state', 'ord_pay_state', 'ord_wor_state', 'ord_payment_way', 'ord_source', 'ord_saleman_performance', 'ord_saleman_type', 'ord_actual_price', 'ord_banlance', 'ord_payment_money', 'ord_zero_price')
            ->groupBy('ord_id')
            ->paginate($show_count);
        $list_items = $list_data->items();
        if ($list_items) {
            $typeName = WashOrderService::getPaymentWayName(true);//获取支付方式名称
            $object_enum = new OrderEnum();
            foreach ($list_items as $key => $value) {
                // 获取枚举数据
                $ord_source_enum = $object_enum->keyValueEnum($object_enum->ord_source_enum);
                $list_items[$key]->ord_source_show = $ord_source_enum[$value->ord_source];
                if (empty($value->orcl_sales_adm_name) && !empty($value->orcl_sales_adm_id)) {
                    $list_items[$key]->orcl_sales_adm_name = DB::table('admin')
                        ->where('adm_id', $value->orcl_sales_adm_id)
                        ->value('adm_name');
                }
                $list_items[$key]->ord_payment_name = WashOrderService::getTypeData($value->ord_payment_way, $typeName);
                $order_goods = DB::table('order_goods')
                    ->where('orgo_ord_id', $value->ord_id)
                    ->where('orgo_sale_performance', '>', 0)
                    ->select('orgo_goo_name', 'orgo_goo_price', 'orgo_sale_performance', 'orgo_goo_quantity', 'orgo_goo_type', 'orgo_goo_return_quantity', 'orgo_goo_unit')
                    ->get()->toArray();
                if ($value->ord_saleman_type == 1) {
                    $list_items[$key]->ord_pername = '按订单金额';
                } elseif ($value->ord_saleman_type == 2) {
                    $list_items[$key]->ord_pername = '按结算金额';
                } else {
                    $list_items[$key]->ord_pername = '按商品/服务计算';
                }
                if ($value->ord_saleman_performance) {
                    if ($value->ord_saleman_type == 1) {
                        $performance = $value->ord_order_price * $value->ord_saleman_performance /100;
                    } else {
                        if ($value->ord_source == 2) {
                            $ord_actual_price = $value->ord_actual_price + $value->ord_zero_price;
                        } else {
                            $ord_actual_price = DB::table('order_settlement_details')
                                ->where('orsd_ord_id', $value->ord_id)
                                ->sum('orsd_pay_money');
                        }
                        $performance = $ord_actual_price * $value->ord_saleman_performance /100;
                    }
                    $list_items[$key]->order_goods = [];
                } else {
                    $performance = 0;
                    foreach ($order_goods as $k => $v) {
                        if ($v->orgo_goo_type == 2) {
                            $v->orgo_goo_unit = '次'; 
                        }
                        $order_goods[$k]->orgo_goo_name = $v->orgo_goo_name.'('.$v->orgo_goo_unit.')';
                        $order_goods[$k]->orgo_sale_performance_amount = $v->orgo_sale_performance*($v->orgo_goo_quantity-$v->orgo_goo_return_quantity);
                        $performance += ($v->orgo_sale_performance*($v->orgo_goo_quantity-$v->orgo_goo_return_quantity));
                    }
                    $list_items[$key]->order_goods = $order_goods;
                }
                if ($value->ord_wor_state == 11) {
                    $performance = 0;
                }
                $list_items[$key]->performance = $performance;
                if ($value->ord_wor_state == 7) {//结算状态1未结算2已结算3部分结算
                    $ord_wor_state_name = '待接单';
                } elseif ($value->ord_wor_state == 1) {
                    $ord_wor_state_name = '待派单';
                } elseif ($value->ord_wor_state == 2) {
                    $ord_wor_state_name = '服务中';
                } elseif ($value->ord_wor_state == 4) {
                    $ord_wor_state_name = '待评价';
                } elseif ($value->ord_wor_state == 11) {
                    $ord_wor_state_name = '已取消';
                } elseif ($value->ord_wor_state == 20) {
                    $ord_wor_state_name = '已完成';
                } else {
                    $ord_wor_state_name = '服务中';
                }
                $list_items[$key]->ord_wor_state_name = $ord_wor_state_name;
            }
            // 获取当前列表下的按钮
            // $list_button = getListButton($search_data['api_token'], $search_data['pri_id']);
            // foreach ($list_items as $key => $value) {
            //     $buttonData = [];
            //     $buttonData[] = 'edit';
            //     $button = CommonService::getListButton($buttonData,$list_button);
            //     $list_items[$key]->button_one = $button['button_one']??[];
            //     $list_items[$key]->button_two = $button['button_two']??[];
            //     $list_items[$key]->button_three = $button['button_three']??[];
            // }
            $data['list'] = $list_items;                        //返回数据
        } else {
            $data['list'] = [];
        }
        $data['pages']['current_page'] = $list_data->currentPage();  //当前页面页码
        $data['pages']['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data['pages']['total'] = $list_data->total();               //总数据个数
        $data['pages']['current_number'] = $show_count;        //一页显示多少个
        return $data;
    }

    // 开启绩效类型
    public static function start($user_info, $request)
    {
        $find_data = DB::table('goods_performance_type')
            ->where('gpt_shop_id', $user_info->adm_shop_id)
            ->where('gpt_type', $request['gpt_type'])
            ->where('gpt_sale_adm_id', $request['gpt_sale_adm_id'])
            ->first();
        if ($request['gpt_state'] == 1) {
            $all_data_update = DB::table('goods_performance_type')
                ->where('gpt_shop_id', $user_info->adm_shop_id)
                ->where('gpt_sale_adm_id', $request['gpt_sale_adm_id'])
                ->update(['gpt_state'=>2, 'gpt_update_time'=>date('Y-m-d H:i:s')]);
            if ($find_data) {
                $find_data_update = DB::table('goods_performance_type')
                    ->where('gpt_shop_id', $user_info->adm_shop_id)
                    ->where('gpt_type', $request['gpt_type'])
                    ->where('gpt_sale_adm_id', $request['gpt_sale_adm_id'])
                    ->update(['gpt_state'=>1, 'gpt_update_time'=>date('Y-m-d H:i:s')]);
                if ($find_data_update) {
                    return ['code' => 200, 'msg' => '开启成功', 'data' => '开启成功'];
                } else {
                    return ['code' => 500, 'msg' => '开启失败', 'data' => '开启失败'];
                }
            } else {
                $add_data['gpt_shop_id'] = $user_info->adm_shop_id;
                $add_data['gpt_sale_adm_id'] = $request['gpt_sale_adm_id'];
                $add_data['gpt_type'] = $request['gpt_type'];
                $add_data['gpt_state'] = $request['gpt_state'];
                $add_data['gpt_create_id'] = $user_info->adm_id;
                $add_data['gpt_create_time'] = date('Y-m-d H:i:s');
                $add_res = DB::table('goods_performance_type')->insertGetId($add_data);
                if ($add_res) {
                    return ['code' => 200, 'msg' => '开启成功', 'data' => '开启成功'];
                } else {
                    return ['code' => 500, 'msg' => '开启失败', 'data' => '开启失败'];
                }
            }
        } else {
            $update_res = DB::table('goods_performance_type')
                ->where('gpt_shop_id', $user_info->adm_shop_id)
                ->where('gpt_type', $request['gpt_type'])
                ->where('gpt_sale_adm_id', $request['gpt_sale_adm_id'])
                ->update(['gpt_state'=>2, 'gpt_update_time'=>date('Y-m-d H:i:s')]);
            if ($update_res) {
                return ['code' => 200, 'msg' => '关闭成功', 'data' => '关闭成功'];
            } else {
                return ['code' => 500, 'msg' => '关闭失败', 'data' => '关闭失败'];
            }
        }
    }

    /**
     * 获取分类及状态
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2025-03-12
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public static function getPerType($user_info, $request) {
        $type[] = ['type'=>1, 'name'=>'按商品/服务'];
        $type[] = ['type'=>2, 'name'=>'按订单'];
        foreach ($type as $key => $value) {
            $find_data = DB::table('goods_performance_type')
                ->where('gpt_shop_id', $user_info->adm_shop_id)
                ->where('gpt_sale_adm_id', $request['gpt_sale_adm_id'])
                ->where('gpt_type', $value['type'])
                ->first();
            if (empty($find_data)) {
                $type[$key]['gpt_state'] = 2;
            } else {
                $type[$key]['gpt_state'] = intval($find_data->gpt_state);
            }
        }

        return ['code' => 200, 'msg' => 'success', 'data' =>$type];
    }

    /**
     * 获取按订单分类的绩效
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2025-03-12
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public static function getOrderPer($user_info, $request) {
        $data[] = ['gppe_goo_id'=>1,'gppe_goo_name'=>'订单销售金额', 'gppe_performance'=>0];
        $data[] = ['gppe_goo_id'=>2,'gppe_goo_name'=>'订单结算金额', 'gppe_performance'=>0];
        foreach ($data as $key => $value) {
            $find_data = DB::table('goods_performance')
                ->where('gppe_shop_id', $user_info->adm_shop_id)
                ->where('gppe_sale_id', $request['gppe_sale_id'])
                ->where('gppe_type', 3)
                ->where('gppe_goo_id', $value['gppe_goo_id'])
                ->value('gppe_performance');
            $data[$key]['gppe_performance'] = $find_data ??0;
        }
        return ['code' => 200, 'msg' => 'success', 'data' =>$data];
    }
}
