<?php

namespace App\Services;
use App\Http\Controllers\BaseController;
use App\Models\OrderList;
use App\Models\Orders;
use App\Models\Refund;
use App\Models\SettlementList;
use App\Models\SettlementThree;
use App\Models\SubmitPlease;
use App\Models\SyncStores;
use BlueCity\Core\Inc\ErrorInc;
use BlueCity\Core\Service\Service;
use DB;
use App\Models\Pt;
use App\Models\Admin;
use App\Models\Note;


class RefundService extends Service
{
    //private static $instance;
    private $modelMain = null;

    public function __construct()
    {
        if (!$this->modelMain) $this->modelMain = new Refund();
    }


    public static function createRefund($poss)
    {

//        $poss['sys_num'] = $data['sys_num'];
//        $poss['order_num'] = $data['order_num'];
//        $poss['pt_id'] = $data['pt_id'];
//        $poss['goods_name'] = $data['goods_name'];
//        $poss['goods_name'] = $data['goods_name'];
//        $poss['goods_price'] = $data['goods_price'];
//        $poss['ser_id'] = $data['ser_id'];
//        $poss['msg_id'] = $data['msg_id'];
//        $poss['user_id'] = $data['user_id'];
//        $poss['shr_name'] = $data['shr_name'];
//        $poss['shr_phone'] = $data['shr_phone'];
//        $poss['shr_sheng'] = $data['shr_sheng'];
//        $poss['shr_shi'] = $data['shr_shi'];
//        $poss['shr_xian'] = $data['shr_xian'];
//        $poss['shr_adress'] = $data['shr_adress'];
//        $poss['state'] = $data['state'];//待审核
//        $poss['order_status'] = $data['order_status'];
//        $poss['refund_reason'] = $data['note_content'];
//        $poss['order_time'] = $data['create_time']; //下单时间
        $poss['created_at'] = date("Y-m-d H:i:s");
//        $poss['urgent_type'] = $data['urgent_type'];
//        $poss['creact_id'] = $data['creact_id'];
//        $poss['creactor'] = $data['creactor'];
//        $poss['state'] = $data['state'];

        $res = Refund::insertGetId($poss);
        return $res;
    }

