<?php

namespace App\Http\Controllers\Mounting\Shop;

use Illuminate\Http\Request;
use BlueCity\Core\Controllers\MountingCoreController as Controller;
use BlueCity\Core\Traits\ResourceControllerMethod;
use App\Services\Shop\ProPerformaceService;
use BlueCity\Core\Inc\ErrorInc;
use App\Services\LoginUserService;
use App\Models\OperationLog;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use \PhpOffice\PhpSpreadsheet\IOFactory;
use App\Services\CommonService;
use App\Http\Controllers\Common\CommonController;
use App\Services\Business\WashOrderService;
use App\Http\Enum\Business\OrderEnum;

// 商品服务绩效管理
class ProPerformanceController extends Controller
{
    public function __construct()
    {
        $this->dataService = $service = new ProPerformaceService();
        $this->bootWithService($service);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->indexValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }

        $user_info = LoginUserService::getUser();
        $search_data = $this->dataService->searchPage($user_info, $request->all(), $request['show_count']);
        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        //获取top按钮
        $sea_button_data = 'add';
        $top_button = CommonService::getTopButton('',$sea_button_data,$list_button);
        if (empty($search_data['list'])) {
            return response()->json(['code'=>200, 'msg'=>'未找到数据', 'data'=>$search_data, 'list_button'=>$list_button, 'top_button'=>$top_button]);
        } else {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$search_data, 'list_button'=>$list_button, 'top_button'=>$top_button]);
        }
    }

    /**
     * 销售员绩效设置-新增
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2025-02-20
     * @param  Request          $request [description]
     */
    public function add(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->addValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }

        // 获取用户信息
        $user_info = LoginUserService::getUser();
        DB::beginTransaction();
        $res = ProPerformaceService::add($user_info, $request->all());
        if ($res['code'] == 200) {
            // 生成操作记录
            OperationLog::addLog($user_info, getRealIp($request), '销售绩效', '新增', '新增成功');
            DB::commit();
            return $this->success('新增成功');
        } else {
            DB::rollBack();
            return response()->json($res);
        }
    }

    /**
     * 编辑绩效
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2025-02-21
     * @param  Request          $request [description]
     */
    public function edit(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->editValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }

        // 获取用户信息
        $user_info = LoginUserService::getUser();
        DB::beginTransaction();
        $res = ProPerformaceService::edit($user_info, $request->all());
        if ($res['code'] == 200) {
            // 生成操作记录
            OperationLog::addLog($user_info, getRealIp($request), '销售绩效', '编辑', '编辑成功');
            DB::commit();
            return $this->success('编辑成功');
        } else {
            DB::rollBack();
            return response()->json($res);
        }
    }

    /**
     * 订单销售员绩效
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2025-02-21
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function ordersp(Request $request) {
        // 验证参数
        $error_message = $this->dataService->mainValidator->orderSalePerformanceValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }

        $user_info = LoginUserService::getUser();
        $search_data = $this->dataService->orderSalePerformance($user_info, $request->all(), $request['show_count']);
        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        //获取top按钮
        $sea_button_data = 'export';
        $top_button = CommonService::getTopButton('',$sea_button_data,$list_button);
        $all_status = WashOrderService::getStatsName(false);
        // 获取枚举数据
        $object_enum = new OrderEnum();
        $ord_source_enum = $object_enum->ord_source_enum;
        $return_data['all_status'] = $all_status;
        $return_data['ord_source_enum'] = $ord_source_enum;
        if (empty($search_data)) {
            return response()->json(['code'=>200, 'msg'=>'未找到数据', 'data'=>$search_data, 'list_button'=>$list_button, 'top_button'=>$top_button, 'return_data'=>$return_data]);
        } else {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$search_data, 'list_button'=>$list_button, 'top_button'=>$top_button, 'return_data'=>$return_data]);
        }
    }

    /**
     * 导出销售员的订单绩效
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2025-02-24
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function export(Request $request)
    {
        // 获取当前操作账号信息
        $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;

        $shop_state = true;
        if (in_array($shop_id, config('apisystem.NO_SHOPID'))) {
            $shop_state = false;
        }
        DB::connection()->enableQueryLog();#开启执行日志
        $search_data = $request->all();
        $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_create_time')
            ->groupBy('ord_id')
            ->get()->toArray();
        $data['sqls'] = DB::getQueryLog()[0];
        $sqls = $data['sqls'];
        $excel = new CommonController();
        $amp_id = $search_data['amp_id']??0;
        return $excel->getExcelOut($amp_id,$user_info,$search_data['pri_id'], $sqls, $search_data['api_token']);
        // ini_set("memory_limit", "1024M");  // 根据电脑配置不够继续增加
        if (!empty($list_data)) {
            // 将对象转化为数组
            $list_data = json_decode(json_encode($list_data), true);
            foreach ($list_data as $key => $value) {
                $order_goods = DB::table('order_goods')
                    ->where('orgo_ord_id', $value->ord_id)
                    ->select('orgo_goo_name', 'orgo_goo_price', 'orgo_sale_performance', 'orgo_goo_quantity', 'orgo_goo_unit')
                    ->get()->toArray();
                $list_data[$key]['order_goods'] = $order_goods;
                $performance = 0;
                $new_order_goods = '';
                foreach ($order_goods as $k => $v) {
                    if (empty($order_goods)) {
                        $new_order_goods = $v->orgo_goo_name.':'. ($v->orgo_sale_performance*$v->orgo_goo_quantity/100).'元';
                    } else {
                        $new_order_goods = $order_goods .','. $v->orgo_goo_name.':'. ($v->orgo_sale_performance*$v->orgo_goo_quantity/100).'元';
                    }
                    $order_goods[$k]->orgo_sale_performance_amount = $v->orgo_sale_performance*$v->orgo_goo_quantity;
                    $performance += ($v->orgo_sale_performance*$v->orgo_goo_quantity);
                }
                $list_data[$key]['performance'] = $performance;
            }
            $pathName = storage_path() . "/app/public/excel"; //获取上传excel路径
            // 创建文件夹
            if (!file_exists($pathName)) {
                mkdir($pathName, 0775, true);
                chmod($pathName, 0775);
            }

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

            $where['action_name'] = '销售员订单绩效表';
            $where['field_name'] = ['订单号', '销售员', '订单金额', '结算状态', '绩效金额', '绩效详情'];
            // 调用导出的公共方法
            export::publicExport(
                $streamFilename, //路径
                $where,    //sheet名及其每一行的标题
                $list_data      //导出数据
            );
            Common::addLog($user_info, getRealIp($request), '销售员订单绩效表', '导出', '导出成功');
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => 'storage/excel/' . $streamFileRand]);
        } else {
            return response()->json(['code' => 500, 'msg' => '暂无数据', 'data' => '暂无数据']);
        }
    }

    /**
     * 绩效计算类型开启关闭
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2025-03-12
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function start(Request $request) {
        // 验证参数
        $error_message = $this->dataService->mainValidator->startValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        DB::beginTransaction();
        $res = ProPerformaceService::start($user_info, $request->all());
        if ($res['code'] == 200) {
            // 生成操作记录
            OperationLog::addLog($user_info, getRealIp($request), '销售绩效', '开启', '开启成功');
            DB::commit();
        } else {
            DB::rollBack();
        }
        return response()->json($res);
    }

    /**
     * 获取类型
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2025-03-12
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function getPerType(Request $request) {
        // 验证参数
        $error_message = $this->dataService->mainValidator->getPerTypeValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        $res = ProPerformaceService::getPerType($user_info, $request->all());
        return response()->json($res);
    }

    /**
     * 获取按订单分类的销售绩效
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2025-03-12
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function getOrderPer(Request $request) {
        // 验证参数
        $error_message = $this->dataService->mainValidator->getOrderPerValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        $res = ProPerformaceService::getOrderPer($user_info, $request->all());
        return response()->json($res);
    }
}