<?php

namespace App\Services\Finance;

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 App\Models\Common;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\Validators\Finance\WashViolationValidator;
use BlueCity\Core\Inc\ErrorInc;
use App\Services\CommonService;
use App\Http\Controllers\Common\CommonController;

// 罚单管理
class WashViolationService extends Service
{
    public static $instance;
    public $modelMain = null;
    public $mainValidator = null;

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

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

    /**
     * 罚单列表
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-07-11
     * @param  [type]           $user_info   [description]
     * @param  [type]           $search_data [description]
     * @param  integer          $show_count  [description]
     * @return [type]                        [description]
     */
    public function index($user_info, $search_data, $show_count = 10)
    {
        if(isset($search_data['is_excel']) && $search_data['is_excel']==2){
            DB::connection()->enableQueryLog();#开启执行日志
        }
        $list_data = DB::table('violation_ticket_detail as vtd')
            ->rightJoin('violation_ticket as v', 'v.viti_id', '=', 'vtd.vtde_viti_id')
            ->where('viti_shop_id', $user_info->adm_shop_id)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['adm_id'])) {
                    $query->where('vtde_adm_id', $search_data['adm_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['viti_order_number'])) {
                    $query->where('viti_order_number', 'like', '%' . $search_data['viti_order_number'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['viti_bind_work'])) {
                    $query->where('viti_bind_work', $search_data['viti_bind_work']);//是否绑定工单绩效1是2否
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['viti_punish_adm_name'])) {
                    $query->where('viti_punish_adm_name', 'like', '%' . $search_data['viti_punish_adm_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //创建时间
                // 如果选择开始时间并且选择结束时间
                if (!empty($search_data['create_time_start']) && !empty($search_data['create_time_end'])) {
                    $query->whereBetween('viti_create_time', [$search_data['create_time_start'], $search_data['create_time_end'] . ' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['create_time_start'])) {
                        $query->where('viti_create_time', '>=', $search_data['create_time_start']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['create_time_end'])) {
                            $query->where('viti_create_time', '<=', $search_data['create_time_end'] . ' 23:59:59');
                        }
                    }
                }
            })
            // ->select('viti_order_number', 'viti_reason', 'viti_create_name', 'viti_create_time', 'viti_reject_reason', 'viti_wor_number', 'viti_after_number', 'viti_state', 'viti_id', '')
            // ->orderBy('viti_id', 'desc')
            ->paginate($show_count);

        $list_items = $list_data->items();
        if(isset($search_data['is_excel']) && $search_data['is_excel']==2){
            if (empty($list_items)) {
                return response()->json(['code'=>500,'msg'=>'暂无数据']);
            }
            $data['sqls'] = DB::getQueryLog()[1];
            $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'],200,'WashViolation','罚单列表');
        }
        // 获取当前列表下的按钮
        $list_button = getListButton($search_data['api_token'], $search_data['pri_id']);
        if ($list_items) {
            foreach ($list_items as $key => $value) {
                $buttonData = [];
                if ($value->viti_state == 1) {
                    $buttonData[] = 'reject';
                }
                if ($value->viti_state == 2) {
                    $buttonData[] = 'restore';
                }
                $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']??[];
            }
        }
        $sum_price = DB::table('violation_ticket_detail as vtd')
            ->leftJoin('violation_ticket as v', 'v.viti_id', '=', 'vtd.vtde_viti_id')
            ->where('viti_shop_id', $user_info->adm_shop_id)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['vtde_adm_id'])) {
                    $query->where('vtde_adm_id', $search_data['adm_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['viti_order_number'])) {
                    $query->where('viti_order_number', 'like', '%' . $search_data['viti_order_number'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['viti_bind_work'])) {
                    $query->where('viti_bind_work', $search_data['viti_bind_work']);//是否绑定工单绩效1是2否
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['viti_punish_adm_name'])) {
                    $query->where('viti_punish_adm_name', 'like', '%' . $search_data['viti_punish_adm_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) { //创建时间
                // 如果选择开始时间并且选择结束时间
                if (!empty($search_data['create_time_start']) && !empty($search_data['create_time_end'])) {
                    $query->whereBetween('viti_create_time', [$search_data['create_time_start'], $search_data['create_time_end'] . ' 23:59:59']);
                } else {
                    // 如果选择开始时间
                    if (!empty($search_data['create_time_start'])) {
                        $query->where('viti_create_time', '>=', $search_data['create_time_start']);
                    } else {
                        // 如果选择结束时间
                        if (!empty($search_data['create_time_end'])) {
                            $query->where('viti_create_time', '<=', $search_data['create_time_end'] . ' 23:59:59');
                        }
                    }
                }
            })
            ->selectRaw('sum(vtde_punish_money) as sum_price')
            ->first();
        $data['sum_price'] = $sum_price->sum_price;
        $data['current_page'] = $list_data->currentPage();  //当前页面页码
        $data['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data['total'] = $list_data->total();               //总数据个数
        $data['current_number'] = $show_count;        //一页显示多少个
        $data['data'] = $list_items;                        //返回数据
        return $data;
    }

    // 新增
    public static function add($user_info, $request)
    {
        $data['viti_cid'] = $user_info->adm_cid;
        $data['viti_shop_id'] = $user_info->adm_shop_id;
        $data['viti_order_number'] = $request['viti_order_number']; //订单号
        $data['viti_reason'] = $request['viti_reason']; //处罚原因
        $data['viti_create_id'] = $user_info->adm_id; //创建人
        $data['viti_create_name'] = $user_info->adm_name; //创建人
        $data['viti_create_time'] = date('Y-m-d H:i:s');
        $data['viti_state'] = 1;
        $viti_id = DB::table('violation_ticket')->insertGetId($data);
        $adm_data = $request['adm_data'];
        foreach ($adm_data as $key => $value) {
            $add_adm_data['vtde_shop_id'] = $user_info->adm_shop_id;
            $add_adm_data['vtde_viti_id'] = $viti_id;
            $add_adm_data['vtde_adm_id'] = $value['vtde_adm_id'];
            $add_adm_data['vtde_adm_name'] = $value['vtde_adm_name'];
            $add_adm_data['vtde_punish_money'] = $value['vtde_punish_money']*100;
            if ($value['vtde_punish_money'] > 0) {
                $add_adm_res = DB::table('violation_ticket_detail')->insert($add_adm_data);
            }
        }
        if ($viti_id) {
            return true;
        } else {
            return false;
        }
    }

    // 驳回
    public static function reject($request)
    {
        $data['viti_reject_reason'] = $request['viti_reject_reason'];//驳回原因
        $data['viti_state'] = 2;//1正常2驳回
        $data['viti_update_time'] = date('Y-m-d H:i:s');
        $viti_id = DB::table('violation_ticket')
            ->where('viti_id', $request['viti_id'])
            ->update($data);
        return $viti_id;
    }

    // 恢复
    public static function restore($ids)
    {
        $update_data['viti_state'] = 1;
        $update_data['viti_update_time'] = date('Y-m-d H:i:s');
        $viti_id = DB::table('violation_ticket')
            ->where('viti_id', $ids)
            ->update($update_data);
        return $viti_id;
    }

    /**
     * 罚单详情
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-07-11
     * @param  [type]           $user_info [description]
     * @param  [type]           $request   [description]
     * @return [type]                      [description]
     */
    public static function info($user_info, $request)
    {
        $info = DB::table('violation_ticket')
            ->where('viti_shop_id', $user_info->adm_shop_id)
            ->where('viti_id', $request['viti_id'])
            ->first();
        $info->detail = DB::table('violation_ticket_detail')
            ->where('vtde_viti_id', $info->viti_id)
            ->get()->toArray();
        if (empty($info)) {
            return ['code'=>ErrorInc::DATA_EMPTY, 'msg'=>'没查到罚单记录', 'data'=>''];
        }

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