<?php

namespace common\models\forms;

use common\components\Model;
use common\helpers\Cache;
use common\helpers\Date;
use common\helpers\user\Info;
use common\models\HistoryBonus;
use common\models\UserBonus;
use common\models\Withdraw;

/**
 * 历史奖金余额表单
 */
class HistoryBonusForm extends Model {
    private $_query;
    private $_totalCount;
    private $_limit = 100;
    private $_backupCompleted = false;
    /**
     * 自动备份
     * @return bool
     * @throws \yii\base\InvalidConfigException
     */
    public function taskAutoBackup(){
        //HistoryWalletHelper::setAutoBackupRunning();
        $this->handleQuery();
        try{
            foreach($this->_query->batch($this->_limit) as $list){
                if($list){
                    $insert = [];
                    foreach($list as $value){
                        if(!$info = Info::baseInfoWithNet($value['USER_ID'])) continue;
                        $insert[] = [
                            'USER_ID' => $value['USER_ID'],
                            'USER_NAME' => $info['USER_NAME'],
                            'REAL_NAME' => $info['REAL_NAME'],
                            'DEC_LV' => $info['DEC_LV'],
                            'EMP_LV' => $info['EMP_LV'],
                            'IS_DEC' => $info['IS_DEC'],
                            'DEC_ROLE_ID' => $info['DEC_ROLE_ID'],
                            'SYSTEM_NAME' => $info['SYSTEM_NAME'],
                            'BONUS' => $value['BONUS'],
                            'CF' => $value['CF'],
                            'LX' => $value['LX'],
                            'WITHDRAW' => Withdraw::getWithdrawTotal($value['USER_ID'], Withdraw::STATUS_WAIT_PAID),
                            'WITHDRAW_TAX' => 0.00,//todo 待提现开发
                            'WITHDRAW_DEDUCT' => 0.00,//todo 待提现开发
                            'WITHDRAW_REAL' => 0.00,//todo 待提现开发
                            'WITHDRAW_FAIL' => Withdraw::getWithdrawTotal($value['USER_ID'], Withdraw::STATUS_PAID_FALSE),
                            'USER_STATUS' => $info['STATUS'],
                            'USER_STATUS_AT' => $info['STATUS_AT'],
                            'HIGHEST_EMP_LV' => $info['HIGHEST_EMP_LV'],
                            'PERIOD_AT' => $info['PERIOD_AT'],
                            'DEC_DEC_ROLE_ID' => $info['DEC_DEC_ROLE_ID'],
                            'DEC_USER_NAME' => $info['DEC_USER_NAME'],
                            'DEC_REAL_NAME' => $info['DEC_REAL_NAME'],
                            'MOBILE' => $info['MOBILE'],
                            'TEL' => $info['TEL'],
                            'PROVINCE' => $info['PROVINCE'],
                            'CITY' => $info['CITY'],
                            'COUNTY' => $info['COUNTY'],
                            'SUB_COM_ID' => $info['SUB_COM_ID'],
                            'IS_DIRECT_SELLER' => $info['IS_DIRECT_SELLER'],
                            'BACKUP_AT' => Date::nowTime(),
                            'PARTITION_DATE' => Date::ociToDate(),
                        ];
                    }
                    if($insert){
                        HistoryBonus::batchInsert($insert);
                    }
                }
            }
            $this->backupCompleted();
        }catch (\PDOException $e) {
            $error = $e->getMessage();
            // 说明数据读取完成了
            if (strpos($error, 'fetch out of sequence') !== false) {
                $this->backupCompleted();
            } else {
                //todo log
                //Logger::error($this->getThrowMessage($e), 'historyBonus');
            }
        }catch(\Exception $e){
            print_r($e->getMessage());
            //todo log
            //Logger::error($this->getThrowMessage($e), 'historyBonus');
        }

        // 开始删除
        if($this->_backupCompleted){
            try{
                $this->_deleteHistoryByLimit();
                return true;
            }catch(\Exception $e){
                //todo log
                //Logger::error('[deleteHistoryByLimit]' . $this->getThrowMessage($e), 'historyBonus');
                return false;
            }
        }
        return true;
    }

    /**
     * 完成
     */
    public function backupCompleted(){
        // todo log
        //Logger::error('备份完成[success]于 ' . date('Y-m-d H:i:s', Date::nowTime()), 'historyBonus');
        $this->_backupCompleted = true;
    }

    /**
     *
     */
    public function handleQuery(){
        UserBonus::prepare();
        $this->_query = UserBonus::$query;
        $countQuery = clone $this->_query;
        $this->_totalCount = $this->_query->count();
        unset($countQuery);
    }



    /**
     * 删除
     */
    private function _deleteHistoryByLimit(){
        $config = Cache::getSystemConfig();
        $historyBonusLimit = (int)$config['historyBonusLimit']['VALUE'];
        if($historyBonusLimit > 0){
            // 604800 = 7 * 86400
            $limit = 604800 * $historyBonusLimit;
            // 多少周以前
            $timestamp = Date::nowTime() - $limit;
            // todo logger
            //Logger::error('开始删除于 ' . date('Y-m-d H:i:s', Date::nowTime()), 'historyBonus');
            HistoryBonus::deleteAll("BACKUP_AT<=:BACKUP_AT", ['BACKUP_AT' => $timestamp]);
            // todo logger
            //Logger::error('删除结束于 ' . date('Y-m-d H:i:s', Date::nowTime()), 'historyBonus');
        }
    }
}
