<?php

namespace common\models\forms;

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

/**
 * 注册信息表单
 */
class RegInfoAuditForm extends Model {
    public $id;
    public $userId;
    public $userName;
    public $realName;
    public $idCard;
    public $type;
    public $regName;
    public $creditCode;
    public $premises;
    public $legalPerson;
    public $regExpires;
    public $createRemark;
    public $auditRemark;
    public $auditStatus;
    public $companyBank;
    public $openName;
    public $openBank;
    public $bankAddress;
    public $bankNo;
    public $bankAreaSelected;

    private $_uid;
    private $_model;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['id', 'userId', 'userName', 'realName', 'idCard', 'type', 'regName', 'creditCode', 'premises', 'legalPerson', 'regExpires', 'createRemark', 'auditRemark', 'auditStatus', 'companyBank', 'openName', 'openBank', 'bankAddress', 'bankNo', 'bankAreaSelected'], 'trim'],
            [['id', 'userName', 'realName', 'idCard', 'type', 'regName', 'creditCode', 'auditStatus'], 'required'],
            [['userName'], 'isUserName'],
            [['id'], 'initModel'],
            [['auditStatus'], 'isAuditStatus'],
            [['type'], 'isType'],
        ];
    }

    /**
     * 指定校验场景
     * @return array
     */
    public function scenarios() {
        $parentScenarios = parent::scenarios();
        $customScenarios = [
            'add' => ['userName', 'realName', 'idCard', 'type', 'regName', 'creditCode', 'premises', 'legalPerson', 'regExpires', 'createRemark', 'companyBank'],
            'excelAdd' => ['userName', 'realName', 'idCard', 'type', 'regName', 'creditCode', 'premises', 'legalPerson', 'regExpires', 'createRemark', 'openName', 'openBank', 'bankAddress', 'bankNo', 'bankAreaSelected'],
            'editRegInfo' => ['userId', 'type', 'regName', 'creditCode', 'premises', 'legalPerson', 'regExpires', 'createRemark', 'companyBank'],
            'edit' => ['id', 'type', 'regName', 'creditCode', 'premises', 'legalPerson', 'regExpires', 'createRemark', 'companyBank'],
            'audit' => ['id', 'type', 'regName', 'creditCode', 'premises', 'legalPerson', 'regExpires', 'createRemark', 'auditStatus', 'companyBank'],
        ];
        return array_merge($parentScenarios, $customScenarios);
    }

    public function attributeLabels() {
        return [
            'userId' => '会员ID',
            'userName' => '会员编号',
            'realName' => '会员姓名',
            'idCard' => '身份证号',
            'type' => '注册类型',
            'regName' => '注册名称',
            'creditCode' => '统一社会信用代码',
            'premises' => '经营场所',
            'legalPerson' => '经营者/法人',
            'regExpires' => '注册有效期',
            'createRemark' => '创建备注',
            'auditRemark' => '审核备注',
            'auditStatus' => '审核状态',
        ];
    }

    /**
     * 初始化model
     * @param $attributes
     */
    public function initModel($attributes) {
        $this->_model = RegInfoAudit::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 (RegInfoAudit::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 isType($attributes) {
        $type = RegType::findOneAsArray('ID=:ID', [':ID' => $this->type], 'ID');
        if ($type) {
            //暂写死
            if ($type['ID'] == '758BF69C25C3422AA7743936BC77EE64') {
                if($this->scenario=='excelAdd'){
                    if ($this->openName == '' || $this->openBank == '' || $this->bankAddress == '' || $this->bankNo == '' || $this->bankAreaSelected == []) {
                        $this->addError($attributes, '请完善公司银行信息');
                    }
                }else {
                    if ($this->companyBank['openBank'] == '' || $this->companyBank['bankAreaSelected'] == [] || $this->companyBank['bankAddress'] == '' || $this->companyBank['openName'] == '' || $this->companyBank['bankNo'] == '') {
                        $this->addError($attributes, '请完善公司银行信息');
                    }
                }
            }
        } 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 {
            $period = Period::instance();
            // 添加会员注册信息
            $model = new RegInfoAudit();
            $model->USER_ID = $this->_uid;
            $model->REG_TYPE = $this->type;
            $model->REG_NAME = $this->regName;
            $model->CREDIT_CODE = $this->creditCode;
            $model->PREMISES = $this->premises;
            $model->LEGAL_PERSON = $this->legalPerson;
            $model->REG_EXPIRES = $this->regExpires ? Date::utcToTime($this->regExpires) : 0;
            $model->AUDIT_STATUS = \Yii::$app->params['auditStatus']['un']['value'];
            $model->CREATE_ADMIN = \Yii::$app->user->id;
            $model->CREATE_REMARK = $this->createRemark;
            $model->CREATE_PERIOD = $period->getNowPeriodNum();
            $model->CREATED_AT = Date::nowTime();
            if (!$model->save()) {
                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
            }
            //暂写死
            if ($this->type == '758BF69C25C3422AA7743936BC77EE64') {
                if (!CompanyBank::find()->where('USER_ID=:USER_ID', [':USER_ID' => $this->_uid])->exists()) {
                    $companyBank = new CompanyBank();
                    $companyBank->USER_ID = $this->_uid;
                    $companyBank->CREATE_ADMIN = \Yii::$app->user->id;
                    $companyBank->CREATED_AT = Date::nowTime();
                } else {
                    $companyBank = CompanyBank::findOne(['USER_ID' => $this->_uid]);
                    $companyBank->UPDATE_ADMIN = \Yii::$app->user->id;
                    $companyBank->UPDATED_AT = Date::nowTime();
                }
                $companyBank->OPEN_NAME = $this->companyBank['openName'];
                $companyBank->OPEN_BANK = $this->companyBank['openBank'];
                $companyBank->BANK_ADDRESS = $this->companyBank['bankAddress'];
                $companyBank->BANK_NO = $this->companyBank['bankNo'];
                $companyBank->BANK_PROVINCE = $this->companyBank['bankAreaSelected'][0] ?? '0';
                $companyBank->BANK_CITY = $this->companyBank['bankAreaSelected'][1] ?? '0';
                $companyBank->BANK_COUNTY = $this->companyBank['bankAreaSelected'][2] ?? '0';
                $companyBank->REMARK = $this->createRemark;
                if (!$companyBank->save()) {
                    throw new Exception(Form::formatErrorsForApi($companyBank->getErrors()));
                }
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('add', $e->getMessage());
            return null;
        }
        return $model;
    }

    /**
     * 批量导入注册信息
     * @return RegInfoAudit|null
     * @throws \yii\db\Exception
     */
    public function excelAdd() {
        if (!$this->validate()) {
            return null;
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $period = Period::instance();
            // 添加会员注册信息
            $model = new RegInfoAudit();
            $model->USER_ID = $this->_uid;
            $model->REG_TYPE = $this->type;
            $model->REG_NAME = $this->regName;
            $model->CREDIT_CODE = $this->creditCode;
            $model->PREMISES = $this->premises;
            $model->LEGAL_PERSON = $this->legalPerson;
            $model->REG_EXPIRES = $this->regExpires ? Date::utcToTime($this->regExpires) : 0;
            $model->AUDIT_STATUS = \Yii::$app->params['auditStatus']['un']['value'];
            $model->CREATE_ADMIN = \Yii::$app->user->id;
            $model->CREATE_REMARK = $this->createRemark;
            $model->CREATE_PERIOD = $period->getNowPeriodNum();
            $model->CREATED_AT = Date::nowTime();
            if (!$model->save()) {
                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
            }
            //暂写死
            if ($this->type == '758BF69C25C3422AA7743936BC77EE64') {
                if (!CompanyBank::find()->where('USER_ID=:USER_ID', [':USER_ID' => $this->_uid])->exists()) {
                    $companyBank = new CompanyBank();
                    $companyBank->USER_ID = $this->_uid;
                    $companyBank->CREATE_ADMIN = \Yii::$app->user->id;
                    $companyBank->CREATED_AT = Date::nowTime();
                } else {
                    $companyBank = CompanyBank::findOne(['USER_ID' => $this->_uid]);
                    $companyBank->UPDATE_ADMIN = \Yii::$app->user->id;
                    $companyBank->UPDATED_AT = Date::nowTime();
                }
                $companyBank->OPEN_NAME = $this->openName;
                $companyBank->OPEN_BANK = $this->openBank;
                $companyBank->BANK_ADDRESS = $this->bankAddress;
                $companyBank->BANK_NO = $this->bankNo;
                $companyBank->BANK_PROVINCE = $this->bankAreaSelected[0] ?? '0';
                $companyBank->BANK_CITY = $this->bankAreaSelected[1] ?? '0';
                $companyBank->BANK_COUNTY = $this->bankAreaSelected[2] ?? '0';
                $companyBank->REMARK = $this->createRemark;
                if (!$companyBank->save()) {
                    throw new Exception(Form::formatErrorsForApi($companyBank->getErrors()));
                }
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('excelAdd', $e->getMessage());
            return null;
        }
        return $model;
    }

    /**
     * 注册信息管理中提交修改注册信息
     * @return RegInfoAudit|null
     * @throws \yii\db\Exception
     */
    public function editRegInfo() {
        if (!$this->validate()) {
            return null;
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $period = Period::instance();
            // 添加会员注册信息
            $model = new RegInfoAudit();
            $model->USER_ID = $this->userId;
            $model->REG_TYPE = $this->type;
            $model->REG_NAME = $this->regName;
            $model->CREDIT_CODE = $this->creditCode;
            $model->PREMISES = $this->premises;
            $model->LEGAL_PERSON = $this->legalPerson;
            $model->REG_EXPIRES = $this->regExpires ? Date::utcToTime($this->regExpires) : 0;
            $model->AUDIT_STATUS = \Yii::$app->params['auditStatus']['un']['value'];
            $model->CREATE_ADMIN = \Yii::$app->user->id;
            $model->CREATE_REMARK = $this->createRemark;
            $model->CREATE_PERIOD = $period->getNowPeriodNum();
            $model->CREATED_AT = Date::nowTime();
            if (!$model->save()) {
                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
            }
            //暂写死
            if ($this->type == '758BF69C25C3422AA7743936BC77EE64') {
                if (!CompanyBank::find()->where('USER_ID=:USER_ID', [':USER_ID' => $this->userId])->exists()) {
                    $companyBank = new CompanyBank();
                    $companyBank->USER_ID = $this->userId;
                    $companyBank->CREATE_ADMIN = \Yii::$app->user->id;
                    $companyBank->CREATED_AT = Date::nowTime();
                } else {
                    $companyBank = CompanyBank::findOne(['USER_ID' => $this->userId]);
                    $companyBank->UPDATE_ADMIN = \Yii::$app->user->id;
                    $companyBank->UPDATED_AT = Date::nowTime();
                }
                $companyBank->OPEN_NAME = $this->companyBank['openName'];
                $companyBank->OPEN_BANK = $this->companyBank['openBank'];
                $companyBank->BANK_ADDRESS = $this->companyBank['bankAddress'];
                $companyBank->BANK_NO = $this->companyBank['bankNo'];
                $companyBank->BANK_PROVINCE = $this->companyBank['bankAreaSelected'][0] ?? '0';
                $companyBank->BANK_CITY = $this->companyBank['bankAreaSelected'][1] ?? '0';
                $companyBank->BANK_COUNTY = $this->companyBank['bankAreaSelected'][2] ?? '0';
                $companyBank->REMARK = $this->createRemark;
                if (!$companyBank->save()) {
                    throw new Exception(Form::formatErrorsForApi($companyBank->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->REG_TYPE = $this->type;
            $model->REG_NAME = $this->regName;
            $model->CREDIT_CODE = $this->creditCode;
            $model->PREMISES = $this->premises;
            $model->LEGAL_PERSON = $this->legalPerson;
            $model->REG_EXPIRES = $this->regExpires ? Date::utcToTime($this->regExpires) : 0;
            if (!$model->save()) {
                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
            }
            //暂写死
            if ($this->type == '758BF69C25C3422AA7743936BC77EE64') {
                if (!CompanyBank::find()->where('USER_ID=:USER_ID', [':USER_ID' => $model->USER_ID])->exists()) {
                    $companyBank = new CompanyBank();
                    $companyBank->USER_ID = $model->USER_ID;
                    $companyBank->CREATE_ADMIN = \Yii::$app->user->id;
                    $companyBank->CREATED_AT = Date::nowTime();
                } else {
                    $companyBank = CompanyBank::findOne(['USER_ID' => $model->USER_ID]);
                    $companyBank->UPDATE_ADMIN = \Yii::$app->user->id;
                    $companyBank->UPDATED_AT = Date::nowTime();
                }
                $companyBank->OPEN_NAME = $this->companyBank['openName'];
                $companyBank->OPEN_BANK = $this->companyBank['openBank'];
                $companyBank->BANK_ADDRESS = $this->companyBank['bankAddress'];
                $companyBank->BANK_NO = $this->companyBank['bankNo'];
                $companyBank->BANK_PROVINCE = $this->companyBank['bankAreaSelected'][0] ?? '0';
                $companyBank->BANK_CITY = $this->companyBank['bankAreaSelected'][1] ?? '0';
                $companyBank->BANK_COUNTY = $this->companyBank['bankAreaSelected'][2] ?? '0';
                $companyBank->REMARK = $this->createRemark;
                if (!$companyBank->save()) {
                    throw new Exception(Form::formatErrorsForApi($companyBank->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 {
            $period = Period::instance();
            $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->REG_TYPE = $this->type;
                $model->REG_NAME = $this->regName;
                $model->CREDIT_CODE = $this->creditCode;
                $model->PREMISES = $this->premises;
                $model->LEGAL_PERSON = $this->legalPerson;
                $model->REG_EXPIRES = $this->regExpires ? Date::utcToTime($this->regExpires) : 0;
            }
            $model->AUDIT_ADMIN = \Yii::$app->user->id;
            $model->CREATE_REMARK = $this->createRemark;
            $model->AUDIT_PERIOD = $period->getNowPeriodNum();
            $model->AUDITED_AT = Date::nowTime();
            if (!$model->save()) {
                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
            }
            //暂写死
            if ($this->type == '758BF69C25C3422AA7743936BC77EE64') {
                if (!CompanyBank::find()->where('USER_ID=:USER_ID', [':USER_ID' => $model->USER_ID])->exists()) {
                    $companyBank = new CompanyBank();
                    $companyBank->USER_ID = $model->USER_ID;
                    $companyBank->CREATE_ADMIN = \Yii::$app->user->id;
                    $companyBank->CREATED_AT = Date::nowTime();
                    $companyBank->UPDATED_AT = Date::nowTime();
                } else {
                    $companyBank = CompanyBank::findOne(['USER_ID' => $model->USER_ID]);
                    $companyBank->UPDATE_ADMIN = \Yii::$app->user->id;
                    $companyBank->UPDATED_AT = Date::nowTime();
                }
                $companyBank->OPEN_NAME = $this->companyBank['openName'];
                $companyBank->OPEN_BANK = $this->companyBank['openBank'];
                $companyBank->BANK_ADDRESS = $this->companyBank['bankAddress'];
                $companyBank->BANK_NO = $this->companyBank['bankNo'];
                $companyBank->BANK_PROVINCE = $this->companyBank['bankAreaSelected'][0] ?? '0';
                $companyBank->BANK_CITY = $this->companyBank['bankAreaSelected'][1] ?? '0';
                $companyBank->BANK_COUNTY = $this->companyBank['bankAreaSelected'][2] ?? '0';
                $companyBank->REMARK = $this->createRemark;
                if (!$companyBank->save()) {
                    throw new Exception(Form::formatErrorsForApi($companyBank->getErrors()));
                }
            }
            //写入会员信息
            if ($this->auditStatus == 'true') {
                $baseInfo = Info::baseInfoZh($model->USER_ID);
                //更改了注册类型
                if ($baseInfo['REG_TYPE'] != $model->REG_TYPE) {
                    UserInfo::updateAll(['REG_TYPE' => $model->REG_TYPE, 'SHOULD_REG_TYPE' => $model->REG_TYPE, 'REG_NAME' => $model->REG_NAME, 'CREDIT_CODE' => $model->CREDIT_CODE, 'PREMISES' => $model->PREMISES, 'LEGAL_PERSON' => $model->LEGAL_PERSON, 'REG_EXPIRES' => $model->REG_EXPIRES], 'USER_ID=:USER_ID', [':USER_ID' => $model->USER_ID]);
                } else {
                    UserInfo::updateAll(['REG_NAME' => $model->REG_NAME, 'REG_TYPE' => $model->REG_TYPE, 'CREDIT_CODE' => $model->CREDIT_CODE, 'PREMISES' => $model->PREMISES, 'LEGAL_PERSON' => $model->LEGAL_PERSON, 'REG_EXPIRES' => $model->REG_EXPIRES], 'USER_ID=:USER_ID', [':USER_ID' => $model->USER_ID]);
                }
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('audit', $e->getMessage());
            return null;
        }
        return $model;
    }

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