<?php
/**
 * 文件名称（门店账目管理）
 * 文件简单描述（操作门店账单审批汇款等权限）
 * @author DouBin
 * @Date: 2021/9/3
 * @Time: 15:44
 * @Email: db@sudianwang.com
 * @version 1.0
 * @copyright BlueCity
 */
namespace App\Services;
use App\Http\Controllers\BaseController;
use App\Models\Admin;
use App\Models\AdminInfor;
use App\Models\AdminKhacclist;
use App\Models\OrderList;
use App\Models\SettlementList;
use App\Models\StatementsList;
use BlueCity\Core\Service\Service;
use App\Models\ServiceCenter;
use BlueCity\Core\Inc\ErrorInc;
use DB;
use Illuminate\Database\Eloquent\Model;

class ServiceCenterService extends Service
{
    /**|---------------------------------------------------------------------------------
     * @name 添加可结算账单
     * @param string $wat_num 结算单号
     * @param int $ser_id 门店id
     * @param string $company_name 门店名称
     * @param string $apply_for_name 操作人
     * @param string $apply_for_money 账单金额
     * @param string $stl_category 结算类型
     * @retrun /multitype:string
     * @author dou 2021/9/3 15:45
     * |---------------------------------------------------------------------------------
    */
    public static function insertServiceCenter ( $wat_num , $ser_id , $company_name , $apply_for_name , $apply_for_money , $stl_category,$company_id='' ){
        $arr['wat_num'] = $wat_num;//结算单号
        $arr['ser_id'] = $ser_id;//服务中心id
        $arr['company_name'] = $company_name;//服务商
        $arr['apply_for_name'] = $apply_for_name;//申请人
        $arr['apply_for_money'] = $apply_for_money ?? 0;//结算金额
        $arr['apply_for_time'] = date("Y-m-d H:i:s");//结算申请时间
        $arr['stl_category'] = $stl_category;//结算申请时间
        $arr['company_id'] = $company_id;
        $res = ServiceCenter::insert($arr);
        return $res;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取列表信息
     * @param array $input 请求参数
     * @param array $session 操作人信息
     * @retrun /multitype:array
     * @author dou 2021/9/8 15:01
     * |---------------------------------------------------------------------------------
    */
    public static function getList ( $input , $session ){
        if(!isset($input['type'])){
            return ['Data' => '', 'ErrorMessage' => '缺少状态参数', 'ErrorCode' => ErrorInc::INVALID_PARAM];
        }
        //判定查询状态是否在查询范围内
        if(!in_array($input['type'],[1,2,3,4,5,6,7,8,9,10])){
            return ['Data' => '', 'ErrorMessage' => '参数错误', 'ErrorCode' => ErrorInc::FAILED_PARAM];
        }
        /*---------------------------------------------拼接订单列表查询条件开始-------------------------------------------*/
        $where = [];
        $statuswhere = self::getStatusWhere($input['type']);
        foreach( $statuswhere as $k => $v ){
            $where[$k] = $v;
        }
        if(isset($input['order_num']) && isset($input['wat_num'])){
            return ['Data' => '', 'ErrorMessage' => '请勿同时添加订单号和结算单号', 'ErrorCode' => ErrorInc::FAILED_PARAM];
        }
        if(isset($input['order_num'])){//订单单号
            $wat_num = SettlementList::where('order_num',$input['order_num'])->value('wat_num');
            $where['wat_num']=$wat_num;
        }
        if(isset($input['invoice']) && (int)$input['invoice']!=0){//发票类型
            $where['gone_admin.invoice'] = (int)$input['invoice'];
        }
        if(isset($input['whether_inv']) && (int)$input['whether_inv']!=0){//收票状态
            $where['whether_inv'] = (int)$input['whether_inv'];
        }
        if(isset($input['mouth_pay']) && (int)$input['mouth_pay']!=0){//结款类型
            $where['mouth_pay']=(int)$input['mouth_pay'];
        }
        if(isset($input['settlement_type']) && (int)$input['settlement_type']!=0){//付款类型
            $where['settlement_type']=(int)$input['settlement_type'];
        }
        if(isset($input['ser_id']) && (int)$input['ser_id']!=0){//结算对象
            $where['ser_id']=(int)$input['ser_id'];
        }
        if(isset($input['apply_for_name'])){//经手人
            $where['apply_for_name']=$input['apply_for_name'];
        }
        if(isset($input['wat_num'])){//结算单号
            $where['wat_num_like']=$input['wat_num'];
        }
        if(isset($input['apply_time'])){//申请时间
            $input['apply_time'][1] = date("Y-m-d", strtotime($input['apply_time'][1] . " +1 day"));
            $where['apply_for_time_between'] = $input['apply_time'];
        }
        if(isset($input['payment_time'])){//付款开始时间
            $input['payment_time'][1] = date("Y-m-d", strtotime($input['payment_time'][1] . " +1 day"));
            $where['apply_pay_time_between'] = $input['payment_time'];
        }
        if(isset($input['accountname'])){//开户公司
            $where['accountname_like'] = $input['accountname'];
        }

        if(isset($input['stl_category'])){//品类搜索
            $where['gone_service_center.stl_category'] = $input['stl_category'];

        }
        /*---------------------------------------------拼接订单列表查询条件结束-------------------------------------------*/
        if ($session['admin_groupnew'] != 7) {
            $where['gone_service_center.company_id'] = $session['company_id'];
        }


        $where = CommonService::jointWhere($where);
        $page_size = $input['page_size']??10;
        if($input['is_excel']==1){
            DB::connection()->enableQueryLog();#开启执行日志
        }
        $db = new ServiceCenter();  //invoice_number  buckle_point  deduct

        $db = $db ->leftjoin('admin','admin.id','=','ser_id') ->leftjoin('admin_infor','admin_infor.admin_id','=','ser_id');
        $paginate = $db->whereRaw($where)->select('service_center.id','wat_num','ser_id','admin.company_name','admin.mouth_pay','service_center.settlement_type','apply_for_name','apply_audit_name','apply_for_money','apply_for_deduct','apply_for_time','apply_pay_time','apply_content','service_center.apply_centent','service_center.type','whether_inv','invoice_number','courier_number','accountname','invoice_pic','deduct','invoice','mouth_pay','company_des','opeaccline','account','settlement_num','deduct_money','pay_money','buckle_point','khaccount')->orderBy('apply_for_time','DESC')->paginate($page_size);

        if($input['is_excel']==1) {
            $data['sqls'] = DB::getQueryLog()[1];
        }
        $data['typeName'] = self::getTypeName();
        $data['mouth_pay'] = ServiceProviderService::getMouthPay();
        $data['showcount'] = self::getStatusBar($session);//获取操作权限可展示订单状态栏
        $all_button = BmmcService::whereButton($input['token'],$input['Pri_id']);
        $export = BmmcService::getTopButton('export,batchPayment,all_auditzd,all_applyPayment,InvoiceInfo','',$all_button);
        $data['button_top'] = $export['button_top']??[];//顶部按钮
        $data['button_search'] = $export['button_search']??[];//搜索栏按钮
        $list = CommonService::dataToArray($paginate->items());
        if($list) {
            $data['list'] = self::jointListData($input, $session, $list, $all_button);//获取列表信息明细说明
        }else{
            $data['list'] = [];
        }
        $data['page'] = [
            'count' => $paginate->total(),
            'page' => $paginate->currentPage(),
            'page_size' => $page_size,
            'allPage' => $paginate->lastPage()
        ];
        return ['Data' => $data, 'ErrorMessage' => '参数错误', 'ErrorCode' => 1];
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取状态查询条件
     * @param string $status 查询状态
     * @retrun /multitype:array
     * @author dou 2021/9/8 19:39
     * |---------------------------------------------------------------------------------
     */
    public static function getStatusWhere ( $status ){
        $where['gone_service_center.type']=$status;
        return $where;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取操作权限可展示结算单状态栏信息
     * @param array $session 操作人信息
     * @retrun /multitype:array
     * @author dou 2021/9/8 19:39
     * |---------------------------------------------------------------------------------
     */
    public static function getStatusBar ( $session , $type = ''){
        $showcount = [
            ['show_name'=>"申请结款",'shownum'=>'--','status'=>1],
            /*['show_name'=>"速电付款",'shownum'=>'--','status'=>2],
            ['show_name'=>"蓝城付款",'shownum'=>'--','status'=>5],
            ['show_name'=>"个人付款",'shownum'=>'--','status'=>6],*/
            ['show_name'=>"对公付款",'shownum'=>'--','status'=>8],
            ['show_name'=>"对私付款",'shownum'=>'--','status'=>9],
           // ['show_name'=>"对平台付款",'shownum'=>'--','status'=>10],
            ['show_name'=>"待审核",'shownum'=>'--','status'=>7],
            ['show_name'=>"已完结",'shownum'=>'--','status'=>3],
           // ['show_name'=>"坏账",'shownum'=>'--','status'=>4]
        ];

        if( $type == '1'){
            foreach( $showcount as $k => $v ){
                $showcount[$k]['shownum'] = self::getStatusNum($v['status'],$session);
            }
        }
        return $showcount;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取类表状态数量
     * @param int $status 结算单状态
     * @param array $session 操作人信息
     * @retrun /multitype:array
     * @author dou 2021/9/8 19:39
     * |---------------------------------------------------------------------------------
     */
    public static function getStatusNum ( $status , $session ){
        if(in_array($status,[1,2,4,5,6,7,8,9,10])){
            $db = new ServiceCenter();
            $db = $db ->leftjoin('admin','admin.id','=','ser_id') ->leftjoin('admin_infor','admin_infor.admin_id','=','ser_id');
            $where = [];
            if($session['admin_groupnew']!=7){
                $where['gone_admin.company_id'] = $session['company_id'];
            }
            $statuswhere = self::getStatusWhere($status);
            if($statuswhere){
                foreach( $statuswhere as $k => $v ){
                    $where[$k] = $v;
                }
            }

            $num = CommonService::getMysqlData($db,$where,[],[],'count');
            $num = $num??'0';
            return $num;
        }else{
            return '--';
        }
    }
    /**
     * 拼接列表数据
     * @param string $session 用户信息
     * @param array $input 请求数据
     * @param array $list 订单数据
     * @param array $all_button 按钮信息
     * @return /multitype:array
     * @author dou 2021/9/8 19:39
     */
    public static function jointListData ( $input , $session , $list , $all_button ){
        $ser_id = array_column($list, 'ser_id');
        $typeName = self::getTypeName(true);

        $mouth_payss = array_column($list,'mouth_pay','ser_id');

        $watType = ServiceProviderService::getWatType(true);
        foreach($list as $k => $v){
            /*---------------------------------------------判定门店展示开户行开始-----------------------------------------*/
//            account,accountname,opeaccline,khaccount
            $wat_type = mb_substr($v['wat_num'], 0, 2);
            $list[$k]['wat_type'] = $watType[$wat_type]??'普通账单';
            if($wat_type!='J2'){
                $khaccdata = AdminKhacclist::where("akl_adminid",$v['ser_id'])->where("akl_wat",$wat_type)->where("akl_state",1)->first();
                if($khaccdata){
                    $khaccdata = CommonService::dataToArray($khaccdata);
                    $list[$k]['account'] = $khaccdata['akl_account'];
                    $list[$k]['accountname'] = $khaccdata['akl_accountname'];
                    $list[$k]['opeaccline'] = $khaccdata['akl_opeaccline'];
                    $list[$k]['khaccount'] = $khaccdata['akl_khaccount'];
                }
            }
            /*---------------------------------------------判定门店展示开户行结束-----------------------------------------*/
            /*---------------------------------------------拼接列表需要展示按钮开始---------------------------------------*/
            $buttonData = [];
            if ($v['type'] == 1){
                $buttonData[] = "ApplyPayment,Badebt,returnSettle,addRemarks,searPrice";
            }elseif (in_array($v['type'],[2,5,6,8,9,10])){
                $buttonData[] = 'lookDetail,confirmPayment,returnApply,addRemarks,searPrice';
            }elseif ($v['type'] == 3){
                $buttonData[] = 'lookDetail,invoice_c,invoice_x,addRemarks';
            }elseif ($v['type'] == 4){
                $buttonData[] = 'lookDetail,Tobepaid,addRemarks';
            }
//            elseif ($v['type'] == 5){
//                $buttonData[] = 'lookDetail,confirmPayment,returnApply,addRemarks,searPrice';
//            }elseif($v['type'] == 6){
//                $buttonData[] = 'lookDetail,confirmPayment,returnApply,addRemarks,searPrice';
//            }
            elseif($v['type'] == 7){
                $buttonData[] = 'auditzd,addRemarks,invoice_c,invoice_x';
            }
            if (in_array($v['type'],[2,3,5,6,8,9,10]) &&(($v['invoice'] == 1) || ($v['invoice']==2))){
                if ($v['whether_inv'] !=1){
                    $buttonData[] = 'Collectickets';
                }else{
                    $buttonData[] = 'ticket';
                }

            }
            $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']??[];
            /*---------------------------------------------拼接列表需要展示按钮结束---------------------------------------*/
            /*------------------------------------------------判定扣点以及金额展示开始-------------------------------------*/
            $deduct=explode(',',$v['deduct']);
            if(count($deduct)==2){
                $list[$k]['deduct']=(int)$deduct[1];
                $list[$k]['fdeduct']=$deduct[0];
            }else{
                $list[$k]['fdeduct']="未设定";
            }

            //判定扣点  扣点后金额   总金额 扣点后金额
            if($v['apply_for_deduct']==$v['apply_for_money'] || $v['apply_for_deduct']==""){
                $list[$k]['deduct_js'] = 0;
            }else{
                $list[$k]['deduct_js'] = 100-$v['apply_for_deduct']/$v['apply_for_money']*100;
            }
            /*------------------------------------------------判定扣点以及金额展示结束-------------------------------------*/
            $list[$k]['note_contents'] = [];
            if($list[$k]['accountname']=="" && $list[$k]['account']=="" && $list[$k]['opeaccline']==""){

            }else{
                $list[$k]['company_des'] = "开户行：".$list[$k]['opeaccline']."<br/>账户名：".$list[$k]['accountname']."<br/>账户：".$list[$k]['account'];
            }

            $getMouthPay = ServiceProviderService::getMouthPay(1);
            $mouth_pays = $getMouthPay[$mouth_payss[$v['ser_id']]]??'';
            $list[$k]['mouth_pay']= $mouth_pays;

            $settlement = $typeName[$v['settlement_type']]??'无';
            $list[$k]['settlement_type'] = $settlement;
            if($v['pay_money']=='0' && $v['deduct_money']=='0'){
                $list[$k]['pay_money']=$v['apply_for_money'];
            }
            if($v['type'] == '1'){
                $list[$k]['apply_for_deduct'] = $list[$k]['pay_money'];
            }
        }
        return $list;
    }

    /**|---------------------------------------------------------------------------------
     * @name 确认付款
     * @param string $wat_num 结算单号
     * @param string $remarks 操作备注
     * @param string $image 处理图片
     * @param int $pay_type 付款类型 2:速电;5:蓝城;6:个人
     * @param array $session 操作人信息
     * @param string $ip 操作设备ip
     * @retrun /multitype:array
     * @author dou 2021/9/9 20:16
     * |---------------------------------------------------------------------------------
    */
    public static function confirmPayment($wat_num , $remarks , $image , $pay_type , $session , $ip){
        $iptv = [];
        $iptv['sett_wat_num'] = $wat_num;
        $iptv['upload_pictures'] = $image;
        $pan = Db::table('pictures')->where('sett_wat_num',$wat_num)->first();
        if($pan){
            Db::table('pictures')->where('sett_wat_num',$wat_num)->update($iptv);
        }else{
            Db::table('pictures')->insert($iptv);
        }

        $arr = [];
        $arr['type'] = 7;
        $arr['apply_pay_time'] = date('Y-m-d H:i:s');
        $res = ServiceCenter::where('wat_num',$wat_num)->where('type',$pay_type)->update($arr);
        $BaseController = new BaseController();
        CommonService::accMe($wat_num, '服务中心账目管理', $remarks, '', 1, $session['admin_groupnew'], $session['admin_acc'], $session['id']);
        if($res) {
            $BaseController->insertingLog("确认付款，", $wat_num, "确认付款，结算单号：" . $wat_num, "服务中心账目管理", $ip, $session['admin_acc']);
            return ['Data' => [], 'ErrorMessage' => '操作成功', 'ErrorCode' => 1];
        }else{
            return ['Data' => [], 'ErrorMessage' => '操作失败', 'ErrorCode' => ErrorInc::MYSQL_FAILED];
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 驳回支付申请
     * @param int $id 数据id
     * @param string $remarks 驳回备注
     * @param array $session 操作人信息
     * @param string $ip 操作设备ip
     * @retrun /multitype:array
     * @author dou 2021/9/9 21:50
     * |---------------------------------------------------------------------------------
    */
    public static function dismissAudit ( $id , $remarks , $session , $ip){
        $ServiceCenter = ServiceCenter::where('id', $id)->where('type',7)->select('settlement_type','wat_num')->first();
        if($ServiceCenter) {
            $res = ServiceCenter::where('id', $id)->where('type',7)->update(['type'=>$ServiceCenter['settlement_type']]);
            if($res){
                $BaseController = new BaseController();
                CommonService::accMe($ServiceCenter['wat_num'], '服务中心账目管理', $remarks, '', 1, $session['admin_groupnew'], $session['admin_acc'], $session['id']);
                $BaseController->insertingLog("驳回付款申请，",$ServiceCenter['wat_num'],"驳回付款申请，结算单号：".$ServiceCenter['wat_num'],"服务中心账目管理",$ip, $session['admin_acc']);
                return ['Data' => [], 'ErrorMessage' => '操作成功', 'ErrorCode' => 1];
            }else{
                return ['Data' => [], 'ErrorMessage' => '操作失败', 'ErrorCode' => ErrorInc::MYSQL_FAILED];
            }
        }else{
            return ['Data' => [], 'ErrorMessage' => '无对应数据', 'ErrorCode' => ErrorInc::DATA_EMPTY];
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 获取可批量处理门店
     * @param string ju_ordernum 订单单号
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2021/9/9 21:38
     * |---------------------------------------------------------------------------------
    */
    public static function getCanDealStore ( $input ){
        $checkKey = CommonService::checkKey(['pay_type', 'accountname_all'],$input);
        if($checkKey['code'] != 1){
            return ['Data' => [], 'ErrorMessage' => '参数'.$checkKey['data'].'未填写,或值为空', 'ErrorCode' => ErrorInc::INVALID_PARAM];
        }
        $pay_type = $input['pay_type'];
        $ser_name = $input['ser_name']??'';
        $accountname_all = $input['accountname_all'];
        if($ser_name!='') {
            $wheres['admin_id'] = $ser_name;
        }
        $wheres['accountname'] = $accountname_all;
        $db = Admin::join('admin_infor','admin.id','=','admin_infor.admin_id','left');
        $admin_id = CommonService::getMysqlData($db, $wheres,['admin.id','company_name','mouth_pay']);
        $list=[];
        if($admin_id){
            $temp_arr = array_column($admin_id, 'id');
            $company_name = array_column($admin_id,'company_name','id');
            $mouth_pay = array_column($admin_id,'mouth_pay','id');
            $db = new ServiceCenter();
            $where['type'] = $pay_type;
            $where['ser_id_searchin'] = $temp_arr;
            if(isset($input['mouth_pay']) && $input['mouth_pay']!='10086'){
                $where['settlement_type'] = $input['mouth_pay'];
            }
            $ser_id = CommonService::getMysqlData($db, $where,['wat_num','ser_id','id','apply_for_money','apply_for_deduct','settlement_type']);
            if ($ser_id){
                foreach ($ser_id as $kk => $vv) {
                    $getMouthPay = ServiceProviderService::getMouthPay(1);
                    $mouth_pays = $getMouthPay[$mouth_pay[$vv['ser_id']]]??'';
                    $list[$kk]['mouth_pay'] = $mouth_pays;
                    $list[$kk]['company_name'] = $company_name[$vv['ser_id']];
                    $list[$kk]['wat_num'] = $vv['wat_num'];
                    $list[$kk]['apply_for_money'] = $vv['apply_for_money'];
                    $list[$kk]['apply_for_deduct'] = $vv['apply_for_deduct'];
                    $list[$kk]['ser_id'] = $vv['ser_id'];
                    $list[$kk]['id'] = $vv['id'];
                }
                return ['Data' => $list, 'ErrorMessage' => '操作成功', 'ErrorCode' => 1];
            }else{
                return ['Data' => [], 'ErrorMessage' => '无数据2', 'ErrorCode' => ErrorInc::DATA_EMPTY];
            }
        }else{
            return ['Data' => [], 'ErrorMessage' => '无数据1', 'ErrorCode' => ErrorInc::DATA_EMPTY];
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 列表页
     * @param int $id 数据id
     * @param string $remarks 驳回备注
     * @param array $session 操作人信息
     * @param string $ip 操作设备ip
     * @retrun  /multitype:array
     * @author dou 2021/9/9 22:06
     * |---------------------------------------------------------------------------------
    */
    public static function auditzd ( $id , $remarks = '' , $session , $ip){
        $ServiceCenter = ServiceCenter::where('id', $id)->where('type',7)->select('settlement_type','wat_num')->first();
        if($ServiceCenter) {
            $arr['type'] = 3;
            $arr['apply_pay_time'] = date("Y-m-d H:i:s");//付款时间
            $attr['sett_status'] = 30;
            $res = ServiceCenter::where('id',$id)->where('type',7)->update($arr);
            $rea = SettlementList::where('wat_num', $ServiceCenter['wat_num'])->update($attr);
            $stl['stl_type']=3;
            $reb = StatementsList::where('stl_wat', $ServiceCenter['wat_num'])->update($stl);
            $numArr = SettlementService::getSettlementListBy('wat_num', $ServiceCenter['wat_num'],['list_id']);
            if ($numArr) {
                $list_id = array_column($numArr, 'list_id');
                $accArr['account_status'] = 30;
                OrderList::whereIn('serial_number',$list_id)->update($accArr);
            }
//            echo $res;echo '---';echo $rea; echo '---'; echo $reb;
            if($res && $rea && $reb){
                $BaseController = new BaseController();
                if($remarks!=''){
                    $rest = CommonService::accMe($ServiceCenter['wat_num'],'服务中心账目管理',"审核，".$remarks,'','',$session['admin_groupnew'],$session['admin_acc'],$session['id']);//添加备注
                }
                $BaseController->insertinglog("审核，",$ServiceCenter['wat_num'],"审核，结算单号号：".$ServiceCenter['wat_num'],"服务中心账目管理",$ip,$session['admin_acc']);
                return ['Data' => [], 'ErrorMessage' => '操作成功', 'ErrorCode' => 1];
            }else{
                return ['Data' => [], 'ErrorMessage' => '操作失败', 'ErrorCode' => ErrorInc::MYSQL_FAILED];
            }
        }else{
            return ['Data' => [], 'ErrorMessage' => '无对应数据', 'ErrorCode' => ErrorInc::DATA_EMPTY];
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取凭证
     * @param array $input 请求参数
     * @param array $session 操作人信息
     * @param string $ip 操作设备ip
     * @retrun /multitype:array
     * @author dou 2021/9/10 16:46
     * |---------------------------------------------------------------------------------
    */
    public static function getCredentialsPic ( $input ){
        $pic = Db::table('pictures')->where('sett_wat_num', $input['wat_num'])->value('upload_pictures');
        if (isset($pic)) {
            $BaseController = new BaseController();
            $pic = $BaseController->picurl($pic);
            return ['Data' => $pic, 'ErrorMessage' => '成功', 'ErrorCode' => 1];
        } else {
            return ['Data' => [], 'ErrorMessage' => '暂无图片', 'ErrorCode' => ErrorInc::DATA_EMPTY];
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 编辑图片
     * @param array $input 请求参数
     * @param array $session 操作人信息
     * @param string $ip 操作设备ip
     * @retrun /multitype:array
     * @author dou 2021/9/10 16:55
     * |---------------------------------------------------------------------------------
    */
    public static function updateCredentialsPic ( $input , $session , $ip){
        if (isset($input['image']) && $input['image']!='') {
            $pic = Db::table('pictures')->where('sett_wat_num', $input['wat_num'])->value('upload_pictures');
            $result = Db::table('pictures')->where('sett_wat_num', $input['wat_num'])->update(['upload_pictures' => $input['image']]);
            //删除旧图片
//            DealPicService::deletPic($pic);
            if ($result) {
                $BaseController = new BaseController();
                $BaseController->insertinglog("编辑凭证，",$input['wat_num'],"编辑凭证，结算单号号：".$input['wat_num'],"服务中心账目管理",$ip,$session['admin_acc']);
                return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功！', 'Data' => ''];
            } else {
                return ['ErrorCode' => ErrorInc::MYSQL_FAILED, 'ErrorMessage' => '操作成功！', 'Data' => ''];
            }
        } else {
            return ['ErrorCode' => ErrorInc::INVALID_PARAM, 'ErrorMessage' => '缺少参数image！', 'Data' => ''];
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 添加凭证
     * @param array $input 请求参数
     * @param array $session 操作人信息
     * @param string $ip 操作设备ip
     * @retrun /multitype:array
     * @author dou 2021/9/10 16:55
     * |---------------------------------------------------------------------------------
     */
    public static function insertCredentialsPic ( $input , $session , $ip){
        if (isset($input['image']) && $input['image']!='') {
            $result = Db::table('pictures')->where('sett_wat_num', $input['wat_num'])->update(['upload_pictures' => $input['image']]);
            if ($result) {
                $BaseController = new BaseController();
                $BaseController->insertinglog("添加凭证，",$input['wat_num'],"添加凭证，结算单号号：".$input['wat_num'],"服务中心账目管理",$ip,$session['admin_acc']);
                return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功！', 'Data' => ''];
            } else {
                return ['ErrorCode' => ErrorInc::MYSQL_FAILED, 'ErrorMessage' => '操作失败！', 'Data' => ''];
            }
        } else {
            return ['ErrorCode' => ErrorInc::INVALID_PARAM, 'ErrorMessage' => '缺少参数image！', 'Data' => ''];
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取后续开票账单信息
     * @param array $input 请求参数
     * @retrun /multitype:array
     * @author dou 2021/9/10 20:18
     * |---------------------------------------------------------------------------------
    */
    public static function getAccumulateInvoice ( $input ){
        $ser_id = ServiceCenter::where('id',$input['id'])->value('ser_id');
        $list = AdminInfor::where('admin_id',$ser_id)->select('accountname','account')->first();
        $admin_id = AdminInfor::where(['accountname'=>$list['accountname'],'account'=>$list['account']])->pluck('admin_id');
        $list = ServiceCenter::whereRaw("((whether_inv=1 and invoice_number='后续开票') or whether_inv=2)")->whereIn('type',[2,3,5,6])->whereIn('ser_id',$admin_id)->select('id','wat_num','company_name','apply_for_deduct')->get();
        if(!empty($list)) {
            return ['ErrorCode' => 1, 'ErrorMessage' => '成功', 'Data' => $list];
        }else{
            return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '无数据！', 'Data' => ''];
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 累计开票（先开票）
     * @param array $input 请求参数
     * @param array $session 操作人信息
     * @param string $ip 操作设备ip
     * @retrun /multitype:array
     * @author dou 2021/9/10 20:18
     * |---------------------------------------------------------------------------------
     */
    public static function getAdvanceInvoice ( $input ){
        $invoice = ServiceCenter::where('id',$input['id'])->select("whether_inv","ser_id","apply_for_deduct")->first();
        if(empty($invoice)){
            return ['ErrorCode'=>ErrorInc::REQUEST_FORBIDDEN,'ErrorMessage'=>'该账单已开票','Data'=>[]];
        }
        if($invoice && $invoice['whether_inv']==1){
            return ['ErrorCode'=>ErrorInc::REQUEST_FORBIDDEN,'ErrorMessage'=>'该账单已开票1','Data'=>[]];
        }
        $list = AdminInfor::where('admin_id',$invoice['ser_id'])->select('accountname','account')->first();
        $ser_id = AdminInfor::where(['accountname'=>$list['accountname'],'account'=>$list['account']])->pluck('admin_id');
        $info = Db::table('invoice_money')->where('status',1)->whereIn('ser_id',$ser_id)->select('sc_id','type','order_money','invoice_money','invoice_num','invoice_nums','residue_money')->first();
        if(!empty($info)){
            $moneys = $info['residue_money']-$invoice['apply_for_deduct'];
            if($moneys>=0){
                $data['code'] = 4;
            }else{
                $data['code'] = 3;
            }
            $data['invoice_num'] = $info['invoice_nums'];
            $data['money'] = $info['residue_money'];
            $data['invoice_money'] = $info['invoice_money'];
            return ['ErrorCode' => 1, 'ErrorMessage' => '成功', 'Data' => $data];
        }else{
            $data['invoice_num'] = '';
            $data['money'] = 0;
            $data['code'] = 1;
            //$data['invoice_money']=$invoice_money;
            return ['ErrorCode' => 1, 'ErrorMessage' => '成功', 'Data' => $data];
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 操作开票（先开票）
     * @param array $input 请求参数
     * @param array $session 操作人信息
     * @param string $ip 操作设备ip
     * @retrun /multitype:array
     * @author dou 2021/9/10 20:18
     * |---------------------------------------------------------------------------------
     */
    public static function operationInvoice ( $input , $session , $ip ){
        //上传图片 凭证
            if(isset($input['inv_pic'])){
            $ass['invoice_pic']=$input['inv_pic'];
        }
        $BaseController = new BaseController();
        $type_inv = (int)$input['type_inv']??'1';
        $send = (int)$input['send']??'2';
        $inv_money = (float)$input['inv_money']??'0';
        $pay_money = (float)$input['pay_money']??'0';
        if($pay_money<0){
            $pay_money=0;
        }
        $inv_notes = $input['inv_notes']??'';
        $inv_note = $input['inv_note'];
        if($type_inv!=3 || $send==1){
            if($inv_notes!=""){
                $ass['invoice_number'] = $inv_note.",".$inv_notes;   //发票号
            }else{
                $ass['invoice_number'] = $inv_note;   //发票号
            }
            $ass['courier_number'] = $input['inv_num']??'';   //快递单号

        }else{
            $ass['invoice_number']='后续开票';
        }
        $ass['invoice_number'] = trim($ass['invoice_number'],',');
        //DB::connection()->enableQueryLog();#开启执行日志
        $where = ServiceCenter::where('id',$input['id']);

        $ass['whether_inv'] = 1;
        if($type_inv==3 && $send==1){
            if (isset($input['note_content'])) {
                $info = ServiceCenter::whereIn('id',$input['inv_ids'])->select('ser_id','apply_for_deduct','wat_num')->first();
                foreach ($info as $k => $v) {
                    //添加备注
                    CommonService::accMe($v['wat_num'], '服务中心账目管理', "已收票，".$input['note_content'], '', 1, $session['admin_groupnew'], $session['admin_acc'], $session['id']);
                }
            }
            if(!isset($input['inv_ids']) || $input['inv_ids']==''){
                return ['ErrorCode' => ErrorInc::FAILED_PARAM, 'ErrorMessage' => '缺少参数：inv_ids', 'Data' => []];
            }
            $where = ServiceCenter::whereIn('id',$input['inv_ids']);
        }elseif($type_inv==2){
            $info = ServiceCenter::where('id',$input['id'])->select('ser_id','apply_for_deduct','wat_num')->first();
            //添加备注
            if (isset($input['note_content'])) {
                //添加备注
                CommonService::accMe($info['wat_num'], '服务中心账目管理', "已收票，".$input['note_content'], '', 1, $session['admin_groupnew'], $session['admin_acc'], $session['id']);
            }
            $money_info = Db::table('invoice_money')->where('status',1)->where('invoice_nums',$inv_note)->select('sc_id','type','order_money','invoice_money','invoice_num','invoice_nums','residue_money')->first();
            if(!$money_info && $inv_note!=''){
                return ['ErrorCode' => ErrorInc::REQUEST_FORBIDDEN, 'ErrorMessage' => '添加失败，累计发票号异常！', 'Data' => []];
            }
        }
        DB::beginTransaction(); //开启事务
        $some = $where->update($ass);
        if($some){
            $inv_noteNew = '';
            if($type_inv==2 || ($type_inv==3 && $send==1)){
                if($inv_note!=""){
                    if ($money_info){
                        $invoice_money = $money_info['residue_money'];
                    }else{
                        $invoice_money = 0;
                    }
                    $money = $invoice_money+$inv_money;//计算发票累计剩余金额
                    $invoice_numArray = Db::table('invoice_money')->whereIn("invoice_nums",explode(',',$inv_note))->where("status",1)->select("residue_money",'invoice_nums')->orderBy('id','asc')->get()->toArray();
                    //根据金额重新累计发票号
                    if(!empty($invoice_numArray)){
                        $allmoney = 0;
                        foreach( $invoice_numArray as $k => $v ) {
                            $allmoney = $allmoney+$v['residue_money'];
                            if($allmoney>$pay_money){
                                $inv_noteNew .= ','.$v['invoice_nums'];
                            }
                        }
                    }
                }else{
                    $money = $inv_money;
                }
                $moneys = $money-$pay_money;
                if($moneys<0){
                    DB::rollback();
                    return ['ErrorCode' => ErrorInc::REQUEST_FORBIDDEN, 'ErrorMessage' => '发票金额不足', 'Data' => []];
                }
                if($inv_notes==""){
                    $invoice_nums = trim($inv_noteNew,',');
                }else{
                    $invoice_nums = $inv_notes.$inv_noteNew;
                }
                if($type_inv == 2){
                    $data = [];
                    $data['invoice_num'] = $ass['invoice_number'];
                    $data['createtime'] = date("Y-m-d H:i:s");
                    $data['creator'] = $session['admin_acc'];
                    $data['invoice_money'] = $money;
                    $data['order_money'] = $pay_money;
                    $data['ser_id'] = $info['ser_id'];
                    $data['invoice_nums'] = $invoice_nums;
                    $data['sc_id'] = $input['id'];
                    $data['type'] = 2;
                    $data['residue_money'] = $money-$pay_money;
                    if($moneys == 0){
                        $data['status'] = 2;
                    }
                    $res = Db::table('invoice_money')->insertGetid($data);
                }elseif($type_inv==3 && $send==1){
                    $inv_ids = ServiceCenter::whereIn('id',$input['inv_ids'])->select('id','ser_id','apply_for_deduct')->get();
                    if(!$inv_ids->isEmpty()){
                        $temp = [];
                        $key = 0;
                        foreach ($inv_ids as $key => $value) {
                            $temp[$key]['invoice_num'] = $ass['invoice_number'];
                            $temp[$key]['createtime'] = date("Y-m-d H:i:s");
                            $temp[$key]['creator'] = $session['admin_acc'];
                            $temp[$key]['invoice_money'] = $inv_money;
                            $temp[$key]['order_money'] = $pay_money;
                            $temp[$key]['ser_id'] = $value['ser_id'];
                            $temp[$key]['invoice_nums'] = $invoice_nums;
                            $temp[$key]['sc_id'] = $value['id'];
                            $temp[$key]['type'] = 3;
                            $temp[$key]['residue_money'] = $money-$pay_money;
                            $temp[$key]['status'] = 2;
                        }
                        if($moneys>0){
                            $key++;
                            $temp[$key]['invoice_num'] = $ass['invoice_number'];
                            $temp[$key]['createtime'] = date("Y-m-d H:i:s");
                            $temp[$key]['creator'] = $session['admin_acc'];
                            $temp[$key]['invoice_money'] = $inv_money;
                            $temp[$key]['order_money'] = $pay_money;
                            $temp[$key]['ser_id'] = $value['ser_id'];
                            $temp[$key]['invoice_nums'] = $invoice_nums;
                            $temp[$key]['sc_id'] = 0;
                            $temp[$key]['type'] = 3;
                            $temp[$key]['residue_money'] = $money-$pay_money;
                            $temp[$key]['status'] = 1;
                        }
                        $res = Db::table('invoice_money')->insertGetid($temp);
                    }else{
                        $res = false;
                    }
                }
                if($res){
                    if($inv_note!=""){
                        $res = Db::table("invoice_money")->where("invoice_nums",$inv_note)->where("id",'!=',$res)->update(['status'=>2]);
                        if(!$res){
                            DB::rollback();
                            return ['ErrorCode' => ErrorInc::MYSQL_FAILED, 'ErrorMessage' => '操作失败(invoice1)', 'Data' => []];
                        }
                    }
                }else{
                    DB::rollback();
                    return ['ErrorCode' => ErrorInc::MYSQL_FAILED, 'ErrorMessage' => '操作失败(invoice)', 'Data' => []];
                }
            }
            DB::commit();
            return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功', 'Data' => []];
        }else{
            DB::rollback();
            return ['ErrorCode' => ErrorInc::MYSQL_FAILED, 'ErrorMessage' => '操作失败(Service)', 'Data' => []];
        }

    }

    /**|---------------------------------------------------------------------------------
     * @name 获取付款类型
     * @retrun /multitype:array
     * @author dou 2021/12/14 4:41
     * |---------------------------------------------------------------------------------
    */
    public static function getTypeName ( $type = false ){
      //  $data = [['type'=>2,'name'=>'速电付款','category'=>'1'],['type'=>5,'name'=>'蓝城付款','category'=>'1'],['type'=>6,'name'=>'个人付款','category'=>'1'],['type'=>8,'name'=>'对公付款','category'=>'3'],['type'=>9,'name'=>'对私付款','category'=>'3'],['type'=>10,'name'=>'对平台付款','category'=>'3']];

        $data = [['type'=>8,'name'=>'对公付款','category'=>'3'],['type'=>9,'name'=>'对私付款','category'=>'3']];

        if($type){
            $data = array_column($data, 'name','type');
        }
        return $data;
    }
}
