<?php
/*
|--------------------------------------------------------------------------
| 账单报表
|--------------------------------------------------------------------------
|  账单信息的基础操作  展示、生成、审核
|  @author doubin
|  @Date: 2021/09/01
|  @Time: 10:29
|  @Email: db@sudianwang.com
|  @version 1.0
|  @copyright BlueCity
*/

namespace App\Http\Controllers\Financial;
use App\Http\Controllers\BaseController;
use App\Http\Controllers\Common\CommonController;
use App\Http\Controllers\ExcelInfo\ExceloutController;
use App\Models\Admin;
use App\Models\AdminInfor;
use App\Models\OrderList;
use App\Models\Orders;
use App\Models\ServiceCenter;
use App\Models\SettlementList;
use App\Models\SettlementMoney;
use App\Models\StatementsList;
use App\Models\SyncStores;
use App\Models\TicketList;
use App\Services\AdminsService;
use App\Services\CompanyService;
use App\Services\ExceloutService;
use App\Services\LabtypeService;
use App\Services\OrderService;
use App\Services\ServiceCenterService;
use App\Services\ServiceProviderService;
use App\Services\SettlementService;
use App\Services\StatementsListService;
use App\Services\SysStoresService;
use App\Services\TicketListService;
use App\User;
use Illuminate\Http\Request;
use DB;
use App\Services\CommonService;//通用服务
use BlueCity\Core\Inc\ErrorInc;

/**
 * @name 账单报表
 * Class InvoiceTableController
 * @package App\Http\Controllers\Financial
 */
class StatementsListController extends BaseController{

    protected $rules = array(
        'start_time' => '开始时间',
        'end_time' => '结束时间',
        'category' => '账单类型',
        'mouth_pay' => '结算方式',
        'stl_serid' => '服务商id',
        'category' => '结算类型',
        'stl_wat' => '结算单号',
        'company_name' => '门店名称',
        'stl_money' => '账单金额',
        'apply_note' => '备注',
    );
    /**|---------------------------------------------------------------------------------
     * @name 列表页
     * @param string/array endDate 查询时间
     * @param int mouth_pay 结算方式  1：月结 2：零散 3：周结 4：五大区
     * @param string stl_type 结算状态  4：未处理 1：商家确认中 2：财务结算中 5：待补货 3：已完成
     * @param string company_name 门店名称
     * @param string ser_yycode 用友系统编号
     * @param int category 结算单类型
     * @param string stl_wat 计算单号
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/1 10:34
     * |---------------------------------------------------------------------------------
    */
    public function index ( Request $request ){
        if(!$request->filled('mouth_pay')){
            return $this->error('请输入查询类型', ErrorInc::INVALID_PARAM);
        }
        $input = $request->all();
        $session = $request->get("session_token");
        if(!in_array($input['mouth_pay'],[0,1,2,3,4])){
            return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);
        }
        $data = StatementsListService::getList($input, $session);

        //导出 start 状态为月结时导出
        if ($input['is_excel'] == 1) {
            $sqls = $data['Data']['sqls'];
           //dump($sqls);
            $excel = new CommonController();
            return $excel->getExcelOut($input['Pri_id'], $sqls, $session);
        }
        if(isset($data['Data']['sqls'])){
            unset($data['Data']['sqls']);
        }

        //导出 end

        //导出 start 所有状态都有 导出报表
        if ($input['is_excel'] == 2) {
            if(!$request->filled('dateMouth')){
                return $this->error('参数错误', ErrorInc::FAILED_PARAM);
            }
            $dateMouth = date("Y-m",strtotime($request->input('dateMouth')));
            $dates = explode('-', $dateMouth);
            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 = $dateMouth . "-01";
            $stl_endtime = $dateMouth . "-" . $text;
            /*$list = DB::table('statements_list')->WhereBetween('stl_endtime', [$stl_startime, $stl_endtime])->select('stl_wat')->get()->toarray();
            if (empty($list)) {
                return $this->error('暂无数据', ErrorInc::DATA_EMPTY);
            }
            $wats = '';
            foreach ($list as $v){
                $wats .= "'".$v['stl_wat']."',";
            }
            $wats = rtrim($wats,',');*/

            if ($session['admin_groupnew'] != 7){//管理员可以看全部
                $sqlnew = "select gone_settlement_list.*,d.p_price,d.wat_num as wat_three from gone_settlement_list left join gone_statements_list on gone_settlement_list.wat_num = gone_statements_list.stl_wat LEFT JOIN gone_settlement_three as d on gone_settlement_list.list_id=d.list_id where gone_settlement_list.company_id='". $session['company_id']."' and gone_statements_list.stl_endtime Between '". $stl_startime."'and '". $stl_endtime."'";
            }else{
                $sqlnew = "select gone_settlement_list.*,d.p_price,d.wat_num as wat_three from gone_settlement_list left join gone_statements_list on gone_settlement_list.wat_num = gone_statements_list.stl_wat LEFT JOIN gone_settlement_three as d on gone_settlement_list.list_id=d.list_id where gone_statements_list.stl_endtime Between '". $stl_startime."'and '". $stl_endtime."'";
            }

            //echo $sqlnew;
            $lists = DB::select($sqlnew);
            if($lists){
                $exceout = new ExceloutService();
                $con_name = '月报表明细';//控制器名称
                $action = 'SettlementMouth';//控制器
                $field_data = $exceout->gainFields($request->get('session_token')['id'], $action);
                if (empty($field_data)) {
                    return $this->error('您暂时无导出权限', ErrorInc::MYSQL_FAILED);
                }
                return $exceout->createPlan($lists,$sqlnew,200,$action,$con_name,$request->get('session_token')['id'],$request->get('session_token')['admin_acc'],$request->get('session_token')['company_id']);
            }else{
                return $this->error('暂无数据', ErrorInc::MYSQL_FAILED);
            }
        }
        //导出 end


