<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Created by 娄凯.
 * Description:
 * Date: 2018\7\31 0031
 */

class lucky_model extends MY_Model {
    public $houses = array(); //用户房源
    public $origin_rowids   = array(); //激活房源的房源id
    public $origin_telnos   = array();  //激活房源的房源电话
    public $no_record_rowids = array();
    public $no_record_telnos = array();
//    public $verified_rowids = array(); //通过权属认证的房源
//    public $verified_telno  = array(); //通过权属认证的房源对应的电话号码
//    public $white_telno     = array(); //过滤过，不在黑名单的并且经过权属认证的号码
//    public $white_rowids    = array(); //过滤过，号码不在黑名单的并且经过权属认证的房源
    public $start_time;
    public $end_time;
    public $used_all;   //代表抽奖机会已经用完
    public $qualifiedtelno;//在运营添加的能够抽奖的名单里面

    public function __construct()
    {
        parent::__construct();
        $this->start_time = strtotime(date('2018-08-09'));
        $this->end_time   = strtotime(date('2018-10-07'));
    }

    public function getLuckyRecords(){
        $sql = "select telno,prize_name from lucky_draw_record where status in (1,2) order by id desc limit 10";
        $data = $this->db_esfhousebak->query($sql)->result_array();
        foreach($data as &$each){
            $each['telno'] = substr($each['telno'],0,3)."****".substr($each['telno'],7,4);
        }
        return $data;
    }

    public function getLuckyRecordByUid($uid){
        $sql = "select telno,prize_name,status from lucky_draw_record where uid =".$uid;
        $data = $this->db_esfhousebak->query($sql)->result_array();
        return $data;
    }

    /**
     * 获取我的中奖记录
     * @param $uid
     * @return mixed
     */
    public function parseRecord($uid){
        $res = array('status'=>0,'prize_name'=>'');
        $win = 0;  //中过奖
        $not_win = 0;  //没中过奖
        $prize_name = '';
        $records = $this->getLuckyRecordByUid($uid);
        if(empty($records)){
            return $res;
        }else{
            foreach($records as $record){
                if(in_array($record['status'],array(1,2,3))){
                    $win = 1;
                    $prize_name = $record['prize_name'];
                }
                if($record['status'] == 4){
                    $not_win = 1;
                }
            }
        }
        //有中奖记录
        if($win == 1){
            $res['status'] = 1;
            $res['prize_name'] = $prize_name;
        }
        elseif($not_win == 1){   //抽过奖，但是没中
            $res['status'] = 4;
        }
        return $res;
    }

    /**
     * 只检查中奖结果
     * @param $uid
     * @return array
     */
    public function checkIfWonBefore($uid){
        $res = array();
        $sql = "select telno,prize_name,status from lucky_draw_record where uid =".$uid." and status in (1,2,3)";
        $data = $this->db_esfhousebak->query($sql)->result_array();
        if(!empty($data)){
             $res['prize_name'] = $data[0]['prize_name'];
        }
        return $res;
    }

    /**
     * 插入没有中奖的记录
     * @param $uid
     * @return bool
     */
    public function InsertNoRecord($uid){
        if(!$uid){
            return false;
        }
        $data = $this->prepareData();
        $winning_time = 0;
        $status = 4; //没抽到
        $prize_name = '';

        $sql_insert = "insert into lucky_draw_record (`rowid`,`uid`,`telno`,`winning_time`,`prize_name`,`status`) value ('{$data['rowid']}',$uid,'{$data['telno']}',$winning_time,"."'{$prize_name}'".",$status)";
        $res = $this->db_esfhouse->query($sql_insert);
        if(!$res){
            return false;
        }
        return true;
    }

    /**
     * 写数据库前获取数据
     * @return array
     */
    protected function prepareData(){
        $data = array();
        $rowids = $this->no_record_rowids;
        $telnos = $this->no_record_telnos;
        $data['rowid'] = $rowids[0];
        $data['telno'] = $telnos[0];
        return $data;
    }
    /**
     * 插入中奖结果
     * @return bool
     */
    public function InsertYesRecord($uid,$prize_name){
        if(!$uid || !$prize_name){
            return false;
        }
        $data = $this->prepareData();
        $winning_time = time();
        $status = 2;
        $begin_date = date('Y-m-d');

        //扣除商品剩余数量
        $sql_update = "update lucky_draw_prize set left_num = left_num-1 where begin_date = "."'{$begin_date}'"." and name = "."'{$prize_name}'";

        $sql_insert = "insert into lucky_draw_record (`rowid`,`uid`,`telno`,`winning_time`,`prize_name`,`status`) value ('{$data['rowid']}',$uid,'{$data['telno']}',$winning_time,"."'{$prize_name}'".",$status)";

        $this->db_esfhouse->trans_start();
        $this->db_esfhouse->query($sql_update);
        $this->db_esfhouse->query($sql_insert);
        $this->db_esfhouse->trans_complete();
        if ($this->db_esfhouse->trans_status() === FALSE)
        {
            return false;
            // generate an error... or use the log_message() function to log your error
        }
        //插入中奖记录

        return true;
    }

