<?php

namespace App\Http\Controllers\Orders;
use App\Http\Controllers\BaseController;

use App\Exceptions\ApiException;
use App\Services\CommonService;
use Illuminate\Http\Request;
use App\Models\OrderList;
use App\Models\Orders;
use App\Models\User;
use App\Models\SettlementList;
use App\Models\TicketList;
use App\Models\Admin;
use App\Models\SetmoneyType;
use App\Models\Aftersale;
use App\Models\StatementsList;
use DB;
use App\Http\Controllers\Controller;
use App\Services\TicketListService;
use BlueCity\Core\Inc\ErrorInc;
use App\Services\OrderListService;

class TicketListController extends BaseController
{
	/**
	 * @name 处罚单列表
     * @param  til_state      处罚单状态 0:全部; 1:新罚单; 5:申诉中; 10:已确认; 20:已执行
     * @param  til_ticnum     处罚单号
     * @param  til_ornum      订单单号
     * @param  til_sernum     派工单号
     * @param  til_creactime  开始时间
     * @param  page           页数
     * @param  page_size      每页数量
	 * @param Request $request
	 * @return \BlueCity\Core\Controllers\mixed
	 * @author du 2021年8月9日上午10:12:01
	 */
    public function index (Request $request)
    {
    	if (!in_array($request->input('til_state'),[0,1,5,10,20,30])){
    		return $this->error('参数错误til_state', ErrorInc::FAILED_PARAM);exit;
    	}
    	$input = $request->all();
    	$list = TicketListService::getTicketList($input, $request->get('session_token'));
    	if($list['list']){
    		return $this->success('获取成功', $list); exit;
    	}else{
    		return $this->error('暂无数据',ErrorInc::DATA_EMPTY,$list);exit;
    	}
    }


    /**
     * @name  获取订单关联信息
     * @param order_num  平台单号
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月9日下午3:32:42
     */
    public function searchRele (Request $request)
    {
        $input = $request->only('order_num');
        $data = TicketListService::searchRele($input);
        if($data['ErrorCode']!=1){
            return $data;exit;
        }else {
            return $this->success('获取成功', $data['Data']);
            exit;
        }

    }

    /**
     * @name 添加罚单(生成处罚单号)
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author du 2021年8月9日下午1:32:43
     */
    public function beforAddEntry (Request $request)
    {
        $til_ticnum = TicketListService::creactTicktNumber();
        return $this->success('获取成功', $til_ticnum); exit;
    }