        //获取结算方式
        $data['Data']['mouthPay'] = ServiceProviderService::getMouthPay();
        //获取结算状态
        $data['Data']['getStlType'] = StatementsListService::getStlType();

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

    /**|---------------------------------------------------------------------------------
     * @name 获取列表异步加载信息
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/2 15:59
     * |---------------------------------------------------------------------------------
    */
    public function getDetails ( Request $request ){
        $data['showcount'] = StatementsListService::getStateBar($request->get("session_token"),1);//获取操作权限可展示订单状态栏
        return $this->success('获取成功', $data);
        exit;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取可出账单门店列表
     * @param string start_time 开始时间
     * @param string end_time 结束时间
     * @param int category 账单类型
     * @param int mouth_pay 结算方式  1：月结 2：零散 3：周结 4：五大区
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/2 16:59
     * |---------------------------------------------------------------------------------
     */
    public function getStoreList ( Request $request ){
        $input = $request->all();
        $checkKey = CommonService::checkKey(['start_time', 'end_time', 'category','mouth_pay'],$input,$this->rules);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        $params['stl_startime'] = $input['start_time'];
        $params['stl_endtime'] = $input['end_time'];
        $ser_id = StatementsListService::getStatementsList($params,['stl_serid'],'pluck');
        $where['mouth_pay'] = $input['mouth_pay'];
        if($ser_id){
            $where['id_notin'] = $ser_id;
        }
        $session = $request->get("session_token");
        $list_service_type40['company_id'] = $session['company_id'];
        $list_service_type40['admin_groupnew'] = 2;
        $list_service_type55['admin_groupnew'] = 3;
        $where['list_service_type_searchor']['list_service_type40_next_level'] = $list_service_type40;
        $where['list_service_type_searchor']['list_service_type55_next_level'] = $list_service_type55;
        $where['ad_project_findinset'] = $input['category'];
        $res = AdminsService::getAdmins($where,['id','company_name']);
        if ($res){
            return $this->success('成功',$res);
        }else{
            return $this->error('无数据', ErrorInc::DATA_EMPTY);
        }

    }

    /**|---------------------------------------------------------------------------------
     * @name 生成结算单
     * @param int stl_serid 服务商id
     * @param string start_time 开始时间
     * @param string end_time 结束时间
     * @param string category 结算类型
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/2 18:34
     * |---------------------------------------------------------------------------------
    */
    public function creactSettle ( Request $request ){
        $input = $request->all();
        $session = $request->get("session_token");
        $checkKey=CommonService::checkKey(['stl_serid', 'start_time', 'end_time','category'],$input,$this->rules);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        $company_name = AdminsService::getAdminsBy('id', $input['stl_serid'],['company_name']);//获取当前操作服务商名称
        $rea = StatementsListService::getStatementsList(['stl_endtime_searcheqgt'=>$input['end_time'],'stl_serid'=>$input['stl_serid']],['stl_id'],'first');
        if($rea){
            return $this->error('该时间段已存在'.$company_name.'的订单', ErrorInc::REPEAT_SUBMIT);exit;
        }
        /*-----------------------------------------------拼接条件获取满足的结算单数据开始-----------------------------------*/
        $admin = Admin::where('id',$input['stl_serid'])->select('admin_groupnew','company_id')->first();
        if($admin['admin_groupnew']==3){
            $stl_serid = Admin::where('company_id',$admin['company_id'])->whereIn('admin_groupnew',[2,3])->select('id')->get();
            $stl_serid = CommonService::dataToArray($stl_serid);
            $stl_serid = array_column($stl_serid, 'id');//
            $where['ser_id_searchin'] = $stl_serid;
        }else {
            $where['ser_id'] = $input['stl_serid'];
        }
        if($input['category'] == 1){
            $where['category_searchin'] = [1,2];
        }else {
            $where['category'] = $input['category'];
        }
       // $where['p_id_noteq'] = 146;
        $wat_num['wat_num'] = "";
        $wat_num['wat_num_isnull'] = "";
        $where['wat_num_searchor'] = $wat_num;
        $where['sett_status'] = 1;
        $list_service_type40['setfeeds_time_searcheqlt'] = $input['end_time']." 23:59:59";
        $list_service_type40['list_service_type'] = 40;
        $list_service_type40['locksel_type'] = 1;
        $list_service_type40['locked'] = 1;
        $list_service_type55['create_time_searcheqlt'] = $input['end_time']." 23:59:59";
        $list_service_type55['list_service_type'] = 55;
        $where['list_service_type_searchor']['list_service_type40_next_level'] = $list_service_type40;
        $where['list_service_type_searchor']['list_service_type55_next_level'] = $list_service_type55;
        $where['company_id'] = $session['company_id'];
        $res = SettlementService::getSettlementList($where,['id','all_price','subsidy_money','list_service_type','wat_judge','order_num','p_id','msg_id']);
        /*-----------------------------------------------拼接条件获取满足的结算单数据结束-----------------------------------*/
        if ($res){
            $return = StatementsListService::creactSettle($res, $request->ip(), $session, $input);
            return $this->error($return['ErrorMessage'], $return['ErrorCode'], $return['Data']);exit;
        }else{
            $mess = "添加失败;暂无可结算订单";
            return $this->error('无数据', ErrorInc::DATA_EMPTY,$mess);exit;
        }

    }

    /**|---------------------------------------------------------------------------------
     * @name 删除账单
     * @param string stl_wat 结算单单号
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/2 20:34
     * |---------------------------------------------------------------------------------
    */
    public function delEntry (Request $request){
        if ($request->filled('stl_wat')){
            $stl_wat = $request->input('stl_wat');
            try {
                DB::beginTransaction(); //开启事务
                $poss['wat_num'] = "";
                $poss['wat_judge'] = "1";
                $stl_ids = StatementsListService::getStatementsListBy('stl_wat', $stl_wat,['stl_ids','stl_serid']);
                if(empty($stl_ids)){
                    $res=1;
                }else{
                    $mouth_pay = AdminsService::getAdminsBy('id', $stl_ids['stl_serid'],['mouth_pay']);
                    if($mouth_pay == 2){
                        $poss['sett_status'] = '63';
                    }
                    $res=SettlementList::where('wat_num',$stl_wat)->update($poss);
                }
                $passa['til_watnum'] = '';
                $til_watnum = TicketListService::getTkicetBy('til_watnum', $stl_wat ,['til_id'],'first');
                if(empty($til_watnum)){
                    $reb = 1;
                }else{
                    $reb = TicketList::where('til_watnum',$stl_wat)->update($passa);
                }
                $passc['til_wats'] = '';
                $til_watnum = TicketListService::getTkicetBy('til_wats', $stl_wat ,['til_id'],'first');
                if(empty($til_wats)){
                    $rec = 1;
                }else{
                    $rec = TicketList::where('til_wats',$stl_wat)->update($passc);
                }
                $rea = StatementsList::where('stl_wat',$stl_wat)->delete();
                if($res && $rea && $reb && $rec){
                    DB::commit();//成功则提交
                    $session = $request->get('session_token');
                    $this->insertingLog('删除账单，',$stl_wat,$stl_wat.'成功删除','月结报表',$request->ip(),$session['admin_acc']);//日志
                    return $this->success('操作成功');exit;
                }else{
                    DB::rollback();//不成功回滚
                    return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
                }
            } catch(\Exception $e){
                DB::rollback();//回滚
                return response()->json(['Data'=>'','ErrorCode'=>2,'ErrorMessage'=>$e->getMessage()]);exit;
            }
        }else{
            return $this->error('参数错误', ErrorInc::FAILED_PARAM);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 提交商家确认
     * @param string stl_wat 结算单号
     * @param string apply_note 提交备注
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/2 20:51
     * |---------------------------------------------------------------------------------
    */
    public function submitMer(Request $request){
        if(!$request->filled('stl_wat')){
            return $this->error('缺少单数结算单号', ErrorInc::FAILED_PARAM);exit;
        }
        $input = $request->only('stl_wat','apply_note');
        $apply_note = $input['apply_note']??'';
        $session = $request->get('session_token');
        $return = StatementsListService::submitMer($input['stl_wat'], $apply_note, $session, $request->ip());
        return $this->error($return['ErrorMessage'], $return['ErrorCode']);exit;
    }

    /**|---------------------------------------------------------------------------------
     * @name 提交待补货
     * @param string stl_wat 结算单号
     * @retrun /multitype:array
     * @author dou 2021/9/2 20:52
     * |---------------------------------------------------------------------------------
    */
    public function suppleSubmit ( Request $request){
        if ($request->filled('stl_wat')) {
            $input = $request->only('stl_wat');
            $session = $request->get('session_token');
            $res = SettlementList::whereRaw("wat_num ='" . $input['stl_wat'] . "' and (list_service_type!=40 and list_service_type!=55")->first();

            if ($res) {//存在状态错误的订单请联系相关人员检查数据
                return $this->error('存在状态错误的订单请联系相关人员检查数据', ErrorInc::REQUEST_FORBIDDEN);exit;
            } else {
                $sel['stl_type'] = 5;
                $res = StatementsList::whereRaw("stl_wat='" . $input['stl_wat'] . "'")->update($sel);
                if ($res) {
                    $this->insertingLog('提交待补货，', $input['stl_wat'], $input['stl_wat'].':月结算审核至待补货', '月结报表', $request->ip(), $session['admin_acc']);//日志
                    return $this->success('操作成功');exit;
                } else {
                    return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
                }
            }
        }else{
            $this->error('参数错误', ErrorInc::FAILED_PARAM);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 驳回账单
     * @param string stl_wat      结算单号
     * @param string company_name 服务商名称
     * @param int stl_serid       服务商id
     * @param string apply_note    驳回备注
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/3 14:34
     * |---------------------------------------------------------------------------------
    */
    public function operation (Request $request)
    {
        $input = $request->all();
        $session = $request->get("session_token");
        $checkKey = CommonService::checkKey(['stl_wat', 'company_name', 'stl_serid','apply_note'],$input,$this->rules);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        $wat_num = SettlementService::getSettlementListBy('wat_num', $input['stl_wat'],[],'first');
        $mouth_pay = AdminsService::getAdminsBy('id', $input['stl_serid'],['mouth_pay']);
        if($mouth_pay==2){
            $poss["sett_status"] = 63;
        }else{
            $poss["sett_status"] = 1;
        }
        $res = SettlementService::getSettlementList(['wat_num'=>$input['stl_wat'],'sett_status_noteq'=>10],['id'],'first');
        if (!empty($res)){
            return $this->error('操作失败stli', ErrorInc::REQUEST_FORBIDDEN);exit;
        }else{
            try{
                DB::beginTransaction(); //开启事务
                $apply = SettlementList::where('wat_num',$input['stl_wat'])->update($poss);
                if(!empty($apply)){
                    $list = SettlementList::where('wat_num',$input['stl_wat'])->get();
                    $list_id = "";
                    $sys_num = "";
                    foreach( $list as $k => $v ){
                        $list_id.=",'".$v['list_id']."'";
                        $sys_num.=",'".$v['sys_num']."'";
                    }
                    $list_id = ltrim($list_id,',');
                    $sys_num = ltrim($sys_num,',');
                    $AccArr["account_status"] = 1;
                    OrderList::whereRaw("serial_number in (".$list_id.")")->update($AccArr);
                    Orders::whereRaw("sys_num in (".$sys_num.")")->update($AccArr);
                    $sel['stl_type'] = 4;
                    $stl = StatementsList::where('stl_wat',$input['stl_wat'])->update($sel);
                    if(!$stl){
                        DB::rollback();//回滚
                        return $this->error('操作失败stlm', ErrorInc::MYSQL_FAILED);exit;
                    }
                    $til['til_wats'] = "";
                    $til['til_state'] = "10";
                    TicketList::where('til_wats',$input['stl_wat'])->update($til);
                    if($request->input('apply_note') !=""){
                        $add_note = CommonService::accMe($input['stl_wat'], '驳回结算单', $input['apply_note'], '', 2, $session['admin_groupnew'], $session['admin_acc'], $session['id']);
                    }
                    /****************************同步通知门店***************************/
//                    $store=SyncStores::where("ser_id",$wat_num['ser_id'])->where("type",2)->value('id');
                    $store = CommonService::getSyncStores($wat_num['ser_id'], $wat_num['category']);
                    if(!empty($store)){
                        $pop = [
                            'sd_bill_bumber' => $input['stl_wat'],
                        ];
                        $store = SysStoresService::sysStore($pop, 'reject',$store);
                        if($store['ErrorCode']!=1){
                            DB::rollBack();
                            return $store;
                        }
                    }
                    /*******************************************************/
                    $content=$input['stl_wat']."结算号（".$input['company_name']."）";
                    $this->insertingLog('驳回结算单，',$input['stl_wat'],$content,'月结报表',$request->ip(),$session['admin_acc']);//日志
                    DB::commit();//提交
                    return $this->success('操作成功');
                    return response()->json(['Data'=>'','ErrorCode'=>'1','ErrorMessage'=>'操作成功']);exit;
                }else{
                    DB::rollback();//回滚
                    return $this->error('操作失败stl', ErrorInc::MYSQL_FAILED);exit;
                }
            }catch(\Exception $e){
                DB::rollback();//回滚
                return $this->error($e->getMessage(), ErrorInc::SERVER_FAILED);exit;
            }
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 确认账单
     * @param string fwids 结算单包含订单id
     * @param string apply_note 处理备注
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/3 15:17
     * |---------------------------------------------------------------------------------
    */
    public function dealWith (Request $request)
    {
        $input = $request->all();
        $session = $request->get("session_token");
        $checkKey = CommonService::checkKey(['fwids', 'apply_note'],$input,$this->rules);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        $wat_num = SettlementService::getSettlementList(['id_searchin'=>$input['fwids']]);
        if($wat_num) {
            $serid = $wat_num[0]['ser_id'];
            $company_name = AdminsService::getAdminsBy('id', $serid,['company_name']);
            $StatementsList = StatementsListService::getStatementsListBy('stl_wat', $wat_num[0]['wat_num'],['stl_money','stl_category','company_id']);
            $apply_for_money = $StatementsList['stl_money'];
            $stl_category = $StatementsList['stl_category'];
            DB::beginTransaction();
            /*--------------------------------------------添加财务结算信息开始----------------------------------------*/
            $res = ServiceCenterService::insertServiceCenter($wat_num[0]['wat_num'], $serid, $company_name, $session['admin_acc'], $apply_for_money,$stl_category,$StatementsList['company_id']);
            /*--------------------------------------------添加财务结算信息结束----------------------------------------*/
            /*--------------------------------------------修改结算单状态开始---------------------------------------------*/
            $poss['sett_status'] = 20;//结算中
            $acc_status = SettlementList::whereRaw("id in (" . $request->input('fwids') . ")")->update($poss);
            /*--------------------------------------------修改结算单状态结束---------------------------------------------*/
            /*--------------------------------------------修改账单状态开始-----------------------------------------------*/
            $stl_type['stl_type'] = 2;
            $rea = StatementsList::where('stl_wat', $wat_num[0]['wat_num'])->update($stl_type);
            /*--------------------------------------------修改账单状态结束-----------------------------------------------*/
            if ($acc_status && $res && $rea) {
                DB::commit();//成功则提交
                $list_id = "";
                $sys_num = "";
                foreach ($wat_num as $k => $v) {
                    $list_id .= ",'" . $v['list_id'] . "'";
                    $sys_num .= ",'" . $v['sys_num'] . "'";
                }
                $list_id = ltrim($list_id, ',');

                $AccArr["account_status"] = 20;
                OrderList::whereRaw("serial_number in (" . $list_id . ")")->update($AccArr);
                $add_note = CommonService::accMe($wat_num[0]['wat_num'], '订单金额确认', $input['apply_note'], '', 2, $session['admin_groupnew'], $session['admin_acc'], $session['id']);
                $content = $wat_num[0]['wat_num'] . "结算号(".$company_name.")";
                $this->insertingLog('商家金额确认，', $wat_num[0]['wat_num'], $content, '月结报表', $request->ip(), $request->get('session_token')['admin_acc']);
                return $this->success('操作成功');
                exit;
            } else {
                DB::rollback();
                return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
            }
        }else{
            return $this->error('无数据', ErrorInc::DATA_EMPTY);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 查看订单详情
     * @param int state     订单状态(搜索)
     * @param int ser_id       服务中心id
     * @param string order_num     平台单号
     * @param string list_id       派工单号
     * @param string wat_num       结算单号
     * @param int p_id          销售平台
     * @param string shr_name      客户姓名
     * @param string shr_phone     客户电话
     * @param page          页数
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/4 16:47
     * |---------------------------------------------------------------------------------
    */
    public function search ( Request $request ){
        $input = $request->all();
        $input['state'] = 0;
        $input['source_type'] = 1;
        $session = $request->get("session_token");
        $data = SettlementService::getList($input, $session);
        if($data['ErrorCode']!=1){
            return $data;
        }else {
            $list = $data['Data'];
            if ($list['list']) {
                return $this->success('获取成功', $list);
                exit;
            } else {
                return $this->error('暂无数据', ErrorInc::DATA_EMPTY, $list);
                exit;
            }
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取结算单明细
     * @param string sem_slid 结算单id
     * @param string list_service_type 结算单状态
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/4 17:27
     * |---------------------------------------------------------------------------------
    */
    public function getPriceDetail ( Request $request ){
         if(!$request->filled('sem_slid') || !$request->filled('list_service_type')){
             return $this->error('参数错误', ErrorInc::FAILED_PARAM);
         }
         $list = SettlementService::getPriceById($request->input('sem_slid'),$request->input('list_service_type'));
         if($list){
             $data['all_price'] = $list['all_price'];
             unset($list['all_price']);
             $data['list'] = $list;
             return $this->success('获取成功', $data);
             exit;
         }else{
             return $this->error('暂无数据', ErrorInc::DATA_EMPTY, $list);exit;
         }
    }

    /**|---------------------------------------------------------------------------------
     * @name 删除金额明细标签
     * @param string sem_slid 结算单id
     * @param string sem_type 删除的标签类型
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/4 18:05
     * |---------------------------------------------------------------------------------
    */
    public function deletPrice ( Request $request ){
        $input = $request->all();
        $return = SettlementService::deletPrice($input,$request->ip(),$request->get("session_token"));
        return $this->error($return['ErrorMessage'], $return['ErrorCode'], $return['Data']);exit;
    }

    /**|---------------------------------------------------------------------------------
     * @name 添加标签
     * @param array money_data 需添加标签  sem_type：标签id  sety_name：标签名称  sem_price：标签金额
     * @param string sem_slid 结算单id
     * @param string sem_synum 系统单号
     * @param string all_price 总金额
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/7 11:43
     * |---------------------------------------------------------------------------------
    */
    public function insertPrice ( Request $request ){
        $input = $request->all();
        $return = SettlementService::insertPrice($input,$request->ip(),$request->get("session_token"));
        return $this->error($return['ErrorMessage'], $return['ErrorCode'], $return['Data']);exit;
    }

    /**|---------------------------------------------------------------------------------
     * @name 编辑标签金额
     * @param int sem_slid     结算单数据id
     * @param int sem_id     金额详情数据id
     * @param string sem_price  金额
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2021/9/7 16:46
     * |---------------------------------------------------------------------------------
    */
    public function updatePrice ( Request $request ){
        $input = $request->all();
        $return = SettlementService::updatePrice($input,$request->ip(),$request->get("session_token"));
        return $this->error($return['ErrorMessage'], $return['ErrorCode'], $return['Data']);exit;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取凭证
     * @param stl_wat 结算单号
     * @return \Illuminate\Http\JsonResponse
     * @author he
     * |---------------------------------------------------------------------------------
     */
    public function uploadView (Request $request)
    {
        if ($request->filled('stl_wat')){
            $stl_wat = $request->input('stl_wat');
            $tomy = DB::table('pictures')->where('sett_wat_num',$stl_wat)->value("upload_pictures");
            if($tomy){
                return $this->success('成功',$this->picurl($tomy));exit;
            }else{
                return $this->error('暂无凭证', ErrorInc::DATA_EMPTY);
            }
        }

    }


    /**
     * 导出门店报表结算算账单
     * @param  accountname  string    账户名
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author du
     * @date 2021/12/16
     */
    public function billExport(Request $request)
    {
        $session = $request->get('session_token');
        $input = $request->all();
        //当是月份的时候
        if(!empty($input['date'])){
            $timestamp = strtotime($input['date']);
            $input['start_time'] = date('Y-m-01 00:00:00', $timestamp);//当月开始时间
            $mdays = date( 't', $timestamp );
            $input['end_time'] = date( 'Y-m-'.$mdays.' 23:59:59',$timestamp);//当月结束时间
        }
        if(empty($input['accountname']) && empty($input['start_time']) && empty($input['end_time'])){
            return $this->error('账户或日期不能为空', ErrorInc::FAILED_PARAM);
        }
        //DB::connection()->enableQueryLog();
        $data = DB::table('admin_infor as ai')
            ->leftjoin('statements_list as sl','ai.admin_id','=','sl.stl_serid')
            ->where('sl.stl_type',$input['stl_type'])
            ->where('ai.accountname',$input['accountname'])
            ->where('sl.stl_startime','>=',$input['start_time'])
            ->where('sl.stl_endtime','<=',$input['end_time']);
        if(isset($input['company_name'])&&$input['company_name']!=''){
            $data = $data->where("sl.stl_serid",$input['company_name']);
        }

        $data = $data->get(['stl_id','stl_wat','sl.stl_serid','ai.accountname','ai.service_name','ai.id','ai.admin_id'])->toArray();
        //print_r(DB::getQueryLog());
        if(empty($data)){
            return response()->json(['Data'=>'','ErrorCode'=>'2','ErrorMessage'=>'未找到未结算账单']);
        }
     $flag = 1;
    $war_num = [];
        $exceout = new ExceloutService();
    $stl_wats = array_column($data, 'stl_wat');
        DB::connection()->enableQueryLog();
        $list = SettlementList::leftjoin('user as u','u.id','=','settlement_list.customer_id')->whereIn('wat_num',$stl_wats)->select("settlement_list.*", "shr_sheng", 'shr_shi', 'shr_xian', 'shr_adress')->get()->toarray();
        $sqls =  DB::getQueryLog()[0];
        //$lists = $exceout->getSqls($sqls)['list'];

       // dump($sql);exit;
        if($list){
            $sql = $exceout->getSqls($sqls)['sqls'];

            if(isset($input['company_name'])){
                $se_name = DB::table('admin')->where('id',$input['company_name'])->value('company_name');;
            }else{
                $se_name = '账号－'.$input['accountname'];
            }

            $con_name = '门店导出-'.$se_name;//控制器名称
            $action = 'SettlementBillExport';//控制器
            $field_data = $exceout->gainFields($request->get('session_token')['id'], $action);
            if (empty($field_data)) {
                $war_num[] = $stl_wats."-nogainFields";
                $flag = 2;
            }else {
                $return = $exceout->createPlan($list, $sql, 300, $action, $con_name, $session['id'], $session['admin_acc'], $session['company_id']);
                //print_r($return);
                if ($return->original['ErrorCode'] != 1) {
                    $flag = 2;
                    $war_num[] = $stl_wats . "-nocreate";
                } else {
                    $war_num[] = $stl_wats. "-success";
                }
            }

        }else{
            $flag = 2;
            $war_num[] = $stl_wats."-nodata";
        }



    /* foreach ($data as $v){
        $sql = "select * from gone_settlement_list where wat_num = '".$v['stl_wat']."'";//where wat_num = '".$v['stl_wat']."'
        $list = DB::select($sql);
        if($list){
            if(isset($input['company_name'])){
                $se_name = DB::table('admin')->where('id',$v['stl_serid'])->value('company_name');
            }else{
                $se_name = '账号－'.$v['accountname'];
            }
            $exceout = new ExceloutService();
            $con_name = '门店导出-'.$se_name;//控制器名称
            $action = 'SettlementBillExport';//控制器
            $field_data = $exceout->gainFields($request->get('session_token')['id'], $action);
            if (empty($field_data)) {
                $war_num[] = $v['stl_wat']."-nogainFields";
                $flag = 2;
            }else {
                $return = $exceout->createPlan($list, $sql, 200, $action, $con_name, $session['id'], $session['admin_acc']);
                //print_r($return);
                if ($return->original['ErrorCode'] != 1) {
                    $flag = 2;
                    $war_num[] = $v['stl_wat'] . "-nocreate";
                } else {
                    $war_num[] = $v['stl_wat'] . "-success";
                }
            }

        }else{
            $flag = 2;
            $war_num[] = $v['stl_wat']."-nodata";
        }
     }*/


     if($flag==1){
         CommonService::addLog('服务商导出账单成功', json_encode($war_num), '','SettlementSER');
         return response()->json(['Data' => '0', 'ErrorMessage' => '去下载列表执行', 'ErrorCode' => 1]);
     }else{
         CommonService::addLog('服务商导出账单失败', json_encode($war_num), '','SettlementSER');
         return response()->json(['Data' => '', 'ErrorMessage' => '存在失败信息', 'ErrorCode' => 2]);
     }

    }


    /**
     * @name 同步账单博世补货
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/4/8
     */
    public function sysRepleni(Request $request){
        if($request->input('type')==1){
            $count = StatementsList::whereIn('stl_type',[4,5])->count();
            return $this->success('操作成功',$count);
        }else{
            $id = $request->input('stl_id')??0;
            $data = StatementsList::where('stl_id','>',$id)->whereIn('stl_type',[4,5])->select('stl_wat','stl_id')->orderBy('stl_id','ASC')->first();
            // dump($data);
            if(!empty($data)){
                $sql = "SELECT b.goods_id,b.goods_name,a.id,wat_num,a.sys_num FROM gone_settlement_list as a LEFT JOIN gone_order_msg as b on a.msg_id=b.id where b.goods_brand='博世' and wat_num='".$data['stl_wat']."' and list_service_type=40";
                $list = DB::select($sql);
                if(count($list)>=5){
                    $good_subsidies = DB::table("good_subsidies")->pluck("gs_price",'gs_pgid');
                    $sql = "INSERT IGNORE INTO gone_repleni_data (rd_setid,rd_price,rd_pgid,rd_goodname,rd_watnum,rd_synum) VALUES ";
                    $sqls = [];
                    foreach( $list as $k => $v ){
                        $sqls[] = "('".$v['id']."','".$good_subsidies[$v['goods_id']]."','".$v['goods_id']."','".$v['goods_name']."','".$v['wat_num']."','".$v['sys_num']."')";
                    }
                    $sql .= implode(',',$sqls);
                    // echo $sql;
                    DB::insert($sql);
                }
                return $this->success('操作成功',$data);
            }else{
                return $this->error('已完成', ErrorInc::MYSQL_FAILED);
            }

        }
    }

    /**
     * @name 同步补货博世补贴金额
     * rd_state 数据执行1未执行2已执行3执行失败
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/4/8
     */
    public function sysSubsidies(Request $request){
        if($request->input('type')==1){
            $count = DB::table("repleni_data")->where("rd_state",1)->count();
            return $this->success('操作成功',$count);
        }else{
            $data = DB::table("repleni_data")->where("rd_state",1)->first();
            if($data){
                $data = CommonService::dataToArray($data);
                DB::beginTransaction(); //开启事务
                $sem_price = SettlementMoney::where('sem_slid',$data['rd_setid'])->where('sem_type',1)->value('sem_price');
                if($sem_price){
                    if($sem_price!='0'){
                        $rea = SettlementMoney::where("sem_slid",$data['rd_setid'])->where('sem_type',1)->update(['sem_price'=>'0']);
                    }else{
                        $rea = 1;
                    }
                }else{
                    $rea = 1;
                }
                $ret = SettlementMoney::where("sem_slid",$data['rd_setid'])->where("sem_type",266)->value('sem_id');
                if(!$ret){
                    $res = SettlementMoney::insert(['sem_slid'=>$data['rd_setid'],'sem_synum'=>$data['rd_synum'],'sem_price'=>$data['rd_price'],'sem_type'=>'266','sem_creacter'=>'研发','add_time'=>date("Y-m-d H:i:s")]);
                }else{
                    $res = SettlementMoney::where("sem_slid",$data['rd_setid'])->where('sem_type',266)->update(['sem_price'=>$data['rd_price']]);
                }
                if($rea && $res){
                    $all_price = SettlementMoney::where("sem_slid",$data['rd_setid'])->sum('sem_price');
                    $red = SettlementList::where("id",$data['rd_setid'])->update(['all_price'=>$all_price]);
                    if($red){
                        $all_price1 = SettlementList::where("wat_num",$data['rd_watnum'])->where("list_service_type",'!=',55)->sum('all_price');
                        $all_price2 = SettlementList::where("wat_num",$data['rd_watnum'])->where("list_service_type",55)->sum('subsidy_money');
                        $possa['stl_money'] = sprintf("%.2f", $all_price1+$all_price2);
                        $ref = StatementsList::where("stl_wat",$data['rd_watnum'])->update($possa);
                        if($ref){
                            $ree = DB::table("repleni_data")->where("rd_id",$data['rd_id'])->update(['rd_state'=>2]);
                        }else{
                            $ree =  DB::table("repleni_data")->where("rd_id",$data['rd_id'])->update(['rd_state'=>3]);
                        }
                    }else{
                        $ree = DB::table("repleni_data")->where("rd_id",$data['rd_id'])->update(['rd_state'=>3]);
                    }
                }else{
                    $ree = DB::table("repleni_data")->where("rd_id",$data['rd_id'])->update(['rd_state'=>3]);
                }
                if($ree){
                    $content = '结算单号：'.$data['rd_watnum'].'（'.$data['rd_setid'].')金额'.$sem_price.'->0';
                    $this->insertingLog('同步补货博世补贴金额', $data['rd_watnum'], $content, '账单报表', $request->ip(), $request->get('session_token')['admin_acc']);
                    DB::commit();
                    return $this->success('操作成功',$data);
                }else{
                    DB::rollback();//不成功回滚
                    return $this->error('操作失败', ErrorInc::FILE_FAILED,$data);exit;
                }

            }else{
                return $this->error('已完成', ErrorInc::MYSQL_FAILED);
            }
        }

    }

}
