<?php
/**
 * 文件名称（结算单列表）
 * 文件简单描述（结算单数据操作）
 * @author DouBin
 * @Date: 2021/9/3
 * @Time: 17:05
 * @Email: db@sudianwang.com
 * @version 1.0
 * @copyright BlueCity
 */

namespace App\Http\Controllers\Financial;
use App\Http\Controllers\BaseController;
use App\Models\OrderList;
use App\Models\OrderMsg;
use App\Models\Orders;
use App\Models\SetmoneyType;
use App\Models\SettlementList;
use App\Models\SettlementMoney;
use App\Services\SettlementService;
use App\Services\StatementsListService;
use Illuminate\Http\Request;
use DB;
use App\Services\CommonService;//通用服务
use BlueCity\Core\Inc\ErrorInc;

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

    protected $rules = array(
        'start_time' => '开始时间',
        'end_time' => '结束时间',
        'category' => '账单类型',
        'stl_serid' => '服务商id',
    );
    /**|---------------------------------------------------------------------------------
     * @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/3 17:09
     * |---------------------------------------------------------------------------------
    */
    public function index ( Request $request ){
        $input = $request->all();
        $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 获取列表异步加载信息
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/2 15:59
     * |---------------------------------------------------------------------------------
     */
    public function getDetails ( Request $request ){
        $data['showcount'] = SettlementService::getStatusBar($request->get("session_token"),1);//获取操作权限可展示订单状态栏
        return $this->success('获取成功', $data);
        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 int stl_serid 服务商id
     * @param string start_time 开始时间
     * @param string end_time 结束时间
     * @param string category 结算类型
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/7 21:08
     * |---------------------------------------------------------------------------------
    */
    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;
        }
//        $list = SettlementList::where('ser_id',$input['ser_id'])->where('sett_status',63)->get()->toArray();

        if($input['start_time']>$input['end_time']){
            return $this->error('开始时间不能大于结束时间', ErrorInc::FAILED_PARAM);
        }

        $res = SettlementService::getSettlementList(['ser_id'=>$input['stl_serid'],'sett_status'=>63,'category'=>$input['category']]);
        if ($res){
            $input['source'] = 2;
            $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 id            id号
     * @param actual_money  金额
     * @param sys_num       系统单号
     * @param serial_number       平台单号
     * @param msg_id        关联order_msg表id
     * @return \Illuminate\Http\JsonResponse
     * @author he <2019/04/25>
     * |---------------------------------------------------------------------------------
     */
    public function editReceipts (Request $request)
    {
        $input = $request->all();
        $checkKey=CommonService::checkKey(['actual_money', 'sys_num','serial_number','msg_id','id'],$input,array('id'=>'数据编号','msg_id'=>'关联商品数据编号','serial_number'=>'工单号','sys_num'=>'系统单号','actual_money'=>'金额'));
        if($checkKey['code']==1){
            $actual_money = sprintf("%.2f",$request->input('actual_money'));
            $msgs = SettlementList::where('sys_num',$input['sys_num'])->where('msg_id','!=',$input['msg_id'])->where('list_service_type','!=','50')->get()->toArray();

            OrderList::where('serial_number',$input['serial_number'])->where('sys_num',$input['sys_num'])->update(['goods_price'=>$actual_money]);

            OrderMsg::where('id',$input['msg_id'])->where('sys_num',$input['sys_num'])->update(['goods_price'=>$actual_money]);
            $msg_id="";
            foreach( $msgs as $k => $v){
                $msg_id.=','.$v['msg_id'];
            }
            $msg_id=ltrim($msg_id,',');
            if($msg_id!=""){
                $other_money = OrderMsg::whereRaw("sys_num='".$input['sys_num']."' and id in (".$msg_id.")")->sum("goods_price");
                $pott['new_money']=sprintf("%.2f",$other_money+$actual_money);
            }else{
                $pott['new_money']=$actual_money;
            }
            $info = Orders::where('sys_num',$input['sys_num'])->update($pott);
            $balance = DB::table('loss_warning')->where('sys_num',$input['sys_num'])->first();
            if(!$balance){
                $loss['earning']=$pott['new_money'];
                $loss['balance']=sprintf("%.2f",$pott['new_money']-$balance['expenditure']);
                DB::table('loss_warning')->where('sys_num',$input['sys_num'])->update($loss);
            }
            if ($info){
                $this->insertingLog("编辑实收，",$input['sys_num'],"编辑实收：".$input['sys_num'],"派工单结算",$request->ip(), $request->get('session_token')['admin_acc']);
                return $this->success('操作成功');exit;
            }else{
                return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
            }
        }else{

            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 审核驳回
     * @param id
     * @return \Illuminate\Http\JsonResponse
     * @author he <2019/05/29>
     * |---------------------------------------------------------------------------------
     */
    public function shut_down (Request $request)
    {
        if ($request->filled('id')){
            $id = $request->input('id');
            $Olaf = SettlementList::where('id',$id)->update(['sett_status'=>1]);
            if ($Olaf){
                $sys_num = SettlementList::where('id',$id)->value("sys_num");
                $this->insertingLog("审核驳回，",$sys_num,"审核驳回：".$sys_num,"派工单结算",$request->ip(), $request->get('session_token')['admin_acc']);
                return $this->success('操作成功');
            }else{
                return $this->error('操作失败', ErrorInc::MYSQL_FAILED);
            }
            exit;
        } else{
            return $this->error('参数错误', ErrorInc::INVALID_PARAM);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 审核（零散未审核）
     * @param type 1:展示数据 2：
     * @param sem_slid 结算信息id(type=1)
     * @param list_service_type 派工单状态(type=1)
     * @param sem_slid   结算id号(type=2)
     * @param sem_type   标签id(type=2)
     * @param all_price  总价(type=2)
     * @param sem_synum  结算单系统单号(type=2)
     *
     * @param ser_id     服务商id(type=3)
     * @param money_data 数组(type=3)
     * @param goods_id   商品id(type=3)
     * @param sem_synum  结算单系统单号(type=3)
     * @param sem_slid   结算单id号(type=3)
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * |---------------------------------------------------------------------------------
     */
    public function EditEntry (Request $request)
    {
        if (!$request->filled('type')){
            return $this->error('缺少请求类型', ErrorInc::INVALID_PARAM);exit;
        }

        if ($request->input('type') == 1){
            if (!$request->filled('sem_slid') || !$request->filled('list_service_type')){
                return $this->error('参数错误1', ErrorInc::INVALID_PARAM);exit;
            }
            $Input = $request->only('type','sem_slid','list_service_type');
            if($Input['list_service_type'] != '55'){
                $type=SetmoneyType::where('sety_id','!=','3')->pluck('sety_name','sety_id');
                $details=SettlementMoney::where('sem_slid',$Input['sem_slid'])->get();
            }else{
                $type = SetmoneyType::where('sety_id','4')->pluck('sety_name','sety_id');
                $details = SettlementMoney::where(['sem_slid'=>$Input['sem_slid'],'sem_type'=>4])->get();
            }

            if (!$details->isEmpty()){
                $sem_price=0;
                foreach( $details as $k=> $v){
                    if (!empty($v) && isset($type[$v['sem_type']])){
                        $sem_price=$sem_price+$v['sem_price'];
                        $details[$k]['sety_name']=$type[$v['sem_type']];
                        $sem_type[]=$v['sem_type'];
                    }

                }
            }
            $set_name=[];
            if($Input['list_service_type']!='50'){
                $set_name = $type;
            }

            $data['list']=$details;
            $data['set_name']=$set_name;
            if (isset($sem_price)){
                $data['all_price']=sprintf('%.2f',$sem_price);
            }else{
                $data['all_price']=0;
            }
            return $this->success('操作成功');exit;

        }elseif ($request->input('type') == 2){
            if (!$request->filled('sem_slid') || !$request->filled('sem_type') || !$request->filled('all_price') || !$request->filled('sem_synum')){
                return $this->error('参数错误2', ErrorInc::INVALID_PARAM);exit;
            }
            $Input = $request->only('sem_slid','sem_type','all_price');
            $money=SettlementMoney::where(['sem_type'=>$Input['sem_type'],'sem_slid'=>$Input['sem_slid']])->value('sem_price');
            DB::beginTransaction(); //开启事务
            if($Input['sem_type'] == 4){
                $poss['list_service_type']=50;
                $poss['subsidy_money']="0";
            }else{
                $poss['all_price']=$Input['all_price']-$money;
            }
            $Nami = SettlementList::where('id',$Input['sem_slid'])->update($poss);
            $Leona = SettlementMoney::where(['sem_type'=>$Input['sem_type'],'sem_slid'=>$Input['sem_slid']])->delete();
            if($Nami && $Leona){
                DB::commit();//成功则提交
                return $this->success('操作成功1');exit;
            }else{
                DB::rollback();//不成功，则回滚
                return $this->error('操作失败1', ErrorInc::MYSQL_FAILED);exit;
            }

        } elseif($request->input('type') == 3){
            if (!$request->filled('ser_id') || !$request->filled('money_data') || !$request->filled('sem_slid') || !$request->filled('sem_synum') || !$request->filled('all_price')){
                return response()->json(['Data'=>'','ErrorMessage'=>'参数错误','ErrorCode'=>3]);exit;
            }
            $Input = $request->only('ser_id','money_data','goods_id','sem_synum','sem_slid','all_price');

            $money_data = $Input['money_data'];
            $list_id = SettlementList::where('id',$Input['ser_id'])->value('list_id');
            foreach ($money_data as $k => $v){
                if (($v['sem_type'] == 1) && ($v['sem_price'] != 0)){
                    $order_price = $v['sem_price'];
                    $posa['order_price'] = $order_price;

                }
                $res = SettlementMoney::where(['sem_slid'=>$Input['sem_slid'],'sem_type'=>$v['sem_type']])->value('sem_price');
                if($res){
                    if($res != $v['sem_price']){
                        $poss['sem_price'] = $v['sem_price'];
                        SettlementMoney::where(['sem_slid'=>$Input['sem_slid'],'sem_type'=>$v['sem_type']])->update(['sem_price'=>$v['sem_price']]);
                        $this->insertingLog('修改价格：',$list_id,$v['sem_type'].'：'.$res.'->'.$v['sem_price'],'派工单结算',$request->ip(),$request->get('session_token')['admin_acc']);//日志
                    }
                }else{
                    $poss['sem_price'] = $v['sem_price'];
                    $poss['sem_type'] = $v['sem_type'];
                    $poss['sem_slid'] = $Input['sem_slid'];
                    $poss['sem_synum'] = $Input['sem_synum'];
                    SettlementMoney::insert($poss);
                }
            }
            $all_price = SettlementList::where('id',$Input['sem_slid'])->first();
            $rae=SettlementMoney::where('sem_slid',$Input['sem_slid'])->sum('sem_price');
            if(($rae == $Input['all_price']) || ($all_price['list_service_type'] == "55")){
                $post['all_price']=$Input['all_price'];
                $posa['sett_status']=63;
                SettlementList::where('id',$Input['sem_slid'])->update($posa);

                if(($all_price['all_price']==$Input['all_price']) || ($all_price['subsidy_money']==$Input['all_price'])){
                    $this->insertingLog('编辑订单金额，',$all_price['sys_num'],$all_price['list_id'],'派工单结算',$request->ip(),$request->get('session_token')['admin_acc']);//日志
                    return $this->success('操作成功2');exit;
                }else{
                    $money = SettlementList::where('id',$Input['sem_slid'])->update($post);

                    if($money){
                        if($all_price['sett_status']>60){
                            $all_price1 = SettlementList::where('wat_num',$all_price['wat_num'])->where('list_service_type','!=','55')->sum('all_price');
                            $all_price2=SettlementList::where(['wat_num'=>$all_price['wat_num'],'list_service_type'=>55])->sum('subsidy_money');
                            $Pantheon['stl_money'] = sprintf("%.2f", $all_price1+$all_price2);

                            StatementsList::where('stl_wat',$all_price['wat_num'])->update($Pantheon);
                        }
                        $this->insertingLog('编辑订单金额，',$all_price['sys_num'],$all_price['list_id'],'派工单结算',$request->ip(),$request->get('session_token')['admin_acc']);//日志
                        return $this->success('操作成功3');exit;
                    }else{
                        return $this->error('操作失败2', ErrorInc::MYSQL_FAILED);exit;
                    }
                }
            }
        }
    }
}
