<?php

/**
|--------------------------------------------------------------------------
 * 标签记录
|--------------------------------------------------------------------------
| 标签记录处理逻辑
 * @author DouBin
 * @Date: 2021/08/17
 * @Time: 上午 17:00
 * @Email: db@sudianwang.com
 * @version 1.0
 * @copyright BlueCity
 */
namespace App\Services;
use App\Models\Aftersale;
use App\Models\SettlementList;
use BlueCity\Core\Inc\ErrorInc;
use BlueCity\Core\Service\Service;
use Illuminate\Support\Facades\Log;
use DB;
use App\Models\SetmoneyType;

class AfterSaleService extends Service
{
    /**|---------------------------------------------------------------------------------
     * @name 添加标签记录
     * @param array $lable 标签内容
     * @param array $orderinfo 订单信息
     * @param $orderinfo order_num 订单单号
     * @param $orderinfo serial_number 工单号
     * @param $orderinfo p_id 平台id
     * @param $orderinfo ser_id 服务商id
     * @param $orderinfo slid 结算单id
     * @param string $content 备注信息
     * @param array $session 登录人信息
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2021/8/17 19:01
     * |---------------------------------------------------------------------------------
    */
    public static function insertData ( $lable , $orderinfo , $session , $content=''){
        $subs = [];
        $setArr = [];
        $granid_search = 0;
        if ($session['admin_groupnew'] != 7) {//管理员可以看全部
            $company_id = $session['company_id'];
        }else{
            $company_id = $orderinfo['company_id']??1;
        }
        foreach ($lable as $k => $v) {
            if($k < 1) {
                $granid_search = $v['sety_id'];
            }
            if ($v['sublevel']) {
                foreach ($v['sublevel'] as $kk => $vv) {
                    $subs[] = $v['sety_id'] . '-' . $vv;
                    $setArr[] = $vv;
                }
            } else {
                $subs[] = $v['sety_id'] . '-' . $v['sety_id'];
                $setArr[] = $v['sety_id'];
            }
        }
        if(!$subs){
            return  false;
        }
        $setArr[] = $granid_search;
        $setArr = array_unique($setArr);
        /*----------------------------------------获取添加需要使用的标签开始-------------------------------------------------*/
        $lablelist = LabtypeService::labelList();
        $lablelist = CommonService::arrayFilterFieldValue($lablelist,array(array('sety_id'=>$setArr)));
        $lablelist = CommonService::jointArrayKey($lablelist, 'sety_id');
        /*----------------------------------------获取添加需要使用的标签结束-------------------------------------------------*/
        $sql = 'INSERT INTO `gone_aftersale` (`afs_statues`,`afs_order`,`afs_serial`,`afs_sales`,`afs_granid`,`afs_paid`,`afs_type`,`afs_pid`,`afs_serid`,`afs_creactime`,`asf_time`,`afs_day`,`afs_creacter`,`afs_dealer`,`afs_content`,`company_id`) VALUES ';
        $sety_name = [];
//        $granid = 60;
        if(isset($lablelist[$granid_search])){
            $granid = $lablelist[$granid_search]['lt_parent_id'];
        }else{
            return false;
        }
        $aftersale = Aftersale::where('afs_order',$orderinfo['order_num'])->where('afs_granid',$granid)->delete();//移除老评价标签便于从新添加
        $sqls = [];
        foreach ($subs as $key => $val) {
            $arr = explode('-', $val);
            $labstate = $lablelist[$arr[1]]??[];
            if(isset($labstate['sety_name'])) {
                $sety_name[] = $labstate['sety_name'];
            }
            if ($orderinfo['serial_number'] <> '') {
                if ($labstate['sety_price'] > 0) {
                    if ($orderinfo['slid']!='') {
                        SettlementService::createSettMoney($orderinfo['slid'], $orderinfo['sys_num'], $labstate['sety_price'], $session['admin_name'], $arr['1']);
                    }
                }
                /*--------------------------------------添加处罚信息开始(暂时仅在撤销触发)--------------------------------------------------*/
                if(in_array($granid, [31,39])) {
                    if (strstr((string)$labstate['sety_price'], '-')) {
                        $new_customer_id = OrderService::getOrderBy('order_num', $orderinfo['order_num'],['new_customer_id']);
                        $user = UserService::getUserBy('id', $new_customer_id,['shr_name','shr_phone','shr_sheng','shr_shi','shr_xian','shr_adress']);
                        $dress = $user['shr_sheng']." ".$user['shr_shi']." ".$user['shr_xian']." ".$user['shr_adress'];
                        $price = substr($labstate['sety_price'], 1);
                        $number = 'C' . date("Ymdhis") . str_pad(rand(0, 999), 3, '0', STR_PAD_LEFT);
                        TicketListService::createTicket($number, $orderinfo['serial_number'], $orderinfo['wat_num'], '', $orderinfo['ser_id'], $price, 1, $labstate['sety_name'], $session['admin_name'],'',1,1,$arr[1],$arr[0],$user['shr_name'],$user['shr_phone'],$dress,$company_id);

                    }
                }
                /*--------------------------------------添加处罚信息结束--------------------------------------------------*/
            }
            $lt_type = $labstate['lt_type']??'2';
            $sqls[] = "('" . $lt_type . "','" . $orderinfo['order_num'] . "','" . $orderinfo['serial_number'] . "','2','" . $granid . "','" . $arr[0] . "','" . $arr[1] . "','" . $orderinfo['p_id'] . "','" . $orderinfo['ser_id'] . "','" . date('Y-m-d H:i:s') . "','" . date('Y-m-d H:i:s') . "','" . date('Y-m-d') . "','" . $session['admin_acc'] . "','" . $session['admin_acc'] . "','" . $content . "','" . $company_id . "')";
        }
        $sql .= implode(',', $sqls);
        $Res = DB::insert($sql);
        if($Res){
            return $sety_name;
        }else{
            return false;
        }
    }

