<?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\Info;
use common\libs\logging\operate\AdminOperate;
use common\models\CFLXAudit;
use common\models\DealType;
use common\models\UserBonus;
use common\models\UserTeamwork;
use yii\base\Exception;

/**
 * Login form
 *
 * @private CFLXAudit $_model
 */
class SendCFAndLXForm extends Model {
    public $id;
    //public $year;
    public $selectedIds;
    public $statusValue;
    public $sendType;
    public $remark;
    public $auditStatus;

    private $_model;

    const SEND_TYPES = ['all' => '车房养老奖和领袖分红奖', 'cf' => '车房养老奖', 'lx' => '领袖分红奖'];

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

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['id', 'remark', 'auditStatus', 'selectedIds', 'sendType', 'statusValue'], 'trim'],
            [['id', 'auditStatus', 'remark', 'sendType', 'statusValue'], 'required'],
            [['sendType'], 'isType'],
            [['statusValue'], 'isStatusValue'],
            [['selectedIds'], 'isSelected'],
            [['auditStatus'], 'isAuditStatus'],
        ];
    }

    public function attributeLabels() {
        return [
            'id' => '审核表ID',
            'sendType' => '发放类型',
            'statusValue' => '包含会员状态',
            //'year' => '发放年度',
            'remark' => '备注',
        ];
    }

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

    /**
     * 年份是否正确
     * @param $attribute
     */
    public function isYear($attribute) {
        if (CFLXAudit::find()->where('YEAR=:YEAR AND AUDIT_STATUS=:AUDIT_STATUS', [':YEAR' => $this->year, ':AUDIT_STATUS' => \Yii::$app->params['auditStatus']['true']['value']])->exists()) {
            $this->addError($attribute, '本年度已经发放');
        }
    }

    /**
     * 发放类型
     * @param $attribute
     */
    public function isType($attribute) {
        if (!in_array($this->sendType, array_keys(self::SEND_TYPES))) {
            $this->addError($attribute, '请选择正确的发放类型');
        }
    }

    /**
     * 状态类型校验
     * @param $attribute
     */
    public function isStatusValue($attribute) {
        foreach ($this->statusValue as $status) {
            if (!array_key_exists($status, \Yii::$app->params['userStatus'])) {
                $this->addError($attribute, '请选择正确的会员状态');
                break;
            }
        }
    }

    /**
     * 校验审核状态
     * @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, 'A piece of data must be selected'); // 必须选择一条数据
        }
        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 ($status = Info::getStatusByUserId($value)) {
                    if (!in_array($status, $this->statusValue)) {
                        unset($this->selectedIds[$key]);
                    }
                }
                if (CFLXAudit::find()->where('USER_ID=:USER_ID AND AUDIT_STATUS =:AUDIT_STATUS', [':USER_ID' => $value, ':AUDIT_STATUS' => \Yii::$app->params['auditStatus']['un']['value']])->exists()) {
                    unset($this->selectedIds[$key]);
                }
            }
            $this->selectedIds = array_values($this->selectedIds);
        }
    }

    /**
     * 申请
     * @return CFLXAudit|null
     * @throws \yii\db\Exception
     */
    public function add() {
        if (!$this->validate()) {
            return null;
        }
        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            $model = $this->_model;
            $model->YEAR = Date::nowYear();
            $model->AUDIT_STATUS = \Yii::$app->params['auditStatus']['un']['value'];
            $model->CREATE_ADMIN = \Yii::$app->user->id;
            $model->CREATE_REMARK = $this->remark;
            $model->CREATED_AT = Date::nowTime();
            if (!$model->save()) {
                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('add', $e->getMessage());
            return null;
        }
        return $model;
    }

    /**
     * 批量发放车房领袖
     * @return array|null
     * @throws \yii\db\Exception
     */
    public function apply() {
        if (!$this->validate()) {
            return null;
        }
        $logs = [];
        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            foreach ($this->selectedIds as $select) {
                $model = new CFLXAudit();
                if ($this->sendType == 'lx') {
                    if (!$oneData = UserBonus::findOneAsArray('LX>0 AND USER_ID=:USER_ID', [':USER_ID' => $select])) continue;
                    $model->LX = $oneData['LX'];
                } elseif ($this->sendType == 'cf') {
                    if (!$oneData = UserBonus::findOneAsArray('CF>0 AND USER_ID=:USER_ID', [':USER_ID' => $select])) continue;
                    $model->CF = $oneData['CF'];
                } else {
                    if (!$oneData = UserBonus::findOneAsArray('(CF>0 OR LX>0) AND USER_ID=:USER_ID', [':USER_ID' => $select])) continue;
                    $model->LX = $oneData['LX'];
                    $model->CF = $oneData['CF'];
                }
                $model->USER_ID = $select;
                $model->YEAR = Date::nowYear();
                $model->AUDIT_STATUS = \Yii::$app->params['auditStatus']['un']['value'];
                $model->CREATE_ADMIN = \Yii::$app->user->id;
                $model->CREATE_REMARK = $this->remark;
                $model->CREATED_AT = Date::nowTime();
                if (!$model->save()) {
                    throw new Exception(Form::formatErrorsForApi($model->getErrors()));
                }
                /*if($model->LX>0){
                    Balance::changeUserBonus($select, 'lx', -$model->LX, ['REMARK' => '年度领袖分红奖申请']);
                }
                if($model->CF>0){
                    Balance::changeUserBonus($select, 'cf', -$model->CF, ['REMARK' => '年度车房养老奖申请']);
                }*/
                $logs[] = $model->ID;
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('apply', $e->getMessage());
            return null;
        }
        $this->adminOperateLogger->fetchClass = CFLXAudit::class;
        $this->adminOperateLogger->setIsBatch(true)->afterUpdate($logs, 'ID');
        $this->adminOperateLogger->clean()->save([
            'optType' => '年度奖申请发放',
            'remark' => $this->remark,
        ]);
        return ['logs' => $logs, 'typeName' => self::SEND_TYPES[$this->sendType]];
    }

    /**
     * 审核
     * @return array|null
     * @throws \yii\db\Exception
     */
    public function audit() {
        if (!$this->validate()) {
            return null;
        }
        $logs = [];
        $uids=[];
        if($this->auditStatus=='true'){
            foreach ($this->selectedIds as $select) {
                $oneBalanceAudit = CFLXAudit::findOneAsArray('AUDIT_STATUS=0 AND ID=:ID',[':ID'=>$select],'USER_ID');
                $uids[]=$oneBalanceAudit['USER_ID'];
            }
        }
        if($this->auditStatus=='true'){
            $this->adminOperateLogger->fetchClass = UserBonus::class;
            $this->adminOperateLogger->setIsBatch(true)->beforeUpdate($uids, 'USER_ID');
        }else{
            $this->adminOperateLogger->fetchClass = CFLXAudit::class;
            $this->adminOperateLogger->setIsBatch(true)->beforeUpdate($this->selectedIds, 'ID');
        }

        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            foreach ($this->selectedIds as $key => $select) {
                $model=CFLXAudit::findOne(['ID'=>$select]);
                $model->AUDIT_STATUS = \Yii::$app->params['auditStatus'][$this->auditStatus]['value'];
                $model->CREATE_REMARK = $this->remark?$this->remark:$model->CREATE_REMARK;
                $model->AUDIT_ADMIN = \Yii::$app->user->id;
                $model->AUDITED_AT = Date::nowTime();
                if ($this->auditStatus == 'true') {
                    if ($model->CF > 0) {
                        Balance::changeUserBonus($model->USER_ID, 'cf', -$model->CF, ['REMARK' => '车房养老转出至会员账户', 'DEAL_TYPE_ID' => DealType::CF_TRANSFER_OUT]);
                        Balance::changeUserBonus($model->USER_ID, 'bonus', $model->CF, ['SORT' => $key *10, 'REMARK' => '车房养老转入至会员账户', 'DEAL_TYPE_ID' => DealType::CF_TRANSFER_IN]);
                        $this->_teamworkBonus($model->USER_ID, $model->CF, 'cf', $key);
                    }
                    if ($model->LX > 0) {
                        Balance::changeUserBonus($model->USER_ID, 'lx', -$model->LX, ['REMARK' => '领袖分红转出至会员账户', 'DEAL_TYPE_ID' => DealType::LX_TRANSFER_OUT]);
                        Balance::changeUserBonus($model->USER_ID, 'bonus', $model->LX, ['SORT' => $key *10 + 5, 'REMARK' => '领袖分红转入至会员账户', 'DEAL_TYPE_ID' => DealType::LX_TRANSFER_IN]);
                        $this->_teamworkBonus($model->USER_ID, $model->LX, 'lx', $key);
                    }
                }
                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($this->auditStatus=='true'){
            $this->adminOperateLogger->fetchClass = UserBonus::class;
            $this->adminOperateLogger->setIsBatch(true)->afterUpdate($uids, 'USER_ID')->clean()->save([
                'optType' => '审核年度奖申请',
                'remark' => $this->remark,
            ]);
        }else{
            $this->adminOperateLogger->fetchClass = CFLXAudit::class;
            $this->adminOperateLogger->setIsBatch(true)->afterUpdate($this->selectedIds, 'ID')->clean()->save([
                'optType' => '审核年度奖申请',
                'remark' => $this->remark,
            ]);
        }

        return ['logs' => $logs];
    }

    /**
     * 点位合作时转账
     * @param $userId
     * @param $amount
     * @param null $type
     * @return bool
     * @throws Exception
     * @throws \yii\db\Exception
     */
    private function _teamworkBonus($userId, $amount, $type = null, $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']);
            if ($type == 'cf') {
                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+1, 'DEAL_TYPE_ID' => DealType::TEAMWORK_TRANSFER_IN, 'REMARK' => 'From:' . $fromUserName . ' Per' . $value['DIVIDE_PERCENT'] . '%']);
            } elseif ($type == 'lx') {
                Balance::changeUserBonus($userId, 'bonus', -abs($bonus), ['SORT' => $key*10+2, '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'] . '%']);
            }
        }
    }

    /**
     * 删除前
     * @param $selected
     */
    public function beforeDelete($selected) {
        $this->adminOperateLogger->fetchClass = CFLXAudit::class;
        $this->adminOperateLogger->setIsBatch(true)->beforeDelete($selected, 'ID');
    }
    /**
     * 删除
     * @param $selected
     * @throws Exception
     */
    public function delete($selected) {
        $this->adminOperateLogger->clean()->save([
            'optType' => '删除年度奖申请',
        ]);
    }

}
