<?php

/**
|--------------------------------------------------------------------------
 * 售后服务
|--------------------------------------------------------------------------
| 售后服务处理逻辑
 * @author DouBin
 * @Date: 2021/08/05
 * @Time: 上午 10:16
 * @Email: db@sudianwang.com
 * @version 1.0
 * @copyright BlueCity
 */
namespace App\Services;
use App\Http\Controllers\BaseController;
use App\Models\Aftersale;
use App\Models\FeedSales;
use App\Models\OrderAfterDetai;
use App\Models\OrderAftertrack;
use App\Models\OrderMsg;
use App\Models\Pt;
use App\Models\RecycleOrders;
use App\Models\SendGoods;
use BlueCity\Core\Inc\ErrorInc;
use BlueCity\Core\Service\Service;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
use App\Models\OrderAfter;
use App\Models\Orders;
use App\Models\Admin;
use App\Models\SetmoneyType;
use DB;
use phpDocumentor\Reflection\Types\Self_;

class AftersaleOrderService extends Service
{

    /**|---------------------------------------------------------------------------------
     * @name 字段条件
     * @retrun multitype:array
     * @author dou 2021/8/7 18:24
     * |---------------------------------------------------------------------------------
     */
    public static function rules ( ){
        return array(
            'id' => '数据id',
            'content' => '备注信息',
            'labs' => '标签',
        );
    }
    /**
     * 售后列表
     * @param array $session 用户信息
     * @param array $input 请求数据
     * @return multitype:array
     * @author dou 2021年8月10日
     */
    public static function getList ( $input , $session ){
        /*---------------------------------------------拼接售后列表查询条件开始-------------------------------------------------------*/
        $db = new OrderAfter();
        $db = $db->leftJoin('orders', 'orders.order_num', 'order_after.order_num');
        $admin_pt_id = $session['admin_pt_id'];//获取当前用户可查看平台权限
        $where[1] = 1;
        if(!in_array($session['admin_groupnew'],[7,8])){
            $where['gone_order_after.p_id_searchin'] = trim($admin_pt_id);
        }
        if ($session['admin_groupnew'] != 7){
            $where['gone_orders.company_id'] = $session['company_id'];
        }

        /*---------------------------------------------状态查询条件开始-------------------------------------------------------*/
        if($input['state']!==0){
            $statuswhere = AftersaleOrderService::getStatusWhere($input['state']);
            foreach( $statuswhere as $k => $v ){
                $where[$k] = $v;
            }
        }
        /*---------------------------------------------状态查询条件结束-------------------------------------------------------*/

        if (isset($input['order_status'])){//订单状态
            $where['gone_orders.order_status'] = $input['order_status'];
        }
        if (isset($input['data_type'])){//售后分类
            $where['gone_order_after.data_type'] = $input['data_type'];
        }
        if (isset($input['category'])){//分类
            $where['gone_order_after.category'] = $input['category'];
        }

        if (isset($input['sys_num'])){
            $where['gone_order_after.sys_num_rlike'] = $input['sys_num'];
        }
        if (isset($input['order_num'])){
            $where['gone_order_after.order_num_rlike'] = $input['order_num'];
        }
        if (isset($input['after_num'])) {
            $where['gone_order_after.after_num_rlike'] = $input['after_num'];

        }
        if (isset($input['serial_number'])){
            $where['gone_order_after.serial_number_like'] = $input['serial_number'];
        }

        if (isset($input['get_id'])){//领取ID
            $where['gone_order_after.get_id'] = $input['get_id'];
        }
        if(isset($input['deal_lable'])){//处理标签
            $where['gone_order_after.deal_lable_findinset'] = $input['deal_lable'];
        }
        if (isset($input['lock_time'])) {
            //date('Y-m-d 23:59:59', strtotime('+2day'));
            $time_arr[0] = date("Y-m-d 00:00:00",strtotime($input['lock_time']));
            $timea = date("Y-m-d", strtotime($input['lock_time'] . " +1 day"));
            $time_arr[1] = date("Y-m-d 23:59:59",strtotime($timea));

            $where['gone_order_after.look_time_between'] = $time_arr;
        }
        if (isset($input['created_time'])){
            $input['created_time'][1] = date("Y-m-d", strtotime($input['created_time'][1] . " +1 day"));

            $where['gone_order_after.create_time_between'] = $input['created_time'];
        }

        if (isset($input['get_time'])){//领取时间搜索
            $input['get_time'][1] = date("Y-m-d", strtotime($input['get_time'][1] . " +1 day"));

            $where['gone_order_after.get_time_between'] = $input['get_time'];
        }

        if (isset($input['p_id'])){
            $where['gone_order_after.p_id'] = $input['p_id'];
        }
        if (isset($input['ser_id'])){
            $deal_serid['gone_order_after.ser_id'] = $input['ser_id'];
            $where['gone_order_after.deal_serid_searchor'] = $deal_serid;
        }
        if (isset($input['shr_name'])){
            $where['gone_order_after.shr_name_like'] = $input['shr_name'];
        }
        if (isset($input['shr_phone'])){
            $where['gone_order_after.shr_phone_like'] = $input['shr_phone'];
        }
        if (isset($input['shr_sheng'])){
            $where['gone_order_after.shr_sheng_like'] = $input['shr_sheng'];
        }
        if (isset($input['shr_shi'])){
            $where['gone_order_after.shr_shi_like'] = $input['shr_shi'];
        }

      //  $where['gone_orders.company_id'] = $session['company_id'];

        if($input['state'] == '30'){
            $orderBy['key'] = 'order_after.feek_time';
            $orderBy['value'] = 'ASC';
        }else if($input['state'] == '10'){
            $orderBy['key'] = 'order_after.create_time';
            $orderBy['value'] = 'DESC';
        }else{
            $orderBy['key'] = 'order_after.create_time';
            $orderBy['value'] = 'ASC';
        }



        /*---------------------------------------------拼接售后列表查询条件结束-------------------------------------------------------*/

        $data['showcount'] = AftersaleOrderService::getStatusBar($session,$admin_pt_id,1);//获取操作权限可展示订单状态栏

        $data['order_status_names'] = OrderService::getOrderStatusName(false);

        $topbtn[] = 'export,fastAfterOrder,moveGetId,AftersaleOrderCarfilms';
        if($input['state'] == '10'){
            $topbtn[] = 'setclassify';
        }
        $all_button = BmmcService::whereButton($input['token'],$input['Pri_id']);
        $export = BmmcService::getTopButton(implode(',', $topbtn),'',$all_button);
        $data['button_top'] = $export['button_top']??[];//顶部按钮
        $data['button_search'] = $export['button_search']??[];//搜索栏按钮

        $labelList = LabtypeService::labelList();
        $getsTree = LabtypeService::getsTree($labelList,511,3);
        $data['getsTree'] = $getsTree;//售后处理标签
        if (isset($input['get_id']) && $input['state']==2) {
            $list = false;
        }else{

            $where = CommonService::jointWhere($where);
            $page_size = $input['page_size'] ?? 10;
            if ($input['is_excel'] == 1) {
                DB::connection()->enableQueryLog();#开启执行日志
            }
            if ($input['is_excel']==2){
                $data['sql2'] = "SELECT a.oad_partname,a.oad_installstate,a.oad_type,a.oad_typepid,a.oad_applycontent,a.oad_dealtype,a.oad_recycle,a.oad_dealcontent,a.oad_dealptype,a.oad_dealtime,a.oad_dealer, gone_order_after.*,gone_orders.order_status,gone_orders.ser_id as order_ser_id FROM gone_order_afterdetail as a LEFT JOIN gone_order_after on a.oad_afid = gone_order_after.id LEFT JOIN gone_orders on gone_orders.order_num = gone_order_after.order_num where gone_order_after.category = 3 and ".$where;

            }

//            CommonService::startmysql();
            $paginate = $db->whereRaw($where)->select('order_after.*','orders.order_status')->orderBy('status', 'ASC')->orderBy($orderBy['key'], $orderBy['value'])->paginate($page_size);
            //dump(CommonService::showmysql());
            //导出所需语句
//            $data['aaaa'] = CommonService::showmysql();
            $data['sqls'] = DB::getQueryLog()[1];
            $list = CommonService::dataToArray($paginate->items());
        }
        if($list){
            $list = AftersaleOrderService::jointListData($input,$session,$list,$all_button);//获取列表信息明细说明
            $data['list'] = $list;
            $data['page'] = [
                'count' => $paginate->total(),
                'page'=>$paginate->currentPage(),
                'page_size'=>$page_size,
                'allPage'=>$paginate->lastPage()
            ];
        }else{
            $data['list'] = [];
        }
        return $data;


    }
    /**
     * 获取指定状态所需必要查询条件
     * @param string $status 状态栏参数
     * @param string $day_time 延期时间
     * @return multitype:array
     * @author dou 2021年8月10日
     */
    public static function getStatusWhere ( $status)
    {
        $where = [];
        if($status==2){
            $where['get_id'] = 0;
        }elseif($status == 3){
            $where['look_type'] = 2;
        }else{
            $where['status'] = $status;
        }

        return $where;
    }
    /**
     * 获取操作权限可展示订单状态栏信息
     * @param string $group 操作人权限
     * @param string $admin_pt_id 可操作平台信息
     * @param string $type 是否查询数据量1是
     * @return multitype:array
     * @author dou 2021年8月11日
     */
    public static function getStatusBar ( $group , $admin_pt_id = '' , $type = '2'){
        $showcount = [
            ['show_name' => '全部', 'shownum' => '--', 'status' => 0],
          //  ['show_name' => '待领取', 'shownum' => '--', 'status' => 2],
            ['show_name' => '未处理', 'shownum' => '--', 'status' => 1],
            ['show_name' => '处理中', 'shownum' => '--', 'status' => 10],
           // ['show_name' => '客服介入', 'shownum' => '--', 'status' => 15],
            ['show_name' => '审核中', 'shownum' => '--', 'status' => 30],
           // ['show_name' => '追踪单', 'shownum' => '--', 'status' => 3],
            ['show_name' => '已完成', 'shownum' => "--", 'status' => 40],
          //  ['show_name' => '已撤销', 'shownum' => '--' , 'status' => 50]
        ];

        if( $type == '1'){
            foreach( $showcount as $k => $v ){
                $showcount[$k]['shownum'] = AftersaleOrderService::getStatusNum($v['status'],$admin_pt_id,$group);
            }
        }
        return $showcount;
    }
    /**
     * 获取指定状态售后数量
     * @param string $status 状态栏参数
     * @param string $admin_pt_id 可操作平台信息
     * @param string $session 操作人权限
     * @return multitype:array
     * @author dou 2021年8月11日
     */
    public static function getStatusNum ( $status , $admin_pt_id , $session){
        if(in_array($status,[1,2,10,15,30,50,3])){
            $db = new OrderAfter();
            if(!in_array($session['admin_groupnew'],[7,8])){
                $where['p_id_searchin'] = trim($admin_pt_id);
            }
           // $where['p_id_searchin'] = trim($admin_pt_id);
            if($session['admin_groupnew']!=7){
                $where['company_id'] = $session['company_id'];
            }

            $statuswhere = AftersaleOrderService::getStatusWhere($status);
            foreach( $statuswhere as $k => $v ){
                $where[$k] = $v;
            }
            $num = CommonService::getMysqlData($db,$where,[],[],'count');
            $num = $num??'0';
            return $num;
        }else{
            return '--';
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 拼接列表数据
     * @param string $session 用户信息
     * @param array $input 请求数据
     * @param array $list 订单数据
     * @param array $all_button 按钮信息
     * @retrun multitype:array
     * @author dou 2021/8/11 1:28
     * |---------------------------------------------------------------------------------
    */
    public static function jointListData ( $input , $session , $list  , $all_button ){
        $serId = [];
        foreach ($list as $ke => $ve) {
            $serId[] = $ve['ser_id'];
            $serId[] = $ve['deal_serid'];
            $serId[] = $ve['order_ser_id'];
        }
        $ids = array_column($list, 'id');
        $after_centent = self::getImgContent($ids,['afid']);
        $after_centent = array_column($after_centent, 'afid');
        $serId = array_unique($serId);
        $companyData = AdminsService::getAdmins(['id_searchin'=>$serId],['company_name', 'id']);
        $companyList = CommonService::jointArrayKey($companyData,'id');
        //$orderafter_status_name = OrderService::getOrderStatusName();//获取售后订单状态数组
        $orderafter_status_name = Self::getOrderAfterStatusName();
        $orderafter_type_name = AftersaleOrderService::getOrderAfterTypeName();//获取售后订单类型
        $applyTypeName = self::getAfterAppealType(true);
        $goodpic = PjBrandsService::getAllPic('name');//获取商品品牌图片 放在此处减少循环调取次数

        $p_ids = array_column($list, 'p_id');
        $p_names = Pt::whereIn('id',$p_ids)->pluck('pt_name','id');

        $get_ids = array_column($list, 'get_id');
        $get_ids = array_unique($get_ids);
        $get_names = AdminsService::getAdmins(['id_searchin'=>$get_ids],['admin_acc','id']);
        $get_names = CommonService::jointArrayKey($get_names,'id');

        $rorder_names = RecycleOrderService::getDealType('',1);//获取回收状态
        $afids = array_column($list, 'id');
       // $afitypes = RecycleOrders::whereIn('afid',$afids)->pluck('ro_dealtype','afid')->toarray();

        $send_names = SendGoodsService::getStatusName();//发货状态
        $afsends = SendGoods::whereIn('afid',$afids)->where('source','2')->pluck('type','afid')->toarray();

        $order_status = OrderService::getOrderStatusName(true);
        foreach( $list as $k => $v ) {
            if($v['create_time'] < '2022-01-17') {
                $names = '老系统核实';
            }else{
                $names = '无对应记录';
            }
            if($v['category']<3){
                $names = '无对应记录';
            }
           // $list[$k]['rorder_name'] = $rorder_names[$afitypes[$v['id']]]??$names;//回收状态
            $list[$k]['send_name'] = $send_names[$afsends[$v['id']]]??$names;//补发状态

            $list[$k]['order_status_name'] = $order_status[$v['order_status']];

            $buttonData = [];
            $buttonData[] = 'remarks';//,getImgContent
            if(in_array($v['id'], $after_centent)){
                $list[$k]['imgcontent_type'] = 1;
                $list[$k]['imgcontent'] = '有图文';
            }else{
                $list[$k]['imgcontent_type'] = 2;
                $list[$k]['imgcontent'] = '无图文';
            }
            if($v['status']==1){
                $buttonData[] = 'handle_ive,looktime_sumb';
            }elseif($v['status']==10){
                $buttonData[] = 'quality,looktime_sumb';
            }elseif($v['status']==30){
                $buttonData[] = 'getImgContent,finish_quality,quality_bohuis,lookpics';
            }elseif($v['status']==40){
                $buttonData[] = 'lookpics,getImgContent';
            }
           /* if($v['get_id'] == 0){
                $buttonData[] = 'getId';
            }*/
          /*  if($input['state'] != 2 ) {
                if($v['look_type'] == '2'){
                    $buttonData[] = 'dealAftertrack';
                }
                $buttonData[] = 'sendSmsAfterModel';
                if ($v['status'] == 30) {
                    $buttonData[] = 'quality_bohuis,finish_quality';
                }else {
                    if ($v['status'] == 1) {
                        $buttonData[] = 'quality_complete,quality,handle_ive,AfterReminder';
                    }

                    if ($v['status'] == 10) {
                        $buttonData[] = 'quality_complete,quality,appoint_time,finish_quality';
                        if ($v['category'] == 3) {
                            $buttonData[] = 'handle_ive';
                        }
                    }

                    if ($v['status'] == 15) {
                        $buttonData[] = 'quality,returnHandle,setapplytype';
                    }

                    if ($v['status'] > 10 && $v['status'] < 50) {
                        $buttonData[] = 'lookpics,afterClassify,AfterReminder';
                    }

                    if ($v['category'] == 3 && $v['status'] < 50) {
                        $buttonData[] = 'afterClassify';
                    }

                    if ($v['status'] < 40) {
                        $buttonData[] = 'looktime_sumb';
                    }

                    if ($v['status'] <= 30) {//AfterTransfer
                        $buttonData[] = 'AfterTransfer';
                    }

                    if ($v['status'] <= 10) {//Customer
                        $buttonData[] = 'Customer';
                    }

                    if ($v['status'] == 1 || $v['status'] == 10) {
                        $buttonData[] = 'apply_acc';
                    }

                    if (in_array($v['status'], [1, 10, 30])) {
                        $buttonData[] = 'setapplytype';
                    }
                }
            }*/
            $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'] ?? [];
            if ($v['status'] == 10) {
                if ($v['data_type'] != 0) {
                    if (isset($Lee[$v['data_type']])) {
                        $list[$k]['class_name'] = $Lee[$v['data_type']]['class_name'];
                    }

                } else {
                    $list[$k]['class_name'] = "未设定归类";
                }
            }
            $list[$k]['pt_name'] = $p_names[$v['p_id']];
            $list[$k]['type_name'] = $orderafter_type_name[$v['type']] ?? '未确认';
            $list[$k]['status_name'] = $orderafter_status_name[$v['status']] ?? '未确认';
            $list[$k]['apply_typename'] = $applyTypeName[$v['apply_type']] ?? '未确认';
            /*---------------------------------------获取订单商品明细信息开始----------------------------------------------------------*/
            $orderMsg = OrderService::getOrderMsg($v['sys_num'],$goodpic);
            $list[$k]['orderMsgArr'] = $orderMsg['orderMsgArr'];
            /*---------------------------------------获取订单商品明细信息结束----------------------------------------------------------*/
            $list[$k]['mess'] = [];//备注信息
//            $labs = Aftersale::where('afs_granid',207)->where('afs_order',$v['order_num'])->pluck('afs_type');
//            if (!$labs->isEmpty()){
//                $labs = $labs->toArray();
//                $labs = array_unique($labs);
//                $set_names = SetmoneyType::whereIn('sety_id',$labs)->pluck('sety_name');
//                if (!$set_names->isEmpty()){
//                    $list[$k]['set_names'] = $set_names;
//                }
//            }else{
                $list[$k]['set_names'] = [];
//            }s
            $list[$k]['type'] = 1;
            $poss[$k] = [];
            if($v['deal_serid'] == 0 && $v['order_ser_id'] !=0){
                $list[$k]['company_name'] = $companyList[$v['order_ser_id']]['company_name'] ?? '';
            }else {
                $list[$k]['company_name'] = $companyList[$v['deal_serid']]['company_name'] ?? '';
            }
            if($v['deal_serid'] == 0 && $v['order_ser_id'] !=0){
                $list[$k]['ser_company'] = $companyList[$v['order_ser_id']]['company_name'] ?? '';
            }else {
                $list[$k]['ser_company'] = $companyList[$v['ser_id']]['company_name'] ?? '';
            }

            $list[$k]['get_name'] = $get_names[$v['get_id']]['admin_acc']??'';
            //获取蓄电池使用时间
            if (!empty($v['create_time']) && $v['create_time']!='0000-00-00 00:00:00' && !empty($v['order_time'])){
                $list[$k]['period']=CommonService::computeTime($v['order_time'],$v['create_time']);
            }else{
                $list[$k]['period']='时间异常请手动计算';
            }
            if ($v['ser_id'] != $v['deal_serid']){
                $list[$k]['transfer_color'] = 1;
            }else{
                $list[$k]['transfer_color'] = 2;
            }
            $list[$k]['cd_name'] = CategoryService::getNameByCdId($v['category']);//订单类型 2021-12-31 du add
            //售后时间颜色警示
            $now = strtotime('-1 day',time());
            $even = strtotime($v['create_time']);
            $cha = $now - $even;
            if ($cha<=24*3600){
                $list[$k]['color_type'] = 0;
            }elseif (24*3600<$cha && $cha<=48*3600){
                $list[$k]['color_type'] = 1;//黄色
            }elseif ($cha>48*3600 && $cha<=72*3600){
                $list[$k]['color_type'] = 2;//橙色
            }elseif ($cha>72*3600){
                $list[$k]['color_type'] = 3;//红色
            }

            $list[$k]['down_time'] = date('Y-m-d H:i:s', strtotime("+15 minute",strtotime($v['create_time'])));
        }
        return $list;

    }

    /**|---------------------------------------------------------------------------------
     * @name 售后追踪列表
     * @param array $session 用户信息
     * @param array $input 请求数据
     * @return multitype:array
     * @author dou 2022/6/19 23:46
     * |---------------------------------------------------------------------------------
    */
    public static function searchAftertrack ( $input , $session ){
        $db = new OrderAftertrack();
        $where = [];
        if(in_array($input['state'], [1,2,3])){
            $where['oat_state'] = $input['state'];
        }
        if (isset($input['oat_afnum'])){//售后单号
            $where['oat_afnum'] = $input['oat_afnum'];
        }
        if (isset($input['oat_ordernum'])){//订单单号
            $where['oat_ordernum'] = $input['oat_ordernum'];
        }
        $page_size = $input['page_size']??10;
        if($where){
            $where = CommonService::jointWhere($where);
            $db = $db->whereRaw($where);
        }
        $paginate = $db ->paginate($page_size);
        $wcl = OrderAftertrack::where('oat_state',1)->count();
        $data['show_Menu'] = [
            ['show_name'=>"全部",'status'=>'0','show_num'=>'--'],
            ['show_name'=>"未处理",'status'=>'1','show_num'=>$wcl??0],
            ['show_name'=>"已替换",'status'=>'2','show_num'=>'--'],
            ['show_name'=>"已处理",'status'=>'3','show_num'=>'--']
        ];
        $all_button = BmmcService::whereButton($input['token'],$input['Pri_id']);
        $data['button_top'] = [];//顶部按钮
        $data['button_search'] = [];//搜索栏按钮
        $list = CommonService::dataToArray($paginate->items());
        if($list){
            $list = self::getAftertrackButtonDatas($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;
    }

    /**|---------------------------------------------------------------------------------
     * @name 拼接追踪数据列表
     * @param string $session 用户信息
     * @param array $input 请求数据
     * @param array $list 订单数据
     * @param array $all_button 按钮信息
     * @retrun /multitype:array
     * @author dou 2022/6/20 10:25
     * |---------------------------------------------------------------------------------
    */
    public static function getAftertrackButtonDatas ( $all_button , $list ){
        $oatStateName = self::getOatStateName(true);
        foreach($list as $k => $v){
            $button = [];
            $list[$k]['oatStateName'] = $oatStateName[$v['oat_state']]??'未设定';
            if($v['oat_state'] == '1'){
                $button[] = 'dealAftertrack';
            }
            $button = BmmcService::getListButton($button,$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;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取追踪时间状态
     * @param string $type 订单单号
     * @retrun /multitype:array
     * @author dou 2022/6/20 10:33
     * |---------------------------------------------------------------------------------
    */
    public static function getOatStateName ( $type = false ){
        $data = [['type'=>1,'name'=>'未处理'],['type'=>2,'name'=>'已替换'],['type'=>3,'name'=>'已处理']];
        if($type){
            $data = array_column($data, 'name', 'type');
        }
        return $data;
    }
    /**
     * 获取售后单状态名
     * @return multitype:array
     * @author dou 2021年8月11日
     */
    public static function getOrderAfterStatusName()
    {
        $data = array("1"=>'未处理','10'=>'处理中','15'=>'客服介入','30'=>'审核中','40'=>'已完成','50'=>'已撤销');
        return $data;
    }
    /**
     * 获取售后单状态名
     * @return multitype:array
     * @author dou 2021年8月11日
     */
    public static function getOrderAfterTypeName()
    {
        $data = array("1"=>'安装前售后','2'=>'安装后售后');
        return $data;
    }
     /**
     * 获取售后单信息
     * @param array $params 请求参数
     * @param string $key 返回键
     * @param array $select 返回键
     * @param string $type 返回键
     * @return multitype:array
     * @author dou 2021年8月5日
     */
    public static function getAfterData ( $params , $key = '' , $select = [] , $type = ''){
	    $db = new OrderAfter();
	    $data = CommonService::getMysqlData($db,$params,$select,['id'=>'ASC']);
	    if($key){
	    	if(!$type){
	    		if($key == 'id'){
	    			$type = 1;
	    		}else{
	    			$type = 2;
	    		}
	    	}
	    	$data = CommonService::jointArrayKey($data, $key , $type);
	    }
	    return $data;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取售后申诉类型
     * @retrun multitype:array
     * @author dou 2021/8/7 14:23
     * |---------------------------------------------------------------------------------
     */
    public static function getAfterAppealType ( $type = false ){
        $applyType = [['type'=>'1','name'=>'未分类'],['type'=>'2','name'=>'工商投诉'],['type'=>'3','name'=>'纠纷单'],['type'=>'4','name'=>'投诉单'],['type'=>'5','name'=>'赔偿单']];
        if($type){
            $applyType = array_column($applyType, 'name', 'type');
        }
        return $applyType;
    }


    /**|------------------------------------------------------------------
     * @name 获取申请售后的必要参数
     * @param string $sys_num 系统单号
     * @param string $order_num 订单单号
     * @return multitype:array
     * |-------------------------------------------------------------------
     */
    public static function pgNumber ($sys_num = '' , $order_num = '')
    {
        if(!$sys_num && !$order_num){
            return false;
        }else {
            if ($sys_num) {
                $order = OrderService::getOrderBy('sys_num',$sys_num);//获取订单信息
                $res = OrderListService::getOrderListBy('sys_num',$sys_num,'first')['serial_number'];//获取工单号
            } elseif ($order_num) {
                $order = OrderService::getOrderBy('order_num',$order_num);//获取订单信息
                $res = OrderListService::getOrderListBy('order_num',$sys_num,'first')['serial_number'];//获取工单号
            }
            if($order) {
                if($order['category'] == 3){
                    $data['derail'] = self::getDerail();
                }else{
                    $data['derail'] = [];
                }
                if($order['category'] == 3){
                    $data['installState'] = self::getInstallState();
                }else{
                    $data['installState'] = [];
                }
                $data['id'] = $order['id'] ?? '';//获取订单id
                $data['serial_number'] = $res ?? '';
                $data['type'] = self::getAfterAppealType();
                $data['time'] = CommonService::computeTime($order['create_time']);
                $data['category'] = $order['category'];
                return  $data;
            }else{
                return false;
            }
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取售后位置信息
     * @retrun /multitype:array
     * @author dou 2021/11/4 19:59
     * |---------------------------------------------------------------------------------
    */
     public static function getDerail ( $type = false ){
         $derail = array(array('type'=>2,'name'=>'前挡','check'=>2),array('type'=>3,'name'=>'侧挡','check'=>2),array('type'=>4,'name'=>'后挡','check'=>2),array('type'=>1,'name'=>'车损','check'=>1));
         if($type){
             $derail = CommonService::jointArrayKey($derail, 'type');
         }
         return $derail;
     }

    /**|---------------------------------------------------------------------------------
     * @name 获取安装状态
     * @retrun /multitype:array
     * @author dou 2021/11/4 19:59
     * |---------------------------------------------------------------------------------
     */
    public static function getInstallState ( $type = false ){
        $installState = array(array('type'=>1,'name'=>'未贴装'),array('type'=>2,'name'=>'已贴装'));
        if($type){
            $installState = CommonService::jointArrayKey($installState, 'type');
        }
        return $installState;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取车膜售后处理类型
     * @retrun /multitype:array
     * @author dou 2021/11/5 17:34
     * |---------------------------------------------------------------------------------
    */
    public static function getDealState ( $type = false ){
        $dealState = array(array('type'=>1,'name'=>'礼品'),array('type'=>2,'name'=>'回收'),array('type'=>3,'name'=>'补发'),array('type'=>4,'name'=>'退款'));
        if($type){
            $dealState = CommonService::jointArrayKey($dealState, 'type');
        }
        return $dealState;
    }

    /**|---------------------------------------------------------------------------------
     * @name 添加售后
     * @param string $input 申请售后需提交信息
     * @param array $session 操作用户信息
     * @retrun multitype:array
     * @author dou 2021/8/7 16:33
     * |---------------------------------------------------------------------------------
     */
    public static function addAfter ( $input , $session , $ip){
        $checkKey=CommonService::checkKey(['id'],$input,AftersaleOrderService::rules());
        if($checkKey['code']!=1){
            $return['code'] = false;
            $return['msg'] = '参数'.$checkKey['data'].'未填写,或值为空';
            $return['data'] = ErrorInc::INVALID_PARAM;
            return $return;
        }
        $sys_num = $input['sys_num'];
//        DB::beginTransaction();
        $serial_number = $input['serial_number']??"";
        $id = $input['id'];
        $labs = $input['labs']??[];//标签数组
        $labe = 207;//祖父类id
        $orderArr = OrderService::getOrderBy('id',$id);
        if(!$orderArr){
//            DB::rollBack();
            $return['code'] = false;
            $return['msg'] = '申请失败4';
            $return['data'] = ErrorInc::DATA_EMPTY;
        }else {
            if($orderArr['category'] != 3){
                $checkKey=CommonService::checkKey(['content','labs'],$input,AftersaleOrderService::rules());
                if($checkKey['code']!=1){
//                    DB::rollBack();
                    $return['code'] = false;
                    $return['msg'] = '参数'.$checkKey['data'].'未填写,或值为空';
                    $return['data'] = ErrorInc::INVALID_PARAM;
                    return $return;
                }
            }else{
                if(!$input['after_derail'] || !is_array($input['after_derail'])){
//                    DB::rollBack();
                    $return['code'] = false;
                    $return['msg'] = '车膜售后详情格式错误或不存在';
                    $return['data'] = ErrorInc::INVALID_PARAM;
                    return $return;
                }
            }
            if($input['content']) {
                $content = $input['content'];
                $rest = CommonService::accMe($orderArr['sys_num'], "订单管理", '【售后】' . $content, '', '', $session['admin_groupnew'], $session['admin_acc'], $session['id']);
            }else{
                $rest = true;
            }
            if($rest) {
                if (!empty($input['serial_number'])) {
                    $orderInfo = OrderListService::getOrderListBy('serial_number', $serial_number, 'first');
                } else {
                    $orderInfo = OrderListService::getOrderListBy('sys_num', $orderArr['sys_num'], 'first');
                }
                $data['serserial_number']=$orderInfo['serial_number']??'';
                $data['order_num']=$orderArr['order_num'];
                $data['sys_num']=$orderArr['sys_num'];
                /*--------------------------------------判定是否有符合当前订单对应门店未完成的售后服务单-开始-------------------------------*/
                $after = new OrderAfter();
                $afterdata = CommonService::getMysqlData($after, ['sys_num' => $orderArr['sys_num'], 'ser_id' => $orderArr['ser_id'], 'status_searchlt' => '40'], ['status', 'id','after_num'], [], 'first');
                if ($afterdata && $orderArr['category'] != 3) {
                    if ($afterdata['status'] > 1) {
                        $rea = OrderAfter::where('id', $afterdata['id'])->update(['status' => '1']);
                    } else {
                        $rea = 1;
                    }
                    if (isset($input['pic']) && $input['pic'] != []) {
                        self::addPic(1000, $input, $afterdata['id'], $session);
                    }
                    if ($rest && $rea) {
//
                        $return['code'] = true;
                        $return['msg'] = '申请成功';
                        $return['data'] = $data;
                    } else {
//                        DB::rollBack();
                        $return['code'] = false;
                        $return['msg'] = '申请失败4';
                        $return['data'] = ErrorInc::MYSQL_FAILED;
                    }
                } /*--------------------------------------判定是否有符合当前订单对应门店未完成的售后服务单-结束----------------------------*/
                else {
                    if ($orderInfo) {
                        $install_id = $orderInfo['install_id'];
                        $goods_name = OrderMsg::where('id', $orderInfo['order_goods_id'])->value('goods_name');

                    } else {
                        $install_id = 0;
                        $order_goods_id = OrderMsg::where('sys_num', $orderArr['sys_num'])->value('id');
                        $goods_name = OrderMsg::where('sys_num', $orderArr['sys_num'])->value('goods_name');
                        $orderInfo = ['order_goods_id' => $order_goods_id, 'serial_number' => "无", 'order_num' => $orderArr['order_num'], 'install_id' => 0];
                    }
                    $input['sys_num'] = $orderArr['sys_num'];//系统单号
                    /*---------------------------------------添加售后数据开始------------------------------------------*/
                    $post['good_names'] = $goods_name;//商品名称
                    $post['msg_id'] = $orderInfo['order_goods_id'];//对应商品详情id
                    $post['order_num'] = $orderArr['order_num'];//平台单号
                    $post['sys_num'] = $orderArr['sys_num'];//系统单号
                    $post['serial_number'] = $orderInfo['serial_number']??"";//工单号
                    $post['after_num'] = $number = 'SH' . date("YmdHis") . str_pad(rand(0, 999), 3, '0', STR_PAD_LEFT);
                    if ($orderArr['order_status'] < 40) {
                        $post['type'] = '1';//安装前售后
                    } else {
                        $post['type'] = '2';//安装后售后
                    }
                    $user = CommonService::getUser('id', $orderArr['new_customer_id']);
                    $post['shr_id'] = $user['id'];
                    $post['shr_name'] = $user['shr_name'];
                    $post['shr_phone'] = $user['shr_phone'];
                    $post['shr_sheng'] = $user['shr_sheng'];
                    $post['shr_shi'] = $user['shr_shi'];
                    $post['shr_xian'] = $user['shr_xian'];
                    $post['shr_address'] = $user['shr_adress'];
                    $post['p_id'] = $orderArr['p_id'];
                    $post['ser_id'] = $orderArr['ser_id'];
                    $post['deal_serid'] = $orderArr['ser_id'];
                    $post['deal_admin'] = $session['admin_acc'];
                    $post['creatym'] = date("Y-m-d");
                    $post['create_time'] = date("Y-m-d H:i:s");
                    $post['install_id'] = $orderInfo['install_id'];
                    $post['order_time'] = $orderArr['order_time'];
                    $post['apply_type'] = $input['apply_type']??1;
                    $post['category'] = $orderArr['category'];
                    if (isset($input['pic']) && ($input['pic'] != []) || isset($input['sound'])) {//有图片、音频
                        $post['datatype'] = 2;
                    } else {
                        $post['datatype'] = 1;
                    }
                    $exts = OrderAfter::where('order_num', $orderArr['order_num'])->where('status', 40)->count();
                    if($exts) {
                        $after_type = $exts + 1;
                    }else{
                        $after_type = 1;
                    }
                    if($orderArr['category'] < 3) {
                        $post['get_id'] = 1133;
                        $post['get_time'] = date("Y-m-d H:i:s");
                    }
                    $post['after_type'] = $after_type;
                    $post['company_id'] = $session['company_id'];
                    $post['agency_id']=$orderInfo['agency_id']??'0';
                    $rea = OrderAfter::insertGetId($post);
                    /*---------------------------------------添加售后数据结束------------------------------------------*/
                    if($rea){
                        //存图文
                        if($input['img_content']){
                            $icarr['afid'] = $rea;
                            $icarr['update_name'] = $session['admin_acc'];
                            $icarr['content'] = $input['img_content'];
                            $icarr['create_time'] = date("Y-m-d H:i:s");
                            $icarr['create_name'] = $session['admin_acc'];
                            $icarr['update_time'] = date("Y-m-d H:i:s");
                            DB::table('order_after_content')->insert($icarr);
                        }

                        if($orderArr['category'] == 3){
                            $child = self::addSolarFilmDetail($input, $rea, $session, $post['after_num'], $ip);
                            if($child['code']){
                                $labs = $child['data'];
                            }else{
//                                DB::rollBack();
                                return $child;
                            }
                        }else {
                            if ($orderInfo) {
                                $slid = SettlementService::getSettlementListBy('list_id', $orderInfo['serial_number'], ['id']);
                            } else {
                                $slid = '0';
                            }
                            /*------------------------------------------------验证并添加图片信息开始--------------------------------------*/
                            if (isset($input['pic']) && $input['pic'] != []) {
                                self::addPic(1000, $input, $rea, $session);
                            }
                            /*------------------------------------------------验证并添加图片信息结束--------------------------------------*/

                            /*------------------------------------------------验证并添加音频信息开始--------------------------------------*/
                            if (isset($input['sound'])) {
                                self::addPic(1001, $input, $rea, $session);
                            }
                            /*------------------------------------------------验证并添加音频信息结束--------------------------------------*/

                        }
                        /*----------------------------------------填写标签开始----------------------------------------------*/
//                        foreach ($labs as $k => $v) {
//                            if ($v['sublevel']) {
//                                foreach ($v['sublevel'] as $kk => $vv) {
//                                    $subs .= $v['sety_id'] . '-' . $vv;
//                                    $subs .= ',';
//                                }
//                            } else {
//                                $subs .= $v['sety_id'] . '-' . $v['sety_id'];
//                                $subs .= ',';
//                            }
//                        }
//                        $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`) VALUES ';
//                        $labs = explode(',', trim($subs, ','));
//                        $serial_number = $orderInfo['serial_number']??'';
//                        foreach ($labs as $key => $val) {
//                            $arr = explode('-', $val);
//                            $lable = LabtypeService::labelList();
//                            $lable = CommonService::jointArrayKey($lable, 'sety_id');
//                            $labstate = $lable[$arr[1]];
//                            $sqls[] = "('" . $labstate['lt_type'] . "','" . $orderArr['order_num'] . "','" . $serial_number . "','2','207','208','" . $arr[1] . "','" . $orderArr['p_id'] . "','" . $orderArr['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'] . "')";
//                        }
//                        $sql = $sql.implode(',', $sqls);
//                        $sle = DB::insert($sql);
                        $orderinfo['order_num'] = $orderArr['order_num'];
                        $orderinfo['serial_number'] = $orderInfo['serial_number']??'';
                        $orderinfo['p_id'] = $orderArr['p_id'];
                        $orderinfo['ser_id'] = $orderArr['ser_id'];
                        $sle = AfterSaleService::insertData($labs, $orderinfo, $session, $content);
                        /*----------------------------------------填写标签结束----------------------------------------------*/
                        if (!$sle) {
//                            DB::rollBack();
                            $return['code'] = false;
                            $return['msg'] = '申请失败5';
                            $return['data'] = ErrorInc::MYSQL_FAILED;
                        }else{
//                            DB::commit();
                            if($orderArr['ser_id'] > 0) {
                                $serid = Admin::whereRaw("FIND_IN_SET(" . $orderArr['ser_id'] . ",children_id)")->value('id');
                                if (!empty($serid)) {
                                    $weixin['ser_id'] = $serid;
                                } else {
                                    $weixin['ser_id'] = $orderArr['ser_id'];
                                }
                                $weixin['shr_name'] = $user['shr_name'];
                                $weixin['shr_phone'] = $user['shr_phone'];
                                $weixin['order_num'] = $orderArr['order_num'] ?? '';
                                $weixin['centent'] = $content;
                                $weixin['serial_number'] = $orderArr['serial_number'] ?? '';
                                CommonService::requestPost('http://weixin.sudianwang.com/index.php/BindingAccount/afterPush', $weixin);
                            }
                            $return['code'] = true;
                            $return['msg'] = '申请成功';
                            $return['data'] = $data;
                        }
                    }else{
//                        DB::rollBack();
                        $return['code'] = false;
                        $return['msg'] = '申请失败3';
                        $return['data'] = ErrorInc::MYSQL_FAILED;
                    }
                }
            }else{
//                DB::rollBack();
                $return['code'] = false;
                $return['msg'] = '备注添加失败';
                $return['data'] = ErrorInc::MYSQL_FAILED;
            }
        }
        return $return;
    }

    /**|---------------------------------------------------------------------------------
     * @name 添加车膜售后详情
     * @param string ju_ordernum 订单单号
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2021/11/3 19:50
     * |---------------------------------------------------------------------------------
    */
     public static function addSolarFilmDetail( $input , $rea , $session , $after_num , $ip ){
         $after_derail = $input['after_derail'];
         $subs = '';
         $BaseController = new BaseController();
         $avtion = FunctionsService::getFunctionsBy('function_id', $input['Pri_id'], ['function_name']);
         foreach($after_derail as $k => $v){
            $detail[$k]['oad_afid'] = $rea;
            $detail[$k]['oad_partid'] = $v['partid'];
            $detail[$k]['oad_partname'] = $v['partname'];
            $detail[$k]['oad_installstate'] = $v['installstate'];
            $detail[$k]['oad_type'] = $v['type'];
            $detail[$k]['oad_typepid'] = $v['typepid'];
            $detail[$k]['oad_applycontent'] = $v['content'];
            $detail[$k]['oad_creactime'] = date("Y-m-d H:i:s");
            $detail[$k]['after_num'] = $after_num;
            $lable[$k]['sety_id'] = $v['typepid'];
            if(isset($v['type']) && $v['type']!='') {
                $lable[$k]['sublevel'][] = $v['type'];
            }
            $childid = OrderAfterDetai::insertGetId($detail[$k]);
            if($childid){
                if($v['content']) {
                    CommonService::accMe($input['sys_num'], '添加售后', '【售后】'.$v['partname'].':'.$v['content'], $after_num, '1', $session['admin_groupnew'], $session['admin_acc'], $session['id']);
                }
                $BaseController->insertingLog('添加售后', $input['sys_num'], '添加售后（'.$after_num.'）,部位：'.$v['partname'].'('.$v['type'].')', $avtion, $ip, $session['admin_acc']);
                unset($detail[$k]);
                if (isset($v['pic']) && $v['pic'] != []) {
                    self::addPic(1000, $v, $rea, $session ,$childid );
                }
            }else{
                $return['code'] = false;
                $return['msg'] = '详情添加失败';
                $return['data'] = ErrorInc::MYSQL_FAILED;
                return $return;
            }
         }
         $return['code'] = true;
         $return['msg'] = '操作成功';
         $return['data'] = $lable;
         return $return;
     }

     /**|---------------------------------------------------------------------------------
      * @name 处理车膜售后
      * @param string ju_ordernum 订单单号
      * @retrun /multitype:array
      * @author dou 2021/11/4 20:51
      * |---------------------------------------------------------------------------------
      * @noinspection DuplicatedCode
      */
    public static function dealSolarFilmDetail( $input , $session , $ip ){
        $after_derail = $input['after_derail'];
        $subs = '';
        $num = 0;
        $lable = [];
        $BaseController = new BaseController();
        $avtion = FunctionsService::getFunctionsBy('function_id', $input['Pri_id'], ['function_name']);
        foreach($after_derail as $k => $v){
            if($v['id']!=''){
                $detail[$k]['oad_partid'] = $v['partid'];
                $detail[$k]['oad_partname'] = $v['partname'];
                $detail[$k]['oad_installstate'] = $v['installstate'];
                $detail[$k]['oad_type'] = $v['type'];
                $detail[$k]['oad_typepid'] = $v['typepid'];
                $detail[$k]['oad_applycontent'] = $v['content'];
                $detail[$k]['oad_creactime'] = date("Y-m-d H:i:s");
                if($v['dealtype']){
                    $lable[$num] = $v['dealtype'][0];
                    $num ++ ;
                    $detail[$k]['oad_dealptype'] = $v['dealtype'][0]['sety_id'];
                    $detail[$k]['oad_dealtype'] = $v['dealtype'][0]['sublevel'][0];
                }
//                if(is_array($v['dealtype'])){
//                    $detail[$k]['oad_dealtype'] = implode(',',$v['dealtype']);
//                }else {
//                    $detail[$k]['oad_dealtype'] = $v['dealtype'];
//                }
                $detail[$k]['oad_recycle'] = $v['recycle'];
                $detail[$k]['oad_dealcontent'] = $v['dealcontent'];
                $detail[$k]['oad_dealer'] = $session['admin_acc'];
                $detail[$k]['oad_dealid'] = $session['id'];
                $detail[$k]['oad_dealtime'] = date("Y-m-d H:i:s");
                $detail[$k]['oad_state'] = 10;
                if(!$v['dealtype']){
                    $childid = true;
                }else {
                    $childid = OrderAfterDetai::where('oad_id', $v['id'])->update($detail[$k]);
                }
                if (!$childid) {
                    unset($detail[$k]);
                    $return['code'] = false;
                    $return['msg'] = '详情处理失败';
                    $return['data'] = ErrorInc::MYSQL_FAILED;
                    return $return;
                }else{
                    if (isset($v['pic']) && $v['pic'] != []) {
                        self::addPic(1000, $v, $input['after_id'], $session, $v['id']);
                    }
                    if($v['dealtype'] !='') {
                        $BaseController->insertingLog('处理售后', $input['sys_num'], '处理售后（' . $input['after_num'] . '）,部位：' . $v['partname'] . '(' . $v['type'] . '-' . $detail[$k]['oad_dealtype'] . ')', $avtion, $ip, $session['admin_acc']);
                    }
                }
            }else {
                $lable[$num]['sety_id'] = $v['typepid'];
                $lable[$num]['sublevel'][] = $v['type'];
                $num++;
                $detail[$k]['oad_afid'] = $input['after_id'];
                $detail[$k]['oad_partid'] = $v['partid'];
                $detail[$k]['oad_partname'] = $v['partname'];
                $detail[$k]['oad_installstate'] = $v['installstate'];
                $detail[$k]['oad_type'] = $v['type'];
                $detail[$k]['oad_typepid'] = $v['typepid'];
                $detail[$k]['oad_applycontent'] = $v['content'];
                $detail[$k]['after_num'] = $input['after_num'];
                $detail[$k]['oad_creactime'] = date("Y-m-d H:i:s");
                if(!$v['dealtype']){
                    $detail[$k]['oad_state'] = 1;
                }else {
                    if($v['dealtype']){
                        $lable[$num] = $v['dealtype'][0];
                        $num ++ ;
                        $detail[$k]['oad_dealptype'] = $v['dealtype'][0]['sety_id'];
                        $detail[$k]['oad_dealtype'] = $v['dealtype'][0]['sublevel'][0];
                    }else{
                        $detail[$k]['oad_dealptype'] = '';
                        $detail[$k]['oad_dealtype'] = '';
                    }
                    $detail[$k]['oad_recycle'] = $v['recycle'];
                    $detail[$k]['oad_dealcontent'] = $v['dealcontent'];
                    $detail[$k]['oad_dealer'] = $session['admin_acc'];
                    $detail[$k]['oad_dealid'] = $session['id'];
                    $detail[$k]['oad_dealtime'] = date("Y-m-d H:i:s");
                    $detail[$k]['oad_state'] = 10;
                }
                $subs .= $v['typepid'] . '-' . $v['type'];
                $subs .= ',';
                $childid = OrderAfterDetai::insertGetId($detail[$k]);
                if ($childid) {
                    if($v['content']) {
                        CommonService::accMe($input['sys_num'], '添加售后', '【售后】'.$v['partname'].':'.$v['content'], $input['after_num'], '1', $session['admin_groupnew'], $session['admin_acc'], $session['id']);
                    }
                    $BaseController->insertingLog('添加售后', $input['sys_num'], '添加售后（'.$input['after_num'].'）,部位：'.$v['partname'].'('.$v['type'].'-'.$detail[$k]['oad_dealtype'].')', $avtion, $ip, $session['admin_acc']);
                    unset($detail[$k]);
                    if (isset($v['pic']) && $v['pic'] != []) {
                        self::addPic(1000, $v, $input['after_id'], $session, $childid);
                    }
                } else {
                    $return['code'] = false;
                    $return['msg'] = '详情添加失败';
                    $return['data'] = ErrorInc::MYSQL_FAILED;
                    return $return;
                }
            }
            if($v['dealcontent']) {
                CommonService::accMe($input['sys_num'], '处理售后', '【售后】'.$v['dealcontent'], $input['after_num'], '1', $session['admin_groupnew'], $session['admin_acc'], $session['id']);
            }
        }
        $return['code'] = true;
        $return['msg'] = '操作成功';
        $return['data'] = $lable;
        return $return;
    }

    /**|---------------------------------------------------------------------------------
     * @name 添加售后图片
     * @param string ju_ordernum 订单单号
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2021/11/3 19:20
     * |---------------------------------------------------------------------------------
     * @noinspection DuplicatedCode
     */
     public static function addPic ( $type , $input , $rea , $session , $child_id = 0 )
     {
         $poss_pic['type'] = $type;
         $poss_pic['gl_id'] = $rea;
         $poss_pic['install_name'] = 1;
         $poss_pic['install_phone'] = 1;
         $poss_pic['install_remark'] = $input['content'];
         $poss_pic['install_time'] = date("Y-m-d H:i:s");
         $poss_pic['admin_id'] = $session['id'];
         $poss_pic['company_name'] = 1;
         $poss_pic['feedback_status'] = 1;
         $poss_pic['sys_num'] = "rwfk" . $rea;
         $poss_pic['child_id'] = $child_id;
         if ($type == 1000) {
             foreach ($input['pic'] as $k => $v) {
                 $poss_pic['feedback_pic'] = $v;
                 FeedSales::insert($poss_pic);
             }
         }if ($type == 1001) {
            $poss_pic['feedback_pic'] = $input['sound'];
            FeedSales::insert($poss_pic);
         }
     }

    /**|---------------------------------------------------------------------------------
     * @name 获取订单详情
     * @param string $order_num 订单单号
     * @retrun /multitype:array
     * @author dou 2021/9/24 19:16
     * |---------------------------------------------------------------------------------
     */
    public static function getDetailByOrder ( $order_num ){
        $list = Self::getAfterData(['order_num'=>$order_num]);
        if($list) {
            $serId = [];
            foreach ($list as $ke => $ve) {
                $serId[] = $ve['ser_id'];
                $serId[] = $ve['deal_serid'];
            }
            $serId = array_unique($serId);
            $companyData = AdminsService::getAdmins(['id_searchin' => $serId], ['company_name', 'id']);
            $companyList = CommonService::jointArrayKey($companyData, 'id');
            //$orderafter_status_name = OrderService::getOrderStatusName();//获取售后订单状态数组
            $orderafter_status_name = Self::getOrderAfterStatusName();
            $orderafter_type_name = AftersaleOrderService::getOrderAfterTypeName();//获取售后订单类型
            $goodpic = PjBrandsService::getAllPic('name');//获取商品品牌图片 放在此处减少循环调取次数

            $p_ids = array_column($list, 'p_id');
            $p_names = Pt::whereIn('id', $p_ids)->pluck('pt_name', 'id');
            $db = new Aftersale();
            $fs_order[] = $order_num;
            $labs = CommonService::getMysqlData($db, ['afs_granid_searchin'=>[207,208,209],'afs_order_searchin'=>$fs_order],['afs_type']);//获取订单添加的售后类型标签
            $set_names = [];
            if($labs){
                $sety_id = array_column($labs, 'afs_type');
                $after_lable = LabtypeService::labelList();
                $after_lable = CommonService::arrayFilterFieldValue($after_lable, array(array('sety_id' => $sety_id)));
                if($after_lable) {
                    $after_lable = CommonService::jointArrayKey($after_lable, 'sety_id');
                    foreach($sety_id as $k => $v){
                        $set_names[] = $after_lable[$v]['sety_name'];
                    }
                }
            }
            foreach ($list as $k => $v) {
                $list[$k]['pic'] = AftersaleOrderService::lookpics($v['id']);
                if ($v['status'] == 10) {
                    if ($v['data_type'] != 0) {
                        if (isset($Lee[$v['data_type']])) {
                            $list[$k]['class_name'] = $Lee[$v['data_type']]['class_name'];
                        }

                    } else {
                        $list[$k]['class_name'] = "未设定归类";
                    }
                }
                $list[$k]['pt_name'] = $p_names[$v['p_id']];
                $list[$k]['type_name'] = $orderafter_type_name[$v['type']] ?? '未确认';
                $list[$k]['status_name'] = $orderafter_status_name[$v['status']] ?? '未确认';
                /*---------------------------------------获取订单商品明细信息开始----------------------------------------------------------*/
                $orderMsg = OrderService::getOrderMsg($v['sys_num'], $goodpic);
                $list[$k]['orderMsgArr'] = $orderMsg['orderMsgArr'];
                /*---------------------------------------获取订单商品明细信息结束----------------------------------------------------------*/
                //            }s
                $list[$k]['type'] = 1;
                $list[$k]['company_name'] = $companyList[$v['deal_serid']]['company_name'] ?? '';
                $list[$k]['ser_company'] = $companyList[$v['ser_id']]['company_name'] ?? '';
                //获取蓄电池使用时间
                if (!empty($v['create_time']) && $v['create_time'] != '0000-00-00 00:00:00' && !empty($v['order_time'])) {
                    $list[$k]['period'] = CommonService::computeTime($v['order_time'], $v['create_time']);
                } else {
                    $list[$k]['period'] = '时间异常请手动计算';
                }
                if ($v['ser_id'] != $v['deal_serid']) {
                    $list[$k]['transfer_color'] = 1;
                } else {
                    $list[$k]['transfer_color'] = 2;
                }
                $list[$k]['set_names'] = $set_names;
                //售后时间颜色警示
                $now = strtotime('-1 day', time());
                $even = strtotime($v['create_time']);
                $cha = $now - $even;
                if ($cha <= 24 * 3600) {
                    $list[$k]['color_type'] = 0;
                } elseif (24 * 3600 < $cha && $cha <= 48 * 3600) {
                    $list[$k]['color_type'] = 1;//黄色
                } elseif ($cha > 48 * 3600 && $cha <= 72 * 3600) {
                    $list[$k]['color_type'] = 2;//橙色
                } elseif ($cha > 72 * 3600) {
                    $list[$k]['color_type'] = 3;//红色
                }
                $list[$k]['down_time'] = date('Y-m-d H:i:s', strtotime("+15 minute", strtotime($v['create_time'])));
            }
        }
        return $list;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取反馈图片
     * @param int/array $gl_id 售后单id
     * @retrun /multitype:array
     * @author dou 2021/9/28 18:23
     * |---------------------------------------------------------------------------------
    */
    public static function lookpics ( $gl_id ){
        $db = new FeedSales();
        if(is_array($gl_id)){
            $list = CommonService::getMysqlData($db, ['gl_id_searchin' => $gl_id], ['feedback_pic','gl_id','child_id','type']);
        }else {
            $type1['type'] =  1000;
            $type2['type'] =  10;
            $type['type1_next_level'] = $type1;
            $type['type2_next_level'] = $type2;
            $list = CommonService::getMysqlData($db, ['gl_id' => $gl_id], ['feedback_pic','gl_id','child_id','type']);
        }
        if($list){
            $BaseController = new BaseController();
            foreach ($list as $k=>$v){
                if ($v['feedback_pic']){
                    $list[$k]['feedback_pic'] = $BaseController->picurl($v['feedback_pic']);
                }
            }
        }
        return $list;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取图文
     * @param int $afid 售后数据id
     * @retrun /multitype:array
     * @author dou 2022/6/22 14:08
     * |---------------------------------------------------------------------------------
    */
     public static function getImgContent ( $afid, $select = [] , $tyep = 'get' ){
         $db = DB::table('order_after_content');
         if(is_array($afid)){
             $where['afid_searchin'] = $afid;
         }else{
             $where['afid'] = $afid;
             $tyep = 'first';
         }
         $list = CommonService::getMysqlData( $db , $where , $select , [] , $tyep );
         return $list;
     }
}
