<?php
namespace Store;
/**
 * User: liuyuzhen
 * Date: 2018/10/18
 * Time: 17:34
 * Description:
 */

class StoreUtil {

    public function checkAddressInServiceAreaByStore($address,$store){
        $storeDao = \DAO\StoreModel::getInstance();
        //$store = $storeDao->get($storeId,false);
        $storeId = $store['store_id'];
        $inAreaFlag = false ;
        $qmStoreClassDao = \DAO\QmStoreClassModel::getInstance();
        $qmClassCon['store_id'] = $storeId;
        $qmSignScopeList = \Our\RedisHelper::cachedFunction(\Redis\Db6\QmStoreClassRedisModel::getInstance(),array(&$qmStoreClassDao, 'getStoreSignClasses'),array($qmClassCon,'sign_scope'),\Our\ApiConst::oneHour,array('store'.$storeId));
        if($qmSignScopeList){
            foreach($qmSignScopeList as $qmSignScope){
                if($qmSignScope['sign_scope']){
                    $inAreaFlag = \Our\CommonExtension::locationInArea($address['lat'],$address['lng'],$qmSignScope['sign_scope']);
                    if($inAreaFlag){
                        return true;
                    }
                }
            }
        }
        if(!$store['store_sales_scope']){
            return false;
        }
        $inAreaFlag = \Our\CommonExtension::locationInArea($address['lat'],$address['lng'],$store['store_sales_scope']);
        return $inAreaFlag;
    }


    public function checkAddressInServiceArea($address,$storeId){
        $storeDao = \DAO\StoreModel::getInstance();
        $store = $storeDao->get($storeId,false);
        $inAreaFlag = false ;
        $qmStoreClassDao = \DAO\QmStoreClassModel::getInstance();
        $qmClassCon['store_id'] = $storeId;
        $qmSignScopeList = \Our\RedisHelper::cachedFunction(\Redis\Db6\QmStoreClassRedisModel::getInstance(),array(&$qmStoreClassDao, 'getStoreSignClasses'),array($qmClassCon,'sign_scope'),\Our\ApiConst::oneHour,array('store'.$storeId));
        if($qmSignScopeList){
            foreach($qmSignScopeList as $qmSignScope){
                if($qmSignScope['sign_scope']){
                    $inAreaFlag = \Our\CommonExtension::locationInArea($address['lat'],$address['lng'],$qmSignScope['sign_scope']);
                    if($inAreaFlag){
                        return true;
                    }
                }
            }
        }
        if(!$store['store_sales_scope']){
            return false;
        }
        $inAreaFlag = \Our\CommonExtension::locationInArea($address['lat'],$address['lng'],$store['store_sales_scope']);
        return $inAreaFlag;
    }

    /**
     * 经纬度是否在店铺地址范围内
     * @param $lat
     * @param $lng
     * @param $storeId
     * @return bool
     */
    public function checkLocationInServiceArea($lat,$lng,$storeId){
        return self::checkAddressInServiceArea(array('lat'=>$lat,'lng'=>$lng),$storeId);
    }


    /**
     * 计算分类对应
     * @param $class
     * @param $storeEndTime
     * @param int $month
     * @return array|bool
     */
    public function getFreeChargeMoney($class,$storeEndTime,$month=1){
        if($month<=0){
            return false;
        }
        $currentTime = mktime(23,59,59,date('m'),date('d'),date('Y'));
        $tempOldTime  = max(array($storeEndTime,$class['deadline']));
        $oldTime = mktime(23,59,59,date('m',$tempOldTime),date('d',$tempOldTime),date('Y',$tempOldTime));
        $currExpTime = $oldTime;
        if($currentTime>$oldTime){
            $currExpTime = $currentTime;
        }
        $currentMonthEnd =  mktime(0,0,0,(date('m',$currExpTime)+1),1,date('Y',$currExpTime))-1;
        $endTime = mktime(0,0,0,(date('m',$currExpTime)+1+$month),1,date('Y',$currExpTime))-1;
        if($currentMonthEnd>$currExpTime){
            $endTime = $currentMonthEnd;
            if($month>1){
                $endTime = mktime(0,0,0,(date('m',$currExpTime)+$month),1,date('Y',$currExpTime))-1;
            }
        }
        return array('service_fee'=>0,'old_end_time'=>$tempOldTime,'new_start_time'=>$currExpTime+1,'new_end_time'=>$endTime,'curr_month_fee'=>0,'pre_month_fee'=>0);
    }


