<?php

/**
 * 账单报表服务
 * 账单报表的基础服务数据操作
 * @author DouBin
 * @Date: 2021/9/1
 * @Time: 11:07
 * @Email: db@sudianwang.com
 * @version 1.0
 * @copyright BlueCity
 */

namespace App\Services;
use App\Http\Controllers\BaseController;
use App\Models\AdminInfor;
use App\Models\OrderList;
use App\Models\Orders;
use App\Models\SettlementList;
use App\Models\TicketList;
use App\Models\User;
use BlueCity\Core\Inc\ErrorInc;
use BlueCity\Core\Service\Service;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
use App\Models\StatementsList;
use DB;

use phpDocumentor\Reflection\Types\Self_;

class StatementsListService extends Service{
    /**|---------------------------------------------------------------------------------
     * @name 获取列表信息
     * @param array $input 请求参数
     * @param array $session 操作人信息
     * @retrun /multitype:array
     * @author dou 2021/9/2 8:57
     * |---------------------------------------------------------------------------------
    */
    public static function getList ( $input , $session ){
        $page_size = $input['page_size']??10;
        $mouth_pay = self::getStateWhere($input['mouth_pay'], $session);
        $where = [];
        foreach( $mouth_pay as $k => $v ){
            $where[$k] = $v;
        }
        $time = self::getTime($input);
        if($time){
            if($time['ErrorCode']!=1){
                return $time;
            }else{
                foreach( $time['Data'] as $k => $v ){
                    $where[$k] = $v;
                }
            }
        }

        if (isset($input['company_name']) && $input['company_name']!=[]){
            $where['stl_serid_searchin'] = $input['company_name'];
        }
        if (isset($input['ser_yycode'])){
            $where['ser_yycode_like'] = $input['ser_yycode'];
        }
        if (isset($input['stl_wat'])){
            $where['stl_wat_like'] = $input['stl_wat'];
        }
        if (isset($input['stl_type'])){
            $where['stl_type'] = $input['stl_type'];
        }
        if (isset($input['category'])){
            $where['stl_category'] = $input['category'];
        }

        $where = CommonService::jointWhere($where);
        $db = new StatementsList();
        $db = $db->leftJoin('admin','admin.id','=','statements_list.stl_serid');
        if($where){
            $db = $db->whereRaw($where);
        }
        $all_money = $db->sum("stl_money");
       // DB::connection()->enableQueryLog();#开启执行日志
        if($input['is_excel']==1){
            DB::connection()->enableQueryLog();#开启执行日志
        }
//        CommonService::startmysql();
        $paginate = $db->select('statements_list.stl_id AS stl_id','statements_list.stl_serid AS stl_serid','statements_list.stl_wat AS stl_wat','statements_list.stl_creacter AS stl_creacter','statements_list.stl_ids AS stl_ids','statements_list.stl_time AS stl_time','statements_list.stl_money AS stl_money','statements_list.stl_ticket AS stl_ticket','statements_list.stl_invoice AS stl_invoice','statements_list.stl_startime AS stl_startime','statements_list.stl_endtime AS stl_endtime','statements_list.stl_type AS stl_type','admin.company_name AS company_name','admin.mouth_pay AS mouth_pay','push_type','stl_category','admin.brand_service','admin.ad_project')->orderBy('stl_time','ASC')->paginate($page_size);
//        dump(CommonService::showmysql());
//        CommonService::addLog('statementlistsql', CommonService::showmysql(), '123','sqlshow');
        $list = CommonService::dataToArray($paginate->items());
        if($input['is_excel']==1) {
            $data['sqls'] = DB::getQueryLog()[1];
        }

        $data['showcount'] = self::getStateBar($session);//获取操作权限可展示订单状态栏
        $all_button = BmmcService::whereButton($input['token'],$input['Pri_id']);

        if ($input['mouth_pay'] == '1' || $input['mouth_pay'] == '3'|| $input['mouth_pay'] == '4') {
            $export = BmmcService::getTopButton('creactsettle,export,billExport,SettlementBillExport,batchSubmitMer,sysRepleni','',$all_button);
        }else{
            $export = BmmcService::getTopButton('creactsettle,billExport,SettlementBillExport,batchSubmitMer,sysRepleni','',$all_button);
        }


       // $export = BmmcService::getTopButton('creactsettle,export,monthlyExport,billExport','',$all_button);

        $data['button_top'] = $export['button_top']??[];//顶部按钮
        $data['button_search'] = $export['button_search']??[];//搜索栏按钮
        $data['station'] = self::getStlType($session['admin_groupnew']);//搜索栏结算状态查询
        $data['all_money'] = $all_money;//获取当前结算方式总金额
        $data['category'] = CategoryService::getAll();//获取可查询品类
        if($list){
            $list = Self::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' => $data, 'ErrorMessage' => '成功', 'ErrorCode' => 1];

    }

    /**
     * 拼接列表数据
     * @param string $session 用户信息
     * @param array $input 请求数据
     * @param array $list 订单数据
     * @param array $all_button 按钮信息
     * @return /multitype:array
     * @author dou 2021年8月3日
     */
    public static function jointListData ( $input , $session , $list , $all_button ){
        $station = self::getStlType($session['admin_groupnew'],1);
        $admin_id = array_column($list, 'stl_serid');
        $admininfor = new AdminInfor();
        $admininfor = CommonService::getMysqlData($admininfor, ['admin_id_searchin'=>array_unique($admin_id)],['admin_id','phone']);
        $admininfor = CommonService::jointArrayKey($admininfor, 'admin_id');
        $category = CategoryService::getAll([],'cd_id');
        $brand_service = ServiceProviderService::getBrandService(true);
        foreach( $list as $k => $v ){
            $buttonData = [];
            $buttonData[] = 'search,remarks';
            if (isset($v['push_type']) && $v['push_type'] == 1) {
                $buttonData[] = 'push_supplychain';
            }
            if ($v['stl_type'] == 1){
                $buttonData[] = 'dealWith,operation';
            }
            if ($v['stl_type'] == 4){
                $buttonData[] = 'delEntry,submit_mer';//,suppleSubmit
            }
           /* if ($v['stl_type'] == 5) {
                $buttonData[] = 'submit_mer';
            }*/
            $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']??[];
            $list[$k]['station'] = $station[$v['stl_type']]??'未确认';
            $list[$k]['phone'] = $admininfor[$v['stl_serid']]['phone']??'';
            if($v['stl_ids']==""){
                $list[$k]['number'] = 0;
            }else{
                $list[$k]['number'] = count(explode(",",$v['stl_ids']));
            }
            $ad_project = trim($v['ad_project']);
            $ad_project = explode(',', $ad_project);
            if(in_array('3', $ad_project)) {
                if (isset($brand_service[$v['brand_service']])) {
                    $list[$k]['company_name'] = $list[$k]['company_name']."(" . $brand_service[$v['brand_service']] . ")";
                }
            }
            $list[$k]['sys_num'] = $v['stl_wat'];//获取备注使用
            $list[$k]['id'] = $v['stl_id'];//获取备注使用
            $list[$k]['category_name'] = $category[$v['stl_category']]['cd_pname']??'未确认';
        }
        return $list;
    }

    /**|---------------------------------------------------------------------------------
     * @name 拼接账单类型对应查询条件
     * @param string $mouth_pay 账单类型
     * @param array $session 操作人信息
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2021/9/2 14:02
     * |---------------------------------------------------------------------------------
    */
    public static function getStateWhere ( $mouth_pay,$session ){
        $where = [];
        if(!in_array($mouth_pay, ['0'])){
            $where['mouth_pay'] = $mouth_pay;
        }
        if ($session['admin_groupnew'] != 7) {//管理员可以看全部
            $where['gone_statements_list.company_id'] = $session['company_id'];
        }
  /*      if($session['admin_groupnew']==96){
            $where['stl_startime_searchgt'] = '2020-01-01';
        }*/
        return $where;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取查询时间
     * @param array $input 请求参数
     * @retrun /multitype:array
     * @author dou 2021/9/2 10:46
     * |---------------------------------------------------------------------------------
    */
    public static function getTime ( $input ){
        if (isset($input['endDate']) && !empty($input['endDate'])){
            if(in_array($input['mouth_pay'],['1','4'])){
                /*--------------------------------------月结和五大区时间拼接开始--------------------------------------*/
                if(is_array($input['endDate']) || strlen($input['endDate'])!=7){
                    return  ['Data' => '','ErrorMessage'=>'参数错误date','ErrorCode'=>ErrorInc::FAILED_PARAM];
                }else{
                    $date = $input['endDate'];
                    $dates = explode('-',$date);
                    if (in_array($dates[1], array('01', '03', '05', '07', '08', '10', '12'))) {
                        $text = '31';
                    }elseif ($dates[1] == '02'){
                        if ($dates[0] % 400 == '0' || ($dates[0] % 4 == '0' && $dates[0] % 100 !== '0')) {        //判断是否是闰年
                            $text = '29';
                        } else {
                            $text = '28';
                        }
                    } else {
                        $text = '30';
                    }
                    $stl_startime = $date."-01";
                    $stl_endtime = $date."-".$text;
                    $where['stl_startime'] = $stl_startime;
                    $where['stl_endtime'] = $stl_endtime;
                }
                /*--------------------------------------月结和五大区时间拼接结束--------------------------------------*/

            }elseif(in_array($input['mouth_pay'],['0','2'])){
                /*--------------------------------------零散和全部时间拼接开始--------------------------------------*/
                if(!is_array($input['endDate']) || count($input['endDate'])!=2 ){
                    return  ['Data' => '','ErrorMessage'=>'参数错误date','ErrorCode'=>ErrorInc::FAILED_PARAM];
                }else{
                    $where['stl_startime_searcheqgt'] = $input['endDate'][0];
                    $where['stl_endtime_searcheqlt'] = $input['endDate'][1];
                }
                /*--------------------------------------零散和全部时间拼接结束--------------------------------------*/
            }elseif ($input['mouth_pay'] == 3){
                /*-----------------------------------------周结时间拼接开始----------------------------------------*/
                $search_data = $input['endDate'];
                if(is_array($input['endDate']) || strlen($input['endDate'])!=10){
                    return  ['Data' => '','ErrorMessage'=>'参数错误date','ErrorCode'=>ErrorInc::FAILED_PARAM];
                }else {
                    $text = date('Y-m-d', strtotime($input['endDate']. '+6 days'));
                    $stl_startime = date("Y-m-d", strtotime($search_data));
                    $stl_endtime = $text;
                    $where['stl_startime'] = $stl_startime;
                    $where['stl_endtime'] = $stl_endtime;
                }
                /*-----------------------------------------周结时间拼接结束----------------------------------------*/
            }
            return  ['Data' => $where,'ErrorMessage'=>'成功','ErrorCode'=>1];
        }else{
            return false;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取获取结算状态
     * @param $group 请求权限
     * @param $type 请求类型 数据返回类型 1：以状态码作为键
     * @retrun /multitype:array
     * @author dou 2021/9/1 11:09
     * |---------------------------------------------------------------------------------
    */
    public static function getStlType ( $group = '' , $type = '' ){
        $showdata = array(array("type"=>1,"name"=>'商家确认中'),array("type"=>2,"name"=>'财务结算中'),array("type"=>3,"name"=>'已完成'),array("type"=>4,"name"=>'未处理'),array("type"=>5,"name"=>'待补货'));
        /*----------------------------------设置当前访问者权限可查看状态开始------------------------------------------------*/
        if(!$group){
            $show = [];
        }else{
            $show = [];
        }
        if($show){
            $data = [];
            foreach( $showdata as $k => $v ){
                if(in_array($k,$show)){
                    $data[] = $v;
                }
            }
            $showdata = $data;
        }
        /*----------------------------------设置当前访问者权限可查看状态结束------------------------------------------------*/
        if( $type =='1'){
            $showdata = array_column($showdata, 'name' , 'type');
        }
        return $showdata;
    }

    /**
     * 获取操作权限可展示订单状态栏信息
     * @param string $type 是否查询数据量1是
     * @param array $session 操作人信息
     * @return /multitype:array
     * @author dou 2021年9月1日
     */
    public static function getStateBar ( $session , $type = '2'){
//        $bmmc_pids=BmmcService::searchPids($session['admin_groupnew']);
//        if(in_array('1',$bmmc_pids)){
//            $showcount = [
//                ['showname' => "全部", 'shownum' => '--','status'=>0],
//                ['showname' => "新订单", 'shownum' => '--','status'=>1],
//                ['showname' => "可派单", 'shownum' => '--','status'=>10],
//                ['showname' => "已派单", 'shownum' => '--','status'=>20]
//            ];
//        }else{
            $showcount = [
                ['showname' => "全部零散", 'shownum' => '--','status'=>0],
              //  ['showname' => "月结", 'shownum' => '--','status'=>1],
             //   ['showname' => "零散", 'shownum' => '--','status'=>2],
               // ['showname' => "周结", 'shownum' => '--','status'=>3],
               // ['showname' => "五大区", 'shownum' => '--','status'=>4]
            ];
//        }
        if( $type == '1'){
            foreach( $showcount as $k => $v ){
                $showcount[$k]['shownum'] = self::getStateNum($v['status'],$session);
            }
        }
        return $showcount;
    }

    /**
     * 获取指定状态订单数量
     * @param string $mouth_pay 状态栏参数
     * @param array $session 操作人信息
     * @return /multitype:array
     * @author dou 2021年8月4日
     */
    public static function getStateNum ( $mouth_pay , $session ){
        if(in_array($mouth_pay,[1,2,3,4])){
            $where = [];
            $db = new StatementsList();
            $db = $db->leftJoin('admin','admin.id','=','statements_list.stl_serid');
            $mouth_pay = self::getStateWhere($mouth_pay, $session);
            foreach( $mouth_pay as $k => $v ){
                $where[$k] = $v;
            }
            $num = CommonService::getMysqlData($db,$where,[],[],'count');
            $num = $num??'0';
            return $num;
        }else{
            return '--';
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 根据指定条件获取账单信息
     * @param string $key 查询键
     * @param string $value 查询值
     * @param array $select 待查询参数
     * @param string $type 查询类型
     * @retrun /multitype:array
     * @author dou 2021/9/2 17:07
     * |---------------------------------------------------------------------------------
    */
    public static function getStatementsListBy ($key, $value, $select = [] , $type = 'get'){
        $db = new StatementsList();
        if(in_array($key, ['stl_id','stl_wat'])){
            $type = 'first';
        }
        if($type == 'first'){
            if(count($select) == 1){
                $type = 'value';
            }
        }
        $list = CommonService::getMysqlData($db,[$key=>$value],$select,[],$type);
        return $list;
    }

    /**|---------------------------------------------------------------------------------
     * @name 根据多条件获取账单信息
     * @param array $params 查询条件
     * @param array $select 待查询参数
     * @param string $type 查询类型
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2021/9/2 17:15
     * |---------------------------------------------------------------------------------
    */
    public static function getStatementsList ($params, $select = [] , $type = 'get'){
        $db = new StatementsList();
        if($type == 'first'){
            if(count($select) == 1){
                $type = 'value';
            }
        }
        $list = CommonService::getMysqlData($db,$params,$select,[],$type);
        return $list;
    }

    /**|---------------------------------------------------------------------------------
     * @name 生成结算单号
     * @param int $type 1结算单号普通  2结算单号3M 3石总线下分销单
     * @retrun  /multitype:tring
     * @author dou 2021/9/2 18:45
     * |---------------------------------------------------------------------------------
    */
    public static function creactWat ($type){
        if($type==1){
            //生成结算单
            //$statements_list=M("statements_list");
            $stl_wat = 'J'.date("Ymdhis").str_pad(rand(0,999),3,'0',STR_PAD_LEFT);
            $res = self::getStatementsListBy('stl_wat', $stl_wat,['stl_id']);
            if($res){
                self::creact_wat(1);
            }else{
                return $stl_wat;
            }
        }elseif ($type == 2){
            $stl_wat = 'J3'.date("Ymdhis").str_pad(rand(0,999),3,'0',STR_PAD_LEFT);
            $res = self::getStatementsListBy('stl_wat', $stl_wat,['stl_id']);
            if($res){
                self::creact_wat(2);
            }else{
                return $stl_wat;
            }
        }elseif ($type == 3){
            $stl_wat = 'J4'.date("Ymdhis").str_pad(rand(0,999),3,'0',STR_PAD_LEFT);
            $res = self::getStatementsListBy('stl_wat', $stl_wat,['stl_id']);
            if($res){
                self::creact_wat(3);
            }else{
                return $stl_wat;
            }
        }else{
            return false;
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 生成账单信息
     * @param array $res 结算单列表数据
     * @param array $input 请求参数
     * @param string $ip 操作设备ip
     * @param string $session 操作人信息
     * @retrun /multitype:array
     * @author dou 2021/9/7 20:35
     * |---------------------------------------------------------------------------------
    */
    public static function creactSettle ( $res , $ip , $session , $input){
//        if(isset($input['source']) && $input['source'] == 2){
////            订单来源为零散
//            $poss['sett_status'] = 10;
//            $poss3m['sett_status'] = 10;
//            $stl_type = 1;
//        }else{
            $stl_type = 4;
//        }
        $brand_service = AdminService::getAdminBy('id', $input['stl_serid'],['brand_service']);
        $stl_wat = self::creactWat(1);//生成结算单号
        $stl_wat3m = self::creactWat(2);//生成结算单号
        $stl_watxx = self::creactWat(3);//生成结算单号
//        $ids = array_column($res, 'id');
        $ids = [];$ids3m = [];$idsxx = [];
        $money1 = 0;$money13m = 0;$money1xx = 0;//服务费
        $money2 = 0;$money23m = 0;$money2xx = 0;//补邮费
        $commission = 0;$commission3m = 0;$commissionxx = 0;//平台提成
        $flag = 1;
        $order_num = [];
        $pt_id_arr = PlatformService::getPtIdByPtType();
        foreach( $res as $k => $v ){
//            $this->RelatedFixPrice($v['sys_num'],$v['order_num'],$v['all_price'],2);
            $order_num[] = $v['order_num'];
            $goods_brand = OrderService::getOrderMsgBy('id', $v['msg_id'],['goods_brand']);
            if($v['wat_judge']=="2"){
                //echo $v['id'];
                $flag=2;
                break;
            }
            if($goods_brand == "3M" && ($brand_service == 2 || $brand_service == 7)){
                if($v['list_service_type']==55){
                    $money23m = $money23m+$v['subsidy_money'];
                }else{
                    $money13m = $money13m+$v['all_price'];
                }
                $commission3m = $commission3m+$v['commis_price'];
                $ids3m[] = $v['id'];
            }//elseif ($v['p_id']=='453')
            elseif(in_array($v['p_id'], $pt_id_arr))
            {
                if($v['list_service_type']==55){
                    $money2xx = $money2xx+$v['subsidy_money'];
                }else{
                    $money1xx = $money1xx+$v['all_price'];
                }
                $commissionxx = $commissionxx+$v['commis_price'];
                $idsxx[] = $v['id'];
            }else{
                if($v['list_service_type']==55){
                    $money2 = $money2+$v['subsidy_money'];
                }else{
                    $money1 = $money1+$v['all_price'];
                }
                $commission = $commission+$v['commis_price'];
                $ids[] = $v['id'];
            }
        }
        if($flag==1){
            DB::beginTransaction(); //开启事务
            $BaseController = new BaseController();
            if($ids3m && !$ids){
                $stl_wat = $stl_wat3m;
            }
            if($order_num){
                $pass['til_watnum'] = $stl_wat;
                TicketList::whereIn('til_ornum',$order_num)->update($pass);
            }
            $passa['til_state'] = '20';
            $passa['til_wats'] = $stl_wat;
            $ras = TicketList::whereRaw("til_creactime<='".$input['end_time']." 23:59:59' and til_state=10 and til_watnum='' and til_serid = '".$input['stl_serid']."'")->update($passa);
            $allmoney3 = TicketList::where('til_wats',$stl_wat)->sum("til_price");
            if($ids) {
                $poss['wat_num'] = $stl_wat;
                $poss['wat_judge'] = 2;
                $aee = SettlementList::whereIn("id", $ids)->update($poss);
                $stl_money = $money1 + $money2;
                $eaa = self::insertStarmentList($stl_money, $allmoney3, $ids, $stl_wat, $session['admin_acc'], $input['stl_serid'], $input['start_time'], $input['end_time'], $input['category'],1,$stl_type,1,$session['company_id']);
                if($eaa && $aee){
                    $BaseController->insertingLog('生成账单，',$stl_wat,$stl_wat.'生成成功','月结报表',$ip,$session['admin_acc']);//日志
                }
            }else{
                $aee = true;
                $eaa = true;
            }
            if($ids3m) {
                if($ids){
                    $allmoney3 = 0;
                }
                $poss3m['wat_num'] = $stl_wat3m;
                $poss3m['wat_judge'] = 2;
                $aee3m = SettlementList::whereIn("id", $ids3m)->update($poss3m);
                $stl_money3m = $money13m + $money23m;
                $eaa3m = self::insertStarmentList($stl_money3m, $allmoney3, $ids3m, $stl_wat3m, $session['admin_acc'], $input['stl_serid'], $input['start_time'], $input['end_time'], $input['category'],2,$stl_type,1,$session['company_id']);
                if($aee3m && $eaa3m){
                    $BaseController->insertingLog('生成账单，',$stl_wat3m,$stl_wat3m.'生成成功','月结报表',$ip,$session['admin_acc']);//日志
                }
            }else{
                $aee3m = true;
                $eaa3m = true;
            }
            if($idsxx) {
                $possxx['wat_num'] = $stl_watxx;
                $possxx['wat_judge'] = 2;
                $aeexx = SettlementList::whereIn("id", $idsxx)->update($possxx);
                $stl_moneyxx = $money1xx + $money2xx;
                $eaaxx = self::insertStarmentList($stl_moneyxx, 0, $idsxx, $stl_watxx, $session['admin_acc'], $input['stl_serid'], $input['start_time'], $input['end_time'], $input['category'],1,$stl_type , 453,$session['company_id']);
                if($aee3m && $eaa3m){
                    $BaseController->insertingLog('生成账单，',$stl_watxx,$stl_watxx.'生成成功','月结报表',$ip,$session['admin_acc']);//日志
                }
            }else{
                $aeexx = true;
                $eaaxx = true;
            }
            if($eaa && $aee && $eaa3m && $aee3m && $aeexx && $eaaxx){
                DB::commit();//成功则提交
                if(isset($input['source']) && $input['source'] == 2) {
                    if ($ids) {
                        StatementsListService::submitMer($stl_wat, '', $session, $ip);
                    }
                    if ($ids3m) {
                        StatementsListService::submitMer($stl_wat3m, '', $session, $ip);
                    }
                    if ($idsxx) {
                        StatementsListService::submitMer($stl_watxx, '', $session, $ip);
                    }
                }
                return ['Data' => $stl_wat, 'ErrorMessage' =>'成功', 'ErrorCode' => 1];exit;
            }else{
                DB::rollback();//不成功，则回滚
                $mess = "添加失败";
                return ['Data' => [], 'ErrorMessage' =>$mess, 'ErrorCode' => ErrorInc::MYSQL_FAILED];exit;
            }
        }else{
            $mess = "添加失败;存在已生成结算单的订单";
            return ['Data' => [], 'ErrorMessage' => $mess, 'ErrorCode' => ErrorInc::REQUEST_FORBIDDEN];exit;
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 添加账单
     * @param string $stl_money 结算单总金额
     * @param string $stl_ticket 罚款单金额
     * @param string $stl_ids 结算单数据id组
     * @param string $stl_wat 结算单号
     * @param string $stl_creacter 创建人
     * @param string $stl_serid 所属门店
     * @param string $stl_startime 账单开始时间
     * @param string $stl_endtime 账单结束时间
     * @param string $stl_category 结算类型
     * @param string $brand_server 结算公司类型（用于公众号展示）1：极限，2：3M
     * @param string $stl_type 默认结算状态
     * @param string $company_type 结算公司类型
     * @retrun /multitype:array
     * @author dou 2021/9/2 20:10
     * |---------------------------------------------------------------------------------
    */
    public static function insertStarmentList ( $stl_money , $stl_ticket , $stl_ids , $stl_wat , $stl_creacter , $stl_serid , $stl_startime , $stl_endtime , $stl_category , $brand_server = 1 , $stl_type = 4 , $company_type = 1,$company_id = ''){
        $theshy['stl_money'] = sprintf("%.2f",$stl_money);
        $theshy['stl_ticket'] = sprintf("%.2f",$stl_ticket);
        $theshy['stl_ids'] = implode(',',$stl_ids);
        $theshy['stl_wat'] = $stl_wat;
        $theshy['stl_creacter'] = $stl_creacter;
        $theshy['stl_type'] = $stl_type;
        $theshy['stl_serid'] = $stl_serid;
        $theshy['stl_startime'] = $stl_startime;
        $theshy['stl_endtime'] = $stl_endtime;
        $theshy['stl_category'] = $stl_category;
        $theshy['brand_server'] = $brand_server;
        $theshy['company_type'] = $company_type;
        $theshy['company_id'] = $company_id;
        $eaa = StatementsList::insert($theshy);
        return $eaa;
    }
    /**|---------------------------------------------------------------------------------
     * @name 操作提交商家确认
     * @param string $stl_wat 结算单号
     * @param string $apply_note 备注
     * @param string $session 用户信息
     * @param string $ip 操作设备ip
     * @retrun /multitype:array
     * @author dou 2022-12-22 022 下午 4:48:48
     * |---------------------------------------------------------------------------------
    */
    public static function submitMer ( $stl_wat , $apply_note = '' , $session , $ip ){
        $input['stl_wat'] = $stl_wat;
        $input['apply_note'] = $apply_note;
        DB::beginTransaction(); //开启事务
        //提交到商家确认
        try {
            $Statements = StatementsListService::getStatementsListBy('stl_wat', $input['stl_wat']);
            //批量商家 ：车膜验证未处理或待补货   电：待补货
            /*  if($Statements['stl_category']==3){
                  if( $Statements['stl_type'] < 4 ){
                      return $this->error('结算单状态异常请先确认当前状态', ErrorInc::REQUEST_FORBIDDEN);exit;
                  }
              }else{
                  if( $Statements['stl_type'] != 5 ){
                      return $this->error('蓄电池结算单状态异常请先确认当前状态', ErrorInc::REQUEST_FORBIDDEN);exit;
                  }
              }*/

            if( $Statements['stl_type'] != 4){
                return ['Data' => [], 'ErrorMessage' =>'结算单状态需要是未处理请先确认当前状态', 'ErrorCode' => ErrorInc::REQUEST_FORBIDDEN];
            }

            $poss["sett_status"] = 10;
            $res = SettlementList::whereRaw("wat_num ='".$input['stl_wat']."' and (list_service_type!=40 and list_service_type!=55 and ser_id!=1695)")->first();
            if($res){//存在状态错误的订单请联系相关人员检查数据
                return ['Data' => [], 'ErrorMessage' =>'存在状态错误的订单请联系相关人员检查数据', 'ErrorCode' => ErrorInc::REQUEST_FORBIDDEN];
            }else{
                $apply = SettlementList::whereRaw("wat_num ='".$input['stl_wat']."'")->update($poss);
                if($apply){
                    $list = SettlementService::getSettlementListBy('wat_num', $input['stl_wat']);
                    /****************************同步通知门店***************************/
                    $store = CommonService::getSyncStores($Statements['stl_serid'], $Statements['stl_category']);
                    if(!empty($store)){
                        $sdob_shop_name = AdminsService::getAdminsBy('id', $Statements['stl_serid'],['company_name']);
                        $ids = array_column($list, 'id');//
                        $userid = array_column($list, 'customer_id');
                        $smoney = SettlementService::getSettlementMoney(['sem_slid_searchin'=>$ids],['sem_slid','sem_type','sem_price']);
                        $user = User::whereIn('id',$userid)->pluck('shr_name','id');
                        $moneytype = LabtypeService::labelList();
                        $moneytype = CommonService::jointArrayKey($moneytype, 'sety_id');
                        $smoneys=[];
                        $relative=[];
                        foreach( $smoney as $k => $v ){
                            $data['name']=$moneytype[$v['sem_type']]['sety_name'];
                            $data['price']=$v['sem_price']*100;
                            if($v['sem_type']=='1' || $v['sem_type']=='15'){
                                $relative[$v['sem_slid']]=$v['sem_price'];
                            }
                            $smoneys[$v['sem_slid']][]=$data;
                        }
                        $allmoney1=0;
                        $allmoney2=0;
                        $list_id = '';
                        $sys_num = '';
                        foreach( $list as $k => $v ){
                            $order_data['ord_order_number']=$v['list_id'];
                            $order_data['sobd_car_owner_name']=$user[$v['customer_id']];
                            $list_id .= ",'" . $v['list_id'] . "'";
                            $sys_num .= ",'" . $v['sys_num'] . "'";
                            if ($v['list_service_type'] == 55) {
                                $order_data['actual_price']=$v['subsidy_money']*100;
                                $order_data['relative_price']=$v['subsidy_money']*100;
                                $allmoney1 = $allmoney1 + $v['subsidy_money'];
                                $order_data['details_price'][0]['name']='撤销补贴';
                                $order_data['details_price'][0]['sem_price']=$v['subsidy_money']*100;
                            } else {
                                $order_data['actual_price']=$v['all_price']*100;
                                $order_data['relative_price']=$relative[$v['id']]*100;
                                $order_data['details_price']=$smoneys[$v['id']];
                                $allmoney2 = $allmoney2 + $v['all_price'];
                            }
                            $orderdata[]=$order_data;
                        }
                    }else{
                        $allmoney1 = 0;
                        $allmoney2 = 0;
                        $list_id = '';
                        $sys_num = '';
                        foreach( $list as $k => $v ){
                            $list_id .= ",'" . $v['list_id'] . "'";
                            $sys_num .= ",'" . $v['sys_num'] . "'";
                            if ($v['list_service_type'] == 55) {
                                $allmoney1 = $allmoney1 + $v['subsidy_money'];
                            } else {
                                $allmoney2 = $allmoney2 + $v['all_price'];
                            }
                        }
                    }
                    $list_id = ltrim($list_id,',');
                    $sys_num = ltrim($sys_num,',');
                    $AccArr["account_status"] = 2;
                    OrderList::whereRaw("serial_number in (".$list_id.")")->update($AccArr);
                    Orders::whereRaw("sys_num in (".$sys_num.")")->update($AccArr);
                    $til_serid = $Statements['stl_serid'];
                    $allmoney3 = $Statements['stl_ticket'];
                    if($allmoney3){
                    }else{
                        $allmoney3 = 0;
                    }
                    //$admin=M("admin");
                    $invoice = AdminsService::getAdminsBy('id', $til_serid,['invoice','deduct']);
                    if($invoice['invoice']==1 || $invoice['invoice']==2){
                        $deduct=explode(",",$invoice['deduct']);
                        if(count($deduct)=='2'){
                            if($deduct[1]==''){
                                $deduct[1] = 0;
                            }
                            $sel['stl_invoice'] = ($allmoney1+$allmoney2-$allmoney3)*(100-$deduct[1])/100;
                        }else{
                            $sel['stl_invoice'] = ($allmoney1+$allmoney2-$allmoney3)*(100-$invoice['deduct'])/100;
                        }
                    }else{
                        $sel['stl_invoice'] = 0;
                    }
                    $sel['stl_invoice'] = sprintf("%.2f",$sel['stl_invoice']);
                    $sel['stl_type'] = 1;
                    $sel['stl_money'] = sprintf("%.2f",$allmoney1+$allmoney2);
                    $res = StatementsList::whereRaw("stl_wat='".$input['stl_wat']."'")->update($sel);
                    if($input['apply_note']!=''){
                        $add_note = CommonService::accMe($input['stl_wat'], '提交至商家确认', $input['apply_note'], '', 2, $session['admin_groupnew'], $session['admin_acc'], $session['id']);
                    }
                    $BaseController = New BaseController();
                    if($res){
                        if(!empty($store)){
                            $company_name = CompanyService::getCompanyById($Statements['company_id'],['com_name'],'value');
                            $pop = [
                                'bill_bumber' => $Statements['stl_wat'],
                                'start_time'        => $Statements['stl_startime'],
                                'end_time'       => $Statements['stl_endtime'],
                                'ord_service_shop_id'    => $Statements['stl_serid'],
                                'bill_price'        => $sel['stl_money']*100,
                                'order_data'   => $orderdata,
                                'sdob_shop_name'	=> $sdob_shop_name,
                                'company_name'	=> $company_name,
                            ];
                            $store = SysStoresService::sysStore($pop, 'importBillOrders',$store);
                            if($store['ErrorCode']!=1){
                                DB::rollBack();
                                return $store;
                            }else{
                                $content = $input['stl_wat']."结算号：月结算审核至商家确认同步门店";
                                $BaseController->insertingLog('月结算审核至商家确认，',$input['stl_wat'],$content,'月结报表',$ip,$session['admin_acc']);//日志
                            }
                        }
                        DB::commit();//成功则提交
                    }else{
                        DB::rollback();//回滚
                        return ['Data' => [], 'ErrorMessage' =>'操作失败stm', 'ErrorCode' => ErrorInc::MYSQL_FAILED];
                    }
                    if($Statements['stl_category']!=3) {
                        $user_phone = AdminInfor::where('admin_id', $til_serid)->value("phone");
                        if ($user_phone != "") {
                            $shr_phone = $user_phone;//手机号
                            $content = DB::table('activitysms')->where('act_type', 3)->value("act_centent");
                            $sms = CommonService::senSms($user_phone, $content, 'SuDianPaw','','',$session['admin_acc']);
                        }
                    }
                    $num1 = SettlementList::whereRaw("sett_status in (1,60,63) and ((list_service_type=40 and setfeeds_time > '2016-08-01 00:00:01') or (list_service_type=55 and `create_time` > '2016-08-01 00:00:01')) and ser_id='".$list[0]['ser_id']."'")->count();
                    $content = $input['stl_wat']."结算号";
                    $BaseController->insertingLog('月结算审核至商家确认，',$input['stl_wat'],$content,'月结报表',$ip,$session['admin_acc']);//日志
                    return ['Data' => [], 'ErrorMessage' =>'操作成功', 'ErrorCode' => 1];
                }else{
                    DB::rollback();//回滚
                    return ['Data' => [], 'ErrorMessage' =>'操作失败stl', 'ErrorCode' => ErrorInc::MYSQL_FAILED];
                }
            }
        }catch(\Exception $e){
            DB::rollback();//回滚
            return ['Data' => [], 'ErrorMessage' =>$e->getMessage(), 'ErrorCode' => ErrorInc::SERVER_FAILED];
        }
    }

}
