<?php
namespace App\Http\Controllers\Financial;
use App\Http\Controllers\BaseController;

use App\Http\Controllers\Common\CommonController;
use App\Http\Controllers\Orders\RefundController;
use App\Models\OrderList;
use App\Models\OrderMsg;
use App\Models\Refund;
use App\Models\SettlementList;
use App\Models\SettlementMoney;
use App\Services\CommonService;
use App\Services\OrderService;
use App\Services\RefundService;
use App\Services\SettlementService;
use App\Services\SubmitPleaseService;
use BlueCity\Core\Inc\ErrorInc;
use Illuminate\Http\Request;
use App\Models\SubmitPlease;
use DB;
use \Exception;
use App\Models\Orders;
use App\Models\Note;
use Excel;

class SubmitPleaseController extends BaseController
{


    /**
     * @name 申请退/收列表
     * @param type 类型: 0:全部;1:财务; 2:服务; 3:已完结 4:红包
     * @param sys_num 系统单号
     * @param order_num 平台单号
     * @param goods_name 商品名称
     * @param user_name 经手人
     * @param pt_id 申请平台
     * @param submit_state 申请类型 1:抹零; 2:平台; 3:服务;4:财务,5:红包
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|mixed
     * @author du
     * @date 2021/9/16
     */
    public function index(Request $request)
    {
        $input = $request->all();
        $list = SubmitPleaseService::getList($input,$request->get('session_token'));

        //导出 start
        if ($input['is_excel'] == 1) {
            if(isset($list['ErrorCode'])){
                return $list;exit;
            }
           $session = $request->get('session_token');
            $sqls = $list['sqls'];
            //dd($sqls);
            $excel = new CommonController();
            return $excel->getExcelOut($input['Pri_id'], $sqls, $session);
        }
        unset($list['sqls']);
        //导出 end

        if($list['list']){
            return $this->success('获取成功', $list); exit;
        }else{
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY,$list);exit;
        }
    }


    /**
     * @name  驳回
     * @param id 数据id
     * @param type 1:获取备注数据; 2:执行驳回
     * @param content 备注内容(type=2)
     * @param Request $request
     * @return array|\Illuminate\Http\JsonResponse|int[]|mixed
     * @author du
     * @date 2021/9/17
     */
    public function addReject (Request $request)
    {
        if(!$request->filled('id')){
            return $this->error('参数错误无ID', ErrorInc::FAILED_PARAM);exit;
        }
        $type = (int)$request->input('type',1);
        $id = (int)$request->input('id',0);
        $session = $request->get('session_token');
        $arr = SubmitPlease::where('submit_please.id',$id)->leftjoin('orders','sys_num','=','submit_sys_num')->selectRaw("msg_id,submit_sys_num as sys_num,gone_submit_please.goods_name,order_num,submit_service,refund_id")->first()->toarray();

        if(!$arr){
            return  $this->error('未找到该申请', ErrorInc::MYSQL_FAILED);exit;
        }
        //驳回前的处理
        //1 查询是否已经财务核对   2查询 备注内容

        //查询是否已对账
        $acc_status = Db::table('settlement_list')->where(['sys_num'=>$arr['sys_num'],'msg_id'=>$arr['msg_id']])->value("acc_status");
        //判断是否已经对账；
        if(!empty($acc_status) && $acc_status !=1){
            return  $this->error('该单金额已审核，请联系财务！不可驳回！', ErrorInc::MYSQL_FAILED);exit;
        }
        if($type==1){
            //2 查询备注列表
            $list = $this->getRemarks($session['admin_groupnew'],$session['id'],$arr['sys_num']);
            if($list){
                return $this->success('获取成功',$list);exit;
            }else{
                return $this->error('暂无数据', ErrorInc::DATA_EMPTY);exit;
            }

        }elseif($type==2){
            try{
                Db::beginTransaction();
                //新退单驳回
                if($arr['refund_id']>0){
                    $ret = SubmitPlease::where(["id"=>$id])->update(['submit_stauas'=>3]);
                    if(!$ret){
                        Db::rollBack();
                        return $this->error('新单更新失败'.$ret, ErrorInc::MYSQL_FAILED);
                    }
                    $input['id'] = $arr['refund_id'];
                    $input['content'] = $request->input('content');
                    $input['refund_id'] = $arr['refund_id'];
                    $data = RefundService::applyReject($request->ip(),$session,$input);
                    if($data['ErrorCode']==1){
                        DB::commit();
                    }else {
                        DB::rollBack();
                    }
                    return $data;exit;
                }
                if($arr['submit_service']==4){
                    $is_bool = '换货';
                }else if($arr['submit_service']==2){
                    $is_bool = '退货';
                }
                $listLog = Db::table("order_log")->where(['msg_id'=>$arr['msg_id'],'is_action'=>$is_bool])->orderBy("id","DESC")->first();
                if(empty($listLog)){
                    throw new Exception("无此记录，该单不可驳回");
                }

                $goods_name = explode('-',$listLog['goods_name']);
                $listGoods = SubmitPleaseService::getLogGoodsName($goods_name);
                if(!$listGoods){
                    throw new Exception("该单不可驳回2");
                }
                $arrMsg = SubmitPleaseService::getUpdateArrMsgData($listGoods);
                $returnMsg = OrderMsg::where(['id'=>$arr['msg_id'],'sys_num'=>$arr['sys_num']])->update($arrMsg);
                if($returnMsg){
                    $sett_ids = SettlementList::where(['msg_id'=>$arr['msg_id'],'sys_num'=>$arr['sys_num']])->value("id");
                    if($arr['submit_service']==4){//业务处理类型 1：正常 2：退货 3：被换 4：换新
                        if($sett_ids){
                            $ret = $this->rejectTypeFoue($sett_ids,$arr,$session);
                            if($ret!=1){
                                Db::rollBack();
                                return $this->error('更新失败'.$ret, ErrorInc::MYSQL_FAILED);
                            }
                        }
                    }else if($arr['submit_service']==2){//2：退货
                        if($sett_ids){
                            SettlementList::where(['sys_num'=>$arr['sys_num'],'msg_id'=>$arr['msg_id']])->delete();
                        }
                        $order_List_ids = OrderList::where(['sys_num'=>$arr['sys_num'],'order_goods_id'=>$arr['msg_id']])->value("id");
                        if($order_List_ids){
                            OrderList::where(['sys_num'=>$arr['sys_num'],'order_goods_id'=>$arr['msg_id']])->delete();
                        }
                        $arrOrder['order_status'] = 1;
                        $arrOrder['ser_id'] = "0";
                        $ret = Orders::where(['sys_num'=>$arr['sys_num']])->update($arrOrder);
                        if(!$ret){
                            Db::rollBack();
                            return $this->error('更新失败', ErrorInc::MYSQL_FAILED);
                        }
                    }else{
                        Db::rollBack();
                        return $this->error('状态不正确',ErrorInc::MYSQL_FAILED);
                    }
                    $returnSubmitplease = SubmitPlease::where(["id"=>$id])->update(['submit_stauas'=>3]);
                    if($returnSubmitplease){
                        //添加 订单备注表
                        if($session['admin_groupnew']==2){
                            $public_state = 2;
                        }
                        $res = OrderList::where('sys_num',$arr['sys_num'])->value('stauas');
                        if(!empty($res) && ($res==60 || $res==65)){
                            $zt = "【售后】";
                        }else{
                            $zt = '';
                        }
                        CommonService::accMe( $arr['sys_num'], '申请退/收列表', $zt.'驳回，'.$request->input('content',''), '', $public_state, $session['admin_groupnew'], $session['admin_acc'], $session['id']);
                         $this->insertingLog("驳回，",$arr['sys_num'],"驳回单","申请退/收列表",$request->ip(),$session['admin_acc']);//日志
                        Db::commit();
                        return response()->json(['ErrorCode'=>1,'ErrorMessage'=>'驳回成功','Data'=>'']);
                    }else{
                        Db::rollBack();
                        throw new Exception("该单在（申请退/收列表）修改失败，驳回失败！");
                    }
                }else{
                    Db::rollBack();
                    throw new Exception("该单商品修改失败，驳回失败！");
                }
            }catch(Exception $e){
                Db::rollBack();
                return $this->error($e->getMessage(), ErrorInc::MYSQL_FAILED);exit;
            }
        }else{
            return $this->error('参数错误', ErrorInc::FAILED_PARAM);exit;
        }
    }

    /**
     * @name 驳回部分
     * @param $sett_ids
     * @param $arr
     * @param $session
     * @return int
     * @author du
     * @date 2021/9/16
     */
    public function rejectTypeFoue($sett_ids,$arr,$session){
        //驳回时计算支持金额
        //活动支持
        $sul_price = Db::table("support_log")->where(['sul_msgid'=>$arr['msg_id'],'sul_type'=>12])->orderBy('sul_id','desc')->value('sul_price');
        if($sul_price){
            $sem_id = SettlementMoney::where(['sem_slid'=>$sett_ids,'sem_type'=>12])->select('sem_id','sem_price')->first();

            if(!$sem_id){
                $money['sem_price'] = $sul_price;
                $saves = SettlementMoney::where(["sem_id"=>$sem_id['sem_id']])->update($money);
            }else{
                $saves = SettlementService::createSettMoney($sett_ids, $arr['sys_num'], $sul_price, $session['admin_acc'], 12);
            }
        }else{
            $sem_id = SettlementMoney::where(['sem_slid'=>$sett_ids,'sem_type'=>12])->select('sem_id','sem_price')->first();
            if($sem_id){
                $saves = SettlementMoney::where(["sem_id"=>$sem_id['sem_id']])->delete();
            }
        }

        //铅价指数补贴
        $ld_price = DB::table('support_log')->where(['sul_msgid'=>$arr['msg_id'],'sul_type'=>14])->orderBy('sul_id','desc')->value('sul_price');

        if($ld_price){
            $sem_id = SettlementMoney::where(['sem_slid'=>$sett_ids,'sem_type'=>14])->select('sem_id','sem_price')->first();
            if($sem_id){
                if($sem_id['sem_price'] != $ld_price) {
                    $money['sem_price'] = $ld_price;
                    $saves = SettlementMoney::where(['sem_slid' => $sett_ids, 'sem_type' => 14])->update($money);
                }else{
                    $saves = true;
                }
            }else{
                $saves = SettlementService::createSettMoney($sett_ids, $arr['sys_num'], $ld_price, $session['admin_acc'], 14);
            }
        }else{
            $sem_id = SettlementMoney::where(['sem_slid'=>$sett_ids,'sem_type'=>14])->select('sem_id','sem_price')->first();
            if($sem_id){
                $saves = SettlementMoney::where(['sem_slid'=>$sett_ids,'sem_type'=>14])->delete();
            }else{
                $saves = true;
            }
        }
        if($saves){
            $all_price['all_price'] = SettlementMoney::where(['sem_slid'=>$sett_ids])->sum('sem_price');
            SettlementList::where(["id"=>$sett_ids])->update($all_price);
        }else{
            Db::rollBack();
            return 3;//更新失败
        }
        $settArr['locksel_type'] = 1;
        $ret = SettlementList::where(['sys_num'=>$arr['sys_num'],'msg_id'=>$arr['msg_id']])->update($settArr);
        if(!$ret){
            Db::rollBack();
            return 2;//更新失败
        }else{
            return 1;//更新成功；
        }

    }


    //获取备注列表
    public function getRemarks($admin_groupnew,$aid,$sys_num){
        //设定只有客服和管理员可以看见所有备注，其他只可以看见公开备注
        $not_show=array('7','28','29','31','34','33','35','36','30','92');
        $ser_show=array('2','8','25','27');
        if(in_array($admin_groupnew,$not_show) || $admin_groupnew==3 || $admin_groupnew==26){
            $rest = Note::where('orders_id',$sys_num)->select('note_time','note_name','note_content','note_type','note_group')->orderBy("id","DESC")->get();
        }else{

            /* $rest = Note::where(['orders_id'=>$sys_num,'public_state'=>2])->whereRaw("note_group in ('3,7,0') or note_adid = $aid")->select('note_time','note_name','note_content','note_type','note_group')->orderBy("id","DESC")->get();*/
            $rest = Note::where(['orders_id'=>$sys_num,'public_state'=>2])->where(function($query) use ($aid){
                 $query->whereIn('note_group',[3,7,0])->orWhere('note_adid',$aid);
             })->select('note_time','note_name','note_content','note_type','note_group')->orderBy("id","DESC")->get();
        }
        if(!$rest->isEmpty()){
            $list=$rest->toArray();
            foreach ($list as $key => $val) {
                if($val['note_group']!=2){
                    $list[$key]['note_name']='速电客服';
                }
            }
        }else{
            $list=[];
        }
        return $list;
    }

    /**
     * @name 审核
     * @param id  数据id
     * @param type 1:获取备注数据; 2:确认申请动作
     * @param remarks 备注
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/9/18
     */
    public function confirmApply(Request $request)
    {
        if(!$request->filled('id')){
            return $this->error('参数错误无ID', ErrorInc::FAILED_PARAM);exit;
        }
        $type = (int)$request->input('type',1);
        $id = (int)$request->input('id',0);
        $session = $request->get('session_token');
        if ($request->filled('remarks')) {
            $remarks = $request->input('remarks');
        } else {
            $remarks = "无";
        }
        $sys_num = SubmitPlease::where('id',$id)->select('msg_id','refund_id','submit_sys_num','goods_name','submitr_pt')->first();
        if($type==1){
            $list = $this->getRemarks($session['admin_groupnew'],$session['id'],$sys_num['submit_sys_num']);
            $pic = DB::table('pictures')->where('sp_id',$id)->where('sett_wat_num',$sys_num['submit_sys_num'])->value('upload_pictures');
            $data['pic'] = $pic??'';
            $data['list'] = $list;
            return $this->success('获取成功', $data);
        }elseif($type==2){
            if(!$request->filled('lt_parent_id')){
                return $this->error('参数错误1', ErrorInc::FAILED_PARAM);exit;
            }


            $image = $request->input('image');
            //上传图片
            if($request->filled('image')){

                $upload_pictures = DB::table('pictures')->where('sp_id',$id)->where('sett_wat_num',$sys_num['submit_sys_num'])->value('upload_pictures');

                $arr['upload_pictures'] = $image;
                if($upload_pictures){

                    $res = DB::table('pictures')->where('sp_id',$id)->where('sett_wat_num',$sys_num['submit_sys_num'])->update($arr);
                }else{

                    $pic = [];
                    $pic['upload_pictures'] = $image;//OSS上传地址
                    $pic['sett_wat_num'] = $sys_num['submit_sys_num'];
                    $pic['sp_id'] = $id;
                    $res = DB::table('pictures')->insert($pic);
                }

                if(!$res){
                    throw new Exception("添加凭证失败!");
                }
            }
            if ($remarks != "无"){
                $remarks = $request->input('remarks');
                $res = CommonService::accMe($sys_num['submit_sys_num'],'申请退/收列表',"确认申请，".$remarks,'',$sys_num['submit_sys_num'],1,$request->get('session_token')['admin_acc'],$request->get('session_token')['id']);
                if(!$res){
                    throw new Exception("添加订单备注失败");
                }
            }



            $input = $request->only('sety_id','lt_parent_id');
            if($sys_num['refund_id']>0){
                $input['stats'] = 1;
                $input['id'] = $sys_num['refund_id'];
                $input['refund_id'] = $sys_num['refund_id'];
                $input['msg_id'] = $sys_num['msg_id'];
                $input['sys_num'] = $sys_num['submit_sys_num'];
                $input['goods_name'] = $sys_num['goods_name'];
                $input['pt_id'] = $sys_num['submitr_pt'];
                $input['deal_note'] = $remarks;
                DB::beginTransaction();
                $ret = SubmitPlease::where(["id"=>$id])->update(['submit_stauas'=>2,'deal_time'=>date("Y-m-d H:i:s"),'deal_id'=>$request->get('session_token')['id'],'deal_name'=>$request->get('session_token')['admin_acc']]);
                if(!$ret){
                    Db::rollBack();
                    return $this->error('状态不正确'.$ret, ErrorInc::MYSQL_FAILED);
                }
                $refund = new RefundController();
                $data = $refund->applyRefundAll($input, $session);
                $data = $data->original;
                if($data['ErrorCode']==1){
                    DB::commit();
                }else {
                    DB::rollBack();
                }
                return $data;
            }
            //执行确认申请动作
            try{
                Db::beginTransaction();

                $submit_res = SubmitPlease::where(['id'=>$id])->update(['submit_stauas'=>2,'pay_comm'=>$remarks,'deal_time'=>date("Y-m-d H:i:s"),'deal_id'=>$request->get('session_token')['id'],'deal_name'=>$request->get('session_token')['admin_acc']]);
                if($submit_res){
                    /*$upAfs = OrderListService::creatAftersale(2, $orderinfo['order_num'], $orderinfo['afs_serial'], 1, 31, $input['lt_parent_id'], $input['sety_id'], $orderinfo['p_id'],  $orderinfo['ser_id'], $afs_content, $session['admin_acc'], $session['admin_acc']);*/

                    SettlementList::where(['sys_num'=>$sys_num['submit_sys_num'],'msg_id'=>$sys_num['msg_id']])->update(['locksel_type'=>1,'locked'=>1]);
                    $this->insertingLog("确认申请，",$sys_num['submit_sys_num'],$remarks,"申请退/收列表",$request->ip(), $request->get('session_token')['admin_acc']);
                    Db::commit();
                    return $this->success('操作成功');
                }else{
                    throw new Exception("确认申请失败！");
                }
            }catch(Exception $e){
                Db::rollBack();
                return $this->error($e->getMessage(), ErrorInc::MYSQL_FAILED);exit;
            }
        }else{
            return $this->error('参数错误', ErrorInc::FAILED_PARAM);exit;
        }
    }


    /**
     * @name  添加凭证
     * @param submit_sys_num  系统单号
     * @param image   图片地址
     * @param id 数据ID
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/9/18
     */
    public function addVoucher(Request $request)
    {
        try{

            $input = $request->only('image','submit_sys_num','id');
            $checkKey = CommonService::checkKey(['image','submit_sys_num','id'],$input);
            if($checkKey['code']!=1){
                return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
            }

            $res = Db::table('pictures')->where('sett_wat_num',$request->input('submit_sys_num'))->where('sp_id',$request->input('id'))->first();
            if($res){
                $ret = Db::table('pictures')->where('sett_wat_num',$request->input('submit_sys_num'))->where('sp_id',$request->input('id'))->update(['upload_pictures'=>$request->input('image')]);

            }else{
                $pic = [];
                $pic['sp_id'] = intval($request->input('id'));
                $pic['sett_wat_num'] = $request->input('submit_sys_num');
                $pic['upload_pictures'] = $request->input('image');//OSS上传
                $ret = DB::table('pictures')->insert($pic);
            }

            if(!$ret){
                throw new Exception("添加凭证失败!");
            }
            $this->insertingLog("添加凭证，",$request->input('submit_sys_num'),"添加凭证：".$request->input('submit_sys_num'),"申请退/收列表",$request->ip(), $request->get('session_token')['admin_acc']);//日志

            return $this->success('上传凭证成功');
        }catch(Exception $e){
            return $this->error($e->getMessage(), ErrorInc::MYSQL_FAILED);exit;
        }
    }

    /**
     * @name  修改凭证
     * @param id  数据ID
     * @param image   图片
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|mixed
     * @author du
     * @date 2021/9/18
     */
    public function editVoucher(Request $request)
    {
        try{
            $input = $request->only('image','submit_sys_num','id');
            $checkKey = CommonService::checkKey(['image','submit_sys_num','id'],$input);
            if($checkKey['code']!=1){
                return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
            }

            $pictures = Db::table('pictures')->where('sett_wat_num',$request->input('submit_sys_num'))->where('sp_id',$request->input('id'))->value('upload_pictures');
            $pic = [];
            $pic['upload_pictures'] = $request->input('image');//OSS
            $pic['sp_id'] = intval($request->input('id'));
            if (!$pictures){
                $pic['sett_wat_num'] = $request->input('submit_sys_num');
                $res = DB::table('pictures')->insert($pic);
            }else{
                $res = DB::table('pictures')->where('sett_wat_num',$request->input('submit_sys_num'))->where(['sp_id'=>$request->input('id')])->update($pic);
            }
            if(!$res){
                throw new Exception("更换凭证失败!");
            }
            $this->insertingLog("修改凭证，",$request->input('submit_sys_num'),"添加凭证：".$request->input('submit_sys_num'),'申请退/收列表',$request->ip(), $request->get('session_token')['admin_acc']);
            return $this->success('更换凭证成功');
        }catch(Exception $e){
            return $this->error($e->getMessage(), ErrorInc::MYSQL_FAILED);exit;
        }
    }

    /**
     * @name  查看凭证
     * @param submit_sys_num  系统单号
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author du
     * @date 2021/9/18
     */
    public function lookVoucher(Request $request)
    {
        if(!$request->filled('submit_sys_num')||!$request->filled('id')){
            return $this->error('缺少系统单号或ID', ErrorInc::FAILED_PARAM);exit;
        }
        $res = Db::table('pictures')->where('sett_wat_num',$request->input('submit_sys_num'))->where('sp_id',$request->input('id'))->first();
        $res['upload_pictures'] = $res['upload_pictures']??'';
        if(!$res){
            return $this->error('未发现申请凭证', ErrorInc::FAILED_PARAM);exit;
        }
        return $this->success('获取成功', $res);
    }


    /**
     * @name 编辑账户信息
     * @param id 数据id
     * @param info_ing 开户行/第三方
     * @param info_acc 账号
     * @param info_name 姓名
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/9/18
     */
    public function editBank(Request $request){
        if(!$request->filled('id')||!$request->filled('info_ing')||!$request->filled('info_acc')||!$request->filled('info_name')){
            return $this->error('参数错误', ErrorInc::FAILED_PARAM);exit;
        }
        $id = (int)$request->input('id');
        $info_ing = $request->input('info_ing','');
        $info_acc = $request->input('info_acc','');
        $info_name = $request->input('info_name','');

        $str = "开户行/第三方：".$info_ing."<br/>帐号：".$info_acc."<br/>姓名：".$info_name;

        $res = SubmitPlease::where(['id'=>$id])->update(['customer_info'=>$str]);
        if($res){
            $submit_sys_num = SubmitPlease::where('id',$id)->value('submit_sys_num');
            $this->insertingLog("编辑，",$submit_sys_num,"编辑账户信息：".$submit_sys_num,"申请退/收款",$request->ip(), $request->get('session_token')['admin_acc']);
            return $this->success('修改账户成功');exit;
        }else{
            return $this->error('修改失败', ErrorInc::MYSQL_FAILED);exit;
        }

    }



   /* private function export_excel ($cellData,$session)
    {
        $res = $cellData->get();
        if(!$res->isEmpty()){
            $list = $res->toArray();
        dump($list);
        return 2;
            foreach ($list as $k=>$v){
                $str=Db::table('pictures')->where('sett_wat_num',$v['submit_sys_num'])->value('upload_pictures');
                $v['order_status']=Db::table('orders')->where('sys_num',$v['submit_sys_num'])->value('order_status');
                if ($v['order_status'] == 1) {
                    $list[$k]['order_status_name'] = "新订单";
                }
                if ($v['order_status'] == 5) {
                    $list[$k]['order_status_name'] = "处理中";
                }
                if ($v['order_status'] == 10) {
                    $list[$k]['order_status_name'] = "可派单";
                }
                if ($v['order_status'] == 20) {
                    $list[$k]['order_status_name'] = "已派单";
                }
                if ($v['order_status'] == 30) {
                    $list[$k]['order_status_name'] = "安装中";
                }
                if ($v['order_status'] == 34) {
                    $list[$k]['order_status_name'] = "待完成";
                }
                if ($v['order_status'] == 40) {
                    $list[$k]['order_status_name'] = "已完成";
                }
                if ($v['order_status'] == 50) {
                    $list[$k]['order_status_name'] = "订单已撤销";
                }
                if(!empty($str)){
                    $list[$k]['is_type']=1;
                }else{
                    $list[$k]['is_type']=2;
                }
                switch ($v['submit_state']){//差额处理类型
                    case 1:
                        $list[$k]['submit_state_name'] = '抹零';
                        break;
                    case 2:
                        $list[$k]['submit_state_name'] = '平台';
                        break;
                    case 3:
                        $list[$k]['submit_state_name'] = '服务';
                        break;
                    case 4:
                        $list[$k]['submit_state_name'] = '财务';
                        break;
                }
                switch ($v['submit_service']){//业务处理类型
                    case 1:
                        $list[$k]['submit_service_name'] = '正常';
                        break;
                    case 2:
                        $list[$k]['submit_service_name'] = '退货';
                        break;
                    case 3:
                        $list[$k]['submit_service_name'] = '被换';
                        break;
                    case 4:
                        $list[$k]['submit_service_name'] = '换货';
                        break;
                }
                switch ($v['submit_stauas']){//差额处理状态
                    case 0:
                        $list[$k]['submit_stauas_name'] = '没有';
                        break;
                    case 1:
                        $list[$k]['submit_stauas_name'] = '申请中';
                        break;
                    case 2:
                        $list[$k]['submit_stauas_name'] = '确认申请';
                        break;
                    case 3:
                        $list[$k]['submit_stauas_name'] = '拒绝申请';
                        break;
                }
                if (empty($v['deal_time'])){
                    $v['deal_time'] = "无";
                }
                //收付类型
                if(substr($v['submit_money'],0,1)=='-'){
                    $list[$k]['submit_money_way']="付款";
                }else{
                    $list[$k]['submit_money_way']="收款";
                }
                if($v['customer_info']){
                    $infoArr=explode("<br/>",$v['customer_info']);
                    $infoArra=explode("开户行/第三方：",$infoArr[0]);
                    $infoArrb=explode("帐号：",$infoArr[1]);
                    $infoArrc=explode("姓名：",$infoArr[2]);
                    $list[$k]['info_ing']=$infoArra[1];
                    $list[$k]['info_acc']=$infoArrb[1];
                    $list[$k]['info_name']=$infoArrc[1];
                }else{
                    $list[$k]['info_ing']='';
                    $list[$k]['info_acc']='';
                    $list[$k]['info_name']='';
                }
                if ($v['submit_service'] == 4){//换货旧商品
                    $goods_name_log = DB::table('order_log')->where('msg_id',$v['msg_id'])->value("goods_name");
                    if (!empty($goods_name_log)){
                        $list[$k]['goods_name_log'] = $goods_name_log;
                    }else{
                        $list[$k]['goods_name_log'] = "";
                    }
                }
            }
            dump($list);
            return 1;
            DB::connection()->enableQueryLog();#开启执行日志
            $excel_count = $cellData->count();
            $query = DB::getQueryLog();//sql数组
            $bindings = $query['0']['bindings'];//sql参数
            $sql = $query['0']['query'];//sql语句
            //正则替换
            foreach ($bindings as $replace){
                $value = is_numeric($replace) ? $replace : "'".$replace."'";
                $sql = preg_replace('/\?/', $value, $sql, 1);
            }
            $Automation = new Automation;
            $action = 'submitplease';//控制器
            // $field_data = $Automation->gainFields($session['id'],$action);
            // if(empty($field_data)){
            //     return response()->json(['Data'=>'','ErrorMessage'=>'您暂时无导出权限','ErrorCode'=>3]);
            // }
            $con_name = '申请退收款';//控制器名称
            $name = "submitplease".date('Ymdhis');
            $field_data = $Automation->gainFields($session['id'],$action);
                if(empty($field_data)){
                    return response()->json(['Data'=>'','ErrorMessage'=>'您暂时无导出权限','ErrorCode'=>3]);
                }
            Excel::create($name,function($excel) use ($list){
                $excel->sheet('申请退、收列表', function($excel) use ($list){
                    $excel->cell('A1', function($cell) {$cell->setValue('【编号】');   });
                    $excel->cell('B1', function($cell) {$cell->setValue('【系统单号】');   });
                    $excel->cell('C1', function($cell) {$cell->setValue('【平台单号】');   });
                    $excel->cell('D1', function($cell) {$cell->setValue('【平台名称】');   });
                    $excel->cell('E1', function($cell) {$cell->setValue('【商品名称】');   });
                    $excel->cell('F1', function($cell) {$cell->setValue('【申请金额】');   });
                    $excel->cell('G1', function($cell) {$cell->setValue('【账户信息】');   });
                    $excel->cell('H1', function($cell) {$cell->setValue('【账号】');   });
                    $excel->cell('I1', function($cell) {$cell->setValue('【姓名】');   });
                    $excel->cell('J1', function($cell) {$cell->setValue('【申请时间】');   });
                    $excel->cell('K1', function($cell) {$cell->setValue('【申请人】');   });
                    $excel->cell('L1', function($cell) {$cell->setValue('【差额处理类型】');   });
                    $excel->cell('M1', function($cell) {$cell->setValue('【业务处理类型】');   });
                    $excel->cell('N1', function($cell) {$cell->setValue('【差额处理状态】');   });
                    $excel->cell('O1', function($cell) {$cell->setValue('【订单状态】');   });
                    foreach ($list as $key => $value){
                        $i= $key+2;
                        $excel->cell('A'.$i, $value['id']);
                        $excel->cell('B'.$i,$value['submit_sys_num']);
                        $excel->cell('C'.$i,"\t".$value['order_num']);
                        $excel->cell('D'.$i, $value['pt_name']);
                        $excel->cell('E'.$i, $value['goods_name']);
                        $excel->cell('F'.$i, $value['submit_money']);
                        $excel->cell('G'.$i, $value['info_ing']);
                        $excel->cell('H'.$i, " ".$value['info_acc']);
                        $excel->cell('I'.$i, $value['info_name']);
                        $excel->cell('J'.$i, $value['submit_time']);
                        $excel->cell('K'.$i, $value['submit_name']);
                        $excel->cell('L'.$i, $value['submit_state_name']);
                        $excel->cell('M'.$i, $value['submit_service_name']);
                        $excel->cell('N'.$i, $value['submit_stauas_name']);
                        $excel->cell('O'.$i, $value['order_status_name']);
                    }
                });
            })->save('xls',public_path('excel'));
            $data = '/excel/'.$name.'.xls';
            $Automation->publicInsert($action,$con_name,$excel_count,$session,$data,$sql);
            return $data;
        } else{
            return false;
        }
    }*/

    /**
     * @name  反馈日志
     * @param Request $request
     * @param submit_sys_num            系统单号
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/9/18
     */
  public function feedbackLog(Request $request){
        $sys_num = $request->input('submit_sys_num');
        if(!empty($sys_num)){
            $status = OrderList::where('sys_num',$sys_num)->where('stauas','>=',34)->select('stauas','id')->get()->toArray();
            if(!empty($status)){
                $id = array_column($status, 'id');
	            $feedAcc = DB::table('feedback')->whereIn('gl_id',$id)->select('is_type','type','feedback_status','feedback_pic','install_name','install_time')->orderBy('id','ASC')->get();
	            if (!$feedAcc->isEmpty()){
	                $feedAcc = $feedAcc->toArray();
	                if($feedAcc[0]['feedback_status'] == 1){
	                    $state = "未安装";
	                }else{
	                    $state = "已安装";
	                }
	                $theShy['install_name'] = $feedAcc[0]['install_name'];
	                $theShy['install_time'] = $feedAcc[0]['install_time'];
	                $theShy['state'] = $state;
	                $theShy['service_name'] = "上门安装";
	                foreach($feedAcc as $k=>$v){
	                    if($v['is_type']==1){
	                        $url = "http://weixin.sudianwang.com".ltrim($v['feedback_pic'],'.');
	                    }else{
		                    $url = $v['feedback_pic'];//OSS图片
	                        //$url=$this->baseurl().ltrim($v['feedback_pic'],'.');
	                    }
	                    switch ( $v['type'] )
	                    {
	                        case 3:
	                            $pictype = '(车牌号图片)';
	                            break;
	                        case 4:
	                            $pictype = '(不断电安装)';
	                            break;
	                        case 5:
	                            $pictype = '(生产日期)';
	                            break;
	                        case 2:
	                            $pictype = '(安装后图片)';
	                            break;
	                        case 6:
	                            break;
	                        case 1:
	                            $pictype = '(安装确认单)';
	                            break;
	                    }
	                    if($v['feedback_pic']){
	                        $feedAcc[$k]['pictype'] = $pictype;
	                        $feedAcc[$k]['url'] = $url;
	                    }else{
	                        $feedAcc[$k]['pictype'] = '';
	                        $feedAcc[$k]['url'] = '';
	                    }
	                }
	                $data['list'] = $feedAcc;
	                $data['theShy'] = $theShy;
	                return $this->success('获取成功',$data);exit;
	            }else{
	                return $this->error('未安装', ErrorInc::MYSQL_FAILED);exit;
	            }
	        }else{
                return $this->error('暂无合适订单', ErrorInc::MYSQL_FAILED);exit;
            }
        }else{
            return $this->error('参数错误', ErrorInc::FAILED_PARAM); exit;
        }
    }


    /**
     * @name 批量处理状态
     * @param type 1:处理状态从 0无 到 1处理 ； 2：处理状态从1 处理 到 2 处理中
     * @param submit_state 差额处理类型1：抹零2：平台3：服务4：财务 5:红包
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/11/2
     */
    public function batchProcessStatus(Request $request){
         $input = $request->only('type','submit_state');
        $checkKey = CommonService::checkKey(['submit_state','type'],$input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        if (!in_array($input['submit_state'],[1,2,3,4,5])){
            return $this->error('差额处理类型错误', ErrorInc::FAILED_PARAM, []);exit;
        }
        if (!in_array($input['type'],[1,2])){
            return $this->error('状态错误', ErrorInc::FAILED_PARAM, []);exit;
        }
       // DB::connection()->enableQueryLog();
        if($input['type']==1){
            $ret = SubmitPlease::where('submit_schedule',0)->where('submit_state',$input['submit_state'])->where('submit_stauas',1)->update(['submit_schedule'=>1]);
        }elseif ($input['type']==2){
            $ret = SubmitPlease::where('submit_schedule',1)->where('submit_state',$input['submit_state'])->where('submit_stauas',1)->update(['submit_schedule'=>2]);
        }
        //print_r(DB::getQueryLog());
        if($ret){
            $this->insertingLog("批量更新处理状态，",$input['submit_state'],'处理状态：'.($input['type']-1)."->".$input['type'],'申请退/收列表',$request->ip(), $request->get('session_token')['admin_acc']);
            return $this->success('更新成功');
        }else{
            return $this->error('更新失败', ErrorInc::MYSQL_FAILED);
        }
    }

    /**
     * @name 单条处理状态
     * @param  id 数据ID
     * @param submit_schedule 处理状态 0无 1：处理 2：处理中 3处理已完成
     * @param submit_stauas  业务处理状态0：没有1：申请中2：确认申请3：拒绝申请
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/11/2
     */
    public function processStatus(Request $request){
        if(!$request->filled('id')||intval($request->input('id'))<=0){
            return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
        }
        $id = intval($request->input('id'));
        $info = SubmitPleaseService::getSubmitPleaseBy('id',$id);
        if(!$info){
            return $this->error('数据不存在', ErrorInc::MYSQL_FAILED);exit;
        }

        if($info['submit_stauas']!=1){
            return $this->error('差额处理状态错误', ErrorInc::FAILED_PARAM, []);exit;
        }
        if (!in_array($info['submit_schedule'],[0,1])){
            return $this->error('状态错误', ErrorInc::FAILED_PARAM, []);exit;
        }


        $submit = $info['submit_schedule']+1;
        $ret = SubmitPlease::where('id',$id)->where('submit_stauas',1)->update(['submit_schedule'=>$submit]);
        if($ret){
            $this->insertingLog("单条处理状态，",$info['submit_sys_num'],'处理状态：'.$info['submit_schedule']."->".$submit,'申请退/收列表',$request->ip(), $request->get('session_token')['admin_acc']);
            return $this->success('更新成功');
        }else{
            return $this->error('更新失败', ErrorInc::MYSQL_FAILED);
        }

    }

    /**
     * @param 处理驳回
     * @param  id 数据ID
     * @param submit_schedule 处理状态 0无 1：处理 2：处理中 3处理已完成
     * @param submit_stauas  业务处理状态0：没有1：申请中2：确认申请3：拒绝申请
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/11/2
     */
    public function rejectStatus(Request $request){
        if(!$request->filled('id')||intval($request->input('id'))<=0){
            return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
        }
        $id = intval($request->input('id'));
        $info = SubmitPleaseService::getSubmitPleaseBy('id',$id);
        if(!$info){
            return $this->error('数据不存在', ErrorInc::MYSQL_FAILED);exit;
        }

        if($info['submit_stauas']!=1){
            return $this->error('差额处理状态错误', ErrorInc::FAILED_PARAM, []);exit;
        }
        if (!in_array($info['submit_schedule'],[1,2])){
            return $this->error('状态错误', ErrorInc::FAILED_PARAM, []);exit;
        }

        $submit = $info['submit_schedule']-1;
        $ret = SubmitPlease::where('id',$id)->where('submit_stauas',1)->update(['submit_schedule'=>$submit]);
        if($ret){
            $this->insertingLog("单条驳回，",$info['submit_sys_num'],'驳回状态：'.$info['submit_schedule']."->".$submit,'申请退/收列表',$request->ip(), $request->get('session_token')['admin_acc']);
            return $this->success('驳回成功');
        }else{
            return $this->error('驳回失败', ErrorInc::MYSQL_FAILED);
        }
    }

    /**
     * @name 财务垫付
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/3/9
     */
    public function editPayType(Request $request){
        if(!$request->filled('id')||intval($request->input('id'))<=0){
            return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
        }
        $id = intval($request->input('id'));
        $info = SubmitPleaseService::getSubmitPleaseBy('id',$id);
        if(!$info){
            return $this->error('数据不存在', ErrorInc::MYSQL_FAILED);exit;
        }
        $ret = SubmitPlease::where('id',$id)->update(['pay_type'=>2]);
        if($ret){
            $this->insertingLog("付款为垫付，",$info['submit_sys_num'],'付款类型：垫付','申请退/收列表',$request->ip(), $request->get('session_token')['admin_acc']);
            return $this->success('操作成功');
        }else{
            return $this->error('操作失败', ErrorInc::MYSQL_FAILED);
        }
    }


    /**
     * @name 账务申请待支付
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/3/9
     */
    public function applyWaitPay(Request $request){
        if(!$request->filled('id')||intval($request->input('id'))<=0){
            return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
        }
        $id = intval($request->input('id'));
        $info = SubmitPleaseService::getSubmitPleaseBy('id',$id);
        if(!$info){
            return $this->error('数据不存在', ErrorInc::MYSQL_FAILED);exit;
        }

        if($info['submit_stauas']!=5){
            return $this->error('差额处理状态错误', ErrorInc::FAILED_PARAM, []);exit;
        }
        if($info['submit_state']!=4){
            return $this->error('不是财务', ErrorInc::FAILED_PARAM, []);exit;
        }
        $ret = SubmitPlease::where('id',$id)->update(['submit_stauas'=>4,'audit_time'=>date("Y-m-d H:i:s"),'audit_name'=>$request->get('session_token')['admin_acc']]);
        if($ret){
            $this->insertingLog("申请待支付，",$info['submit_sys_num'],'申请待支付','申请退/收列表',$request->ip(), $request->get('session_token')['admin_acc']);
            return $this->success('操作成功');
        }else{
            return $this->error('操作失败', ErrorInc::MYSQL_FAILED);
        }

    }

    /**|---------------------------------------------------------------------------------
     * @name 提交申请
     * @param int id 数据id
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2022/5/6 16:46
     * |---------------------------------------------------------------------------------
    */
    public function appSubmit(Request $request){
        if(!$request->filled('id')||intval($request->input('id'))<=0){
            return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
        }
        $id = intval($request->input('id'));
        $info = SubmitPleaseService::getSubmitPleaseBy('id',$id);
        if(!$info){
            return $this->error('数据不存在', ErrorInc::MYSQL_FAILED);exit;
        }

        if($info['submit_stauas']!=1){
            return $this->error('差额处理状态错误', ErrorInc::FAILED_PARAM, []);exit;
        }
        if($info['submit_state']!=4){
            return $this->error('不是财务', ErrorInc::FAILED_PARAM, []);exit;
        }
        $ret = SubmitPlease::where('id',$id)->update(['submit_stauas'=>5,'apply_time'=>date("Y-m-d H:i:s"),'apply_name'=>$request->get('session_token')['admin_acc'],'reject_type'=>1]);
        if($ret){
            $this->insertingLog("提交申请，",$info['submit_sys_num'],'提交申请','申请退/收列表',$request->ip(), $request->get('session_token')['admin_acc']);
            return $this->success('操作成功');
        }else{
            return $this->error('操作失败', ErrorInc::MYSQL_FAILED);
        }

    }

    /**|---------------------------------------------------------------------------------
     * @name 驳货审核
     * @param int id 数据id
     * @param string content 驳回备注
     * @param string sys_num 系统单号
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2022/5/6 17:32
     * |---------------------------------------------------------------------------------
    */

    public function rejSubmit(Request $request){
        if(!$request->filled('id')||intval($request->input('id'))<=0||!$request->filled('content')||!$request->filled('sys_num')){
            return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
        }
        $id = intval($request->input('id'));
        $info = SubmitPleaseService::getSubmitPleaseBy('id',$id);
        if(!$info){
            return $this->error('数据不存在', ErrorInc::MYSQL_FAILED);exit;
        }

        if($info['submit_stauas']!=5){
            return $this->error('差额处理状态错误', ErrorInc::FAILED_PARAM, []);exit;
        }
        if($info['submit_state']!=4){
            return $this->error('不是财务', ErrorInc::FAILED_PARAM, []);exit;
        }
        DB::beginTransaction();
        $acc = CommonService::accMe($request->input('sys_num'), '驳回退款首轮审核', $request->input('content'), '', 1, $request->get('session_token')['admin_groupnew'], $request->get('session_token')['admin_acc'], $request->get('session_token')['id']);
        $ret = SubmitPlease::where('id',$id)->update(['submit_stauas'=>1,'apply_time'=>null,'apply_name'=>null,'reject_reason'=>$request->input('content'),'reject_type'=>2]);
        if($ret && $acc){
            DB::commit();
            $this->insertingLog("驳回退款首轮审核，",$info['submit_sys_num'],'驳回退款首轮审核','申请退/收列表',$request->ip(), $request->get('session_token')['admin_acc']);
            return $this->success('操作成功');
        }else{
            DB::rollback();
            return $this->error('操作失败', ErrorInc::MYSQL_FAILED);
        }

    }

    /**|---------------------------------------------------------------------------------
     * @name 驳回付款
     * @param int id 数据id
     * @param string content 驳回备注
     * @param string sys_num 系统单号
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2022/5/6 18:24
     * |---------------------------------------------------------------------------------
    */

    public function rejPayment(Request $request){
        if(!$request->filled('id')||intval($request->input('id'))<=0||!$request->filled('content')||!$request->filled('sys_num')){
            return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
        }
        $id = intval($request->input('id'));
        $info = SubmitPleaseService::getSubmitPleaseBy('id',$id);
        if(!$info){
            return $this->error('数据不存在', ErrorInc::MYSQL_FAILED);exit;
        }

        if($info['submit_stauas']!=4){
            return $this->error('差额处理状态错误', ErrorInc::FAILED_PARAM, []);exit;
        }
        if($info['submit_state']!=4){
            return $this->error('不是财务', ErrorInc::FAILED_PARAM, []);exit;
        }
        DB::beginTransaction();
        $acc = CommonService::accMe($request->input('sys_num'), '驳回付款', $request->input('content'), '', 1, $request->get('session_token')['admin_groupnew'], $request->get('session_token')['admin_acc'], $request->get('session_token')['id']);
        $ret = SubmitPlease::where('id',$id)->update(['submit_stauas'=>1,'audit_time'=>null,'audit_name'=>null,'reject_reason'=>$request->input('content'),'reject_type'=>2]);
        if($ret && $acc){
            DB::commit();
            $this->insertingLog("驳回付款，",$info['submit_sys_num'],'驳回付款','申请退/收列表',$request->ip(), $request->get('session_token')['admin_acc']);
            return $this->success('操作成功');
        }else{
            DB::rollback();
            return $this->error('操作失败', ErrorInc::MYSQL_FAILED);
        }

    }

    /**
     * @name 获取付款类型
     * @return mixed
     * @author du
     * @date 2022/3/9
     */
    public function getPayType(){
        $data = SubmitPleaseService::getPayType();
        return $this->success('获取成功',$data);
    }


    /**
     * @name 获取处理状态
     * @return mixed
     * @author du
     * @date 2021/11/2
     */
    public function getSubmitStaues(){
        $data = SubmitPleaseService::getSubmitSchedule();
        return $this->success('获取成功',$data);
    }


    /**
     * @name 获取差额处理类型
     * @return array[]
     * @author du
     * @date 2021/11/3
     */
    public function getSubmitState($type = false ){
        $applyType = array(array('type'=>3,'name'=>'服务'),array('type'=>4,'name'=>'财务'),array('type'=>5,'name'=>'红包'));
        if($type){
            $applyType = array_column($applyType, 'name' , 'type');
        }
        return $this->success('获取成功',$applyType);
    }


    /**
     * @name 编辑申请金额
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/4/14
     */
    public function editSubmitMoney(Request $request){
        if(!$request->filled('id')||intval($request->input('id'))<=0 || !$request->filled('submit_money')){
            return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
        }
        $id = intval($request->input('id'));
        $money = $request->input('submit_money');
        $frist = substr( $money, 0, 1 );
        if($frist!='-'){
            return $this->error('金额错误', ErrorInc::FAILED_PARAM, []);exit;
        }
        $money_r = 0 - $request->input('submit_money');
        $info = SubmitPleaseService::getSubmitPleaseBy('id',$id);
        if(!$info){
            return $this->error('数据不存在', ErrorInc::MYSQL_FAILED);exit;
        }
        $category = OrderService::getOrderBy('sys_num', $info['submit_sys_num'],['category']);
        if($category==3){
            return $this->error('数据品类不正确', ErrorInc::MYSQL_FAILED);exit;
        }
        DB::beginTransaction();
        if(in_array($info['submit_state'],['2','4'])){
          if($info['submit_state']==4 && $info['submit_stauas']>1){
              return $this->error('状态不正确', ErrorInc::MYSQL_FAILED);exit;
          }
          $ret = SubmitPlease::where('id',$id)->update(['submit_money'=>$money]);
          $res = Refund::where('id',$info['refund_id'])->update(['goods_price'=>$money_r,'updated_at'=>date('Y-m-d H:i:s')]);
          if($ret && $res){
              DB::commit();
              $this->insertingLog("修改申请金额，",$info['submit_sys_num'],'修改金额：(,'.$id.')'.$info['submit_money'].'->'.$money,'申请退/收列表',$request->ip(), $request->get('session_token')['admin_acc']);
              return $this->success('操作成功');
          }else{
              DB::rollback();
              return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
          }
        }else{
            return $this->error('差额处理类型不正确', ErrorInc::MYSQL_FAILED);exit;
        }
    }

}

