<?php

namespace App\Services;
use App\Models\SettlementList;
use App\Models\TicketList;
use BlueCity\Core\Inc\ErrorInc;
use BlueCity\Core\Service\Service;
use DB;
use App\Models\Pt;
use App\Models\SetmoneyType;
use App\Models\OrderList;
use App\Models\Admin;
use PhpParser\Builder\Use_;
use App\Models\User;
use App\Models\OrderMsg;

class TicketListService extends Service
{
    //private static $instance;
    private $modelMain = null;

    public function __construct()
    {
        if (!$this->modelMain) $this->modelMain = new TicketList();
    }

    /**
     * 添加罚单
    * @param  $til_ornum
    * @param  $til_sernum
    * @param  $til_watnum
    * @param  $til_wats
    * @param  $til_serid
    * @param  $til_price
    * @param  $til_state
    * @param  $til_cause
    * @param  $til_creactor
    * @return
    * @author du 2021年8月3日上午10:50:07
    */
   public static function createTicket($til_ornum,$til_sernum,$til_watnum,$til_wats,$til_serid,$til_price,$til_state,$til_cause,$til_creactor,$til_ticnum='',$til_type=1,$til_data=1,$til_lable='',$til_lablepid='',$til_sname='',$til_phone='',$til_dress='',$company_id=1){
	if($til_ticnum){
        $til_ticnum = $til_ticnum;
	}else{
        $til_ticnum = 'C'.date("Ymdhis").str_pad(rand(0,999),3,'0',STR_PAD_LEFT);
	}

   	$ticket['til_ticnum'] = $til_ticnum;
   	$ticket['til_ornum'] = $til_ornum;
   	$ticket['til_sernum'] = $til_sernum;
   	$ticket['til_watnum'] = $til_watnum;
   	$ticket['til_wats'] = $til_wats;
   	$ticket['til_serid'] = $til_serid;
   	$ticket['til_price'] = $til_price;
   	$ticket['til_state'] = $til_state;
   	$ticket['til_cause'] = $til_cause;
   	$ticket['til_creactor'] = $til_creactor;
   	$ticket['til_creactime'] = date('Y-m-d H:i:s');

   	$ticket['til_type'] = $til_type;
   	$ticket['til_data'] = $til_data;
   	$ticket['til_lable'] = $til_lable;
   	$ticket['til_lablepid'] = $til_lablepid;
   	$ticket['til_sname'] = $til_sname;
   	$ticket['til_phone'] = $til_phone;
   	$ticket['til_dress'] = $til_dress;
   	$ticket['company_id'] = $company_id;
       $res = TicketList::insertGetId($ticket);
   	return $res;
   }

   /**
    * 添加罚单数据表
    * @param  $til_pic
    * @param  $til_sound
    * @param  $til_evid
    * @param  $til_creactid
    * @param  $til_creacter
    * @param  $til_content
    * @param  $til_type
    * @return
    * @author du 2021年8月9日下午2:24:07
    */
   public static function createTicketData($til_pic,$til_sound,$til_evid,$til_creactid,$til_creacter,$til_content,$til_type,$til_label=0){
   	$til['til_pic'] = $til_pic;
 	$til['til_sound'] = $til_sound;
   	$til['til_evid'] = $til_evid;
   	$til['til_creactid'] = $til_creactid;
   	$til['til_creacter'] = $til_creacter;
   	$til['til_creactime'] = date("Y-m-d H:i:s");
   	$til['til_content'] = $til_content;
   	$til['til_type'] = $til_type;
   	$til['til_label'] = $til_label;
   	$res = DB::table('ticket_data')->insert($til);
   	return $res;
   }

   /**|---------------------------------------------------------------------------------
    * @name 生成罚单号
    * @retrun /multitype:string
    * @author dou 2021/8/31 20:27
    * |---------------------------------------------------------------------------------
   */
    public static function creactTicktNumber ( ){
        $til_ticnum = 'C'.date("Ymdhis").str_pad(rand(0,999),3,'0',STR_PAD_LEFT);
        $res = TicketList::where("til_ticnum",$til_ticnum)->value('til_id');
        if($res){
            self::creactTicktNumber();
        }else{
            return $til_ticnum;
        }
    }
    /**
     * 获取罚单信息
     * @param string $key 查询键
     * @param string $value 查询值
     * @param array $select 展示参数
     * @param string $type 查询类型
     * @return unknown|boolean
     * @author du 2021年8月9日上午8:52:39
     */
    public static function getTkicetBy($key , $value , $select , $type = 'get')
    {
        if($key == 'til_id'){
            $type = 'first';
        }
        if($type == 'first' && count($select) == 1){
            $type = 'value';
        }
        $db = new TicketList();
        $list = CommonService::getMysqlData($db,[$key=>$value],$select,[],$type);
        if($list){
            return $list;
        }else{
            return false;
        }
    }