    /**
     * 列表
     * @param array $input
     * @param array $session
     * @return multitype:multitype: multitype:string  multitype:multitype:string   unknown multitype:unknown NULL
     * @author du 2021年8月18日下午2:12:06
     */
    public static function getList($input,$session){

    	$where = [];
    	$where['1'] = 1;
    	$Db = Aftersale::whereHas('pt',function ($que)use($input){
    		if (!empty($input['pt_id'])){
    			$que->where('id',$input['pt_id']);
    		}
    	})->with('pt')->whereHas('admin',function ($query)use($input){
    		if (!empty($input['company_name'])){
    			$query->where('company_name','like','%'.$input['company_name'].'%');
    		}
    	})->with('admin');
    	$Maokai = Aftersale::whereHas('pt',function (){
    	})->with('pt')->whereHas('admin',function ($query)use($input){
    	})->with('admin');

    	if($session['admin_groupnew']=='7'){
    		$where['afs_granid_noteq'] = 0;
    		$Maokai = $Maokai->whereRaw("afs_granid!=0");
    	}else{
    	    $where['company_id'] = $session['company_id'];
    		$where['afs_granid_noteq'] = 0;
    	//	$where['lt_group_findinset'] = $session['admin_groupnew'];
    		//$Maokai = $Maokai->whereRaw('afs_granid!=0 and FIND_IN_SET('.$session["admin_groupnew"].',lt_group)');
            $Maokai = $Maokai->where('company_id',$session['company_id']);

    	}
    	$Maokai = $Maokai->selectRaw("afs_statues,count('id') as num")->groupBy('afs_statues')->get();
    	if (!$Maokai->isEmpty()){
    		$Maokai = $Maokai->toArray();
    		foreach ($Maokai as $k => $v){
    			if($v['afs_statues'] == 1){
    				$wcl = $v['num'];
    			}elseif ($v['afs_statues'] == 2){
    				$ycl = $v['num'];
    			}
    		}
    		$data['show_Menu'] = [
    				['show_name'=>"未处理",'show_num'=>$wcl??0,'statues'=>1],
    				['show_name'=>"已处理",'show_num'=>$ycl??0,'statues'=>2],
    		];
    	}else{
    		$data['show_Menu'] = [
    				['show_name'=>"未处理",'show_num'=>0,'statues'=>1],
    				['show_name'=>"已处理",'show_num'=>0,'statues'=>2],
    		];
    	}


    	if (isset($input['afs_statues'])){//状态
    		$where['afs_statues'] = $input['afs_statues'];
    	}

    	if (isset($input['afs_order'])){//订单单号
    		$where['afs_order_like'] = $input['afs_order'];
    	}
    	if (isset($input['afs_serial'])){//派工单号
    		$where['afs_serial_like'] = $input['afs_serial'];
    	}
    	if (isset($input['afs_serid'])){//网点id
    		$where['afs_serid'] = $input['afs_serid'];
    	}
    	$where = CommonService::jointWhere($where);
    	$page_size = $input['page_size']??10;
    	//DB::connection()->enableQueryLog();#开启执行日志
    	$paginate = $Db->whereRaw($where)
			    	->orderBy('afs_statues','ASC')
			    	->orderBy('afs_id','DESC')
			    	->paginate($page_size);

    	$all_button = BmmcService::whereButton($input['token'],$input['Pri_id']);
    	$export = BmmcService::getTopButton('export','',$all_button);
    	$data['button_top'] = $export['button_top']??[];//顶部按钮
    	$data['button_search'] = $export['button_search']??[];//搜索栏按钮
    	$list = CommonService::dataToArray($paginate->items());
    	if($list){
    		$list = AfterSaleService::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  $all_button
     * @param  $list
     * @return string
     * @author du 2021年8月18日下午2:30:18
     */
    public static function getButtonDatas($all_button,$list){

    	$labArr = SetmoneyType::where('lt_statues','!=',2)->pluck('sety_name','sety_id')->toArray();
    	foreach ($list as $k => $v){
            $buttonData = [];
    		$list[$k]['labname'] = $labArr[$v['afs_type']];

    		if ($v['afs_sales'] == 1){
    			$list[$k]['afs_sales_name'] = "售前";
    		}else{
    			$list[$k]['afs_sales_name'] = "售后";
    		}
    		if ($v['afs_statues'] == 1){
    			$list[$k]['afs_statues_name'] = "未处理";
    		}else{
    			$list[$k]['afs_statues_name'] = "已处理";
    		}
    		$list[$k]['pt_name'] = $v['pt']['pt_name'];
    		$list[$k]['company_name'] = $v['admin']['company_name'];
    		unset($list[$k]['pt']);
    		unset($list[$k]['admin']);
    		if($v['afs_statues']==1){
    			$buttonData[] = 'chuliOrder';
    		}
    		$button = BmmcService::getListButton($buttonData,$all_button);
    		$list[$k]['button_one'] = $button['button_one']??[];
    		$list[$k]['button_two'] = $button['button_two']??[];
    		$list[$k]['button_three'] = $button['button_three']??[];
    	}
    	return $list;
    }



}