    /**
     * @name 添加罚单
     * @param til_ticnum 处罚单号
     * @param til_ornum  订单单号
     * @param til_price  处罚金额
     * @param til_cause  处罚原因
     * @param til_type string	1:罚款；2：追款
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\BlueCity\Core\Controllers\mixed
     * @author du 2021年8月9日下午2:29:51
     */
    public function addList (Request $request)
    {
        $input = $request->only('til_ticnum','til_ornum','til_price','til_cause','til_sernum','til_watnum','til_wats','til_serid','til_type','sety_id','shr_sheng','shr_shi','shr_xian','til_dress','shr_name','shr_phone');

        $checkKey = CommonService::checkKey(['til_ticnum','til_ornum','til_price','til_cause','til_sernum','til_watnum','til_wats','til_serid','til_type','sety_id','shr_sheng','shr_shi','shr_xian','til_dress','shr_name','shr_phone'],$input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }

        if (!$request->filled('sety_id')) {
            return $this->error('参数错误无sety_id', ErrorInc::FAILED_PARAM);exit;
        }
        $old = TicketList::where('til_ornum', $input['til_ornum'])->value('til_id');
        if (isset($old) && $request->input('type') == 1) {
        	//return $this->error('已存在该罚单，是否确认重复处罚？', ErrorInc::FAILED_PARAM);exit;
            return response()->json(['ErrorCode' => 77, 'ErrorMessage' => '已存在该罚单，是否确认重复处罚？']);
            exit;
        }


        $session = $request->get('session_token');
        DB::beginTransaction();//开启事务
        $rest = CommonService::accMe($input['til_ticnum'],'罚单管理',$input['til_cause'],'','2',$session['admin_groupnew'],$session['admin_acc'],$session['id']);
        //aftersale表添加标签记录
        OrderListService::creatAftersale(1, $input['til_ornum'], $input['til_sernum'], 1, 230, 231, $input['sety_id'], 0, $input['til_serid'], '', $session['admin_acc'], $session['admin_acc'], $session['company_id']);

        if ($request->filled('pic') && $request->input('pic') != []) {
            $til_data = 2;
        } else {
            $til_data = 1;
        }
        $til_dress = $input['shr_sheng'].$input['shr_shi'].$input['shr_xian'].$input['til_dress'];
        $res = TicketListService::createTicket($input['til_ornum'],$input['til_sernum'],$input['til_watnum'],$input['til_wats'],$input['til_serid'],$input['til_price'],1,$input['til_cause'],$session['admin_acc'],$input['til_ticnum'],$input['til_type'],$til_data,$input['sety_id'],231,$input['shr_name'],$input['shr_phone'],$til_dress);

        if($res){
            $sys_num = OrderList::where('order_num',$input['til_ornum'])->value("sys_num");
            if ($request->filled('pic') && $request->input('pic') != []) {
                $pic = $request->input('pic');
           		$til_pic = implode(',',$pic);
            }else{
            	$til_pic = '';
            }
            if ($request->filled('sound')) {
                $til_sound = $request->input('sound');;
            }else{
            	$til_sound = '';
            }
           TicketListService::createTicketData($til_pic, $til_sound, $res, $session['id'], $session['admin_acc'], $input['til_cause'], 10);
            DB::commit();//成功则提交
            $this->insertingLog("添加，",$input['til_ticnum'],"添加罚单，".$input['til_ticnum'],"罚单管理",$request->ip(),$session['admin_acc']);//日志
            return $this->success('添加成功'); exit;
        }else{
            DB::rollback();//不成功，则回滚
            return $this->error('添加失败', ErrorInc::MYSQL_FAILED);
        }
    }


   /**
     * @name 编辑罚款金额
     * @param id ID号
     * @param til_price 修改后处罚金额
     * @param til_oldprice 修改前处罚金额
     * @param ticnum 处罚单号
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月9日下午2:32:02
    */
    public function editEntry (Request $request)
    {
    	if (!$request->filled('til_id')||!$request->filled('til_price')) {
    		return $this->error('参数错误无til_id或无til_price', ErrorInc::FAILED_PARAM);exit;
    	}
        $input = $request->only('til_id','til_price','til_oldprice','ticnum');
        $session = $request->get('session_token');
        $poss['til_price'] = $input['til_price'];
        $res = TicketList::where('til_id',$input['til_id'])->update($poss);
        if($res){
            $this->insertingLog("编辑，",$input['ticnum'],"编辑罚款金额，".$input['til_oldprice']."->".$input['til_price'],"罚单管理",$request->ip(),$session['admin_acc']);//日志
            return $this->success('修改成功'); exit;
        }else{
        	return $this->error('修改失败', ErrorInc::MYSQL_FAILED);
        }
    }


