<?php

namespace common\models\forms;

use common\helpers\Date;
use common\components\Model;
use common\helpers\Form;
use common\helpers\Tool;
use common\helpers\user\Balance;
use common\helpers\user\Reconsume;
use common\helpers\user\Info;
use common\helpers\user\Status;
use common\libs\logging\operate\AdminOperate;
use common\models\Ad;
use common\models\CalcBonus;
use common\models\DealType;
use common\models\PerfMonth;
use common\models\Period;
use common\models\ReconsumePool;
use common\models\ReconsumePoolFlow;
use common\models\ResendQY;
use common\models\ResendQYAudit;
use common\models\UserBonus;
use common\models\UserInfo;
use common\models\UserTeamwork;
use yii\base\Exception;

/**
 * Login form
 */
class ResendQYForm extends Model {
    public $id;
    public $selectedIds;
    public $userName;
    public $periodNum;
    public $remark;
    public $auditStatus;

    private $_model;
    private $_userId;
    private $_calcBonus;

    public function init() {
        parent::init();
        $this->adminOperateLogger = new AdminOperate([
            'fetchClass' => ResendQY::class,
        ]);
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['id', 'userName', 'periodNum', 'remark', 'auditStatus', 'selectedIds'], 'trim'],
            [['id', 'userName', 'periodNum', 'auditStatus'], 'required'],
            ['id', 'initModel'],
            ['userName', 'isUser'],
            ['periodNum', 'isCanResend'],
            ['auditStatus', 'isAuditStatus'],
            [['selectedIds'], 'isSelected'],
        ];
    }

    public function attributeLabels() {
        return [
            'userName' => '用户名',
            'periodNum' => '期数',
            'remark' => '备注',
            'auditStatus' => '审核状态',
        ];
    }

    /**
     * 指定校验场景
     * @return array
     */
    public function scenarios() {
        $parentScenarios = parent::scenarios();
        $customScenarios = [
            'apply' => ['selectedIds', 'remark'],
            'audit' => ['selectedIds', 'remark', 'auditStatus'],
        ];
        return array_merge($parentScenarios, $customScenarios);
    }

    /**
     * 检查记录是否存在并初始化model
     * @param $attribute
     * @throws \yii\db\Exception
     */
    public function initModel($attribute) {
        $model = ResendQY::findOne(['ID' => $this->id]);
        if ($model) {
            $this->_model = $model;
            $period = Period::instance();
            $yearMonth = $period->getYearMonth($model->PERIOD_NUM);
            if (!$this->_calcBonus = CalcBonus::find()->yearMonth($yearMonth)->where('USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM AND BONUS_QY<=0 AND SHOULD_QY>0 AND IS_SENT=1', [':USER_ID' => $model->USER_ID, ':PERIOD_NUM' => $model->PERIOD_NUM])->one()) {
                $this->addError($attribute, '该会员暂无可补发区域津贴');
            }
        } else {
            $this->addError($attribute, '该数据不存在');
        }

    }

    /**
     * 会员是否存在
     * @param $attribute
     */
    public function isUser($attribute) {
        if (!$this->_userId = Info::getUserIdByUserName($this->userName)) {
            $this->addError($attribute, '会员不存在');
        }
    }

    /**
     * 是否能补发
     * @param $attribute
     * @throws \yii\db\Exception
     */
    public function isCanResend($attribute) {
        $period = Period::instance();
        $yearMonth = $period->getYearMonth($this->periodNum);
        // 查看会员对应的期数奖金结算表中是否有应发金额>0和实发金额=0
        $this->_calcBonus = CalcBonus::find()->yearMonth($yearMonth)->where('USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM AND BONUS_QY<=0 AND SHOULD_QY>0 AND IS_SENT=1', [':USER_ID' => $this->_userId, ':PERIOD_NUM' => $this->periodNum])->asArray()->one();
        if (!$this->_calcBonus) {
            $this->addError($attribute, '该会员暂无可补发区域津贴');
        }
        // 如果有的话，再看看有没有补发记录，如果有补发记录则也不能补发
        if (ResendQY::find()->where('USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM AND (AUDIT_STATUS=:AUDIT_STATUS_UN OR AUDIT_STATUS=:AUDIT_STATUS_TRUE)', [':USER_ID' => $this->_userId, ':PERIOD_NUM' => $this->periodNum,':AUDIT_STATUS_UN'=>\Yii::$app->params['auditStatus']['un']['value'], ':AUDIT_STATUS_TRUE'=>\Yii::$app->params['auditStatus']['true']['value']])->exists()) {
            $this->addError($attribute, '该会员已经补发或申请补发指定期数的区域津贴');
        }
    }

    /**
     * 校验审核状态
     * @param $attributes
     */
    public function isAuditStatus($attributes) {
        if (!array_key_exists($this->auditStatus, \Yii::$app->params['auditStatus'])) {
            $this->addError($attributes, '无效的审核状态');
        }
    }

    /**
     * 批量数据
     * @param $attributes
     */
    public function isSelected($attributes) {
        if (!$this->selectedIds) {
            $this->addError($attributes, '必须选择一条数据');
        }
        if (!is_array($this->selectedIds)) {
            $this->selectedIds = [$this->selectedIds];
        }
        if($this->scenario == 'apply') {
            $this->selectedIds = array_unique($this->selectedIds);
            //根据会员状态及审核状态筛选
            foreach ($this->selectedIds as $key => $value) {
                //有了复销活跃资格才能补发
                if($resendQY = ResendQY::findOneAsArray('ID=:ID',[':ID'=>$value],'USER_ID,CALC_MONTH')){
                    if(!ReconsumePoolFlow::find()->yearMonth($resendQY['CALC_MONTH'])->select('USER_ID')->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH AND IS_FX_DEDUCT=1', [':USER_ID' => $resendQY['USER_ID'], ':CALC_MONTH' => $resendQY['CALC_MONTH']])->exists()){
                        unset($this->selectedIds[$key]);
                    }
                }else{
                    unset($this->selectedIds[$key]);
                }
                //去掉已存在的待审核申请
                if (ResendQYAudit::find()->where('RESEND_ID=:RESEND_ID AND AUDIT_STATUS =:AUDIT_STATUS', [':RESEND_ID' => $value, ':AUDIT_STATUS' => \Yii::$app->params['auditStatus']['un']['value']])->exists()) {
                    unset($this->selectedIds[$key]);
                }
                //实发为0，应发大于0
                if (!ResendQY::find()->where('ID=:ID AND BONUS_QY=0 AND SHOULD_QY>0', [':ID' => $value])->exists()) {
                    unset($this->selectedIds[$key]);
                }
            }
            $this->selectedIds = array_values($this->selectedIds);
        }
    }


    /**
     * 添加
     * @return array|null
     * @throws \yii\db\Exception
     */
    public function apply() {
        if (!$this->validate()) {
            return null;
        }
        $logs = [];
        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            if ($this->selectedIds) {
                foreach ($this->selectedIds as $select) {
                    $resend = ResendQY::findOneAsArray('ID=:ID', [':ID' => $select], 'USER_ID,SHOULD_QY,PERIOD_NUM');
                    //是否已挂网
                    $period = Period::instance();
                    //if (!$period->isSent($resend['PERIOD_NUM'])) continue;
                    //会员本月是否复销
                    //if (!Status::fxGetBonusStatusByPeriodNum($resend['USER_ID'], $resend['PERIOD_NUM'])) continue;
                    $resendAudit = new ResendQYAudit();
                    $resendAudit->USER_ID = $resend['USER_ID'];
                    $resendAudit->RESEND_ID = $select;
                    $resendAudit->SHOULD_BONUS = $resend['SHOULD_QY'];
                    $resendAudit->RESEND_BONUS = 0;
                    $resendAudit->PERIOD_NUM = $resend['PERIOD_NUM'];
                    $resendAudit->AUDIT_STATUS = \Yii::$app->params['auditStatus']['un']['value'];
                    $resendAudit->RESEND_ADMIN_ID = \Yii::$app->user->id;
                    $resendAudit->RESEND_REMARK = $this->remark;
                    $resendAudit->CREATED_AT = Date::nowTime();
                    if (!$resendAudit->save()) {
                        throw new Exception(Form::formatErrorsForApi($resendAudit->getErrors()));
                    }
                    if (!ResendQY::updateAll(['RESEND_AUDIT_ID' => $resendAudit->ID, 'RESEND_AUDIT_STATUS' => \Yii::$app->params['auditStatus']['un']['value'], 'RESEND_STATUS' => ResendQY::STATUS_HAS], 'ID=:ID', [':ID' => $select])) {
                        throw new Exception('更新申请状态失败');
                    }
                    $logs[] = $resend['USER_ID'];
                }
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('apply', $e->getMessage());
            return null;
        }
        if ($this->selectedIds) {
            $this->adminOperateLogger->setIsBatch(true)->afterUpdate($this->selectedIds, 'ID')->setOptObjField('USER_ID')->clean()->save([
                'optType' => '申请补发区域津贴',
                'remark' => $this->remark,
            ]);
        }
        return ['logs' => $logs];
    }

    /**
     * 审核补发区域津贴
     * @return null
     * @throws \yii\db\Exception
     */
    public function audit() {
        if (!$this->validate()) {
            return null;
        }
        $logs = [];
        $ids = [];
        foreach ($this->selectedIds as $key => $select) {
            $resendId = ResendQYAudit::findOneAsArray('ID=:ID', [':ID' => $select], 'RESEND_ID');
            $ids[] = $resendId['RESEND_ID'];
        }
        if($ids) {
            $this->adminOperateLogger->setIsBatch(true)->beforeUpdate($ids, 'ID');
        }
        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            foreach ($this->selectedIds as $key=>$select) {
                $model=ResendQYAudit::findOne(['ID'=>$select]);
                $model->AUDIT_STATUS = \Yii::$app->params['auditStatus'][$this->auditStatus]['value'];
                $model->RESEND_REMARK = $this->remark?$this->remark:$model->RESEND_REMARK;
                $model->AUDIT_ADMIN_ID = \Yii::$app->user->id;
                $model->AUDITED_AT = Date::nowTime();
                if ($this->auditStatus == 'true') {
                    Balance::changeUserBonus($model->USER_ID, 'bonus', $model->SHOULD_BONUS, [
                        'REMARK' => '补发' . $model->PERIOD_NUM . '期薪资',
                        'PERIOD_NUM' => $model->PERIOD_NUM,
                        'QY' => $model->SHOULD_BONUS,
                        'DEAL_TYPE_ID' => DealType::RESEND,
                        'SORT' => $key * 10
                    ]);
                    //更新计算奖金
                    $period = Period::instance();
                    $yearMonth = $period->getYearMonth($model->PERIOD_NUM);
                    if($calcBonusModel = CalcBonus::find()->where('USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM AND BONUS_QY<=0 AND SHOULD_QY>0 AND IS_SENT=1', [':USER_ID' => $model->USER_ID, ':PERIOD_NUM' => $model->PERIOD_NUM])->yearMonth($yearMonth)->one()){
                        $calcBonusModel->BONUS_QY = $model->SHOULD_BONUS;
                        $calcBonusModel->BONUS_TOTAL = $calcBonusModel->BONUS_TOTAL + $model->SHOULD_BONUS;
                        $calcBonusModel->BONUS_INCOME = $calcBonusModel->BONUS_INCOME + $model->SHOULD_BONUS;
                        $calcBonusModel->P_CALC_MONTH = Date::ociToDate($yearMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
                        if (!$calcBonusModel->save()) {
                            throw new Exception(Form::formatErrorsForApi($calcBonusModel->getErrors()));
                        }
                    }
                    //更新对应补发列表状态
                    if (!ResendQY::updateAll(['BONUS_QY'=>$model->SHOULD_BONUS,'RESEND_AUDIT_STATUS' => \Yii::$app->params['auditStatus'][$this->auditStatus]['value']], 'ID=:ID', [':ID' => $model->RESEND_ID])) {
                        throw new Exception('更新申请审核状态失败');
                    }

                    $this->_teamworkBonus($model->USER_ID,$model->SHOULD_BONUS,$key);

                }elseif($this->auditStatus == 'reject'){
                    //更新对应补发列表状态
                    if (!ResendQY::updateAll(['RESEND_AUDIT_STATUS' => \Yii::$app->params['auditStatus'][$this->auditStatus]['value'], 'RESEND_STATUS' => ResendQY::STATUS_WAIT], 'ID=:ID', [':ID' => $model->RESEND_ID])) {
                        throw new Exception('更新申请状态失败');
                    }
                }
                if (!$model->save()) {
                    throw new Exception(Form::formatErrorsForApi($model->getErrors()));
                }

                $logs[] = $model->USER_ID;
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('audit', $e->getMessage());
            return null;
        }
        if($ids) {
            $this->adminOperateLogger->setIsBatch(true)->afterUpdate($ids, 'ID')->setOptObjField('USER_ID')->clean()->save([
                'optType' => '审核补发区域津贴',
                'remark' => $this->remark,
            ]);
        }
        return ['logs' => $logs];
    }

    /**
     * 删除前
     * @param $selected
     * @throws Exception
     */
    public function beforeDelete($selected) {
        //恢复
        foreach ($selected as $value){
            if($resendAudit = ResendQYAudit::findOneAsArray('ID=:ID',[':ID'=>$value],'RESEND_ID')){
                if (!ResendQY::updateAll(['RESEND_AUDIT_ID' => null,'RESEND_AUDIT_STATUS' => null, 'RESEND_STATUS' => ResendQY::STATUS_WAIT], 'ID=:ID', [':ID' => $resendAudit['RESEND_ID']])) {
                    throw new Exception('更新申请状态失败');
                }
            }
        }
        $this->adminOperateLogger->fetchClass = ResendQYAudit::class;
        $this->adminOperateLogger->setIsBatch(true)->beforeDelete($selected, 'ID');
    }

    /**
     * 删除
     * @param $selected
     * @throws Exception
     */
    public function delete($selected) {
        $this->adminOperateLogger->clean()->save([
            'optType' => '删除补发区域津贴待审核数据',
        ]);
    }

    /**
     * 点位合作发放
     * @param $userId
     * @param $amount
     * @return bool
     * @throws Exception
     * @throws \yii\db\Exception
     */
    private function _teamworkBonus($userId, $amount, $key) {
        if (!$teamwork = UserTeamwork::findAllAsArray('USER_ID!=:MAIN_UID AND MAIN_UID=:MAIN_UID AND IS_DEL=0', [':MAIN_UID' => $userId], 'USER_ID,DIVIDE_PERCENT')) return false;
        $fromUserName = Info::getUserNameByUserId($userId);
        foreach ($teamwork as $value) {
            $bonus = Tool::formatPrice($amount * $value['DIVIDE_PERCENT'] * 0.01);
            if ($bonus <= 0) continue;
            $toUserName = Info::getUserNameByUserId($value['USER_ID']);
            Balance::changeUserBonus($userId, 'bonus', -abs($bonus), ['SORT' => $key*10+1, 'DEAL_TYPE_ID' => DealType::TEAMWORK_TRANSFER_OUT, 'REMARK' => 'To:' . $toUserName . ' Per:' . $value['DIVIDE_PERCENT'] . '%']);
            Balance::changeUserBonus($value['USER_ID'], 'bonus', abs($bonus), ['SORT' => $key*10+2, 'DEAL_TYPE_ID' => DealType::TEAMWORK_TRANSFER_IN, 'REMARK' => 'From: ' . $fromUserName . ' Per:' . $value['DIVIDE_PERCENT'] . '%']);
        }
    }
}