    /**
     * 是否抽奖次数已经用完
     * @return mixed
     */
    public function getUsedAll(){
        return $this->used_all;
    }
    /**
     * 有没有抽奖资格：
     * 1. 活动期间 （写死的）
     * 2. 南京的 (理解：如果在权属核验表的，一定是南京的)
     * 3. 激活房源
     * 4. 通过系统核验的
     * 5. 电话不在黑名单的
     * 6. 个人出租房源，非中介
     * 7. 一个号码只能抽奖一次
     * @param $uid
     * @return bool
     */
    public function checkIfQualified($uid){
        //是否活动期间
        if(!$this->checkIfWithinActivity()){
            return false;
        }
        //是否有个人激活房源
        if(!$this->checkValidHouses($uid)){
            return false;
        }

        //号码是否在允许抽奖的号码名单
        if(!$this->checkQualifiedTelno()){
            return false;
        }

        //在名单的号码是否抽过奖了
        if(!$this->checkIfUsedAll($uid)){
            $this->used_all = 1;
            return false;
        }
        //需求变更，下面的不用去验证了。运营会指定哪些号码能够参与抽奖
//        //是否通过权属认证
//        if(!$this->checkPublicVerification()){
//            return false;
//        }
//        //是否在黑名单
//        if(!$this->checkIfBlacklistTel()){
//            return false;
//        }

        return true;
    }

    /**
     * 用户房源的电话号码在不在允许抽奖的号码名单里面
     * @return bool
     *
     */
    protected function checkQualifiedTelno(){
        $this->parseHouses();
        $telnos = implode(',',$this->origin_telnos);
        $sql = "select telno from lucky_draw_qualified_list where telno in (".$telnos.")";
        $data = $this->db_esfhousebak->query($sql)->result_array();

        if(empty($data)){
            return false;
        }
        $qualifiedtelno = array();
        foreach($data as $item){
            $qualifiedtelno[] = $item['telno'];
        }
        $this->qualifiedtelno = $qualifiedtelno;
        return true;
    }
    /**
     * 检测号码是否都已经抽过奖了,并过滤出没有抽过奖的号码和房源
     * @return bool
     */
    protected function checkIfUsedAll($uid){
        $telnos = implode(',',$this->qualifiedtelno);

        $sql = "select telno from lucky_draw_record where telno in (".$telnos.")"." and uid =".$uid;
        $data = $this->db_esfhousebak->query($sql)->result_array();
        $no_record_telno = $this->qualifiedtelno;

        if(!empty($data)){
            if(count($data) == count($this->qualifiedtelno)){
                return false; //代表所有的号码都抽过奖了
            }else{
                foreach($data as $item){
                    if(in_array($item['telno'],$this->qualifiedtelno)){
                        $index = array_search($item['telno'],$this->qualifiedtelno);
                        unset($no_record_telno[$index]);
                    }
                }
            }
        }

       $this->no_record_telnos = $no_record_telno;

       if($no_record_telno == $telnos){
            $this->no_record_rowids = $this->origin_rowids;
            return true;
       }else{
           $no_record_rowids = array();
           foreach($this->houses as $house){
               if(in_array($house['telno'],$this->no_record_telnos)){
                   $no_record_rowids[] = $house['id'];
               }
           }
           $this->no_record_rowids = $no_record_rowids;
       }

        return true;
    }

    /**
     * 从用户名下的激活房源中获取房源id和房源电话
     */
    protected function parseHouses(){
        $houses = $this->houses;
        $origin_telnos = array();
        $origin_rowids = array();
        foreach($houses as $house){
            $origin_rowids[] = $house['id'];
            $origin_telnos[] = $house['telno'];
        }
        $this->origin_rowids = $origin_rowids;
        $this->origin_telnos = $origin_telnos;
    }
    protected function getVerfiedTel(){
        $telnos = array();
        foreach($this->houses as $house){
            if(in_array($house['id'],$this->verified_rowids)){
                $telnos[] = $house['telno'];
            }
        }

        return $telnos;
    }