  /**
   * @name 驳回
   * @param til_id          处罚单id号
   * @param til_ornum   订单单号
   * @param til_content 备注内容
   * @param Request $request
   * @return \BlueCity\Core\Controllers\mixed
   * @author du 2021年8月9日下午3:56:21
   */
  public function repeal (Request $request)
    {
    	if (!$request->filled('til_id')||!$request->filled('til_ornum')) {
    		return $this->error('参数错误无til_id或无til_ornum', ErrorInc::FAILED_PARAM);exit;
    	}
        $input = $request->only('til_id','til_ornum','til_content');
        $poss['til_state'] = 1;
        $session = $request->get('session_token');
        $exit = TicketList::where('til_id',$request->input('til_id'))->select('til_state','til_ticnum','til_ornum')->first();
        if ($exit['til_state']!=10){
        	return $this->error('该罚单不可驳回', ErrorInc::MYSQL_FAILED);exit;
        }
        if ($request->filled('til_content')) {
        	$sys_num = Orders::where('order_num',$exit['til_ornum'])->value('sys_num');
            $rest = CommonService::accMe($sys_num,'罚单管理',$input['til_content'],'','2',$session['admin_groupnew'],$session['admin_acc'],$session['id']);
        }
        $res = TicketList::where('til_id',$input['til_id'])->update($poss);
        if($res){
            $this->insertingLog("驳回，",$input['til_ornum'],"驳回罚单，".$input['til_ornum'],"罚单管理",$request->ip(),$session['admin_acc']);//日志
            return $this->success('驳回成功'); exit;
        }else{
            return $this->error('驳回失败', ErrorInc::MYSQL_FAILED);
        }
    }


    /**
     * @name  审核
     * @param type 1:确认 2；撤消罚单
     * @param til_id       数据id
     * @param til_content  备注内容
     * @param til_sound    音频
     * @param til_pic      图片
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月9日下午4:09:04
     */
    public function toExamine (Request $request)
    {
        if (!$request->filled('til_id')||!$request->filled('til_content')||!$request->filled('type')){
            return $this->error('参数错误无til_id或无til_content或无type', ErrorInc::FAILED_PARAM);exit;
        }
        $input = $request->only('til_id','til_content','pic');
        $session = $request->get('session_token');

        if($request->input('type')==2){
            $res = $this->unsetTicket($request);
            return $res;
        }

        if ($request->filled('til_pic') && $request->input('til_pic') != []) {
        	$pic = $request->input('pic');

        	if(is_array($pic)){
           	$til_pic = implode(',',$pic);
        	}else{
        		$til_pic = $pic;
        	}
        }
        if ($request->filled('til_sound')) {
        	$til_sound = $request->input('til_sound');
        }
        $res = TicketListService::createTicketData($til_pic, $til_sound, $request->input('til_id'), $session['id'], $session['admin_acc'], $input['til_content'], 1);
        $til = TicketList::where('til_id',$input['til_id'])->select('til_price','til_ornum')->first();
        $sys_num = Orders::where('order_num',$til['til_ornum'])->value('sys_num');
        if (empty($til['til_price']) || $til['til_price'] == 0) {
        	TicketList::where('til_id',$input['til_id'])->update(['til_state'=>20]);
        } else {
        	TicketList::where('til_id',$input['til_id'])->update(['til_state'=>10]);
        }
        $rest = CommonService::accMe($sys_num,'罚单管理',$input['til_content'],'','2',$session['admin_groupnew'],$session['admin_acc'],$session['id']);

         if($res){
            $this->insertingLog("审核，",$til['til_ornum'],"审核罚单，".$input['til_ornum'],"罚单管理",$request->ip(),$session['admin_acc']);//日志
            return $this->success('审核成功'); exit;
        }else{
            return $this->error('审核失败', ErrorInc::MYSQL_FAILED);
        }
    }


