<?php

/**
 * 文件名称（第三方结算单）
 * 文件简单描述（第三方结算单相应数据展示以及权限操作）
 * @author DouBin
 * @Date: 2021/9/13
 * @Time: 18:28
 * @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\Models\OrderList;
use App\Models\OrderMsg;
use App\Models\Orders;
use App\Models\PtPrice;
use App\Models\PtThree;
use App\Models\SettlementList;
use App\Models\SettlementThree;
use App\Models\User;
use App\Services\GoodsService;
use App\Services\OrderService;
use App\Services\SettlementThreeService;
use App\Services\StatementsListService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use DB;
use App\Services\CommonService;//通用服务
use BlueCity\Core\Inc\ErrorInc;

class SettlementThreeController extends BaseController{
    /**|---------------------------------------------------------------------------------
     * @name 列表页
     * @param string three_status 第三方结算单状态
     * @param string sys_num 系统单号
     * @param string order_num 平台单号
     * @param int p_id 平台id
     * @param string shr_name 姓名
     * @param string shr_phone 电话
     * @param array creactDate 创建时间
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/13 18:19
     * |---------------------------------------------------------------------------------
     */
    public function index ( Request $request ){
        $input = $request->all();
        $session = $request->get('session_token');
        $data = SettlementThreeService::getList($input, $session);

        if($data['ErrorCode']!=1){
            return $data;
        }else {
            $list = $data['Data'];

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

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

    /**|---------------------------------------------------------------------------------
     * @name 审核
     * @param int id 数据id
     * @param int goods_id 商品id
     * @param int p_id 平台id
     * @param int p_name 平台名称
     * @param string collecting 平台价格
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/14 18:47
     * |---------------------------------------------------------------------------------
    */
    public function examine ( Request $request ){
        $input = $request->all();
        $session = $request->get("session_token");
        $checkKey = CommonService::checkKey(['id', 'goods_id', 'p_id','p_name','collecting'],$input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        if($input['collecting']>0){
            $ir_is = SettlementThree::where('id',$input['id'])->first();
            if(!$ir_is){
                return $this->error('无对应数据', ErrorInc::DATA_EMPTY);
            }
//            $ghRes = PtPrice::where(['good_id'=>$input['goods_id'],'pt_id'=>$input['p_id']])->limit('1')->first();
//            if ($ghRes){
//                if($ghRes['price'] != $input['collecting']){
//                    $goodsArr = GoodsService::getGoodsBy(['pg_id'=>$input['p_id']]);
//                    $goods_name = $goodsArr['good_name'];
//                    $post['price']=$input['collecting'];
//                    PtPrice::where(['good_id'=>$input['goods_id'],'pt_id'=>$input['p_id']])->update($post);
//                    $this->insertingLog('修改平台商品价格，',$ir_is['sys_num'],$input['p_name'].":商品：".$goods_name.";".$ghRes['price']."->".$input['collecting'],'第三方结算',$request->ip(),$request->get('session_token')['admin_acc']);//日志
//                }
//            }else{
//
//                $goodsArr = GoodsService::getGoodsBy(['pg_id'=>$input['p_id']]);
//                $goods_name = $goodsArr['good_name'];
//                SettlementThreeService::insertPtPrice($input['collecting'], $input['goods_id'], $input['p_id']);
//                $this->insertingLog('添加平台商品价格，',$ir_is['sys_num'],$input['p_name'].":商品：".$goods_name.";".$input['collecting'],'第三方结算',$request->ip(),$request->get('session_token')['admin_acc']);//日志
//            }
            $shen['three_status'] = 10;//修改第三方付款状态
            $shen['p_price'] = $input['collecting'];//保存审核的平台价格
            $re = SettlementThree::where('id',$input['id'])->update($shen);
            $ir_is = SettlementThree::where('id',$input['id'])->first();

            $msgs = SettlementList::where('sys_num',$ir_is['sys_num'])->where('list_id','!=',$ir_is['list_id'])->get();
            $actual_money = sprintf("%.2f",$input['collecting']);
            $poss['goods_price'] = $actual_money;//编辑派工单列表商品价格
            $poee['goods_price'] = $actual_money;//编辑msg列表商品价格
            //统计数据存储对应信息便于后续计算盈亏
            OrderList::where(['serial_number'=>$ir_is['list_id'],'sys_num'=>$ir_is['sys_num']])->update($poss);
            OrderMsg::where(['id'=>$ir_is['msg_id'],'sys_num'=>$ir_is['sys_num']])->update($poee);
            $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='".$ir_is['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',$ir_is['sys_num'])->update($pott);
            $balance = DB::table('loss_warning')->where('sys_num',$ir_is['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',$ir_is['sys_num'])->update($loss);
            }
            if($re){
                $content = "审核，订单(".$ir_is['list_id'].")，第三方平台结算金额";
                $order_num = $ir_is['sys_num'];
                $this->insertinglog('审核，',$order_num,$content,'第三方结算',$request->ip(),$request->get('session_token')['admin_acc']);//日志
                return $this->success('操作成功');exit;
            }else{
                return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
            }
        }else{
            return $this->error('平台价格必须大于0', ErrorInc::FAILED_PARAM);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 编辑
     * @param int id 数据id
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/14 20:26
     * |---------------------------------------------------------------------------------
    */
    public function editEntry (Request $request){
        if ($request->filled('id')){
            $id = $request->input('id');//结算id
            $arr['three_status'] = 1;//1未审核-第三方结算

            $ir_is = SettlementThree::where('id',$id)->first();
            $re = SettlementThree::where('id',$id)->update($arr);
            if($re){
                $content = "编辑，订单(".$ir_is['list_id'].")";
                $order_num = $ir_is['sys_num'];
                //dd($content);
                $this->insertingLog('编辑，',$order_num,$content,'第三方结算',$request->ip(),$request->get('session_token')['admin_acc']);//日志
                return $this->success('操作成功');exit;
            }else{
                return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
            }
        }else{
            return $this->error('缺少参数id', ErrorInc::INVALID_PARAM);exit;
        }

    }

    /**|---------------------------------------------------------------------------------
     * @name 获取可更新数据数量
     * @param int p_id 平台id
     * @param string pt_name 平台名称
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/14 21:18
     * |---------------------------------------------------------------------------------
    */
    public function queryPt (Request $request)
    {
        if ($request->filled('p_id')){
            $p_id = $request->input('p_id');
            $db = new SettlementList();
            $ress = CommonService::getMysqlData($db, ['p_id'=>$p_id,'update_three'=>0],[],[],'count');
            if ($ress){
                $arr['pt_name'] = $request->input('pt_name');
                $arr['key'] = $ress;
                return $this->success('操作成功',$arr);exit;

            }else{
                return $this->error('无平台数据', ErrorInc::DATA_EMPTY);exit;
            }
        }else{
            return $this->error('缺少参数p_id', ErrorInc::INVALID_PARAM);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 更新数据
     * @param int p_id 平台id
     * @param string pt_name 平台名称
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/14 21:39
     * |---------------------------------------------------------------------------------
    */
    public function AjaxSQL (Request $request){
        $input = $request->all();
        $session = $request->get("session_token");
        $checkKey = CommonService::checkKey(['pt_name', 'p_id'],$input);
        if($checkKey['code']==1){
            $pt_name = $request->input('pt_name');
            $db = new SettlementList();
            $ress = CommonService::getMysqlData($db, ['p_id'=>$input['p_id'],'update_three'=>0],[],['id'=>'asc'],'get','10');
            if($ress){
                foreach($ress as $k => $v){
                    $post['p_name']=$pt_name;
                    $post['sys_num']=$v['sys_num'];
                    $post['msg_id']=$v['msg_id'];
                    $post['p_id']=$v['p_id'];
                    $post['order_num']=$v['order_num'];
                    $post['list_id']=$v['list_id'];
                    $post['ser_id']=$v['ser_id'];
                    $post['customer_id']=$v['customer_id'];
                    $post['pgid']=$v['id'];
                    $post['list_service_three']=$v['list_service_type'];
                    $psd['update_three']=1;
                    $creact_time = OrderService::getOrderBy('sys_num', $v['sys_num'],['create_time']);
                    $post['create_time'] = $creact_time??$v['create_time'];
                    $goods_id = OrderMsg::where('id',$v['msg_id'])->select("goods_id","goods_name")->first();
                    $goods_id = OrderService::getOrderMsgBy('id', $v['msg_id'],["goods_id","goods_name"]);
                    if($goods_id){
                        $post['goods_id'] = $goods_id['goods_id'];
                        $post['goods_name']=$goods_id['goods_name'];
                        $p_price=DB::table('pt_price')->whereRaw("pt_id='".$v['p_id']."' and good_id='".$goods_id['goods_id']."'")->value("price");
                        if (isset($p_price)){
                            $post['p_price'] = $p_price;
                        }else{
                            $post['p_price'] = 0;
                        }

                    }
                    $post['three_pd'] = 1;
                    $post['jd_time'] = $v['create_time'];
                    $post['fk_time'] = $v['setfeeds_time'];

                    $post['company_id'] = $session['company_id'];
                    $rea = SettlementThree::insert($post);
                    if($rea){
                        SettlementList::where('id',$v['id'])->update($psd);
                    }else{
                        return $this->error('数据异常'.$v['order_num'], ErrorInc::INVALID_PARAM);exit;
                    }
                }
                return $this->success('操作成功',count($ress));
            }else{
                return $this->error('今日已更新完毕', ErrorInc::MYSQL_FAILED);exit;
            }
        }else{
            return $this->error('缺少参数', ErrorInc::INVALID_PARAM);exit;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 搜索可结算订单
     * @param int p_id 平台id
     * @param string pt_name 平台名称
     * @param string shr_phone 客户电话
     * @param int service_type 0：全部结算；1：完成结算；2预收结算
     * @param array handletiem 时间
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/14 22:02
     * |---------------------------------------------------------------------------------
    */
    public function search (Request $request){
        $input = $request->all();
        $checkKey = CommonService::checkKey(['p_id', 'service_type'],$input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        $where = [];
        $where['three_status'] = 10;
        $where['p_id'] = $input['p_id'];
        if(isset($input['handletiem'])){//创建时间
            $input['handletiem'][1] = date("Y-m-d", strtotime($input['handletiem'][1] . " +1 day"));
            $where['gone_settlement_three.create_time_between'] = $input['handletiem'];
        }
        if(isset($input['shr_phone'])){//客户电话
            $useid = CommonService::getUser('shr_phone', $input['shr_phone'],['id']);
            if(!$useid){
                return $this->error('无可操作数据', ErrorInc::DATA_EMPTY);exit;
            }
            $useid = array_column($useid, 'id');
            $where['customer_id_searchin'] = $useid;
        }
        $wat_num['wat_num'] = '';
        $wat_num1['wat_num_isnull'] = '';
        $where['wat_num_searchor']['wat1_next_level'] = $wat_num;
        $where['wat_num_searchor']['wat2_next_level'] = $wat_num1;
        if($input['service_type']==0){
            $where['list_service_three_searchlt'] = 50;
        }
        if($input['service_type']==2){
            $where['list_service_three_searchlt'] = 50;
            $where['list_service_three_noteq'] = 30;
        }
        if($input['service_type']==3){
            $where['list_service_three'] = 30;
        }
        $db = new SettlementThree();
        $set_list = CommonService::getMysqlData($db, $where,['id','order_num','goods_name','create_time','p_price','p_name','customer_id']);
        if($set_list) {
            $customer_id = array_column($set_list, 'customer_id');
            $db = new User();
            $user = CommonService::getMysqlData($db, ['id_searchin' => $customer_id], ['id', 'shr_name', 'shr_phone']);
            $user = CommonService::jointArrayKey($user, 'id');
            $sys_bh = 'J' . date("Ymdhis") . str_pad(rand(0, 999), 3, '0', STR_PAD_LEFT);
            foreach ($set_list as $k => $v) {
                $set_list[$k]['shr_name'] = $user[$v['customer_id']]['shr_name'];
                $set_list[$k]['shr_phone'] = $user[$v['customer_id']]['shr_phone'];
            }
//            $data['wat_num'] = $sys_bh;
//            $data['list'] = $set_list;
            return $this->success('操作成功',$set_list);exit;
        }else{
            return $this->error('无可操作数据', ErrorInc::DATA_EMPTY);exit;
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 申请结算
     * @param string pt_name 平台名称
     * @param int pt_id 平台名称
     * @param string ids 第三方数据
     * @param string zje_money 结算金额
     * @param string note_content 申请备注
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2021/9/14 22:37
     * |---------------------------------------------------------------------------------
    */
    public function applicationSub (Request $request)
    {
        $session = $request->get("session_token");
        $input = $request->all();
        $checkKey = CommonService::checkKey(['pt_name', 'ids', 'zje_money','note_content','pt_id'],$input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        if($input['pt_id'] == 0){
            return $this->error('参数错误pt_id', ErrorInc::FAILED_PARAM);exit;
        }
        $wat_num = StatementsListService::creactWat(1);
        $apply_for_money = $input['zje_money'];//结算金额
        $apply_for_time = date("Y-m-d H:i:s");

        $apply_for_name = $session['admin_acc'];
        $ids = explode(',', $input['ids']);
        $three_status = SettlementThree::whereIn("id",$ids)->where("three_status",'>=','20')->value("id");
        if($three_status){
            return $this->error('存在状态异常的订单'.$three_status, ErrorInc::REPEAT_SUBMIT);exit;
        }
        if($apply_for_money !=""){
            DB::beginTransaction(); //开启事务
            $attr['three_status'] = 20;
            $attr['wat_num'] = $wat_num;
            $re = SettlementThree::whereIn("id",$ids)->update($attr);
            $arr['wat_num'] = $wat_num;//结算单号
            $arr['p_name'] = $input['pt_name'];//第三方平台
            $arr['pt_id'] = $input['pt_id'];//第三方平台id
            $arr['apply_for_name'] = $apply_for_name;//操作人
            $arr['apply_for_id'] = $session['id'];//操作人id
            $arr['apply_for_money'] = $apply_for_money;//结算总金额
            $arr['apply_for_time'] = $apply_for_time;//添加时间
            $arr['settlement_num'] = $input['ids'];//数据id
            $arr['company_id'] = $session['company_id'];
            if(substr($apply_for_money,0,1)=='-'){
                $arr['type'] = 2;
            }else{
                $arr['type'] = 1;
            };
            $res = PtThree::insert($arr);
            if(isset($input['note_centent'])){
                $Olaf = CommonService::accMe($wat_num, '第三方结算申请', $input['note_centent'], '', 1, $session['admin_groupnew'], $session['admin_acc'], $session['id']);
            }else{
                $Olaf = true;
            }
            if($Olaf && $res && $re){
                DB::commit();
                $this->insertinglog("申请结算，",$wat_num,"结算单号：".$wat_num,"第三方付款",$request->ip(), $session['admin_acc']);
                return $this->success('操作成功');exit;
            }else{
                DB::rollback();
                return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
            }
        }else{
            return $this->error('服务中心或结算金额不能为空', ErrorInc::FAILED_PARAM);exit;
        }
    }
}