    /**
     *
     * 获取退单信息
     * @param string $key 查询键
     * @param string $value 查询值
     * @param array $select 需查询参数
     * @param string $type 查询类型
     * @return unknown|boolean
     * @author du 2021年8月10日下午2:00:02
     */
    public static function getInfoByKeyValue($key , $value , $select = [] , $type = 'get')
    {
        $db = new Refund();
        if($key == 'id'){
            $type = 'first';
        }
        if($type == 'first' && count($select)=='1'){
            $type = 'value';
        }
        $list = CommonService::getMysqlData($db,[$key=>$value],$select,[],$type);
        return $list;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取订单详情
     * @param string $order_num 订单单号
     * @retrun /multitype:array
     * @author dou 2021/11/5 15:57
     * |---------------------------------------------------------------------------------
    */
    public static function getDetailByOrder ( $order_num ){
        $list = self::getInfoByKeyValue('order_num', $order_num);
        if($list) {
            $list = self::getButtonDatas(false, $list);
        }
        return $list;
    }

    /**
     * 获取退单列表
     * @param array $params
     * @param array $session
     * @return Ambigous <multitype:, multitype:unknown NULL >
     * @author du 2021年8月10日下午3:13:43
     */
    public static function getRefundList($params,$session){
    	$admin_pt_id = $session['admin_pt_id'];//获取当前用户可查看平台权限
        $Db = new Refund();
        $where = [];
        $where[1] = 1;
        if(!in_array($session['admin_groupnew'],[7,8])){
            $where['pt_id_searchin'] = trim($admin_pt_id);
        }
        if ($session['admin_groupnew'] != 7) {//管理员可以看全部
            $where['company_id'] = $session['company_id'];
        }
       // $where['pt_id_searchin'] = $admin_pt_id;

        if (isset($params['state'])){
	        if($params['state']!='100'){
            	$where['state'] = $params['state'];
        	}
        }
		if(isset($params['creact_id'])){
			$where['creact_id'] = $params['creact_id'];
		}
		if(isset($params['created_at'])){
			$params['created_at'][1] = date("Y-m-d", strtotime($params['created_at'][1] . " +1 day"));
			$where['created_at_between'] = $params['created_at'];
		}
        if (isset($params['order_num'])){
            $where['order_num_rlike'] = $params['order_num'];
        }
        if (isset($params['category'])){//订单商品服务类型
            $where['category'] = $params['category'];
        }
        if (isset($params['pt_id'])){
            $where['pt_id'] = $params['pt_id'];
        }
        if (isset($params['ser_id'])){
            $where['ser_id'] = $params['ser_id'];
        }
        if (isset($params['shr_name'])){
            $where['shr_name_rlike'] = $params['shr_name'];
        }
        if (isset($params['shr_phone'])){
            $where['shr_phone_rlike'] = $params['shr_phone'];
        }
        if (isset($params['order_status'])){
            $where['order_status'] = $params['order_status'];
        }
        if (isset($params['attribute'])){
            $where['attribute'] = $params['attribute'];
        }
        $where = CommonService::jointWhere($where);
        $page_size = $params['page_size']??10;

        $is_excel = $params['is_excel']??'0';
        if ($is_excel == 1) {
            DB::connection()->enableQueryLog();#开启执行日志
        }

        if ($params['state'] == 4 || $params['state'] == 5){
        	$paginate = $Db->whereRaw($where)->orderBy('updated_at','DESC')->paginate($page_size);
        }else{
        	$paginate = $Db->whereRaw($where)->orderBy('urgent_type','urgent_type','ASC')->orderBy('created_at','DESC')->paginate($page_size);
        }
       // print_r(DB::getQueryLog());

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

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

        //未处理
        $wcl = Refund::where('state',0)->whereRaw($where1)->count();

        $sjqr = Refund::where('state',1)->whereRaw($where1)->count();
        $whz = Refund::where('state',2)->whereRaw($where1)->count();
        $yhf = Refund::where('state',3)->whereRaw($where1)->count();
        $data['show_Menu'] = [
            ['show_name'=>"全部",'show_num'=>"--",'status'=>'100'],
            ['show_name'=>"待确认",'show_num'=>'--','status'=>'50'],
            ['show_name'=>"未处理",'show_num'=>$wcl??0,'status'=>'0'],
            ['show_name'=>"商家确认",'show_num'=>$sjqr??0,'status'=>'1'],
            ['show_name'=>"电话回访中",'show_num'=>$whz??0,'status'=>'2'],
            ['show_name'=>"已回访",'show_num'=>$yhf??0,'status'=>'3'],
            ['show_name'=>"已审核",'show_num'=>"--",'status'=>'4'],
            ['show_name'=>"已驳回",'show_num'=>"--",'status'=>'5'],
        ];

        $all_button = BmmcService::whereButton($params['token'],$params['Pri_id']);
        $export = BmmcService::getTopButton('manualSync','',$all_button);
        $data['button_top'] = $export['button_top']??[];//顶部按钮
        $data['button_search'] = $export['button_search']??[];//搜索栏按钮
        $data['attributeName'] = self::getAttributeName();//退款属性
        $data['order_status_names'] = OrderService::getOrderStatusName(false);//订单状态
        $list = CommonService::dataToArray($paginate->items());
        if($list){
        	$list = RefundService::getButtonDatas($all_button, $list);
        	$data['list'] = $list;
        	$data['page'] = [
        			'count' => $paginate->total(),
        			'page'=>$paginate->currentPage(),
        			'page_size'=>$page_size,
        			'allPage'=>$paginate->lastPage()
        	];
        }else{
        	$data['list'] = [];
        }

    	return $data;
    }
    /**
     * 获取按钮和数据
     * @param array $all_button
     * @param array $list
     * @return string
     * @author du 2021年8月10日下午3:40:48
     */
    public static function getButtonDatas( $all_button , $list ){
    	$ptArr = Pt::pluck('pt_name','id');
         $adminArr = Admin::where('admin_group',2)->pluck('company_name','id');

    	$order_status_name = OrderService::getOrderStatusName();//获取订单状态数组
        $serviceTypes = CategoryService::getAll([],'cd_id'); //服务类型
    	$goodpic = PjBrandsService::getAllPic('name');
        $attributeName = self::getAttributeName(true);
        $good_state_name = self::getGoodsstateName(true);
    	foreach ($list as $k => $v){
    	    $list[$k]['sendOrderStaue'] = '';
            $list[$k]['list'] = [];
    	    if($all_button) {
                $buttonData = [];
                $buttonData[] = 'remarks,sendSmsRefundModel';
                if ($v['creactor'] == '') {
                    $list[$k]['creactor'] = "系统同步";
                }
//                if ($v['state'] == 0 ) {
//                    $buttonData[] = 'telephone,applyReject,applyRefund';
//                }
//                elseif ($v['state'] == 3) {
//                    $buttonData[] = 'telephone,applyReject,applyRefund';
//                }
                if(in_array($v['state'], [0,1,3])){
                    $buttonData[] = 'telephone,applyReject,applyRefund';
                }elseif ($v['state'] == 4) {
                    $buttonData[] = 'appyLabel';
                }
                if ($v['urgent_type'] == 1 && in_array($v['state'], [0, 2, 3])) {
                    $buttonData[] = 'urgent';
                }

                $button = BmmcService::getListButton($buttonData, $all_button);
                $list[$k]['button_one'] = $button['button_one'] ?? [];
                $list[$k]['button_two'] = $button['button_two'] ?? [];
                $list[$k]['button_three'] = $button['button_three'] ?? [];
            }
            $noteRes = Note::where('orders_id',$v['sys_num'])->select('note_name','note_type','note_time','note_content')->orderBy('note_time','DESC')->get();

            if (!$noteRes->isEmpty()){
                $list[$k]['mess'] = $noteRes->toArray();
            }else{
                $list[$k]['mess'] = [];
            }
            $list[$k]['messtype'] = 1;

            if (isset($ptArr[$v['pt_id']])){
                $list[$k]['pt_name'] = $ptArr[$v['pt_id']];
            }else{
                $list[$k]['pt_name'] = "无";
            }

            if (isset($adminArr[$v['ser_id']])){
                $list[$k]['company_name'] = $adminArr[$v['ser_id']];
            }else{
                $list[$k]['company_name'] = "无";
            }

            $list[$k]['order_status_name'] = $order_status_name[$v['order_status']]??'未确认';

            if ($v['state'] == 0 || $v['state'] == 1 || $v['state'] == 2 || $v['state'] == 3){
                $list[$k]['state_name'] = "未审核";
            }elseif ($v['state'] == 4){
                $list[$k]['state_name'] = "已审核";
            }elseif ($v['state'] == 5){
                $list[$k]['state_name'] = "已驳回";
            }
            $list[$k]['category_name'] = $serviceTypes[$v['category']]['cd_pname']??'未设定';
            $list[$k]['attribute_name'] = $attributeName[$v['attribute']]??'未设定';
            $list[$k]['good_state_name'] = $good_state_name[$v['goods_state']];
        }
    	return $list;
    }

    /**|---------------------------------------------------------------------------------
     * @name 退款驳回
     * @param array $input 请求参数
     * @param string $ip 操作设备ip
     * @param string $session 操作人信息
     * @retrun /multitype:array
     * @author dou 2021/9/17 10:22
     * |---------------------------------------------------------------------------------
    */
    public static function applyReject ( $ip , $session , $input){
        if (!isset($input['id']) || $input['id']==''){
            return ['Data' => [], 'ErrorMessage' =>'参数错误', 'ErrorCode' => ErrorInc::FAILED_PARAM];
        }
        $db = new Refund();
        $infoRefund = CommonService::getMysqlData($db, ['id'=>$input['id']],['sys_num','state','goods_state','order_num','apply_type'],[],'first');
        if(!$infoRefund){
            return ['Data' => [], 'ErrorMessage' =>'数据异常', 'ErrorCode' => ErrorInc::DATA_EMPTY];
        }
        if($infoRefund['state']==5){
            return ['Data' => [], 'ErrorMessage' =>'状态是已驳回', 'ErrorCode' => ErrorInc::MYSQL_FAILED];
        }
        $reArr = $infoRefund['sys_num'];
        $order_find = OrderService::getOrderBy('sys_num',$reArr,['order_status','id','ser_id','store_type','category','p_id']);
        if($order_find['order_status']>'40'){
            if($infoRefund['apply_type']==1 || $order_find['category']!=3){
                return ['Data' => [], 'ErrorMessage' => '状态异常请刷新后从新操作', 'ErrorCode' => ErrorInc::MYSQL_FAILED];
            }
        }
        try {
            $BaseController = new BaseController();
            if (isset($input['content'])){
                $poss['deal_note'] = $input['content'];
                CommonService::accMe($reArr,'退款管理',"驳回退款".$input['content'],'','',$session['admin_groupnew'],$session['admin_acc'],$session['id']);
            }
            $order_status = $order_find['order_status'];
            $orderArr['lock_type'] = 1;
            $orderListArr['locklist_type'] = 1;
            $orderSettArr['locksel_type'] = 1;
            $orderSetteArr['locksee_type'] = 1;
            $orderSettArr['locked'] = 1;
            $a = SettlementList::where('sys_num',$reArr)->update($orderSettArr);
            $b = Orders::where('sys_num',$reArr)->update($orderArr);
            $c = OrderList::where('sys_num',$reArr)->update($orderListArr);
            $d = SettlementThree::where('sys_num',$reArr)->update($orderSetteArr);
            $poss['state'] = 5;
            $poss['updated_at'] = date("Y-m-d H:i:s");
            $info = Refund::where('id',$input['id'])->update($poss);
            if(empty($b)){
                $lock_type = Orders::where('sys_num',$reArr)->value("lock_type");
                if($lock_type=='1'){
                    $b = 1;
                }
            }
            if ($info && $b){
                if($infoRefund['goods_state'] == 2 && !isset($input['refund_id'])) {
                    SubmitPlease::where('refund_id', $input['id'])->update(['submit_stauas' => 3]);
                }
                /****************************同步通知门店***************************/
                if($order_find['order_status']>10 && $order_find['store_type']=='5'){
//                    $store=SyncStores::where("ser_id",$order_find['ser_id'])->where("type",2)->value('id');
                    $store = CommonService::getSyncStores($order_find['ser_id'], $order_find['category']);
                    if(!empty($store)){
                        $returnOrderList = OrderList::where('sys_num', $reArr)->select('serial_number')->get()->toArray();
                        foreach ($returnOrderList as $k => $v) {
                            $pop = [
                                'order_num' => $v['serial_number'],
                                'type' => 2
                            ];
                            $store = SysStoresService::sysStore($pop, 'lockUrl',$store);
                            if ($store['ErrorCode'] != 1) {
                                return $store;
                            }
                        }
                    }
                }
                /*******************************************************/
                $content = "驳回订单".$reArr;
                $BaseController->insertingLog('驳回，',$reArr,$content,'退款管理',$ip,$session['admin_acc']);
                $BaseController->pushWebDel($infoRefund['order_num'],3);

                return ['Data' => [], 'ErrorMessage' =>'操作成功', 'ErrorCode' => 1];
            }else {
                return ['Data' => [], 'ErrorMessage' =>'操作失败', 'ErrorCode' => ErrorInc::MYSQL_FAILED];
            }
        }catch(\Exception $e){
            return ['Data' => [], 'ErrorMessage' =>$e->getMessage(), 'ErrorCode' => ErrorInc::MYSQL_FAILED];
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取退款申请类型
     * @retrun  /multitype:array
     * @author dou 2021/11/2 15:53
     * |---------------------------------------------------------------------------------
    */
    public static function getRefundApplyType ( $type = false , $add = false , $datatype = 1){
        $applyType = array(
            array('type'=>1,'name'=>'退单(撤销订单)','datatype'=>'1','sety_id'=>0),
            array('type'=>2,'name'=>'中奖油卡','datatype'=>'1','sety_id'=>631),
            array('type'=>3,'name'=>'施工返款','datatype'=>'1','sety_id'=>632),
            array('type'=>4,'name'=>'安抚补偿','datatype'=>'1','sety_id'=>639),
            array('type'=>5,'name'=>'半价返款','datatype'=>'1','sety_id'=>640),
            array('type'=>6,'name'=>'换货运费','datatype'=>'1','sety_id'=>641),
            array('type'=>7,'name'=>'好评返款','datatype'=>'1','sety_id'=>633),
            array('type'=>8,'name'=>'退货款+邮费','datatype'=>'1','sety_id'=>642),
            array('type'=>9,'name'=>'退货款','datatype'=>'1','sety_id'=>643),
            array('type'=>10,'name'=>'撤销后退款','datatype'=>'1','sety_id'=>644),
           // array('type'=>11,'name'=>'京东E卡','datatype'=>'1','sety_id'=>645),
            array('type'=>12,'name'=>'其它','datatype'=>'2','sety_id'=>646),
            array('type'=>13,'name'=>'运损赔付','datatype'=>'2','sety_id'=>647),
          //  array('type'=>14,'name'=>'f6赔付','datatype'=>'2','sety_id'=>648)
        );
        if(in_array($datatype, [1,2])){
            $applyType = CommonService::arrayFilterFieldValue($applyType, array(array('datatype'=>$datatype)));
        }
        if($add){
            unset($applyType[0]);
        }
        $applyType = CommonService::resetListKey($applyType);
        if($type){
            $applyType = array_column($applyType, 'name' , 'type');
        }
        return $applyType;
    }

    /**|---------------------------------------------------------------------------------
     * @name 编辑退款用户地址
     * @param string $order_num 订单单号
     * @param string $user_id 用户id
     * @param string $shr_name 姓名
     * @param string $shr_phone 电话
     * @param string $shr_sheng 省份
     * @param string $shr_shi 城市
     * @param string $shr_xian 区县
     * @param string $shr_adress 详细地址
     * @retrun /multitype:array
     * @author dou 2021/12/29 18:23
     * |---------------------------------------------------------------------------------
    */
    public static function editUserData ( $order_num , $shr_name , $shr_phone , $shr_sheng , $shr_shi , $shr_xian , $shr_adress , $user_id ){
        $poss['user_id'] = $user_id;
        $poss['shr_name'] = $shr_name;
        $poss['shr_phone'] = $shr_phone;
        $poss['shr_sheng'] = $shr_sheng;
        $poss['shr_shi'] = $shr_shi;
        $poss['shr_xian'] = $shr_xian;
        $poss['shr_adress'] = $shr_adress;
        $res = Refund::where("order_num",$order_num)->update($poss);
        return $res;
    }

    /**|---------------------------------------------------------------------------------
     * @name 退款属性
     * @retrun /multitype:array
     * @author dou 2022/1/26 16:54
     * |---------------------------------------------------------------------------------
     */
    public static function getAttributeName ( $type = false ){
        $data = [
            ['type'=>1,'name'=>'服务退款'],
            ['type'=>2,'name'=>'商品退款'],
            ['type'=>3,'name'=>'业务收款']
        ];
        if( $type ){
            $data = array_column($data, 'name' , 'type');
        }
        return $data;
    }

    /**
     * @param false $type
     * @return array|array[]
     * @author du
     * @date 2022/4/12
     */
    public static function getGoodsstateName ( $type = false ){
        $data = [
            ['type'=>1,'name'=>'抹零'],
            ['type'=>2,'name'=>'平台'],
            ['type'=>3,'name'=>'服务中心'],
            ['type'=>4,'name'=>'财务'],
        ];
        if( $type ){
            $data = array_column($data, 'name' , 'type');
        }
        return $data;
    }

}