    /**
     * @name  申诉
     * @param til_id      数据id
     * @param til_content 备注内容
     * @param til_lable   申诉标签
     * @param til_pic     图片
     * @param til_sound   音频
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月9日下午4:31:58
     */
    public function toAppeal (Request $request)
    {
        if (!$request->filled('til_id')||!$request->filled('til_content')){
        	 return $this->error('参数错误无til_id或无til_content', ErrorInc::FAILED_PARAM);exit;
        }

        $input = $request->only('til_id','til_content','til_lable');
        $session = $request->get('session_token');
        $til_ornum = TicketList::where('til_id',$input['til_id'])->value('til_ornum');
        if ($request->filled('til_pic') && $request->input('til_pic') != []) {
        	$pic = $request->input('til_pic');
           	$til_pic = implode(',',$pic);
        }
        if ($request->filled('til_sound')) {
        	$til_sound = $request->input('til_sound');
        }
        DB::beginTransaction(); //开启事务
        $input['til_lable'] = $input['til_lable']??0;
        $res = TicketListService::createTicketData($til_pic, $til_sound, $request->input('til_id'), $session['id'], $session['admin_acc'], $input['til_content'], 5,$input['til_lable']);
        OrderListService::creatAftersale(1, $til_ornum, '--', 1, 230, 232, $input['til_lable'], 0, 0,$input['til_content'], $session['admin_acc'], $session['admin_acc'], $session['company_id']);
        $dell = TicketList::where('til_id',$input['til_id'])->update(['til_state'=>5]);
        if($res&&$dell){
     		DB::commit(); //提交
            $this->insertingLog("申诉，",$til_ornum,"申诉罚单，".$input['til_ornum'],"罚单管理",$request->ip(),$session['admin_acc']);//日志
            return $this->success('申诉成功'); exit;
        }else{
        	DB::rollback();//回滚
            return $this->error('申诉失败', ErrorInc::MYSQL_FAILED);
        }
    }

    /**
     * @name  订单信息（申诉时）
     * @param til_id  数据id
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月9日下午4:57:20
     */
    public function toDetails (Request $request)
    {
        if (!$request->filled('til_id')) {
           return $this->error('参数错误无til_id', ErrorInc::FAILED_PARAM);exit;
        }
        $info = $this->getInfo($request->input('til_id'));
        $data['til_ticnum'] = $info['til_ticnum'];//处罚单号
        $data['til_ornum'] = $info['til_ornum'];//订单号
        $data['til_creactime'] = $info['til_creactime'];//处罚时间
        $data['company_name'] = $info['company_name'];//服务商名称
        $data['til_cause'] = $info['til_cause'];//处罚原因
        //获取数据  1,5表示审核，申诉图片
        $list = DB::table('ticket_data')->where('til_evid',$request->input('til_id'))
		        ->select('til_creactime','til_content','til_type','til_pic','til_sound','til_creacter')
		        ->get();
        if ($list) {
            $list = CommonService::dataToArray($list);
        	foreach ($list as $k => $v) {
        		if ($v['til_type'] == 1) {
        			$list[$k]['til_type_name'] = "审核";
        		} elseif ($v['til_type'] == 5) {
        			$list[$k]['til_type_name'] = "申诉";
        		}else{
                    $list[$k]['til_type_name'] = "未确认";
                }
        		if ($v['til_pic']) {
        			$list[$k]['pic_arr'] = explode(',',$v['til_pic']);
        		} else {
        			$list[$k]['pic_arr'] = [];
        		}
        		if ($v['til_sound']){
        			$list[$k]['til_sound'] = $v['til_sound'];
        		} else {
        			$list[$k]['til_sound'] = "";
        		}
        		$list[$k]['typesd'] = 1; //前段要求多传一个字段
        	}
        	$data['list'] = $list;
        } else {
        	$data['list'] = [];
        }
        return $this->success('获取成功',$data); exit;
    }

    /**
     * @name  查看附件
     * @param til_id  数据id
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月9日下午5:05:58
     */
    public function viewAttachments (Request $request)
    {
        if (!$request->filled('til_id')) {
        	return $this->error('参数错误无til_id', ErrorInc::FAILED_PARAM);exit;
        }
        $id = intval($request->input('til_id'));

        $list = DB::table('ticket_data')->where('til_evid',$id)->orderBy('til_creactime','DESC')->get()->toarray();
        if ($list){
        	return $this->success('获取成功',$list); exit;
        }else{
        	return $this->error('暂无数据',ErrorInc::DATA_EMPTY);
        }
    }


    /**
     * 获取订单信息
     * @param $param
     * @return mixed
     */

    public function getInfo ($param)
    {
        $info = TicketList::where('til_id',$param)->first(['til_ticnum','til_ornum','til_creactime','til_serid','til_cause']);
        $company_name = DB::table('admin')->where('id',$info['til_serid'])->value('company_name');
        $info['company_name'] = $company_name;
        return $info; exit;
    }


