<?php
class dailiAction extends baseAction
{
	private $allStyle;
	function __construct()
	{
		parent::__construct();
		$this->allStyle = [
			'shop'=>'商家入驻',
			'pcyear'=>'pc年卡',
			'pchyear'=>'pc半年卡',
			'pcmonth'=>'pc月卡'
		];
		LibTpl::Set('allStyle', $this->allStyle);
	}

	//重置跑街令代理的邀请码价格
	function initAllInvcodePrice()
	{
		LibRule::Check('PP00');
		$PjlDaili = new PjlDaili();
		$PjlDaili->initAllInvcodePrice();
		echo 'ok';
	}

	//重置邀请码的二维码
	function rebuildinvcodeEwm()
	{
		LibRule::Check('PP00');
		$PjlDaili = new PjlDaili();
		$PjlDaili->rebuildinvcodeEwm('all');
		echo 'ok';
	}


	//代理商
	function lists()
	{
		LibRule::Check('DL03');
		$PjlBase= new PjlBase();
		$table = 'dl_company';
		$where = ' order by dco_status desc, dco_name asc';
		$res = $PjlBase->get($table, ['*'], $where);
		$lists = array_column($res['data'], null, 'dco_id');
		if(!empty($lists))
		{
			$table = 'dl_company_target left JOIN dl_company_target_pcts ON dctp_dct_id = dct_id left JOIN yp_province_city ON dctp_pc_id = pc_id';
			$filed = ['dct_dco_id, dct_id, dct_begin, dct_end, dct_shop_tar, dctp_pc_id, dctp_pc_type, pc_name'];
			$res = $PjlBase->get($table, $filed, sprintf(" and dct_dco_id in (%s)  ORDER BY dct_end DESC, pc_name", implode(',', array_keys($lists))));
			foreach($res['data'] as $v)
			{
				$tjwhere = sprintf(" and dml_style='shop' and dml_dco_id = %d and dml_daili_area = 1", $v['dct_dco_id']);
				$tjwhere .= $v['dctp_pc_type'] == 1 ? sprintf(" and dml_pc_pid=%d", $v['dctp_pc_id']): sprintf(" and dml_pc_cid=%d", $v['dctp_pc_id']);
				$tjRes = $PjlBase->get('dl_order_list', ['count(*) as shop_count'], $tjwhere, true);
				$v['shop_ok'] = $tjRes['data']['shop_count'];
				$v['days'] = ceil(($v['dct_end'] - time())/3600/24);
                $lists[$v['dct_dco_id']]['shop_ok'] += $v['shop_ok'];
                //todo dct_shop_tar 值是否相加
                $lists[$v['dct_dco_id']]['dct_shop_tar'] = $v['dct_shop_tar'];
                $lists[$v['dct_dco_id']]['pc_name'][] = $v['pc_name'];
                if($v['days'] <= 0){
                    $lists[$v['dct_dco_id']]['time'] = date('Y-m-d', $v['dct_begin']).' ~ '.date('Y-m-d', $v['dct_end']). '/<span class="red2">已过期</span><span class="warn">剩'.$v['days'].'天</span>';
                }else{
                    $lists[$v['dct_dco_id']]['time'] = date('Y-m-d', $v['dct_begin']).' ~ '.date('Y-m-d', $v['dct_end']). '/<span class="green">剩'.$v['days'].'天</span>';
                }
			}

			foreach($lists as $dcoid=>$v)
			{
				$v['dco_tc'] = json_decode($v['dco_tc'], true);
				$lists[$dcoid] = $v;
			}
			$YpwBase = new YpwBase();
			$res = $YpwBase->get('yp_user', ['*'], sprintf(" and u_id in (%s)", implode(',', array_column($lists, 'dco_uid'))));
			$userArr = array_column($res['data'], null, 'u_id');
			LibTpl::Set('userArr', $userArr);
		}
		//var_dump($lists);exit();
		LibTpl::Set('lists', $lists);
		LibTpl::Set('title', '代理商');
		LibTpl::Put();
	}


