<?php

namespace App\Services;
use App\Models\PjGoods;
use BlueCity\Core\Service\Service;
use App\Models\SubmitPlease;
use DB;

class SubmitPleaseService extends Service
{
	/**
	 * 添加
	 * @param  $submit_name
	 * @param  $submitr_pt
	 * @param  $submit_sys_num
	 * @param  $goods_name
	 * @param  $submit_money
	 * @param  $submit_state
	 * @param  $submit_service
	 * @param  $state_stauas
	 * @param  $submit_schedule
	 * @param  $submit_stauas
	 * @param  $msg_id
     * @param  $apply_reason
	 * @return int
	 * @author du 2021年8月11日上午10:24:38
	 */
	public static function createSubmitPlease($submit_name,$submitr_pt,$submit_sys_num,$goods_name,$submit_money,$submit_state,$submit_service,$state_stauas,$submit_schedule,$submit_stauas,$msg_id,$refund_id = 0,$customer_info = '',$apply_reason = '',$attribute = '1',$refund_num = 0,$company_id=''){
		$pleArr['submit_name'] = $submit_name;//申请人
		$pleArr['submit_time'] = date("Y-m-d H:i:s");//申请时间
		$pleArr['submitr_pt'] = $submitr_pt;//申请平台
		$pleArr['submit_sys_num'] = $submit_sys_num;//系统单号
		$pleArr['goods_name'] = $goods_name;//商品名称
		$pleArr['submit_money'] = $submit_money;//申请金额
		$pleArr['submit_state'] = $submit_state;////差额处理，1抹零2平台3服务中心4财务
		$pleArr['submit_service'] = $submit_service;////业务处理，1正常2退货3被换4换新
		$pleArr['state_stauas'] = $state_stauas;//业务处理，2确认申请
		$pleArr['submit_schedule'] = $submit_schedule;//处理状态
		$pleArr['submit_stauas'] = $submit_stauas;//差额处理状态
		$pleArr['msg_id'] = $msg_id;//退货的msg_id
        $pleArr['refund_id'] = $refund_id;//申请退款单id
        $pleArr['customer_info'] = $customer_info;//客户账号信息
        $pleArr['apply_reason'] = $apply_reason;//申请退款原因
        $pleArr['attribute'] = $attribute;//申请属性
        $pleArr['refund_num'] = $refund_num;//退款次数
        $pleArr['company_id'] = $company_id;//公司ID
		$res = SubmitPlease::insertGetId($pleArr);
		return $res;
	}
	/**|---------------------------------------------------------------------------------
	 * @name 获取退收款数据信息
     * @param string $key 查询键
     * @param string $value 查询值
     * @param array $select 待查询参数
     * @param string $type 待查询参数
	 * @retrun /multitype:array
	 * @author dou 2021/8/24 11:17
	 * |---------------------------------------------------------------------------------
	*/
	public static function getSubmitPleaseBy ( $key , $value , $select = [] , $type = 'get' ){
	    $db = new SubmitPlease();
	    $orderby = [];
	    if( $key == 'id'){
            $type = 'first';
        }
	    if( $type == 'first' && count($select) == 1){
            $type = 'value';
            $orderby = ['id'=>'DESC'];
        }
	    return CommonService::getMysqlData($db,[$key=>$value],$select,$orderby,$type);
	}