    /**
     * 获取罚单列表
     * @param array $input
     * @param array $session
     * @return Ambigous <multitype:, unknown, multitype:unknown NULL >
     * @author du 2021年8月7日下午3:39:38
     */
    public static function getTicketList($input,$session){
    	$Db = new TicketList();
        $Db = $Db->leftJoin('orders','orders.order_num','=','ticket_list.til_ornum')->leftJoin('user','orders.customer_id','=','user.id');

        $where = [];
        if($session['admin_groupnew'] != 7){//管理员可以看全部
            $where['gone_orders.company_id'] = $session['company_id'];
        }
        //$where['til_state_noteq'] = 30;
        if ($input['til_state'] == 0){//全部

        } elseif ($input['til_state'] == 1){
            $where['til_state'] = 1;
        } elseif ($input['til_state'] == 5){
            $where['til_state'] = 5;
        } elseif ($input['til_state'] == 10){
        	$where['til_state'] = 10;
        } elseif ($input['til_state'] == 20){
        	$where['til_state'] = 20;
        }elseif ($input['til_state'] == 30){
            $where['til_state'] = 30;
        }
        if (isset($input['til_ticnum'])){ //处罚单号
            $where['til_ticnum_rlike'] = $input['til_ticnum'];
        }
        if (isset($input['til_ornum'])){ //订单单号
            $where['til_ornum_llike'] = $input['til_ornum'];
        }
        if (isset($input['til_sernum'])){ //派工单号
            $where['til_sernum_rlike'] = $input['til_sernum'];
        }
        if (isset($input['ser_id'])) { //服务商id
            $where['til_serid'] = $input['ser_id'];
        }
        if (isset($input['til_creactime'])){ //时间
        	$input['til_creactime'][1] = date("Y-m-d", strtotime($input['til_creactime'][1] . " +1 day"));
            $where['til_creactime_between'] = $input['til_creactime'];
        }

        $where['1'] = 1;
    	$where = CommonService::jointWhere($where);
    	$page_size = $input['page_size']??10;
    	//DB::connection()->enableQueryLog();#开启执行日志
    	$paginate = $Db->whereRaw($where)
    				->select('ticket_list.*','orders.sys_num','orders.order_num','user.shr_name','user.shr_phone','user.shr_sheng','user.shr_shi','user.shr_xian','user.shr_adress')
			    	->orderBy('til_creactime','DESC')
			    	->paginate($page_size);
    	//print_r(DB::getQueryLog());
        $where1['1'] = 1;
        if($session['admin_groupnew'] != 7){//管理员可以看全部
            $where1['company_id'] = $session['company_id'];
        }
        $where1 = CommonService::jointWhere($where1);
        $xfd = TicketList::where('til_state',1)->whereRaw($where1)->count(); //新罚单
        $ssz = TicketList::where('til_state',5)->whereRaw($where1)->count(); //申诉中
    	$yqr = TicketList::where('til_state',10)->whereRaw($where1)->count(); //已确认
    	$yzx = TicketList::where('til_state',20)->whereRaw($where1)->count();  //已执行
        $ycx = TicketList::where('til_state',30)->whereRaw($where1)->count();  //已撤消
    	$data['show_Menu'] = [
    			['showname'=>"全部",'status'=>0,'shownum'=>"--"],
    			['showname'=>"新罚单",'status'=>1,'shownum'=>$xfd??0],
    			['showname'=>"申诉中",'status'=>5,'shownum'=>$ssz??0],
    			['showname'=>"已确认",'status'=>10,'shownum'=>$yqr??0],
    			['showname'=>"已执行",'status'=>20,'shownum'=>$yzx??0],
                ['showname'=>"已撤消",'status'=>30,'shownum'=>$ycx??0],
    	];

    	$all_button = BmmcService::whereButton($input['token'],$input['Pri_id']);
    	$export = BmmcService::getTopButton('addList','',$all_button);
    	$data['button_top'] = $export['button_top']??[];//顶部按钮
    	$data['button_search'] = $export['button_search']??[];//搜索栏按钮
    	$list = CommonService::dataToArray($paginate->items());

    	if($list){

    		$list = TicketListService::getButtonDatas($all_button, $list);
    		$data['list'] = $list;
    		$data['page'] = [
    				'count' => $paginate->total(),
    				'page'=>$paginate->currentPage(),
    				'page_size'=>$page_size,
    				'allPage'=>$paginate->lastPage()
    		];
    	}else{
    		$data['list'] = [];
    	}
    	return $data;
    }
    /**
     * 获取按钮和数据
     * @param array $all_button
     * @param array $list
     * @return string
     * @author du 2021年8月7日下午3:40:48
     */
    public static function getButtonDatas($all_button,$list){

    	$adminRes = Admin::where('admin_groupnew',2)->pluck('company_name','id')->toArray();

    	$statusArr = TicketListService::getTicketStatusName();
    	foreach ($list as $key => $value){
            $buttonData = [];


    		if (isset($adminRes[$value['til_serid']])){
    			$list[$key]['company_name'] = $adminRes[$value['til_serid']];
    		} else {
    			$list[$key]['company_name'] = "";
    		}

    		$list[$key]['til_state_name'] = $statusArr[$value['til_state']];

    		if ($value['til_type'] == 1){
    			$list[$key]['til_type_name'] = "罚款";
    		}elseif ($value['til_type'] == 2){
    			$list[$key]['til_type_name'] = "追款";
    		}

    		if ($value['til_state'] == 1){//新罚单
    			$buttonData[] = 'editEntry,toappeal,toexamine,remarks';
    		}elseif ($value['til_state'] == 5){//申诉中
    			$buttonData[] = 'toexamine,repeal,remarks';
    		} elseif ($value['til_state'] == 10) {//已确认
    			$buttonData[] = 'repeal,remarks,executed,unsetTicket';
    		} elseif ($value['til_state'] == 20) {//已执行
    			$buttonData[] = 'remarks';
    		}elseif ($value['til_state'] == 30) {//已撤消
                $buttonData[] = 'remarks';
            }

    		$button = BmmcService::getListButton($buttonData,$all_button);
    		$list[$key]['button_one'] = $button['button_one']??[];
    		$list[$key]['button_two'] = $button['button_two']??[];
    		$list[$key]['button_three'] = $button['button_three']??[];
    	}
    	return $list;
    }


