<?php

namespace Active\Lib;

use Dever;
class Active
{
    public function action($uid, $active_id, $num, $path, $remark = false, $idcard = false)
    {
    	$user = Dever::db('active/user')->find($uid);
		// print_R(json_decode('[{"id":"1","value":"文本"},{"id":"2","value":"文本"},{"id":"3","value":"1"}]'));die;
		$data = Dever::db('active/info')->find($active_id);
		if ($data['col'] && $data['col'] == 'idcard' && (!$idcard || !preg_match(Dever::rule('idcard'), $idcard))){
			Dever::alert('身份证号不能为空或身份证号不正确');
		}
		// if ($data['act_status'] == 1 || (isset($data['act_start']) && $data['act_start'] && time() < $data['sign_start'])) {
		// 	Dever::alert('活动还未开始报名');
		// }
		if ($data['act_status'] >=3 || (isset($data['sign_end']) && $data['sign_end'] && time()>$data['sign_end'])){
			Dever::alert('活动报名已结束');
		}

		$insert['active_id'] = $active_id;
		$insert['num'] = $num;
		$insert['price'] = $num * $data['price'];
		if ($remark) {
			$insert['remark'] = $remark;
		}
		if ($path) {
			$insert['path'] = $path;
		}
		$insert['uid'] = $user['id'];
		$title = array();
		if ($data['attr']) {
			if ($data['attr_input']) {
				$input['num'] = explode(',',$data['attr_input']);
			}
			$data['attr'] = explode(',',$data['attr']);
			foreach ($data['attr'] as $k => $v) {
				foreach ($input['num'] as $k1 => $v1) {
					if($k == $k1){
						$title[$k]['id'] = $v;
						$title[$k]['num'] = $v1;
					}
				}
			}
		}
		$order = Dever::db('active/order')->getNum(array('uid'=>$uid,'active_id'=>$active_id,'status' => '2,4,5'));
		$member = Dever::load('active/lib/user')->agent($user);
		if ($data['status'] == 2) {
			
			if (!$member) {
				Dever::alert('本活动只能是代理商报名');
			}
		}
		if ($title && $member && $member['title_id'] && $member['title_id'] > 1) {
			foreach ($title as $k => $v) {
				$title_id = explode(',',$member['title_id']);
				if($title_id && in_array($v['id'],$title_id)) {
					if ($v['num'] > 0 && $num > $v['num']) {
						Dever::alert('您已超过限购数量');
					}
					if ($order) {
						if ($order['total']  && $v['num'] > 0 && ($order['total']+$num) > $v['num']) {
							Dever::alert('您已超过限购数量');
						}
					}
				}
			}
		} else {
			if ($order) {
				if ($data['num'] > 0 && $order['total'] && ($order['total'] + $num) > $data['num']) {
					Dever::alert('您已超过限购数量');
				}
			} elseif ($data['num']>0 && $num > $data['num'] ) {
				Dever::alert('您已超过限购数量');
			}
		}
		
		

		$test = Dever::input('test', 1);
		$info = false;
		if ($test == 1) {
			$time = time();
	        $order_data_where = $insert;
	        $order_data_where['start'] = $time - 20;
	        $order_data_where['end'] = $time;
	        $order_data_where['option']['start'] = array('yes-cdate', '>=');
	        $order_data_where['option']['end'] = array('yes-cdate', '<=');

	        $info = Dever::db('active/order')->find($order_data_where);
		}

        $insert['order_num'] = $this->getOrderId();
        
        if (!$info) {
            $ids = Dever::db('active/order')->insert($insert);
        } else {
            Dever::alert('请不要重复提交');
        }

		$url = Dever::url();
		$refer = 'https://www.churenyiliao.com/';
		if (strstr($url, 'uat.')) {
			$refer = 'http://guanli.uat.churenyiliao.com/';
		}
		$refer .= 'data/payback/active.html?order_id=' . $ids;
		if ($ids) {
			$info = Dever::db('active/order')->find($ids);
			$active = Dever::db('active/info')->find($info['active_id']);
			$param = array
	        (
	            'project_id' => 6,
	            'channel_id' => 1,
	            'system_source' => 1,
	            'account_id' => 8,
	            'uid' => $uid,
	            'name' => $active['name'],
	            //'openid' => $data['openid'],
	            'cash' => $info['price'],
	            'product_id' => $ids,
	            'order_id' => $info['order_num'],
	            'h5' => 1,
	            'refer' => $refer,
	        );

	        $result = Dever::load('pay/api.pay', $param);
	        if ($result['order']) {
	        	Dever::db('active/order')->update(array('where_id'=>$ids,'url'=>$result['order']));
	        }
	        $result['order_num'] = $info['order_num'];
	        $result['order_id'] = $info['id'];
	        $jump = Dever::input('jump');
	        if ($jump == 1) {
	        	Dever::location($result['order']);
	        }

	        return $result;
		} else {
			Dever::alert('提交失败');
		}
    }

     # 支付成功回调 安全加密 设置token
    public function success_secure_api_token()
    {
        $project_id = Dever::input('pay_project_id');
        $info = Dever::db('pay/project')->one($project_id);
        if ($info) {
            return $info['key'];
        }
        return 'agent_buy_dever_2020';
    }

    # 支付成功回调 安全加密
    public function success_secure_api($param = array())
    {
        $this->success($param);
    }

    # 支付成功回调
    public function success($param = array())
    {
        $send = $param ? $param : Dever::preInput('pay_');
        $product_id = $send['pay_product_id'];
        $order_id = $send['pay_order_id'];
        $status = $send['pay_status'];
        $cash = $send['pay_cash'];
        $msg = $send['pay_msg'];

        $order = Dever::db('active/order')->one(array('id' => $product_id, 'clear' => true));
        if ($order && $status == 2) {
        	
        	$code = Dever::db('active/code')->find(array('join_uid'=>$order['uid'],'active_id'=>$order['active_id']));
        	if (!$code) {
        		$active = Dever::db('active/info')->find($order['active_id']);
        		$insert['join_uid'] = $order['uid'];
        		$insert['active_id'] = $order['active_id'];
        		$insert['buy_uid'] = $order['uid'];
        		$insert['order_id'] = $order['id'];
        		$insert['write_code'] = $this->getCode();
        		$insert['act_status'] = $active['act_status'];
        		$ids = Dever::db('active/code')->insert($insert);
        		if ($ids) {
        			$update['code_num'] = 1;
        		}
        	} 
        	$update['status'] = 2;
            $update['where_id'] = $order['id'];
            
            Dever::db('active/order')->update($update);
        }

        return 'ok';
    }

    #活动核销码
    public function getCode()
    {
        $where['write_code'] = Dever::rand(6, 0);
        $state = Dever::db('active/code')->one($where);
        if (!$state) {
            return $where['write_code'];
        } else {
            return $this->getCode();
        }
    }

    #生成订单号
    public function getOrderId()
    {
        $where['order_num'] = Dever::order('D');
        $where['clear'] = true;
        $state = Dever::db('active/order')->one($where);
        if (!$state) {
            return $where['order_num'];
        } else {
            return $this->getOrderId();
        }
    }
	
}