    /**
     * 生成随机数
     * @param $len 随机数
     */
    private function createncode($len=10) {
        $strs = '0123456789';
        $strlen = strlen($strs)-1;
        $rt = '';
        for($i=0;$i<$len;$i++) {
            $rt.= $strs[rand(0,$strlen)];
        }
        return $rt;
    }

    /**
     * 计算试用期即将到期的店铺续费
     * @param $param array(11=>array('month'=>1,'store_end_time'=>1548950399,'contract_time'=>'1577807999'))
     * @return bool
     */
    public function calcChargeMoney($param){
        $storeIds = array_keys($param);
        $dbName = \Our\DbNameConst::masterDBConnectName;
        $qmStoreClassModel = \DAO\QmStoreClassModel::getInstance($dbName);
        $qmStoreClassModel->setDb($dbName);
        $list = $qmStoreClassModel->selectByWhere(array('store_id'=>array('in',$storeIds),'class_style'=>2,'is_charged'=>1));//当前店铺正在经营的二级签约分类
        //,'qm_store_class.deadline'=>array('lt',$store['contract_time'])
        $currentTime = TIMESTAMP;

        $qmStoreClassModel->db->doTransaction();
        $addKey=\Our\Common::getConfig('password.key');
        $payLogList = array();
        $newChargeList = array();
        foreach($list as $class){
            $paySn = date('YmdHis').$this->createncode(18);
            $storeId = $class['store_id'];
            $payLog = array();
            $payLog['store_id'] = $storeId;
            $payLog['pay_state'] = 1;
            $payLog['pay_sn'] = $paySn;
            $payLog['gmt_create'] = $currentTime;
            $payLog['gmt_update'] = $currentTime;
            $payLog['pay_time'] = $currentTime;
            $payLog['pay_type'] = 3;
            $payContent  = array();
            $chargeLog = array();
            $feeArr = $this->getFreeChargeMoney($class,$param[$storeId]['store_end_time'],$param[$storeId]['month']);
            if($feeArr['new_end_time']>$param[$storeId]['contract_time']){
                \Our\Log::getInstance()->write(json_encode($class).'分类超过有效期','/data/log/feeMonth');
                continue;
            }
            $chargeLog['gc_id'] = $class['gc_id'];
            $chargeLog['store_id'] = $storeId;
            $chargeLog['pay_sn'] = $paySn;
            $chargeLog = array_merge($feeArr,$chargeLog);
            $payContent[] = $chargeLog;
            $payLog['pay_content'] = serialize($payContent);
            $payLog['pay_amount'] = 0;
            $chargeLog['gmt_create'] = $currentTime;
            $chargeLog['gmt_update'] = $currentTime;
            $chargeLog['service_fee_sign'] = md5($currentTime,$chargeLog['service_fee'],$addKey);
            $newChargeList[] = $chargeLog;
            $resultClass = $qmStoreClassModel->update(array('deadline'=>$chargeLog['new_end_time'],'deadline_sign'=>md5($class['gmt_create'],$chargeLog['new_end_time'],$addKey),'gmt_update'=>$currentTime),array('gc_id'=>$chargeLog['gc_id'],'store_id'=>$chargeLog['store_id']));
            if($resultClass===false){
                $qmStoreClassModel->db->doRollback();
            }
            $payLogList[] = $payLog;
        }
        $resultPayLog = \DAO\Store\StoreClassPayLogModel::getInstance($dbName)->insertBatch($payLogList);
        if(!$resultPayLog){
            $qmStoreClassModel->db->doRollback();
        }
        $resultChargeLog = \DAO\GoodsClass\StoreClassChargeLogModel::getInstance($dbName)->insertBatch($newChargeList);
        if(!$resultChargeLog){
            $qmStoreClassModel->db->doRollback();
        }
        $qmStoreClassModel->db->doCommit();
        return true ;
    }

    /**
     * 类实例
     *
     */
    private static $_instance = null;

    /**
     * 单例模式获取类实例
     *
     */
    public static function getInstance()
    {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }
}