    /**
     *
     * @return multitype:string
     * @author du 2021年8月9日上午9:43:14
     */
    public static function getTicketStatusName()
    {
    	$data = array("1"=>'新罚单','5'=>'申诉中','10'=>'已确认','20'=>'已执行','30'=>'已撤消');
    	return $data;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取罚单信息
     * @param array $input 请求参数
     * @param array $type 是否必须派单1是
     * @retrun /multitype:array
     * @author dou 2021/9/14 9:24
     * |---------------------------------------------------------------------------------
    */
    public static function searchRele ( $input , $type = 2){
        if(!isset($input['order_num']) || $input['order_num'] ==''){
            return ['Data' => [], 'ErrorMessage' => '缺少参数order_num', 'ErrorCode' => ErrorInc::INVALID_PARAM];
        }
        $order_num = $input['order_num'];
        $order = OrderService::getOrderBy('order_num', $order_num,['new_customer_id','ser_id']);
        if(!$order){
            return ['Data' => [], 'ErrorMessage' => '无对应单号数据', 'ErrorCode' => ErrorInc::DATA_EMPTY];
        }
        $xinxi = SettlementList::where('order_num',$order_num)->first();
        //dump($xinxi);
        $adminInfo = Admin::where('id',$xinxi['ser_id'])->pluck('company_name','id');
        if (!$xinxi && $type==1){
            return ['Data' => [], 'ErrorMessage' => '门店暂未接单无法开罚单', 'ErrorCode' => ErrorInc::DATA_EMPTY];
        }
        if (!$xinxi || $xinxi['wat_num'] == "") {
            $data['til_watnum'] = "暂无";
            $data['til_wats'] = "暂无";
        } else {
            $data['til_watnum'] = $xinxi['wat_num'];
            $data['til_wats'] = $xinxi['wat_num'];
        }
        $user = User::where('id',$order['new_customer_id'])->select('shr_name','shr_phone','shr_sheng','shr_shi','shr_xian','shr_adress')->first();
        $data['til_sernum'] = $xinxi['list_id']??'';//派工单号
        $data['til_serid'] = $xinxi['ser_id']??0;//服务商id
        $data['company_name'] = $adminInfo[$order['ser_id']]??'';
        $data['shr_name'] = $user['shr_name']??"";
        $data['shr_phone'] = $user['shr_phone']??"";
        $data['shr_sheng'] = $user['shr_sheng']??"";
        $data['shr_shi'] = $user['shr_shi']??"";
        $data['shr_xian'] = $user['shr_xian']??"";
        $data['shr_adress'] = $user['shr_adress']??"";
        $data['shr_name'] = $user['shr_name']??"";
        return ['Data' => $data, 'ErrorMessage' => '获取成功', 'ErrorCode' => 1];
    }

}
