<?php

namespace common\models\forms;

use common\helpers\Date;
use common\helpers\user\Balance;
use common\helpers\user\Info;
use common\helpers\user\Status;
use common\components\Model;
use common\helpers\Form;
use common\models\InvoiceAudit;
use common\models\InvoiceBalanceAudit;
use common\models\Period;
use common\models\RegInfoAudit;
use common\models\User;
use common\models\UserInfo;
use yii\base\Exception;

/**
 * 点位绑定表单
 */
class InvoiceBalanceAuditForm extends Model {
    public $id;
    public $userName;
    public $realName;
    public $idCard;
    public $regType;
    public $amount;
    public $createRemark;
    public $auditRemark;
    public $auditStatus;

    private $_uid;
    private $_model;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['id', 'userName', 'realName', 'idCard', 'regType', 'amount', 'createRemark', 'auditRemark', 'auditStatus'], 'trim'],
            [['id', 'userName', 'realName', 'idCard', 'regType', 'amount', 'auditStatus'], 'required'],
            [['userName'], 'isUserName'],
            [['id'], 'initModel'],
            [['auditStatus'], 'isAuditStatus'],
        ];
    }

    /**
     * 指定校验场景
     * @return array
     */
    public function scenarios() {
        $parentScenarios = parent::scenarios();
        $customScenarios = [
            'add' => ['userName', 'realName', 'idCard', 'regType', 'amount', 'createRemark'],
            'edit' => ['id', 'amount', 'createRemark'],
            'audit' => ['id', 'amount', 'auditRemark', 'auditStatus'],
        ];
        return array_merge($parentScenarios, $customScenarios);
    }

    public function attributeLabels() {
        return [
            'userName' => '会员编号',
            'realName' => '会员姓名',
            'idCard' => '身份证号',
            'regType' => '注册类型',
            'amount' => '交易金额',
            'createRemark' => '创建备注',
            'auditRemark' => '审核备注',
            'auditStatus' => '审核状态',
        ];
    }

    /**
     * 初始化model
     * @param $attributes
     */
    public function initModel($attributes) {
        $this->_model = InvoiceBalanceAudit::findOne(['ID' => $this->id]);
        if (!$this->_model) {
            $this->addError($attributes, '数据不存在');
        }
        if ($this->_model->AUDIT_STATUS != \Yii::$app->params['auditStatus']['un']['value']) {
            $this->addError($attributes, '本数据已经被处理过了');
        }
    }

    /**
     * 用户名是否正确
     * @param $attributes
     */
    public function isUserName($attributes) {
        $userInfo = UserInfo::findOneAsArray(['USER_NAME' => $this->userName]);
        if ($userInfo) {
            $baseInfo = Info::baseInfoZh($userInfo['USER_ID']);
            if ($baseInfo['REAL_NAME'] != $this->realName || $baseInfo['ID_CARD'] != $this->idCard) {
                $this->addError($attributes, '输入的会员姓名或身份证号与系统不一致');
            }
            if ($userInfo['REG_TYPE'] != $this->regType) {
                $this->addError($attributes, '选择的会员注册类型与系统不一致');
            }
            if (InvoiceBalanceAudit::find()->where('USER_ID=:USER_ID AND AUDIT_STATUS=0', [':USER_ID' => $userInfo['USER_ID']])->exists()) {
                $this->addError($attributes, '填写的会员有待审核的发票调整');
            }
            $this->_uid = $userInfo['USER_ID'];
        } else {
            $this->addError($attributes, '会员不存在');
        }
    }

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

    /**
     * 添加
     * @return RegInfoAudit|null
     * @throws \yii\db\Exception
     */
    public function add() {
        if (!$this->validate()) {
            return null;
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            // 添加会员合作点位
            $model = new InvoiceBalanceAudit();
            $model->USER_ID = $this->_uid;
            $model->AMOUNT = $this->amount;
            $model->AUDIT_STATUS = \Yii::$app->params['auditStatus']['un']['value'];
            $model->CREATE_ADMIN = \Yii::$app->user->id;
            $model->CREATE_REMARK = $this->createRemark;
            $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 null
     * @throws \yii\db\Exception
     */
    public function edit() {
        if (!$this->validate()) {
            return null;
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $model = $this->_model;
            $model->AMOUNT = $this->amount;
            $model->CREATE_REMARK = $this->createRemark;
            if (!$model->save()) {
                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('edit', $e->getMessage());
            return null;
        }
        return $model;
    }

    /**
     * 审核操作
     * @return null
     * @throws \yii\db\Exception
     */
    public function audit() {
        if (!$this->validate()) {
            return null;
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $model = $this->_model;
            if ($this->auditStatus == 'reject') {
                $model->AUDIT_STATUS = \Yii::$app->params['auditStatus']['reject']['value'];
            } elseif ($this->auditStatus == 'true') {
                $model->AUDIT_STATUS = \Yii::$app->params['auditStatus']['true']['value'];
                $model->AMOUNT = $this->amount;
            }
            $model->AUDIT_ADMIN = \Yii::$app->user->id;
            $model->AUDIT_REMARK = $this->auditRemark;
            $model->AUDITED_AT = Date::nowTime();
            if (!$model->save()) {
                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
            }
            //更新会员税款信息
            if ($this->auditStatus == 'true') {
                Balance::changeInvoice($model->USER_ID, $model->AMOUNT, [
                    'REMARK' => '审核发票调整',
                    'CREATE_ADMIN' => $model->CREATE_ADMIN,
                    'CREATE_REMARK' => $model->CREATE_REMARK,
                    'CREATE_TIME' => $model->CREATED_AT,
                    'AUDIT_ADMIN' => $model->AUDIT_ADMIN,
                    'AUDIT_REMARK' => $model->AUDIT_REMARK,
                    'AUDIT_TIME' => $model->AUDITED_AT,
                ]);
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('audit', $e->getMessage());
            return null;
        }
        return $model;
    }

    /**
     * 删除
     * @param $selected
     */
    public static function delete($selected) {
    }
}