    /**
     * @name 获取列表
     * @param $input
     * @return array
     * @author du
     * @date 2021/9/16
     */
    public static function getList($input,$session){
        $where = [];
        $Db = SubmitPlease::leftjoin('pt','pt.id','=','submitr_pt')->leftjoin('orders','orders.sys_num','=','submit_sys_num')->leftjoin('refund','refund.id','=','submit_please.refund_id');
        $type = $input['type']??1;
        if($type==3){     //已完结
            $where['submit_stauas'] = 2;
        }
        if($type==2){//服务
            $where['submit_stauas'] = 1;//差额处理状态0：没有1：申请中2：确认申请 3：拒绝申请 4:待支付
            //$where['submit_state_noteq'] = 4;
            $where['submit_state'] = 3;
        }
        if ($type == 1) {            //财务待申请
            $where['submit_stauas'] = 1;
            $where['submit_state'] = 4;
        }
        if ($type == 5) {            //财务待支付
            $where['submit_stauas'] = 4;
            $where['submit_state'] = 4;
        }
        if ($type == 6) {            //待审核
            $where['submit_stauas'] = 5;
            $where['submit_state'] = 4;
        }
        if ($type == 7) {            //财务代收款
            $where['submit_stauas'] = 7;
            $where['submit_state'] = 4;
        }

        if ($type==4){           //红包
            $where['submit_stauas'] = 1;
            $where['submit_state'] = 5;
        }
        if($input['sys_num']){
            $where['submit_sys_num_rlike'] = $input['sys_num'];
        }

        if($input['goods_name']){
            $where['gone_submit_please.goods_name_like'] = $input['goods_name'];
        }

        if($input['user_name']){
            $where['submit_name'] = $input['user_name'];
        }
        if ($input['pt_id']){//申请平台
            $where['submitr_pt'] = $input['pt_id'];
        }

        if (isset($input['category'])){//品类搜索
            $where['gone_orders.category'] = $input['category'];
        }

        if ($input['submit_state'] && $input['submit_state'] !=0){//申请类型
            $where['submit_state'] = $input['submit_state'];
        }
        if ($input['order_num']){//平台单号
            $where['gone_orders.order_num_rlike'] = $input['order_num'];
        }
        if ($input['attribute']){//退款属性
            $where['attribute'] = $input['attribute'];
        }
        if ($input['submit_time']){
            $submit_time = $input['submit_time'];
            $end = $submit_time[1].' 23:59:59';
            $time = [$submit_time[0], $end];
            $where['submit_time_between'] = $time;
        }

        if ($input['deal_time']){//2022-4-22
            $deal_time = $input['deal_time'];
            $end = $deal_time[1].' 23:59:59';
            $time = [$deal_time[0], $end];
            $where['deal_time_between'] = $time;
        }


        if (isset($input['submit_schedule'])){//处理状态 0无 1：处理 2：处理中 3处理已完成
            $where['submit_schedule'] = $input['submit_schedule'];
        }

        if($input['pay_type']){ //付款类型 1客服付款2垫付
            $where['gone_submit_please.pay_type'] = $input['pay_type'];
        }
        if($input['apply_type']){ //退款标签
            $where['apply_type'] = $input['apply_type'];
        }

        if ($session['admin_groupnew'] != 7) {//管理员可以看全部
            $where['gone_orders.company_id'] = $session['company_id'];
        }

        $where[1] = 1;
        $where = CommonService::jointWhere($where);
        $data['where'] = $where;
        $page_size = $input['page_size']??10;

        if($input['is_excel']==1){
                /*if (!in_array($type,[2,1,4])){
                    return ['ErrorCode'=>2,'ErrorMessage'=>'状态不正确','Data'=>''];
                }*/
            DB::connection()->enableQueryLog();#开启执行日志
        }
        $paginate = $Db->whereRaw($where)->select('submit_please.id','submit_please.pay_type','submit_name','apply_reason','submit_time','submit_sys_num','submit_please.goods_name','submit_please.msg_id','submit_money','submit_state','submit_service','submit_stauas','state_stauas','customer_info','pay_comm','pt_name','orders.order_num','customer_id','deal_time','submit_schedule','submit_please.attribute','submit_please.refund_id','submit_please.deal_id','submit_please.deal_name','submit_please.refund_num','orders.category','apply_type','apply_time','audit_time','apply_name','audit_name','reject_reason','reject_type')
            ->orderBy('reject_type','desc')
            ->orderBy('submit_time','desc')
            ->paginate($page_size);

        //导出所需语句
        if($input['is_excel']==1){
            $data['sqls'] = DB::getQueryLog()[1];
        }

        $where1[1] = 1;
        if ($session['admin_groupnew'] != 7) {//管理员可以看全部
            $where1['company_id'] = $session['company_id'];
        }
        $where1 = CommonService::jointWhere($where1);

        $dfk = SubmitPlease::where(['submit_state'=>4,'submit_stauas'=>1])->whereRaw($where1)->count();
        $dsk = SubmitPlease::where('submit_state','!=',4)->where('submit_stauas',1)->whereRaw($where1)->count();
        $hb = SubmitPlease::where('submit_state',5)->where('submit_stauas',1)->whereRaw($where1)->count();

        $dfk5 = SubmitPlease::where(['submit_state'=>4,'submit_stauas'=>4])->whereRaw($where1)->count();
        $dsh = SubmitPlease::where(['submit_state'=>4,'submit_stauas'=>5])->whereRaw($where1)->count();
        $dsk7 = SubmitPlease::where(['submit_state'=>4,'submit_stauas'=>7])->whereRaw($where1)->count();
        $data['show_Menu'] = [
            ['show_name' => '全部 ', 'show_num' => '--', 'status' => 0],
            ['show_name' => '待申请', 'show_num' => $dfk??0, 'status' => 1],
            ['show_name' => '待审核', 'show_num' => $dsh??0, 'status' => 6],
            ['show_name' => '财务待支付', 'show_num' => $dfk5??0, 'status' => 5],
            ['show_name' => '财务代收款', 'show_num' => $dsk7??0, 'status' => 7],
            ['show_name' => '服务', 'show_num' => $dsk??0, 'status' => 2],
            ['show_name' => '红包', 'show_num' => $hb??0, 'status' => 4],
            ['show_name' => '已完成', 'show_num' => '--', 'status' => 3],
        ];

        $all_button = BmmcService::whereButton($input['token'],$input['Pri_id']);
        $searchdata = 'export,batchProcessStatus';
        if($input['type'] == '6'){
            $searchdata .= ',applyWaitPay';
        }
        $data['apply_type'] = RefundService::getRefundApplyType();
        $export = BmmcService::getTopButton('',$searchdata,$all_button);
        $data['button_top'] = $export['button_top']??[];//顶部按钮
        $data['button_search'] = $export['button_search']??[];//搜索栏按钮
        $data['attributeName'] = RefundService::getAttributeName();//退款属性
        $list = CommonService::dataToArray($paginate->items());
        if($list){
            $list = self::getButtonDatas($all_button, $list,$session);
            $data['list'] = $list;
            $data['page'] = [
                'count' => $paginate->total(),
                'page'=>$paginate->currentPage(),
                'page_size'=>$page_size,
                'allPage'=>$paginate->lastPage()
            ];
        }else{
            $data['list'] = [];
        }
        return $data;
    }