    /**
     * 已经过权属认证的房源，获取不在黑名单的号码
     * @return bool
     */
    protected function checkIfBlacklistTel(){
        $white_telno = $this->verified_telno;

        $telnos_str = implode(',',$this->verified_telno);
        $sql = "select telno from agencytel where telno in (".$telnos_str.")";
        $data = $this->db_esfhousebak->query($sql)->result_array();

        if(!empty($data)){
            foreach($data as $item){
                if(in_array($item['telno'],$this->verified_telno)){
                    $index = array_search($item['telno'],$this->verified_telno);
                    unset($white_telno[$index]);
                }
            }
        }
        $this->white_telno = $white_telno;
        if(empty($this->white_telno)){
            return false;
        }else{
            //获取最终的房源id
            $white_rowids = array();
            foreach($this->houses as $house){
                if(in_array($house['telno'],$this->white_telno)){
                    $white_rowids[] = $house['id'];
                }
            }
            $this->white_rowids = $white_rowids;
            return true;
        }
    }
    /**
     * 是否有激活房源
     * @param $uid
     * @return bool
     */
    public function checkValidHouses($uid){
        $this->houses = $this->getHousesByUid($uid);
        if(empty($this->houses)){
            return false;
        }
        return true;
    }

    /**
     * 是否在活动期间通过权属认证，并获取通过权属认证的房子
     * @return bool
     */
    protected function checkPublicVerification(){
        $rowids = implode(',',$this->no_record_rowids);
        if(empty($rowids)){
            return false;
        }

        $sql = "select house_id from owner_rent where owner_real = 1 and house_id in (".$rowids.") and update_time between ".$this->start_time." and ".$this->end_time;
        $data = $this->db_esfhousebak->query($sql)->result_array();
        if(empty($data)){
            return false;
        }
        $verified_rowids = array();
        foreach($data as $item){
            $verified_rowids[] = $item['house_id'];
        }
        $this->verified_rowids = $verified_rowids;
        $this->verified_telno = $this->getVerfiedTel();
        return true;
    }

    /**
     * 获取个人的激活房源,排除二房东
     * @param $uid
     * @return mixed
     */
    public function getHousesByUid($uid){
        $sql = "select id,telno from rent where esta = 1 and infofrom = 1 and uid=".$uid;
        $data = $this->db_esfhousebak->query($sql)->result_array();
        return $data;
    }
    /**
     * 判断是否在活动期间
     * @return bool
     */
    public function checkIfWithinActivity(){
        $start_time = strtotime('2018-08-09');
        $end_time   = strtotime('2018-10-07');
        $now = time();
        if($now >= $start_time && $now <=$end_time){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 判断是否第偶数个抽奖人
     * @return bool
     */
    public function checkIfEven(){
        $total = $this->getCountRecords();
        $num = $total+1;
        if($num%2==0){
            return true;
        }else{
            return false;
        }
    }
    /**
     * 获取总记录，也即参与抽奖总人数
     * @return mixed
     */
    public function getCountRecords(){
        $sql = "select count(*) as total from lucky_draw_record";
        $data = $this->db_esfhousebak->query($sql)->result_array();
        return $data[0]['total'];
    }

    /**
     * 奖品池是否还有奖品
     * @return bool
     */
    public function checkIfLeftPrizePool(){
        $date = date('Y-m-d');
        $sql = "select sum(left_num) as total from lucky_draw_prize where begin_date ="."'{$date}'";
        $data = $this->db_esfhousebak->query($sql)->result_array();
        if(!empty($data)){
            $num = $data[0]['total'];
            if($num>0){
                return true;
            }else{
                return false;
            }
        }
        return false;
    }

    public function getPoolPrize(){
        $default = array(
            '1'=>'小米手环',
            '2'=>'感谢参与',
            '3'=>'飞利浦剃须刀',
            '4'=>'九阳榨汁机',
            '5'=>'电热水壶',
            '6'=>'精美马克杯'
        );
        $default1 = array_flip($default);

        $data = $this->getExistsPrize();
        if(empty($data)){
            return false;
        }
        $prize = array();
        $ids   = array();
        //组装奖池
        foreach($data as $each){
            if(in_array($each['name'],$default)){
                $ids[] = $default1[$each['name']];
            }
        }

        //概率抽奖
        $rand_num = $this->get_rand($ids);

        //返回奖品和奖品id
        $prize['prize_id'] = $ids[$rand_num];
        $prize['prize_name'] = $default[$ids[$rand_num]];
        return $prize;
    }

    /**
     * 获取奖池今日剩余奖品
     * @return mixed
     */
    protected function getExistsPrize(){
        $date = date('Y-m-d');
        $sql = "select name from lucky_draw_prize where begin_date ="."'{$date}'"." and left_num >0";
        $data = $this->db_esfhousebak->query($sql)->result_array();
        return $data;
    }

    /**
     * 概率抽数字
     * @param $proArr
     * @return int|string
     */
    protected function get_rand($proArr) {
        $result = '';
        //概率数组的总概率精度
        $proSum = array_sum($proArr);
        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);
        return $result;
    }

}