    /**|---------------------------------------------------------------------------------
     * @name  罚单标签
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse

     * |---------------------------------------------------------------------------------
     */
/*     public function ticketLabel (Request $request)
    {
        if ($request->filled('type')) {
            $type = $request->input('type');
            $group = $request->get('session_token')['admin_groupnew'];

            if ($type == 1) {//添加罚单标签
                $list = SetmoneyType::where(['lt_parent_id'=>231,'lt_statues'=>1])->whereRaw("FIND_IN_SET('".$group."',lt_group)")->select('sety_id','sety_name')->get();
            } elseif ($type == 2) {//罚单申诉标签
                $list = SetmoneyType::where(['lt_parent_id'=>232,'lt_statues'=>1])->whereRaw("FIND_IN_SET('".$group."',lt_group)")->select('sety_id','sety_name')->get();
            }

            if (!$list->isEmpty()) {
                return response()->json(['Data' => $list->toArray(), 'ErrorCode' => 1, 'ErrorMessage' => '']);
                exit;
            } else {
                return response()->json(['Data' => '', 'ErrorCode' => 2, 'ErrorMessage' => '暂无标签']);
                exit;
            }

        } else {
            throw new ApiException("参数错误");
        }
    } */


    /**
     * @name  执行
     * @param til_id   数据id
     * @param til_wats 执行结算单号
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月10日上午9:02:44
     */
    public function executed (Request $request)
    {
        if (!$request->filled('til_id')||!$request->filled('til_wats')){
           return $this->error('参数错误无til_id或无til_wats', ErrorInc::FAILED_PARAM);exit;
        }
        $til_wats = $request->input('til_wats');
        $til_id = intval($request->input('til_id'));
        if (!preg_match('/^[J]+\d{5,15}/',$til_wats)) {
        	return $this->error('执行结算单号格式错误', ErrorInc::MYSQL_FAILED);exit;
        }
        $exists = StatementsList::where('stl_wat',$til_wats)->whereIn('stl_type',[4,5])->value('stl_id'); //stl_type:结算状态1：未结算（商家未确认）；2：结算中（商家已确认）；3：已结算　４:未处理 5:待发货'
        if($exists) {
        	$res = TicketList::where('til_id',$til_id)->update(['til_wats' => $til_wats,'til_state' => 20]);
	        if($res){
	            $this->insertingLog("执行，",$til_id,"执行罚单，".$til_id,"罚单管理",$request->ip(),$request->get('session_token')['admin_acc']);//日志
	            return $this->success('执行成功'); exit;
	        }else{
	            return $this->error('执行失败', ErrorInc::MYSQL_FAILED);exit;
	        }
        } else {
        	return $this->error('该执行结算单号不存在或状态不正确', ErrorInc::MYSQL_FAILED);exit;
        }

    }


    /**
     * @name 撤消
     * param til_id 罚单ID
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/10/14
     */
    public function unsetTicket(Request $request){
        if (!$request->filled('til_id')){
            return $this->error('参数错误无til_id', ErrorInc::FAILED_PARAM);exit;
        }
        $til_id = intval($request->input('til_id'));
        $info = TicketList::where('til_id',$til_id)->value('til_state');
        if(!$info){
            return $this->error('无此罚单', ErrorInc::MYSQL_FAILED);
        }
        if(!in_array($info, [1,5,10])){
            return $this->error('罚单状态不正确', ErrorInc::MYSQL_FAILED);
        }
        $res = TicketList::where('til_id',$til_id)->update(['til_state' => 30]);
        if($res){
            $this->insertingLog("撤消，",$til_id,"撤消罚单，".$til_id,"罚单管理",$request->ip(),$request->get('session_token')['admin_acc']);//日志
            return $this->success('撤消成功'); exit;
        }else{
            return $this->error('撤消失败', ErrorInc::MYSQL_FAILED);exit;
        }

    }




}