    /**
     * @param $all_button
     * @param $list
     * @return array
     * @author du
     * @date 2021/9/16
     */
    public static function getButtonDatas($all_button,$list,$session){
        $submitState = self::getSubmitState();
        $submitService = self::getSubmitService();
        $submitStauas = self::getSubmitStauas();
        $attributeName = RefundService::getAttributeName(true);
        $payType = self::getPayType(true);
        foreach ($list as $k => $v){
            if($v['reject_type']=='2'){
                $list[$k]['reject_typename'] = '驳回';
            }else{
                $list[$k]['reject_typename'] = '正常';
            }
            $list[$k]['aply_name'] = RefundService::getRefundApplyType(true)[$v['apply_type']];
            $button = [];
            $str = Db::table('pictures')->where('sett_wat_num',$v['submit_sys_num'])->value('upload_pictures');
            if(!empty($str)){
                $list[$k]['is_type'] = 1;
            }else{
                $list[$k]['is_type'] = 2;
            }
            $list[$k]['submit_state_name'] = $submitState[$v['submit_state']];
            $list[$k]['submit_service_name'] = $submitService[$v['submit_service']];//业务处理类型
            $list[$k]['submit_stauas_name'] = $submitStauas[$v['submit_stauas']];//差额处理状态
            $list[$k]['attribute_name'] = $attributeName[$v['attribute']]??'未设定';//退款属性名称

            $list[$k]['payType_name'] = $payType[$v['pay_type']];

            if (empty($v['deal_time'])){
                $v['deal_time'] = "无";
            }
            //收付类型
            if(substr($v['submit_money'],0,1)=='-'){
                $list[$k]['submit_money_way'] = "付款";
            }else{
                $list[$k]['submit_money_way'] = "收款";
            }
            if($v['customer_info']){
                $infoArr = explode("<br/>",$v['customer_info']);
                $infoArra = explode("开户行/第三方：",$infoArr[0]);
                $infoArrb = explode("帐号：",$infoArr[1]);
                $infoArrc = explode("姓名：",$infoArr[2]);
                $list[$k]['info_ing'] = $infoArra[1];
                $list[$k]['info_acc'] = $infoArrb[1];
                $list[$k]['info_name'] = $infoArrc[1];
            }else{
                $list[$k]['info_ing'] = '';
                $list[$k]['info_acc'] = '';
                $list[$k]['info_name'] = '';
            }
            if ($v['submit_service'] == 4){//换货旧商品
                $goods_name_log = DB::table('order_log')->where('msg_id',$v['msg_id'])->value("goods_name");
                if (!empty($goods_name_log)){
                    $list[$k]['goods_name_log'] = $goods_name_log;
                }else{
                    $list[$k]['goods_name_log'] = "";
                }
            }
            if ($v['submit_stauas'] == 1){
                if($v['submit_schedule']==0||$v['submit_schedule']==1){
                    $button[] = 'processStatus';
                }
                if ($v['submit_schedule']==2||$v['submit_schedule']==1){
                    $button[] = 'rejectStatus';
                }
                if ($v['submit_state'] == 4 ) {
                    $button[] = 'appSubmit';
                }if ($v['submit_state'] == 3 ) {
                    $button[] = 'confirmApply';
                }
//                if ($v['submit_state'] == 4 ) {
                    $button[] = 'editPayType';
//                }else{
                    $button[] = 'addVoucher,feedbackLog';//confirmApply,
//                }
                $button[] = 'addReject';
            }elseif ($v['submit_stauas'] == 2){
                //已完成状态只有管理员和梦可以有驳回按钮 || $session['admin_groupnew']==7
                if($session['admin_groupnew']==7){
                    $button[] = 'addReject';
                }
                $button[] = 'editVoucher,lookVoucher,feedbackLog';
            }elseif ($v['submit_stauas'] == 4 && $v['submit_state'] == 4){
                /*if(in_array($session['admin_groupnew'], [31,35,92,97])){
                    $button[] = 'addReject';
                }*/
                $button[] = 'confirmApply,addVoucher,feedbackLog,editPayType,rejPayment';
            }elseif ($v['submit_stauas'] == 7 && $v['submit_state'] == 4){
                /*if(in_array($session['admin_groupnew'], [31,35,92,97])){
                    $button[] = 'addReject';
                }*/
                $button[] = 'confirmApply,addVoucher,feedbackLog';
            }elseif ($v['submit_stauas'] == 5){
                $button[] = 'applyWaitPay,rejSubmit';
            }elseif ($v['submit_stauas'] == 7){
                $button[] = 'applyWaitPay';
            }
            $button[] = 'editRemark';

            if($v['category']!=3){
                $button[] = 'editSubmitMoney';
            }
            $button = BmmcService::getListButton($button,$all_button);
            $list[$k]['button_one'] = $button['button_one']??[];
            $list[$k]['button_two'] = $button['button_two']??[];
            $list[$k]['button_three'] = $button['button_three']??[];
            unset($button);
        }
        return $list;
    }

