<?php

namespace App\Services\Api\MobileWeb;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use BlueCity\Core\Inc\ErrorInc;
use App\Models\{Admin,
    GhPrice,
    GoodsBrand,
    InstallLine,
    Management,
    Note,
    OrderList,
    OrderMsg,
    OrderRejected,
    Orders,
    InstallPerson,
    OrderTime,
    SetmoneyType,
    SettlementList,
    SettlementMoney,
    SubmitPlease,
    TicketList,
    User,
    OrderAfter};
use App\Services\{BmmcService, Api\OrderManage\OrdersVehicleService, CommonService};

class StatementsListService extends Model
{
    /**
     * 售后列表
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-09-12
     * @param  [type]           $request    [description]
     * @param  integer          $show_count [description]
     * @return [type]                       [description]
     */
    public static function index($request, $show_count = 10)
    {
        $session = $request['session'];
        // 查询列表
        if ($request['status'] == 1) {//未出账单
            $list_data = DB::table('settlement_list as s')
                ->leftJoin('order_list as o', 'o.serial_number', '=', 's.list_id')
                ->leftJoin('order_msg as om', 'om.id', '=', 'o.order_goods_id');
                if($session['user_type']==3){
                    $list_data = $list_data->where('s.agency_id', $session['company_id']);
                    if(isset($request['search_company_id']) && !empty($request['search_company_id'])){//仅展示本门店
                        $list_data = $list_data->where('s.ser_id', $request['search_company_id']);
                    }
                    if(!isset($request['search_all']) || $request['search_all']==1){//仅展示本门店
                        $list_data = $list_data->where('s.ser_id', $session['admin_id']);
                    }
                }else {
                    $list_data = $list_data->where('s.ser_id', $session['admin_id']);
                }
                $list_data = $list_data->where('list_service_type', 40)
                ->whereIn('sett_status', [1,60,63])
                ->select('s.id','s.order_num as sys_num', 's.create_time', 'all_price', 'list_id', 'om.goods_name', 'om.goods_num', 'o.id as wor_id', 'o.stauas as wor_state')
                ->paginate($show_count);
            $page['count'] = 0;
            $page['page'] = 0;
            $page['page_size'] = $show_count;
            $page['allPage'] = 0;
            $data['list'] = [];
            $data['page'] = $page;

            $list_items = $list_data->items();
            foreach ($list_items as $key => $value) {
                switch ($value['wor_state']) {
                    case '10':
                        $list_items[$key]['wor_state'] = 1;
                        break;
                    case '10':
                        $list_items[$key]['wor_state'] = 1;
                        break;
                    case '10':
                        $list_items[$key]['wor_state'] = 1;
                        break;
                    case '10':
                        $list_items[$key]['wor_state'] = 1;
                        break;
                    case '10':
                        $list_items[$key]['wor_state'] = 1;
                        break;
                }
            }
            if ($list_items) {
                $list_items = CommonService::dataToArray($list_items);
                $page['count'] = $list_data->total(); //总数据个数
                $page['page'] = $list_data->currentPage(); //当前页面页码
                $page['page_size'] = $show_count; //一页显示多少个
                $page['allPage'] = $list_data->lastPage(); //表示最后一页的页码
                $data['list'] = $list_items;
                $data['page'] = $page;
            }
        } else {//已出账单
            $list_data = DB::table('statements_list as sl')
                ->leftJoin('company as c', 'c.com_id', '=', 'sl.company_id')
                ->where('stl_serid', $session['admin_id'])
                ->where('stl_type', '!=', 4)
                ->select('stl_wat', 'stl_type', 'com_name', 'stl_startime', 'stl_endtime', 'stl_money', 'stl_ticket', 'stl_id')
                ->orderByRaw("stl_type asc,stl_endtime desc")
                ->paginate($show_count);
            $page['count'] = 0;
            $page['page'] = 0;
            $page['page_size'] = $show_count;
            $page['allPage'] = 0;
            $data['list'] = [];
            $data['page'] = $page;

            $list_items = $list_data->items();
            if ($list_items) {
                $list_items = CommonService::dataToArray($list_items);
                $getStauasName = self::getStauasName();
                foreach ($list_items as $key => $value) {
                    if($value['stl_ticket']>0){
                        $list_items[$key]['stl_money'] = sprintf("%.2f",($value['stl_money']-$value['stl_ticket']));;
                    }
                    $list_items[$key]['stl_type_name'] = $getStauasName[$value['stl_type']]['name'];
                    $list_items[$key]['pic_data'] = DB::table('pictures')
                        ->where('sett_wat_num', $value['stl_wat'])
                        ->get();
                    $list_items[$key]['button'] = [];
                    $list_items[$key]['button'] = [['action'=>'info','name'=>'查看详情']];
                    if(in_array($value['stl_type'],[1])){
                        $list_items[$key]['button'][] = ['action'=>'businessFirm','name'=>'商家确认'];
                    }
                }
                $page['count'] = $list_data->total(); //总数据个数
                $page['page'] = $list_data->currentPage(); //当前页面页码
                $page['page_size'] = $show_count; //一页显示多少个
                $page['allPage'] = $list_data->lastPage(); //表示最后一页的页码
                $data['list'] = $list_items;
                $data['page'] = $page;
            }
        }

        if ($data['list']) {
            return ['ErrorCode' => 1, 'ErrorMessage' => '成功', 'Data' => $data];
        } else {
            return ['ErrorCode' => 1, 'ErrorMessage' => '暂无数据', 'Data' => $data];
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 工单状态
     * @param string $type
     * @retrun  /multitype:array
     * @author dou 2024/9/10 10:51
     * |---------------------------------------------------------------------------------
    */
    public static function getStauasName ( $type = true ){
        $stauasName = [['type'=>'1','name'=>'未确认'],['type'=>'2','name'=>'已确认'],['type'=>'3','name'=>'已结算'],['type'=>'30','name'=>'审核中'],['type'=>'4','name'=>'已完成']];
        if($type){
            $stauasName = CommonService::jointArrayKey($stauasName, 'type');
        }
        return $stauasName;
    }

    /**|---------------------------------------------------------------------------------
     * @name 立即处理
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * |---------------------------------------------------------------------------------
     */
    public static function businessFirm ($request)
    {
        DB::beginTransaction();
        $session = $request['session'];
        $find_data = DB::table('statements_list')
            ->where('stl_id', $request['id'])
            ->first();

        if ($find_data['stl_type'] !=1){
            return ['ErrorCode' => 2, 'ErrorMessage' => '账单状态不正确', 'Data' => ''];
        }

        $info['stl_type'] = 2;//改为处理中
        $res = DB::table('statements_list')
            ->where('stl_id', $request['id'])
            ->update($info);
        if ($res){
            DB::commit();
            return ['ErrorCode' => 1, 'ErrorMessage' => '确认成功', 'Data' => []];
        }else{
            DB::rollback();//回滚
            return ['ErrorCode' => ErrorInc::MYSQL_FAILED, 'ErrorMessage' => '操作失败', 'Data' => []];
        }
    }

    public static function info($request,$show_count=80) {
        $session = $request['session'];
        $data = DB::table('statements_list')
            ->where('stl_id', $request['id'])
            ->select('stl_money', 'stl_wat','stl_ticket')
            ->first();
        $type = $request['type']??1;
        if($type==1) {
            $info_data = DB::table('settlement_list as s')
                ->leftJoin('order_list as o', 'o.serial_number', '=', 's.list_id')
                ->leftJoin('order_msg as om', 'om.id', '=', 'o.order_goods_id')
                ->where('s.ser_id', $session['admin_id'])
                ->where('wat_num', $data['stl_wat'])
                ->select('s.id', 's.sys_num', 's.create_time', 'all_price', 's.order_num as list_id', 'om.goods_name', 'om.goods_num')
                ->orderBy('s.id', 'asc')
                ->paginate($show_count);
            $list = $info_data->items();
        }else{
            $info_data = TicketList::where('til_wats',$data['stl_wat'])
                ->select('til_id as id', 'til_ticnum as sys_num', 'til_creactime as create_time', 'til_price as all_price', 'til_ornum as list_id', 'til_cause as goods_name')
                ->orderBy('til_id', 'asc')
                ->paginate($show_count);
            $list = $info_data->items();
            $list = CommonService::dataToArray($list);
            if($list) {
                foreach ($list as $k => $v) {
                    $list[$k]['all_price'] = '-' . $v['all_price'];
                }
            }
        }
        $page['count'] = $info_data->total(); //总数据个数
        $page['page'] = $info_data->currentPage(); //当前页面页码
        $page['page_size'] = $show_count; //一页显示多少个
        $page['allPage'] = $info_data->lastPage(); //表示最后一页的页码
        $data['info_data'] = $list;
        $data['page'] = $page;
        return ['ErrorCode' => 1, 'ErrorMessage' => '成功', 'Data' => $data];
    }
}