	//业绩统计
	function yjTj()
	{
		LibRule::Check('DL03');
		$Params = mvc::$URL_PARAMS;
		$fastTime = [
			'本月'=>date('Y-m-01').' ~ '.date('Y-m-d'),
			'上个月'=>date('Y-m-01', strtotime('-1 month', strtotime(date('Y-m')))).' ~ '.date('Y-m-d', strtotime(date('Y-m-01'))-1),
			'本年'=>date('Y-01-01').' ~ '.date('Y-m-d')
		];
		LibTpl::Set('fastTime', $fastTime);


		$groupByArr = [
			'day'=>['日统计', '%Y-%m-%d'],
			'month'=>['月统计', '%Y-%m'],
			'year'=>['年统计', '%Y']
		];
		LibTpl::Set('groupByArr', $groupByArr);

		$Params['group'] = empty($groupByArr[$Params['group']]) ? 'day': $Params['group'];
		$groupBy = $groupByArr[$Params['group']][1];

		$PjlBase= new PjlBase();
		$res = $PjlBase->get('dl_company JOIN dl_company_target ON dct_dco_id = dco_id', ['dco_id, dco_name, dco_short_name'], ' GROUP BY dco_id ORDER BY MAX(dct_end) DESC, dco_name');
		$dcoArr = array_column($res['data'], null, 'dco_id');

		$where ='';
		$Params['betime'] = empty($Params['betime'])? $fastTime['本月']: $Params['betime'];
		foreach($Params as $k=>$v)
        {
            $v = trim($v);
            if($v == '') continue;
            switch($k)
            {
				case 'betime':
					$t = explode(' ~ ', $v);
					$where .= sprintf(" and dml_atime >= %d and dml_atime < %d", strtotime($t[0]), strtotime($t[1])+86400);
				break;
            }
        }

		$where .= ' ORDER BY dml_atime desc';
		$tjArr = [];
		$sum = [];
		$filed = ["dml_dco_id, FROM_UNIXTIME(dml_atime, '".$groupBy."') as pay_date, dml_money_pay, dml_money_gstc, dml_money_selftc, dml_daili_area"];
		$res = $PjlBase->get('dl_order_list', $filed, $where);
		foreach($res['data'] as $v)
		{
			$tjArr[$v['dml_dco_id']][$v['pay_date']]['dml_money_pay'] += $v['dml_money_pay'];
			$tjArr[$v['dml_dco_id']][$v['pay_date']]['dml_money_gstc'] += $v['dml_money_gstc'];
			$tjArr[$v['dml_dco_id']][$v['pay_date']]['dml_money_selftc'] += $v['dml_money_selftc'];
			$tjArr[$v['dml_dco_id']][$v['pay_date']]['count'] += 1;
			$tjArr[$v['dml_dco_id']][$v['pay_date']]['area1_count'] += $v['dml_daili_area']? 1: 0;
			$tjArr[$v['dml_dco_id']][$v['pay_date']]['area1_gstc'] += $v['dml_daili_area']? $v['dml_money_gstc']: 0;
			$tjArr[$v['dml_dco_id']][$v['pay_date']]['area1_selftc'] += $v['dml_daili_area']? $v['dml_money_selftc']: 0;
			$tjArr[$v['dml_dco_id']][$v['pay_date']]['area0_count'] += !$v['dml_daili_area']? 1: 0;
			$tjArr[$v['dml_dco_id']][$v['pay_date']]['area0_gstc'] += !$v['dml_daili_area']? $v['dml_money_gstc']: 0;
			$tjArr[$v['dml_dco_id']][$v['pay_date']]['area0_selftc'] += !$v['dml_daili_area']? $v['dml_money_selftc']: 0;
		}

		foreach($tjArr as $dcoid=>$dv)
		{
			foreach($dv as $date=>$dvv)
			{
				foreach($dvv as $filed=>$val)
				{
					$sum[$dcoid][$filed] += $val;
					$sum['all'][$filed] += $val;
				}
			}
		}

		LibTpl::Set('sum',$sum);
		LibTpl::Set('dcoArr', $dcoArr);
		LibTpl::Set('tjArr',$tjArr);
		LibTpl::Set('Params',$Params);
		LibTpl::Set('title','业绩统计');
		LibTpl::Put();
	}