    /**
     * @name 获取商品信息
     * @param $goods_name
     * @return false
     * @author du
     * @date 2021/9/16
     */
    public static function getLogGoodsName($goods_name){
        if(count($goods_name) > '2'){
            $version = "";
            $versions = "";
            foreach( $goods_name as $k => $v ){
                if($k > 1){
                    $version.=$v."-";
                }
            }
            foreach( $goods_name as $k => $v ){
                if($k > 0){
                    $versions.=$v."-";
                }
            }
            $version = trim($version,"-");
            $versions = trim($versions,"-");
            $listGoods = PjGoods::where(['brand_name'=>$goods_name[0],'pg_series'=>$goods_name[1],'version'=>$version])->first();
            if(!$listGoods){
                $listGoods = PjGoods::where(['brand_name'=>$goods_name[0],'version'=>$versions])->first();
            }
        }else{
            $listGoods = PjGoods::where(['brand_name'=>$goods_name[0],'version'=>$goods_name[1]])->first();
        }
        if($listGoods){
            return $listGoods;
        }else{
            return false;
        }

    }

    /**
     * @name 获取需更新商品信息
     * @param $listGoods
     * @return array
     * @author du
     * @date 2021/9/16
     */
    public static function getUpdateArrMsgData($listGoods){
        if($listGoods['pg_series']!=""){
            $pg_series = $listGoods['brand_name']."-".$listGoods['pg_series']."-".$listGoods['version'];
        }else{
            $pg_series = $listGoods['brand_name']."-".$listGoods['version'];
        }
        $arrMsg['goods_id'] = $listGoods['pg_id'];//商品id
        $arrMsg['goods_name'] = $pg_series;//商品名称
        $arrMsg['goods_number'] = "";//商品型号
        $arrMsg['goods_service'] = 1;//业务处理类型1正常
        $arrMsg['goods_state'] = 0;//差额处理类型0没有
        $arrMsg['goods_difference'] = 0;//差额金额
        $arrMsg['goods_brand'] = $listGoods['brand_name'];//商品品牌名称
        return $arrMsg;
    }

    /**
     * $name 获取差额处理类型
     * @return string[]
     * @author du
     * @date 2021/9/17
     */
    public static function getSubmitState(){
        $data = ['1'=>'抹零','2'=>'平台','3'=>'服务','4'=>'财务','5'=>'红包'];
        return $data;

    }

    /**
     * @name 获取业务处理类型
     * @return string[]
     * @author du
     * @date 2021/9/17
     */
    public static function getSubmitService(){
        $data = ['1'=>'正常','2'=>'退货','3'=>'被换','4'=>'换货'];
        return $data;
    }

    /**
     * @name 差额处理状态
     * @return string[]
     * @author du
     * @date 2021/9/17
     */
    public static function getSubmitStauas(){
        $data = ['0'=>'没有','1'=>'申请中','2'=>'确认申请','3'=>'拒绝申请','4'=>'待支付','5'=>'审核中','7'=>'代收款'];
        return $data;
    }

    /**
     * @return string[]
     * @author du
     * @date 2021/11/2
     */
    public static function getSubmitSchedule( $type = false ){
        $applyType = array(array('type'=>0,'name'=>'未处理'),array('type'=>1,'name'=>'处理'),array('type'=>2,'name'=>'处理中'),array('type'=>3,'name'=>'处理已完成'));
        if($type){
            $applyType = array_column($applyType, 'name' , 'type');
        }
        return $applyType;

}

    /**
     * @name 获取付款类型
     * @param false $type
     * @return array|array[]
     * @author du
     * @date 2022/3/9
     */
    public static function getPayType( $type = false ){
        $payType = array(array('type'=>1,'name'=>'客户收款'),array('type'=>2,'name'=>'客服垫付'));
        if($type){
            $payType = array_column($payType, 'name' , 'type');
        }
        return $payType;

    }


}