	//提成统计
	public function yjTjTotal()
	{
		LibRule::Check('DL04');
		$Params = mvc::$URL_PARAMS;
		$pjlBase= new PjlBase();
		$perPage = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 20;
		$userModel = new YpwBase;
		$page = isset($Params['page']) ? $Params['page'] : 1;
		$where = '';
		if(isset($Params['user_info']) && !empty($Params['user_info'])){
			$shopId = $pjlBase->get("pl_shop",['shop_id'],sprintf(" and shop_name like '%%%s%%'",$Params['user_info']));
			if(isset($shopId['data']['0']) && !empty($shopId['data']['0'])){ //商铺名匹配到了
				$temp = sprintf(" and dml_shop_id in (%s)",implode(',',array_column($shopId['data'],'shop_id')));
			}else{
				$userId = $userModel->get("yp_user",['u_id'],sprintf(" and u_name = '%s' or u_mobile = '%s'",$Params['user_info'],$Params['user_info']));
				if(isset($userId['data']['0']) && !empty($userId['data']['0'])){
					$temp = sprintf(" and dml_order_uid in (%s)",implode(',',array_column($userId['data'],'u_id')));
				}
			}
			if(empty($temp)){
				$where .= ' and dml_order_uid=0';
			}else{
				$where .= $temp;
			}
			unset($temp);
		}
		if(!empty($Params['dml_dco_id'])){
			$where .= sprintf(" and dml_dco_id = %d",$Params['dml_dco_id']);
		}
		if(!empty($Params['dml_dwi_invcode'])){
			$where .= sprintf(" and dml_dwi_invcode = '%s'",$Params['dml_dwi_invcode']);
		}

		if(!empty($Params['dml_dwo_uid'])){
		   $where .= sprintf(" and dml_dwo_uid = '%d'",$Params['dml_dwo_uid']);
		}

		if(!empty($Params['dml_style'])){
			$where .= sprintf(" and dml_style = '%s'",$Params['dml_style']);
		}

		if(is_numeric($Params['dml_daili_area'])){
			$where .= sprintf(" and dml_daili_area=%d",$Params['dml_daili_area']);
		}
		if(!empty($Params['dml_atime'])){
			$temp = explode('~',$Params['dml_atime']);
			$where .= sprintf(" and dml_atime between %s and %s",strtotime($temp['0']),strtotime($temp['1'])+86439);
		}
		if(!empty($Params['dml_pc_pid'])){
			$where .= sprintf(" and dml_pc_pid = %d",$Params['dml_pc_pid']);
		}
		$list = $pjlBase->get("dl_order_list left join dl_company on dco_id=dml_dco_id left join pl_shop on shop_id=dml_shop_id left join yp_province_city on dml_pc_pid=pc_id and pc_pid=0 left join yp_province_city as city on dml_pc_cid=city.pc_id",['city.pc_name as city_name','yp_province_city.pc_name','dml_pc_cid','dml_dco_id','dml_dwo_uid','dml_order_uid','dml_id','dml_daili_area','dml_atime','dml_dwo_name','dml_style','dml_money_pay', 'dml_por_id','dml_money_selftc','dml_money_ywytc','dml_dwi_invcode','dml_order_id','dml_remark','dco_short_name','shop_name'],sprintf('%s order by dml_atime desc limit %d,%d',$where,($page-1)*$perPage, $perPage));
		$count = $pjlBase->get('dl_order_list',['count(*) count'],$where);
		if(!empty($list['data']))
		{
			$uids = implode(',',array_unique(array_column($list['data'],'dml_order_uid')));

			$userInfo = $userModel->get('yp_user', ['u_id,u_name'], sprintf(" and u_id in (%s)", $uids));

			$userInfo = array_column($userInfo['data'],null,'u_id');
			//获取当前列表最新的vip订单记录
			$uvlIdArr = [];
			$zxuvlArr = $pjlBase->get('pl_user_vip pv1', ['*'], 
			sprintf(" AND pv1.uvip_uid in (%s) AND pv1.uvip_etime = (
				SELECT MAX(pv2.uvip_etime) 
				FROM pl_user_vip pv2 
				WHERE pv2.uvip_uid = pv1.uvip_uid
			)", $uids));
				
			if($zxuvlArr['data']){
				$uvlIdArr = array_column($zxuvlArr['data'],null,'uip_uvl_id');
			}
			//获取当前用户的店铺入驻到期时间
			$shopInfoArr = [];
			$shopInfo = $pjlBase->get('pl_shop',['shop_pu_id','shop_vip_etime'],sprintf(" AND shop_pu_id in (%s)",$uids));
			if($shopInfo['data']){
				$shopInfoArr = array_column($shopInfo['data'],null,'shop_pu_id');
			}
			//获取当前订单的付款金额
			$orderIdArr = implode(',',array_unique(array_column($list['data'],'dml_order_id')));
			if($orderIdArr){
				$vres = $pjlBase->get('pl_user_vip_list',['uvl_id','uvl_paymoney','uvl_pay_time'],sprintf(" AND uvl_id in (%s)",$orderIdArr));
				if($vres['data']){
					$uvlMoneyArr = array_column($vres['data'],null,'uvl_id');
				}
				$refundMoneyArr = [];
				$rres = $pjlBase->get('pl_user_vip_refund',['uvr_uvl_id','uvr_money','uvr_status'],sprintf(" AND uvr_uvl_id in (%s)",$orderIdArr));
				if($rres['data']){
					foreach ($rres['data'] as $key => $val) {
						
						$refundMoneyArr[$val['uvr_uvl_id']]['total_refund_money'] += $val['uvr_money'];
						if($val['uvr_status']==1){
							$refundMoneyArr[$val['uvr_uvl_id']]['real_refund_money'] += $val['uvr_money'];
						}  
					}
				}
			}
			//是否是管理员
			$B2cBase = new B2cBase();
			$isAdminRes = $B2cBase->get('an_user',['au_isadmin'],sprintf(" AND au_uid=%d",$_SESSION['admin_userid']),true);
			$isAdmin = $isAdminRes['data']?1:0;
			foreach ($list['data'] as &$value) {
				$value['canChange'] = 0; //是否可以转入驻
				if(isset($userInfo[$value['dml_order_uid']]))
				{
					$value['user_info'] = $userInfo[$value['dml_order_uid']]['u_name'];
					$value['dml_atime'] = date('Y-m-d H:i',$value['dml_atime']);
				}
				//当前订单是能关联最新的vip订单
				if(isset($uvlIdArr[$value['dml_order_id']]) 
				&& isset($shopInfoArr[$value['dml_order_uid']]) 
				&& $shopInfoArr[$value['dml_order_uid']]['shop_vip_etime']!=$uvlIdArr[$value['dml_order_id']]['uvip_etime'])
				{
					$value['canChange']=1;
				}
				
				$pay_time = $uvlMoneyArr[$value['dml_order_id']]['uvl_pay_time']??0;
				$value['canRefund']=0;
				//只有管理员且订单付款不超过30天才能退款
				if($isAdmin && time()> $pay_time &&(time()<$pay_time+86400*30)){
					$value['canRefund']=1;
				}
				$value['uvl_paymoney'] = $uvlMoneyArr[$value['dml_order_id']]['uvl_paymoney'] ?? 0;
				$value['total_refund_money'] = $refundMoneyArr[$value['dml_order_id']]['total_refund_money'] ?? 0;
				$value['real_refund_money'] = $refundMoneyArr[$value['dml_order_id']]['real_refund_money'] ?? 0;
			}
			unset($value);

		}

		$Page = LibPage::Show($count['data']['0']['count'], $perPage);
		$city = $userModel->get("yp_province_city",['pc_id','pc_name'],sprintf(" and pc_pid=0"));
		LibTpl::Set("city",$city);
		LibTpl::Set('Page', $Page);
		LibTpl::Set('list',$list['data']);
		LibTpl::Set('param',$Params);
		LibTpl::Set('dls',$pjlBase->get("dl_company",['dco_id','dco_short_name']));
		LibTpl::Set('ywy',$pjlBase->get('dl_worker',['dwo_uid','dwo_name']));
		LibTpl::Set('title', '代理邀请');
		LibTpl::Put();
	}

	public function dls()
	{

		$params = mvc::$URL_PARAMS;
		$YpwBase = new YpwBase();
		$PjlBase = new PjlBase();
		if($params['dco_id'] > 0){

			$where = sprintf(" and dco_id = %d group by dco_id ",$params['dco_id']);
			$filed = ['dl_company.*,dct_dco_id, dct_id, dct_begin, dct_end, dct_shop_tar, group_concat(dctp_pc_id) as dctp_pc_id, dctp_pc_type, pc_name'];
			$res = $PjlBase->get("dl_company left join dl_company_target on dco_id=dct_dco_id left JOIN dl_company_target_pcts ON dctp_dct_id = dct_id left JOIN yp_province_city ON dctp_pc_id = pc_id", $filed, $where,true);
		//	var_dump($res);exit();
			$lists = $res['data'];
     		if(!empty($lists['dctp_pc_id'])){
     		    $lists['dctp_pc_id'] = explode(',',$lists['dctp_pc_id']);
            }
			//var_dump($lists);exit();
			$config = json_decode($lists['dco_tc'],true);
			unset($lists['dco_tc']);
			$user = $YpwBase->get('yp_user', ['u_id,u_name'], sprintf(" and u_id = %d", $lists['dco_uid']));
			$lists['u_name'] = $user['data']['0']['u_name'];
		    LibTpl::Set('list', $lists);
		}else{
			//默认配置
            //todo
            //{"shop":{"price":818,"min":600,"max":818,"tc":"gs","tcmoney":300},
            //"pcyear":{"price":818,"min":600,"max":818,"tc":"gs","tcmoney":300},
            //"pchyear":{"price":528,"min":400,"max":528,"tc":"self","tcmoney":0.5},
            //"pcmonth":{"price":108,"min":80,"max":108,"tc":"self","tcmoney":0.5}}
			$config = [
				'shop' => ['price' => '818', 'min' => '600', 'max' => '818', 'tc' => 'gs', 'tcmoney' =>  '300'],
		     	'pcyear' => ['price' => '818', 'min' => '600', 'max' => '818', 'tc' => 'gs', 'tcmoney' => '300'],
		        'pchyear' => ['price'=> '528', 'min' => '400', 'max' => '528', 'tc' => 'self', 'tcmoney' => '0.5'],
		        'pcmonth' => ['price' => '108', 'min' => '80', 'max' => '108', 'tc' => 'self', 'tcmoney' => '0.5']
			];
			$max = $PjlBase->get("dl_company",['max(dco_code) as max_code'],'',true);
			LibTpl::Set('maxCode',$max['data']['max_code']+1);
		}


		$city = $YpwBase->get("yp_province_city",['pc_id','pc_name'],sprintf(" and pc_pid=0"));
		LibTpl::Set("city",$city);
		LibTpl::Set('config', $config);
		LibTpl::Put();
	}

	private function arrayTrim($value)
	{
		if(is_array($value))
		{
		    if(count($value) == count($value,1))
		    { //一维数组
		        $value = array_map('trim',$value);
            }
		    else
		    {
                foreach($value as &$v)
                {
                    $v = array_map('trim',$v);
                }
            }

		}
		else
		{
			$value = trim($value);
		}

		return $value;
	}

	public function addDls()
	{
		$_POST = array_map([__CLASS__,'arrayTrim'],$_POST);
		$userInfo = [];
		if(!is_numeric($_POST['dco_uid']))
		{
			LibFc::ajaxJsonEncode(['status' => false,'data' => 'UID 不是一个数字']);
		}
		if(!empty($_POST['dco_uid']))
		{
			$userInfo = (new YpwBase)->get('yp_user',['*'],sprintf(" and u_id=%d",$_POST['dco_uid']));
		}
		if(empty($userInfo['data']['0']))
		{
			LibFc::ajaxJsonEncode(['status' => false,'data' => 'uid不存在']);exit();
		}
		if(!in_array($_POST['dco_status'],['0','1']))
		{
			   LibFc::ajaxJsonEncode(['status' => false,'data' => '参数错误']);
		}

		$tempStyle = array_keys($this->allStyle);
		$itemConfigKey = ['price', 'max', 'min', 'tc', 'tcmoney'];

		//验证配置v
		foreach($_POST['dco_tc'] as $index => $item)
		{
			 if(!in_array($index,$tempStyle))
			 {
				  LibFc::ajaxJsonEncode(['status' => false,'data' => '参数错误']);
			 }
			 foreach($item as $k => $v){
				 if(!in_array($k,$itemConfigKey))
				 {
					 LibFc::ajaxJsonEncode(['status' => false,'data' => '参数错误']);
				 }
				 if($k == 'tc')
				 {
					 if(!in_array($v,['self','gs'])){
						 LibFc::ajaxJsonEncode(['status' => false,'data' => '参数错误']);
					 }
				 }
				 else
				 {
					 if(!is_numeric($v))
					 {
						 LibFc::ajaxJsonEncode(['status' => false,'data' => '参数错误']);
					 }
				 }
			 }
		}
		if(mb_strlen($_POST['dco_name']) > 32)
		{
			LibFc::ajaxJsonEncode(['status' => false,'data' => '代理名称长度超过了限制32']);
		}
		if(empty($_POST['dco_name']))
		{
			LibFc::ajaxJsonEncode(['status' => false,'data' => '代理名称不可为空']);
		}

		if(mb_strlen($_POST['dco_short_name']) > 16)
		{
			LibFc::ajaxJsonEncode(['status' => false,'data' => '代理短名称长度超过了限制16']);
		}
		if(empty($_POST['dco_short_name']))
		{
			LibFc::ajaxJsonEncode(['status' => false,'data' => '代理短名称不可为空']);
		}

		if($_POST['dco_code'] > 99)
		{
			LibFc::ajaxJsonEncode(['status' => false,'data' => '唯一编码不能超过99']);
		}

		if(mb_strlen($_POST['dco_link']) > 32)
		{
			LibFc::ajaxJsonEncode(['status' => false,'data' => '联系人长度超过了限制32']);
		}
		if(!empty($_POST['dco_tel'])){
			if(!$this->checkPhoneNumberValidate($_POST['dco_tel'])){
				LibFc::ajaxJsonEncode(['status' => false,'data' => '请填写一个正确得手机号']);
			}
		}
		if(!empty($_POST['dco_addr']))
		{
			if(mb_strlen($_POST['dco_addr']) > 128)
			{
				LibFc::ajaxJsonEncode(['status' => false,'data' => '地址长度超过了限制128']);
			}
		}

		if(!is_numeric($_POST['dct_shop_tar']))
		{
			LibFc::ajaxJsonEncode(['status' => false,'data' => '入驻目标数不是一个数字']);
		}

		if(empty($_POST['dct_begin']))
		{
			LibFc::ajaxJsonEncode(['status' => false,'data' => '开始时间不可为空']);
		}

		if(empty($_POST['dct_end']))
		{
			LibFc::ajaxJsonEncode(['status' => false,'data' => '结束时间不可为空']);
		}

//		if((int) $_POST['pc_id'] <=0)
//		{
//			LibFc::ajaxJsonEncode(['status' => false,'data' => '代理城市不可为空']);
//		}

		if($_POST['dct_shop_tar'] > 32767){
			LibFc::ajaxJsonEncode(['status' => false,'data' => '目标数超过了32767最大范围']);
		}

		$time = time();
		$postData = [
			//dl_company代理商
			'dl_company' => [
				'dco_tc' => $_POST['dco_tc'],
				'dco_name' => $_POST['dco_name'],
				'dco_dltype' => $_POST['dco_dltype'],
				'dco_short_name' => $_POST['dco_short_name'],
				'dco_code' => $_POST['dco_code'],
				'dco_uid' => $_POST['dco_uid'],
				'dco_link' => $_POST['dco_link'],
				'dco_tel' => $_POST['dco_tel'],
				'dco_status' => $_POST['dco_status'],
				'dco_addr' => $_POST['dco_addr'],
				'dco_id' => $_POST['dco_id'],
				'dco_atime' => $time
			],
	    	//dl_company_target代理目标
	    	'dl_company_target' => [
				'dct_id' => '',
				'dct_dco_id' => $_POST['dco_id'],
	    		'dct_begin' => strtotime($_POST['dct_begin']),      //代理开始时间
	    		'dct_end' => strtotime($_POST['dct_end']),//代理结束时间
	    		'dct_shop_tar' => $_POST['dct_shop_tar'],// 商家入驻目标数
	    	],
	     	// dl_company_target_pcts  代理目标区域限制
	        'dl_company_target_pcts' => [
	        	'dctp_dct_id' => 0 ,
	        	'dctp_pc_id' => $_POST['pc_id'],
	        	'dctp_pc_type' => 1 ,
	        ],
		    //dl_worker
		    'dl_worker' => [
		    	'dwo_uid' => $_POST['dco_uid'],
		    	'dwo_dco_id' => $_POST['dco_id'],
		    	'dwo_status' => $_POST['dco_status'],
		    	'dwo_name' => $userInfo['data']['0']['u_name'],
		    	'dwo_tel' => $userInfo['data']['0']['u_mobile'] ?: '',
		    	'dwo_remark' => '',
		    	'dwo_atime'=> $time,
		    ]
		];


		//todo 表单验证
		$result = (new PjlDaili)->addOrEditDls($postData);
		LibFc::ajaxJsonEncode($result);
	}

	private function checkPhoneNumberValidate($phoneNumber){
		//@2017-11-25 14:25:45 https://zhidao.baidu.com/question/1822455991691849548.html
		//中国联通号码：130、131、132、145（无线上网卡）、155、156、185（iPhone5上市后开放）、186、176（4G号段）、175（2015年9月10日正式启用，暂只对北京、上海和广东投放办理）,166,146
		//中国移动号码：134、135、136、137、138、139、147（无线上网卡）、148、150、151、152、157、158、159、178、182、183、184、187、188、198
		//中国电信号码：133、153、180、181、189、177、173、149、199
		$g = "/^1[34578]\d{9}$/";
		$g2 = "/^19[89]\d{8}$/";
		$g3 = "/^166\d{8}$/";
		if(preg_match($g, $phoneNumber)){
			return true;
		}else  if(preg_match($g2, $phoneNumber)){
			return true;
		}else if(preg_match($g3, $phoneNumber)){
			return true;
		}
		return false;
	}

	public function getUserInfo()
	{
		$userInfo = (new YpwBase)->get('yp_user',['u_id,u_name,u_mobile'],sprintf(" and (u_name like '%%%s%%' or u_mobile like '%%%s%%')",$_POST['text'],$_POST['text']),true);
		LibFc::ajaxJsonEncode($userInfo);
	}

	//个人邀请码
	public function personalInvitation()
    {
		LibRule::Check('DL04');
        $param = mvc::$URL_PARAMS;
        $pageSize = isset($_COOKIE['perPage']) ? $_COOKIE['perPage'] : 20;
        $page = LibFc::Int($param['page']) ? LibFc::Int($param['page']) : 1;
        $where = '';
        $ypBase = new YpwBase;

        if($param['sor_share_code']) $where .= sprintf(" and sor_share_code like '%%%s%%'",trim($param['sor_share_code']));

        if($param['sor_title']) $where .= sprintf(" and sor_title like '%%%s%%'",trim($param['sor_title']));

        if(is_numeric($param['sor_selftc_status'])) $where .= sprintf(" and sor_selftc_status='%s'",trim($param['sor_selftc_status']));

        if(is_numeric($param['uvl_status']))  $where .= sprintf(" and uvl_status ='%s'",$param['uvl_status']);

        if($param['sor_pu_id'])
        {
            $userId = $ypBase->get('yp_user',['u_id'],sprintf(" and (u_name like '%%%s%%' or u_mobile like '%%%s%%')",trim($param['sor_pu_id']),trim($param['sor_pu_id'])),true);
            if($userId['data']['u_id'] > 0)
            {
                $where .= sprintf(" and sor_pu_id=%d",$userId['data']['u_id']);
            }
            else
            {
                $where .= sprintf(" and sor_pu_id < 0");
            }
        }

        if($param['sor_selftc_jstime'])
        {
            $temp = explode(" ~ ", $param['sor_selftc_jstime']);
            $temp = array_map(function ($value) {
                return strtotime(trim($value));
            }, $temp);
            $where .= sprintf(" and sor_selftc_jstime between '%s' and '%s'",$temp['0'],$temp['1']);
        }

        if($param['uvl_btime'])
        {
            $temp = explode(" ~ ", $param['uvl_btime']);
            $temp = array_map(function ($value) {
                return strtotime(trim($value));
            }, $temp);
            $where .= sprintf(" and uvl_btime between '%s' and '%s'",$temp['0'],$temp['1']);
        }

        $db = new PjlBase;
        $count = $db->get('pl_share_order inner join pl_user_vip_list on uvl_id=sor_uvl_id',['count(*) as count'],$where,true);
        $count = $count['data']['count'] > 0 ? $count['data']['count'] : 0;
        $list = [];
        if($count > 0)
        {
            $where .= sprintf(" order by sor_id desc limit %s,%s",($page-1)*$pageSize,$pageSize);
            $list = $db->get('pl_share_order inner join pl_user_vip_list on uvl_id=sor_uvl_id',['pl_share_order.*','uvl_id','uvl_status','uvl_btime'],$where);
            $list = $list['data'];
            if(!empty($list))
            {
                $userIds = implode(',',array_unique(array_column($list,'sor_pu_id')));
                $userInfo = $ypBase->get('yp_user',['u_id','u_name'],sprintf(" and u_id in (%s)",$userIds));
                if(!empty($userInfo['data']))
                {
                    $userInfo = array_column($userInfo['data'],'u_name','u_id');
                }
                else
                {
                    $userInfo = [];
                }
                LibTpl::Set('userInfo',$userInfo);
            }
        }
        $uvlStatus = [
            '0' => ['value' => '待付款','color' => 'red'],
            '1' => ['value' => '已付款','color' => 'green'],
            '2' => ['value' => '已完成' ,'color' => 'green'],
            '-1' => ['value' => '关闭','color' => 'gray']
        ];
        $selStatus = [
             '-1' => ['color' => 'gray', 'value' => '无效'],
             '0'  => ['color' => '', 'value' => '待结算'],
             '1'  => ['color' => 'green', 'value' => '已结算']
        ];
        $pages = LibPage::Show($count, $pageSize);
        LibTpl::Set('list',$list);
        LibTpl::Set('page', $pages);
        LibTpl::Set('param',$param);
        LibTpl::Set('uvl_status',$uvlStatus);
        LibTpl::Set('sor_selftc_status',$selStatus);
        LibTpl::Set('title', '个人邀请');
        LibTpl::Put();
    }

    public function updateOrderListById()
    {
        LibRule::Check('PC03');
        $id = (int) $_POST['dml_id'];
        $porId = (int) $_POST['por_id'];
        $dmlDcoId = (int) $_POST['dml_dco_id'];
        if($id <= 0) LibFc::ajaxJsonEncode(['status' => false, 'data' => '参数错误']);
        // if($porId <= 0) LibFc::ajaxJsonEncode(['status' => false, 'data' => '参数错误']);
        if($dmlDcoId <= 0) LibFc::ajaxJsonEncode(['status' => false,'data' => '参数错误']);
        $invcode = trim($_POST['dml_dwi_invcode']);
        if(empty($invcode)) LibFc::ajaxJsonEncode(['status' => false, 'data' => '邀请码不可为空']);
        $db = new PjlBase;
        $details = $db->get('dl_worker_invcode join dl_worker on dwo_uid=dwi_dwo_uid',['*'],sprintf(" and dwi_invcode='%s' and dwi_status=1",LibFc::Escape($invcode)),true);
        if(empty($details['data'])) LibFc::ajaxJsonEncode(['status' => false,'data' => '邀请码不存在']);
        $details = $details['data'];
       
        $company = $db->get('dl_company',['*'],sprintf(" and dco_id=%d",$details['dwi_dco_id']),true);
        if(empty($company['data'])) LibFc::ajaxJsonEncode(['status' => false,'data' => '代理公司不存在']);
        $company = $company['data'];

		$remark = [];
		//存在支付单ID
		if($porId)
		{
			$yeJiList = $db->get('bu_yeji_list',['*'],sprintf(" and yl_por_id=%d",$porId),true);
			if(empty($yeJiList['data'])) LibFc::ajaxJsonEncode(['status' => false, 'data' => '订单数据找不到']);
			$yeJiList = $yeJiList['data'];
			$remark = $yeJiList['yl_remark'];
        	$remark = explode('邀请人',$remark);
			if($company['dco_isyp'] == 1){
				$remark = $remark['0'].'邀请人：'.$company['dco_short_name'].'-'.$details['dwo_name'].'['.$invcode.']';
				$updataArr = [
					'yl_user' => $details['dwo_name'],
					'yl_user_money' => $_POST['dml_money_selftc'] ?: 0,
					'yl_com_money' => $yeJiList['yl_pay_money'] - $_POST['dml_money_selftc'] - $yeJiList['yl_shui_money'],
					'yl_check_time' => time(),
					'yl_check_user' => $_SESSION['admin_uname'],
					'yl_remark' => $remark,
				];
	
			}else{
				$remark = $remark['0'].'邀请人：'.$company['dco_short_name'].'-'.$details['dwo_name'].'['.$invcode.']';
				$updataArr = [
					'yl_user' => '代理-'.$company['dco_short_name'],
					'yl_user_money' => $_POST['dml_money_selftc'] ?: 0,
					'yl_com_money' => $yeJiList['yl_pay_money'] - $_POST['dml_money_selftc'] - $yeJiList['yl_shui_money'],
					'yl_check_time' => time(),
					'yl_check_user' => $_SESSION['admin_uname'],
					'yl_remark' => $remark,
				];
			}
			$result = $db->set('bu_yeji_list',$updataArr,sprintf(" and yl_id=%d",$yeJiList['yl_id']));
		}
		
        

        $dmlData = $db->get('dl_order_list',['*'],sprintf(" and dml_id=%d",$_POST['dml_id']),true);
        if(empty($dmlData['data'])) LibFc::ajaxJsonEncode(['status' => false,'data' => '参数错误']);
        $dmlData = $dmlData['data'];
        //开票税不变
        $dmlUpdate = [
            'dml_dwo_uid' => $details['dwi_dwo_uid'],
            'dml_dwi_invcode' => $invcode,
            'dml_dwo_name' => $details['dwo_name'],
            'dml_money_selftc' => $_POST['dml_money_selftc'] ?: $_POST['dml_money_ywytc'],
            'dml_money_ywytc' => $_POST['dml_money_ywytc'] <= 0 ? $_POST['dml_money_selftc'] : $_POST['dml_money_ywytc'],
            'dml_dco_id' => $details['dwi_dco_id'],
        ];
        $dmlUpdate['dml_money_gstc'] = $dmlData['dml_money_pay'] - $dmlUpdate['dml_money_selftc'];
        $result = $db->set('dl_order_list',$dmlUpdate,sprintf(" and dml_id=%d",$dmlData['dml_id']));
		//存在支付单id
		if($porId)
		{
			//更新crm里的业绩
			$uvlRes = $db->get('pl_user_vip_list',['uvl_id,uvl_uid,uvl_style'],sprintf(" AND uvl_style='%s' AND uvl_id = %d",$dmlData['dml_style'],$dmlData['dml_order_id']),true);
			$uvlData = $uvlRes['data'];
			
			if($uvlData){
				$CrmSbModel	 = new BaseDb(mvc::$cfg['DB']['CRMS']);
				$yjaMoenySerRes = $CrmSbModel->get('yja_money_ser',['mos_id'],sprintf(" AND mos_from='PJLVIP' AND mos_from_id=%d",$uvlData['uvl_id']),true);
				if(empty($yjaMoenySerRes['data'])) LibFc::ajaxJsonEncode(['status' => false, 'data' => 'money_ser数据找不到']);
				//查找crm对应业务员
				$userRes = $CrmSbModel->get('yj_user',['u_id,u_name'],sprintf(" AND u_name = '%s'",$updataArr['yl_user']),true);
				if(empty($userRes['data'])) LibFc::ajaxJsonEncode(['status' => false, 'data' => 'crm找不到该业务员']);
				$user = $userRes['data'];
				$monUpdata = [
					'mon_u_name' => $updataArr['yl_user'],
					'mon_u_id' => $user['u_id'] ?? 0,
					'mon_check1_time' => $updataArr['yl_check_time'],
					'mon_check1_usr' => $updataArr['yl_check_user'],
					'mon_remark' => $updataArr['yl_remark']
				];
				$result = $CrmSbModel->set('yja_money', $monUpdata, sprintf(" AND mon_from='PJLVIP' AND mon_from_id=%d", $uvlData['uvl_id']));
				$mosUpdata = [
					'mos_user_money' => $updataArr['yl_user_money'],
					'mos_com_money' => $updataArr['yl_com_money'],
				];
				$result = $CrmSbModel->set('yja_money_ser',$mosUpdata,sprintf(" AND mos_from='PJLVIP' AND mos_from_id=%d",$uvlData['uvl_id']));
				//变更CRM合同的业务员和客户状态
				//先找合同再找合同对应的业务员
				if($invcode!=$dmlData['dml_dwi_invcode']){
					$CrmBase = new CrmBase();
					$res = $CrmBase->get('crm_customer',['ctr_id'],sprintf(" AND ctr_uid=%d",$uvlData['uvl_uid']),true);
					$ctr_id = $res['data']['ctr_id'];
					$sve_id = $uvlData['uvl_style'] == 'shop' ? 1 : 2;
					
					$res = $CrmBase->get('fad_link_fct_sve join fad_contract on fct_id = fsl_fct_id', ['fct_id'], sprintf(" and fct_ctr_id=%d and fsl_sve_id=%d and fsl_des_id=%d", $ctr_id, $sve_id, $uvlData['uvl_id']), true);
					if(!empty($res['data'])){
						$fct_id = $res['data']['fct_id'];
						$CrmBase->set('fad_link_fct_usr', ['duc_usr_id'=>$details['dwi_dwo_uid']], sprintf(' and duc_fct_id=%d',$fct_id));
						
						$LibYpApi = new LibYpApi();
						$getArr = ['ctr_id'=>$ctr_id];
						$res = $LibYpApi->Get('crm/initCtrStatus', $getArr, []);
					} 
				}
				

				
			}
		}
		
        LibFc::ajaxJsonEncode($result);
    }


	/**
	 * @method 获取邀请码对应提成
	 * @author zhengweihua 
	 * @copyright 2024-02-27
	 */
	public function getInvcodePrice()
	{
		$Params = mvc::$URL_PARAMS;
		$arr = [];
		if($Params['dwi_invcode'] && $Params['price']){
			$invcode = $Params['dwi_invcode'];
			$db = new PjlBase;
			$res = $db->get('dl_worker_invcode',['*'],sprintf(" and dwi_invcode='%s' and dwi_status=1",LibFc::Escape($invcode)),true);
			
			if($res['data']){
				$details = $res['data'];
				$arr = [
					$details['dwi_shop_price']=>['gstc'=>$details['dwi_shop_gstc'],'ywytc'=>$details['dwi_shop_ywytc']],
					$details['dwi_pcyear_price']=>['gstc'=>$details['dwi_pcyear_gstc'],'ywytc'=>$details['dwi_pcyear_ywytc']],
					$details['dwi_pchyear_price']=>['gstc'=>$details['dwi_pchyear_gstc'],'ywytc'=>$details['dwi_pchyear_gstc']],
					$details['dwi_pcmonth_price']=>['gstc'=>$details['dwi_pcmonth_gstc'],'ywytc'=>$details['dwi_pcmonth_ywytc']]
				];
			}
		}
		return LibFc::ReturnJson(true,$arr[$Params['price']]??[]);
	}

	/**
	 * @method 会员转商家入驻
	 * @author zhengweihua 
	 * @copyright 2025-09-01
	 */
	public function changeVipToShop()
	{
		if($_SERVER['REQUEST_METHOD'] != 'POST') LibFc::ajaxJsonEncode(['status' => false,'data' => '请求方式错误']);
		if($_POST['order_id']){
			$result = (new PjlDaili())->changeVipToShop($_POST['order_id']);
			LibFc::ajaxJsonEncode($result);
		}
	}


	/**
	 * @method 退款
	 * @author zhengweihua 
	 * @copyright 2025-11-11
	 */
	public function refundMoney()
	{
		if($_SERVER['REQUEST_METHOD'] != 'POST') LibFc::ajaxJsonEncode(['status' => false,'data' => '请求方式错误']);
		if($_POST['refund_money']>0 && $_POST['refund_password'] && $_POST['u_id']  && $_POST['uvl_id'] && $_POST['remark']){		
			$LibYpApi = new LibYpApi();
			$postArr = [
				'u_id'=> $_POST['u_id'],
				'uvl_id'=>$_POST['uvl_id'],
				'refund_password'=>$_POST['refund_password'],
				'refund_money'=>$_POST['refund_money'],
				'selftc_money'=>$_POST['selftc_money'] ?: 0,
				'ywytc_money'=>$_POST['ywytc_money'] ?: 0,
				'remark'=>$_POST['remark'],
				'by_uid'=> $_SESSION['admin_userid'],
			];
			$res = $LibYpApi->Get('pjl/refundPjViplOrder', [], $postArr);
			LibFc::ajaxJsonEncode($res);
		}else{
			LibFc::ajaxJsonEncode(['status' => false,'data' => '参数错误']);
		}
		
	}

	/**
	 * @method 获取退款详情
	 * @author zhengweihua 
	 * @copyright 2025-11-11
	 */
	public function getRefundDetail()
	{
		$Params = mvc::$URL_PARAMS;
		if(!$Params['order_id']) LibFc::ReturnJson(false,'参数错误');
		$order_id = $Params['order_id'];
		$pjlBase= new PjlBase();
		$refundDetails = $pjlBase->get('pl_user_vip_refund',['*'],sprintf(" AND uvr_uvl_id = %d",$order_id));
		$statusArr = [-1=>'已关闭',0=>'待处理',1=>'已完成'];
		if($refundDetails['data'])
		{
			$uidArr = array_column($refundDetails['data'],'uvr_by_uid');
			$YpwBase = new YpwBase();
			$res = $YpwBase->get('yp_user', ['*'], sprintf(" and u_id in (%s)", implode(',', $uidArr)));
			$userArr = array_column($res['data'], null, 'u_id');
			foreach ($refundDetails['data'] as $key => &$val) {
				$val['status_text'] = $statusArr[$val['uvr_status']];
				$val['operator'] = $userArr[$val['uvr_by_uid']]['u_name'];
				$val['uvr_atime'] = date('Y-m-d H:i',$val['uvr_atime']);
				$val['uvr_refunded_time'] = $val['uvr_refunded_time']?date('Y-m-d H:i',$val['uvr_refunded_time']):'';
			}
		}
		
		LibFc::ajaxJsonEncode($refundDetails);
	}

}

