<?php
namespace common\models\forms;

use common\components\Model;
use common\helpers\Cache;
use common\helpers\Date;
use common\helpers\Form;
use common\helpers\user\Cash;
use common\helpers\user\Reconsume;
use common\helpers\user\Info;
use common\models\DeclarationPackage;
use common\models\DecOrder;
use common\models\EmployLevel;
use common\models\Order;
use common\models\OrderGoods;
use common\models\Period;
use common\models\ReceiveAddress;
use common\models\ReconsumePool;
use common\models\ReconsumePoolFlow;
use common\models\DeclarationLevel;
use common\models\Region;
use common\models\ShopGoods;
use common\models\User;
use common\models\UserInfo;
use common\models\UserNetwork;
use common\models\UserRelation;
use yii\base\Exception;

/**
 * Login form
 */
class DeclarationForm extends Model
{
    public $type;
    public $decLv;
    public $decWay;
    public $packageId;
    public $goodsId;
    public $goodsNum;
    public $insertUserName;
    public $password;
    public $payPassword;
    public $realName;
    public $insertUserIdCard;
    public $mobile;
    public $email;
    public $address;
    public $openBank;
    public $bankAddress;
    public $bankNo;
    public $bankProvince;
    public $bankCity;
    public $bankCounty;
    public $conUserName;
    public $recUserName;
    public $decUserName;
    public $location;
    public $consignee;
    public $acceptMobile;
    public $province;
    public $city;
    public $county;
    public $cityName;
    public $lgaName;

    // 传过来的全部数据
    public $allData;
    private $_decId;
    public $_insertUserId;
    private $_decAmount;
    private $_decPv;
    private $_orderGoods;

    // 批量报单时添加会员的REDIS里面缓存的添加的会员资料
    const REDIS_WAIT_ADD_USER = 'user:dec:waitAdd';

    const TYPE_ZC = 'ZC';
//    const TYPE_YH = 'YH';
    const TYPE_ZG = 'ZG';
    const TYPE_LS = 'LS';
    const TYPE_FX = 'FX';

//    private $_modelClass = null;
    private $_oneOrder = null;
    private $_userForm = null;
    // 全部的上级（安置网和开拓网）
    private $_tempParentUser = [];
    // 全部的安置网上级
    private $_tempNetworkParentUser = [];
    // 全部的开拓网上级
    private $_tempRelationParentUser = [];
    private $_types = [
        self::TYPE_ZC => [
            'name' => '首购单',
        ],
//        self::TYPE_YH => [
//            'class' => DeclarationYH::class,
//            'table' => '{{%DECLARATION_YH}}',
//            'name' => '优惠单',
//        ],
        self::TYPE_ZG => [
            'name' => '升级增购单',
        ],
        self::TYPE_LS => [
            'name' => '零售单',
        ],
        self::TYPE_FX => [
            'name' => '复销单',
        ],
    ];


    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['type','decLv','decWay','packageId', 'insertUserName', 'realName',/* 'insertUserIdCard',*/ 'mobile', 'address', 'openBank', 'bankAddress', 'bankNo','bankProvince','bankCity','bankCounty','consignee','acceptMobile','province','city','county','cityName','lgaName','decUserName', 'conUserName', 'recUserName', 'location'], 'trim'],
            [['type','decLv','decWay','insertUserName',/* 'insertUserIdCard',*/'password','payPassword','decUserName'], 'required'],
            [['type'], 'isType', 'on'=>['userDec', 'canDec']],
            [['insertUserName'], 'isCanAddUser'],
            [['decUserName'], 'issetDec'],
            [['conUserName'], 'isConUserName'],
            [['recUserName'], 'isRecUserName'],
            [['location'], 'isLocation'],
//            [['insertUserIdCard'], 'isSameSystem'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'type' => 'Entry type', // 报单类型
            'decLv' => 'Entry level', // 报单级别
            //'decPv' => '报单PV',
            'decWay' => 'Entry method', // 报单方式
            'packageId' => 'Entry Package', // 报单套餐
            'goodsId' => 'product ID', // 商品ID
            'goodsNum' => 'Product quantity', // 商品数量
            //'addType' => '新增会员方式',
            'insertUserName' => 'Member user name', // 会员用户名
            'password' => 'Login password', // 登陆密码
            'payPassword' => 'Payment password', // 支付密码
            'realName' => 'Member name', // 会员姓名
            'insertUserIdCard' => 'ID', // 身份证号
            'mobile' => 'Phone Number', // 手机号
            'openBank' => 'openBank', // 开户行
            'bankAddress' => 'bankAddress', // 开户支行
            'bankNo' => 'bankNo', // 银行账号
            'bankProvince' => 'bankProvince', // 银行省份
            'bankCity' => 'bankCity', // 银行城市
            'bankCounty' => 'bankCounty', // 银行县区
            'conUserName' => 'Instructor user name', // 指导老师用户名
            'recUserName' => 'Developer user name', // 开拓人用户名
            'decUserName' => 'Stockist user name', // 报单中心用户名
            'conUid' => 'Instructor Member ID', // 指导老师会员ID
            'recUid' => 'Sponsor Member ID', // 开拓人会员ID
            'location' => 'market', // 市场
            'consignee' => 'Recipient', // 收货人
            'acceptMobile' => 'Recipient Phone Number', // 收货人手机
            'province' => 'Receiving Province',//收货省
            'city' => 'Receiving City',//收货市
            'county' => 'Receiving area / county',//收货区县
            'address' => 'Receiving detailed address',//收货详细地址
        ];
    }

    /**
     * 指定场景
     * @return array
     */
    public function scenarios()
    {
        $parentScenarios =  parent::scenarios();
        $customScenarios = [
            'userDec' => ['type','allData', 'decLv','decWay','insertUserName','password','payPassword', 'realName',/* 'insertUserIdCard',*/ 'mobile', 'address', 'openBank', 'bankAddress', 'bankNo', 'bankProvince','bankCity','bankCounty', 'consignee','acceptMobile','province',/*'city','county',*/ 'conUserName', 'recUserName','decUserName', 'location', 'email'],
            'canDec' => ['type', 'insertUserName',/* 'insertUserIdCard',*/ 'conUserName', 'recUserName', 'location'],
            'notFull' => ['type', 'insertUserName', 'conUserName', 'recUserName', 'location'],
        ];
        return array_merge($parentScenarios, $customScenarios);
    }

    /**
     * 判断报单中心是否存在
     * @param $attribute
     */
    public function issetDec($attribute){
        if (!$decUser = User::find()->select('ID')->where('IS_DEC=1 AND USER_NAME=:USER_NAME', [':USER_NAME' => $this->decUserName])->asArray()->one()) {
            $this->addError($attribute, 'Stockist does not exist');//报单中心不存在
            return false;
        } else {
            // 判断报单中心是否在新加入会员的安置网上级中
            $this->loopFindParentToNetwork($this->insertUserName);
            //反转数组，in_array搜索错误
            //in_array($this->decUserName, $this->_tempNetworkParentUser[$this->insertUserName]);
            $flipParent = array_flip(array_filter($this->_tempNetworkParentUser[$this->insertUserName]));
//            var_dump($flipParent);
//            echo $this->insertUserName.'=='.$this->decUserName;
//            exit;
            if (!isset($flipParent[$this->decUserName])) {
                //$this->addError($attribute, '为' . $this->insertUserName . '报单，报单中心' . $this->decUserName . '不在' . $this->insertUserName . '的安置网上级中');
                $this->addError($attribute, 'To' . $this->insertUserName . 'Entry, Stockist' . $this->decUserName . 'not in exist' . $this->insertUserName . 'in the placement superiors');
                return ;
            }
            $this->_decId = $decUser['ID'];
        }
    }

    /**
     * 判断指导老师
     * @param $attribute
     */
    public function isConUserName($attribute){
        if($this->type == self::TYPE_ZC){
            // 从数据库查看接点会员是否在
            if(!isset($this->_tempParentUser[$this->conUserName])){
                $conUserTemp = UserInfo::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME' => $this->conUserName]);
                if(!$conUserTemp){
                    if($this->insertUserName){
                        //$this->addError($attribute, '为'.$this->insertUserName.'报单，指导老师'.$this->conUserName.'不存在');
                        $this->addError($attribute, 'To'.$this->insertUserName.'Entry,Instructor'.$this->conUserName.'not in exist');
                    } else {
                        //$this->addError($attribute, '指导老师'.$this->conUserName.'不存在');
                        $this->addError($attribute, 'Instructor'.$this->conUserName.'not in exist');
                    }
                    return ;
                }
                $conUserTemp['CON_NUM'] = UserNetwork::firstFloorChildNum($conUserTemp['USER_ID']);
                $conUserTemp['REC_NUM'] = UserRelation::firstFloorChildNum($conUserTemp['USER_ID']);
                $this->_tempParentUser[$this->conUserName] = [
                    'USER_NAME' => $this->conUserName,
                    'ZC_PV' => $conUserTemp['ZC_PV'],
                    'CON_USER_NAME' => Info::getUserNameByUserId($conUserTemp['CON_UID']),
                    'REC_USER_NAME' => Info::getUserNameByUserId($conUserTemp['REC_UID']),
                    'CON_NUM' => $conUserTemp['CON_NUM'],
                    'REC_NUM' => $conUserTemp['REC_NUM'],
                    'SYSTEM_ID' => $conUserTemp['SYSTEM_ID'],
                    'LOCATION' => UserNetwork::getLocation($conUserTemp['USER_ID'], $conUserTemp['CON_UID']),
                ];
                // 把该会员下面的5个区是否存在会员都付上
                for($i=1;$i<=5;$i++){
                    $this->_tempParentUser[$this->conUserName]["LOCATION$i"] = UserNetwork::issetUserInLocation($conUserTemp['USER_ID'], $i);
                }
            }
            $conUser = $this->_tempParentUser[$this->conUserName];
            // 判断接点会员的下级会员是否大于三个，如果大于三个则不允许
            if($conUser['CON_NUM'] >= 3){
                if($this->insertUserName){
                   // $this->addError($attribute, '为'.$this->insertUserName.'报单，指导老师'.$this->conUserName.'下级点位已满');
                    $this->addError($attribute, 'To'.$this->insertUserName.'Entry，Instructor'.$this->conUserName.'lower level is full');
                } else {
                    //$this->addError($attribute, '指导老师'.$this->conUserName.'下级点位已满');
                    $this->addError($attribute, 'Instructor'.$this->conUserName.'lower level is full');
                }
                return;
            }
            if($this->insertUserName){
                // 把自己加入到临时上级会员数组中
                $this->_tempParentUser[$this->insertUserName] = [
                    'USER_NAME' => $this->insertUserName,
                    //'ZC_PV' => $this->decPv,
                    'CON_USER_NAME' => $this->conUserName,
                    'REC_USER_NAME' => $this->recUserName,
                    'CON_NUM' => 0,
                    'REC_NUM' => 0,
                    'SYSTEM_ID' => $conUser['SYSTEM_ID'],
                    'LOCATION' => $this->location,
                    'LOCATION1' => 0,
                    'LOCATION2' => 0,
                    'LOCATION3' => 0,
                    'LOCATION4' => 0,
                    'LOCATION5' => 0,
                ];
            }

        }
    }

    /**
     * 判断开拓人
     * @param $attribute
     */
    public function isRecUserName($attribute){
        if($this->type == self::TYPE_ZC){
            // 开拓人
            if(!isset($this->_tempParentUser[$this->recUserName])){
                $recUserTemp = UserInfo::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME' => $this->recUserName]);
                if(!$recUserTemp){
                    if($this->insertUserName){
                        //$this->addError($attribute, '为'.$this->insertUserName.'报单，开拓人'.$this->recUserName.'不存在');
                        $this->addError($attribute, 'To'.$this->insertUserName.'Entry, Sponsor'.$this->recUserName.'not in exist');
                    } else {
                       // $this->addError($attribute, '开拓人'.$this->recUserName.'不存在');
                        $this->addError($attribute, 'Sponsor'.$this->recUserName.'not in exist');
                    }

                    return ;
                }
                $recUserTemp['CON_NUM'] = UserNetwork::firstFloorChildNum($recUserTemp['USER_ID']);
                $recUserTemp['REC_NUM'] = UserRelation::firstFloorChildNum($recUserTemp['USER_ID']);
                $this->_tempParentUser[$this->recUserName] = [
                    'USER_NAME' => $this->recUserName,
                    'ZC_PV' => $recUserTemp['ZC_PV'],
                    'CON_USER_NAME' => Info::getUserNameByUserId($recUserTemp['CON_UID']),
                    'REC_USER_NAME' => Info::getUserNameByUserId($recUserTemp['REC_UID']),
                    'CON_NUM' => $recUserTemp['CON_NUM'],
                    'REC_NUM' => $recUserTemp['REC_NUM'],
                    'SYSTEM_ID' => $recUserTemp['SYSTEM_ID'],
                    'LOCATION' => UserNetwork::getLocation($recUserTemp['USER_ID'], $recUserTemp['CON_UID']),
                ];
                // 把该会员下面的5个区是否存在会员都付上
                for($i=1;$i<=5;$i++){
                    $this->_tempParentUser[$this->recUserName]["LOCATION$i"] = UserNetwork::issetUserInLocation($recUserTemp['USER_ID'], $i);
                }
            }
            $recUser = $this->_tempParentUser[$this->recUserName];
            $this->_tempParentUser[$this->recUserName]['REC_NUM'] += 1;

            // 存在新加入会员时查看开拓人是否在新加入会员的安置网上级中
            if($this->insertUserName) {
                $this->loopFindParentToNetwork($this->insertUserName);
                if (!$this->recUserIsInNetworkParent()) {
                   // $this->addError($attribute, '为' . $this->insertUserName . '报单，开拓人' . $this->recUserName . '不在' . $this->insertUserName . '的安置网上级中');
                    $this->addError($attribute, 'To' . $this->insertUserName . 'Entry, Sponsor' . $this->recUserName . 'not in exist' . $this->insertUserName . 'in the placement superiors');
                    return ;
                }
            }

            // 把自己加入到临时上级会员数组中
            $this->_tempParentUser[$this->insertUserName] = [
                'USER_NAME' => $this->insertUserName,
                //'ZC_PV' => $this->decPv,
                'CON_USER_NAME' => $this->conUserName,
                'REC_USER_NAME' => $this->recUserName,
                'CON_NUM' => 0,
                'REC_NUM' => 0,
                'SYSTEM_ID' => $recUser['SYSTEM_ID'],
                'LOCATION' => $this->location,
                'LOCATION1' => 0,
                'LOCATION2' => 0,
                'LOCATION3' => 0,
                'LOCATION4' => 0,
                'LOCATION5' => 0,
            ];
        }

    }

    /**
     * 循环把所有新加入的会员的上级加入到临时变量中
     * @param null $conUserName
     * @return bool
     */
    private function loopFindParentToNetwork($conUserName = null) {
        if($conUserName == null ){
            $conUserName = $this->insertUserName;
        }
        $findUserKey = array_search($conUserName, array_column($this->allData, 'insertUserName'));
        // 如果有这个新加入的会员，则查找其上级接点
        if($findUserKey !== false){
            if(strtoupper($this->allData[$findUserKey]['type']) == 'ZC'){
                $this->_tempNetworkParentUser[$this->insertUserName][] = $this->allData[$findUserKey]['conUserName'];
                $this->loopFindParentToNetwork($this->allData[$findUserKey]['conUserName']);
            }
        }
        // 如果没有这个新加入的接点，
        else {
            if($this->insertUserName == $conUserName){
               // $this->addError('recUserName', '新加入的会员不存在');
                $this->addError('recUserName', 'New member does not exist');
                return false;
            }
            // 去数据库里查找这个会员的所有上级
//            $allParentUser = UserNetwork::find()->select('PUI.USER_NAME')->where('UI.USER_NAME=:USER_NAME', [':USER_NAME'=>$conUserName])->from(UserNetwork::tableName().' AS UN')->join('LEFT JOIN', UserInfo::tableName().' AS UI', 'UN.USER_ID=UI.USER_ID')->join('LEFT JOIN', UserInfo::tableName().' AS PUI', 'UN.PARENT_UID=PUI.USER_ID')->orderBy('PUI.NETWORK_DEEP DESC')->asArray()->all();
            $baseUser = Info::getBaseUserByUserName($conUserName);
            $userNetworkInfo = UserNetwork::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $baseUser['ID']]);
            unset($baseUser);
            $allParentUserIdsArr = explode(',', $userNetworkInfo['PARENT_UIDS']);
            unset($userNetworkInfo);
            $allParentUserIds = array_reverse($allParentUserIdsArr);
            unset($allParentUserIdsArr);
            if($allParentUserIds){
                foreach($allParentUserIds as $parentUserId) {
                    $parentBaseUser = Info::getBaseUserById($parentUserId);
                    $this->_tempNetworkParentUser[$this->insertUserName][] = $parentBaseUser['USER_NAME'] ;

                    unset($parentUserId, $parentBaseUser);
                }
            }
            unset($allParentUserIds);
        }
        return true;
    }

    /**
     * 开拓人是否在新加入会员的上级中
     * @return bool
     */
    private function recUserIsInNetworkParent(){
        return in_array($this->recUserName, $this->_tempNetworkParentUser[$this->insertUserName]);
    }

    /**
     * 判断区域是否正确
     * @param $attribute
     */
    public function isLocation($attribute){
        if($this->type == self::TYPE_ZC){
            if(!in_array($this->location, [1, 2, 3])){
                //$this->addError($attribute, '市场必须在第1市场、第2市场或第三3市场');
                $this->addError($attribute, 'Please select a market');
            }
            $conUser = $recUser = null;
            if(isset($this->_tempParentUser[$this->conUserName])){
                $conUser = $this->_tempParentUser[$this->conUserName];
            }
            if(isset($this->_tempParentUser[$this->recUserName])){
                $recUser = $this->_tempParentUser[$this->recUserName];
            }
            if($conUser){
                // 判断指导老师相应的区位是否已满
                if($conUser['LOCATION'.$this->location]){
                    if($this->insertUserName){
                       // $this->addError($attribute, '为'.$this->insertUserName.'报单，指导老师'.$this->conUserName.'的第'.$this->location.'市场已存在会员');
                        $this->addError($attribute, 'To'.$this->insertUserName.'Entry,Instructor'.$this->conUserName.'the'.($this->location == 1 ? 'left' : 'regiht').' superior already existing member');
                    } else {
                       // $this->addError($attribute, '指导老师'.$this->conUserName.'的第'.$this->location.'市场已存在会员');
                        $this->addError($attribute, 'Instructor'.$this->conUserName.'the'.($this->location == 1 ? 'left' : 'regiht').'superior already existing member');
                    }
                    return;
                }
                //市场顺序判断
//                if($conUser['CON_NUM'] == 0 && $this->location != 1){
//                    if($this->insertUserName){
//                        $this->addError($attribute, '为'.$this->insertUserName.'报单，市场必须为指导老师'.$this->conUserName.'下第一市场');
//                    } else {
//                        $this->addError($attribute, '市场必须为指导老师'.$this->conUserName.'下第一市场');
//                    }
//                    return;
//                }
//                if($conUser['CON_NUM'] == 1 && $this->location == 3){
//                    if($this->insertUserName){
//                        $this->addError($attribute, '为'.$this->insertUserName.'报单，市场必须为指导老师'.$this->conUserName.'第二市场');
//                    } else {
//                        $this->addError($attribute, '市场必须为指导老师'.$this->conUserName.'第二市场');
//                    }
//                    return;
//                }
                $this->_tempParentUser[$this->conUserName]['CON_NUM'] += 1;
                $this->_tempParentUser[$this->conUserName]['LOCATION'.$this->location] = true;
            }
        }
    }

    /**
     * 判断会员是否可加入（通过redis结合数据库判断上级会员的情况）
     * @param $attribute
     */
    public function isCanAddUser($attribute){
        if($this->type == self::TYPE_ZC){
            // 从数据库查看接点会员是否在
            if(!isset($this->_tempParentUser[$this->conUserName])){
                $conUserTemp = UserInfo::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME' => $this->conUserName]);
                if(!$conUserTemp){
//                    $this->addError($attribute, '为'.$this->insertUserName.'报单，指导老师'.$this->conUserName.'不存在');
                    $this->addError($attribute, 'To'.$this->insertUserName.'Entry,Instructor'.$this->conUserName.'not in exist');
                    return ;
                }
                $conUserTemp['CON_NUM'] = UserNetwork::firstFloorChildNum($conUserTemp['USER_ID']);
                $conUserTemp['REC_NUM'] = UserRelation::firstFloorChildNum($conUserTemp['USER_ID']);
                $this->_tempParentUser[$this->conUserName] = [
                    'USER_NAME' => $this->conUserName,
                    //'ZC_PV' => $conUserTemp['ZC_PV'],
                    'CON_USER_NAME' => Info::getUserNameByUserId($conUserTemp['CON_UID']),
                    'REC_USER_NAME' => Info::getUserNameByUserId($conUserTemp['REC_UID']),
                    'CON_NUM' => $conUserTemp['CON_NUM'],
                    'REC_NUM' => $conUserTemp['REC_NUM'],
                    'SYSTEM_ID' => $conUserTemp['SYSTEM_ID'],
                    'LOCATION' => UserNetwork::getLocation($conUserTemp['USER_ID'], $conUserTemp['CON_UID']),
                ];
                // 把该会员下面的5个区是否存在会员都付上
                for($i=1;$i<=5;$i++){
                    $this->_tempParentUser[$this->conUserName]["LOCATION$i"] = UserNetwork::issetUserInLocation($conUserTemp['USER_ID'], $i);
                }
            }
            $conUser = $this->_tempParentUser[$this->conUserName];

            // 开拓人
            if(!isset($this->_tempParentUser[$this->recUserName])){
                $recUserTemp = UserInfo::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME' => $this->recUserName]);
                if(!$recUserTemp){
//                    $this->addError($attribute, '为'.$this->insertUserName.'报单，开拓人'.$this->recUserName.'不存在');
                    $this->addError($attribute, 'To'.$this->insertUserName.'Entry, Sponsor'.$this->recUserName.'not in exist');
                    return ;
                }
                $recUserTemp['CON_NUM'] = UserNetwork::firstFloorChildNum($recUserTemp['USER_ID']);
                $recUserTemp['REC_NUM'] = UserRelation::firstFloorChildNum($recUserTemp['USER_ID']);
                $this->_tempParentUser[$this->recUserName] = [
                    'USER_NAME' => $this->recUserName,
                    //'ZC_PV' => $recUserTemp['ZC_PV'],
                    'CON_USER_NAME' => Info::getUserNameByUserId($recUserTemp['CON_UID']),
                    'REC_USER_NAME' => Info::getUserNameByUserId($recUserTemp['REC_UID']),
                    'CON_NUM' => $recUserTemp['CON_NUM'],
                    'REC_NUM' => $recUserTemp['REC_NUM'],
                    'SYSTEM_ID' => $recUserTemp['SYSTEM_ID'],
                    'LOCATION' => UserNetwork::getLocation($recUserTemp['USER_ID'], $recUserTemp['CON_UID']),
                ];
                // 把该会员下面的5个区是否存在会员都付上
                for($i=1;$i<=5;$i++){
                    $this->_tempParentUser[$this->recUserName]["LOCATION$i"] = UserNetwork::issetUserInLocation($recUserTemp['USER_ID'], $i);
                }
            }
            $recUser = $this->_tempParentUser[$this->recUserName];

            // 判断接点会员的下级会员是否大于三个，如果大于三个则不允许
            if($conUser['CON_NUM'] >= 3){
//                $this->addError($attribute, '为'.$this->insertUserName.'报单，指导老师'.$this->conUserName.'下级点位已满');
                $this->addError($attribute, 'To'.$this->insertUserName.'Entry, Sponsor'.$this->conUserName.'lower level is full');
                return;
            }
            // 判断指导老师相应的区位是否已满
            if($conUser['LOCATION'.$this->location]){
//                $this->addError($attribute, '为'.$this->insertUserName.'报单，指导老师'.$this->conUserName.'该市场已存在会员');
                $this->addError($attribute, 'To'.$this->insertUserName.'Entry, Sponsor'.$this->conUserName.'Members already exist in this market');
                return;
            }
//            if($conUser['CON_NUM'] == 0 && $this->location != 1){
//                $this->addError($attribute, '为'.$this->insertUserName.'报单，市场必须为指导老师'.$this->conUserName.'下第一市场');
//                return;
//            }

            // 把指导老师的变量的相关数量增加数量
//            $this->_tempParentUser[$this->conUserName]['CON_NUM'] += 1;
//            $this->_tempParentUser[$this->conUserName]['LOCATION'.$this->location] = true;
//            $this->_tempParentUser[$this->recUserName]['REC_NUM'] += 1;

            // 把自己加入到临时上级会员数组中
            $this->_tempParentUser[$this->insertUserName] = [
                'USER_NAME' => $this->insertUserName,
                //'ZC_PV' => $this->decPv,
                'CON_USER_NAME' => $this->conUserName,
                'REC_USER_NAME' => $this->recUserName,
                'CON_NUM' => 0,
                'REC_NUM' => 0,
                'SYSTEM_ID' => $recUser['SYSTEM_ID'],
                'LOCATION' => $this->location,
                'LOCATION1' => 0,
                'LOCATION2' => 0,
                'LOCATION3' => 0,
                'LOCATION4' => 0,
                'LOCATION5' => 0,
            ];
        }
    }

    /**
     * 报单类型
     * @param $attribute
     * @param $params
     */
    public function isType($attribute, $params){
        if(array_key_exists($this->type, $this->_types)){
            if($this->type == self::TYPE_ZC){
                if($this->scenario == 'userDec'){
                    if(!$this->insertUserName) $this->addError($attribute, 'Membership number must be filled in for initial purchase');//首购必须填写加入会员编号
                }
                if(!$this->insertUserName) $this->addError($attribute, 'Membership number must be filled in for initial purchase');//首购必须填写加入会员编号
//                if(!$this->insertUserIdCard) $this->addError($attribute, 'For the first purchase, the ID number of the member must be filled in');//首购必须填写加入会员的身份证号
                if(!$this->conUserName) $this->addError($attribute, 'For the first purchase, you must fill in the instructor number of the member');//首购必须填写加入会员的指导老师编号
                if(!$this->recUserName) $this->addError($attribute, 'For the first purchase, the Sponsor number of the member must be filled in');//首购必须填写加入会员的开拓人编号
                if(!$this->location) $this->addError($attribute, 'The first purchase must be filled in the market of the member');//首购必须填写加入会员的市场
            }
        } else {
            $this->addError($attribute, 'Incorrect entry type');//报单类型不正确
        }
    }

    /**
     * 检验相同身份证 会员是否同一体系内（接点）
     * @param $attribute
     */
//    public function isSameSystem($attribute){
//        if(isset($this->_tempParentUser[$this->conUserName])){
//            // 新加入会员的身份证号对应网内的其他会员
//            $otherUser = User::findAllAsArray("ID_CARD=:ID_CARD AND IS_UNION=0 AND DELETED=0 AND (ID_CARD_PREFIX IS NULL OR ID_CARD_PREFIX='')", [':ID_CARD'=>$this->insertUserIdCard]);
//            if(count($otherUser)>=7){
//                $this->addError($attribute, 'Only 7 documents can be reported for the same ID card');//同一个身份证限制只能报7单
//            }
//            if($otherUser){
//                $flipParent = array_flip(array_filter($this->_tempNetworkParentUser[$this->insertUserName]));
//                $isExsit = false;
//                foreach ($otherUser as $conUser){
//                    if(isset($flipParent[$conUser['USER_NAME']])){
//                        $isExsit = true;
//                        break;
//                    }
//                }
//                if (!$isExsit) {
////                    $this->addError($attribute, '为' . $this->insertUserName . '报单，身份证号码相同的会员'.$otherUser[0]['USER_NAME'].'不在' . $this->insertUserName . '的安置网上级中');
//                    $this->addError($attribute, 'To' . $this->insertUserName . 'Entry,Members with the same ID number'.$otherUser[0]['USER_NAME'].'not in exist' . $this->insertUserName . 'in the placement superiors');
//                    return ;
//                }
//            }
//        } else {
////            $this->addError($attribute, '为'.$this->insertUserName.'报单，接点人'.$this->conUserName.'不存在');
//            $this->addError($attribute, 'To'.$this->insertUserName.'Entry,Contact person'.$this->conUserName.'not in exist');
//        }
//    }

    /**
     * 添加报单
     * @param $allData
     * @return bool|null
     * @throws Exception
     * @throws \yii\db\Exception
     */
    public function add($allData){
        if(!$this->validate()){
            return null;
        }

        // 首购单，需要添加会员操作
        if($this->type == self::TYPE_ZC){
            if (preg_match("/[\x7f-\xff]/", $this->insertUserName)) {  //判断字符串中是否有中文
                throw new Exception('Member number cannot contain Chinese characters');//会员编号中不能含有汉字
            }
            //报单商品及PV判断
            $decLevelConfig = Cache::getDecLevelConfig();
            $decLevel = $decLevelConfig[$this->decLv];
            $toDecLevel = $this->decLv;
            if(!$this->decLv){
                throw new Exception('Please select the entry level');//请选择报单级别
            }
            if($this->decWay==1) {
                $decPackage = DeclarationPackage::findOneAsArray('ID=:ID', [':ID'=>$this->packageId]);
                $this->_decAmount = $decPackage['AMOUNT'];
                $this->_decPv = $decPackage['PV'];
                $this->_orderGoods[] = [
                    'GOODS_ID' => $this->packageId,
                    'PRICE' => $this->_decAmount,
                    'REAL_PRICE' => $this->_decAmount,
                    'PV' => $this->_decPv,
                    'REAL_PV' => $this->_decPv,
                    'BUY_NUMS' => 1,
                    'SKU_CODE' => $decPackage['PACKAGE_NO'],
                    'GOODS_TITLE' => $decPackage['PACKAGE_NAME'],
                    'EMAIL' => $this->email
                ];
            }else{
                $ids = $this->goodsId;
                $totalAmount = 0;
                $totalPv = 0;
                foreach ($this->goodsNum as $k => $v) {
                    if ($v) {
                        $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
                        if($goods['STORE_NUMS']>0){
                            $totalAmount += $goods['SELL_PRICE'] * intval($v);
                            $totalPv += $goods['PRICE_PV'] * intval($v);
                            $this->_orderGoods[] = [
                                'GOODS_ID' => $goods['ID'],
                                'PRICE' => $goods['SELL_PRICE'],
                                'REAL_PRICE' => $goods['SELL_PRICE'],
                                'PV' => $goods['PRICE_PV'],
                                'REAL_PV' => $goods['PRICE_PV'],
                                'POINT' => $goods['POINT'],
                                'BUY_NUMS' => intval($v),
                                'SKU_CODE' => $goods['GOODS_NO'],
                                'GOODS_TITLE' => $goods['GOODS_NAME'],
                                'EMAIL' => $this->email,
                                'TAX_RATE' => $goods['TAX_RATE'],
                            ];
                        }
                    }
                }
                if($totalPv<$decLevel['PERF']){
                    throw new Exception('The total BV of self selected goods cannot be less than the BV of the selected entry level');//自选商品总BV不能小于所选报单级别BV
                }
                foreach ($decLevelConfig as $key=>$val){
                    if($totalPv>=$val['PERF']){
                        $toDecLevel = $key;
                    }
                }
                if($this->decLv!=$toDecLevel){
                    throw new Exception('The total BV of self selected goods cannot exceed the BV value of the next level under the selected level');//自选商品总BV不能超过已选级别下一个级别的BV值
                }
                $this->_decAmount = $totalAmount;
                $this->_decPv = $totalPv;
            }
            //看现金余额是否充足
            $loginUserId = \Yii::$app->user->id;
            if (Cash::getAvailableBalance($loginUserId) < $this->_decAmount){
                throw new Exception('The applicant is short of cash and cannot complete the declaration');//报单人现金不足，无法完成报单
            }

            if(!($zcResult = $this->addUser($allData))) {
                throw new Exception(Form::formatErrorsForApi($this->_userForm->getErrors()));
            }
            if(!($decResult = $this->addDecOrder())) {
                throw new Exception(Form::formatErrorsForApi($decResult->getErrors()));
            }
        }
        return true;
    }

    /**
     * 添加会员
     * @param $allData
     * @return bool|UserInfo|null
     * @throws \yii\db\Exception
     */
    public function addUser($allData){
        $period = Period::instance();
        // 增加会员
        $user = new User();
        $user->USER_NAME = $this->insertUserName;
        $user->PASSWORD_HASH = \Yii::$app->security->generatePasswordHash($this->password);
        $user->PAY_PASSWORD = \Yii::$app->security->generatePasswordHash($this->payPassword);
        $user->NATION = 0;
        $user->REAL_NAME = $this->realName;
        $user->ID_CARD = $this->mobile;
        $user->MOBILE = $this->mobile;
        $user->EMAIL = $this->email;
        $user->ADDRESS = $this->address ? $this->address : 'nothing';//无
        $user->OPEN_BANK = $this->openBank;
        $user->BANK_ADDRESS = $this->bankAddress;
        $user->BANK_NO = $this->bankNo;
        $user->BANK_PROVINCE = $this->bankProvince ?? 0;
        $user->BANK_CITY = $this->bankCity ?? 0;
        $user->BANK_COUNTY = $this->bankCounty ?? 0;
        $user->CREATED_AT = Date::nowTime();
        $user->STATUS = 1;
        $user->DEC_LV = $this->decLv;
        $user->LAST_DEC_LV = $this->decLv;
        $user->EMP_LV = EmployLevel::getDefaultLevelId();
        $user->PROVINCE = $this->province ?? 0;
        $user->LGA_NAME = $this->lgaName;
        $user->CITY_NAME = $this->cityName;
//        $user->CITY = $this->city ?? 0;
//        $user->COUNTY = intval($this->county) ?? 0;
        $user->AVATAR = 'avatar/1.png';
        $user->IS_DEC = 0;
        $user->DEC_ID = $this->_decId ?? null;
        $user->DEC_ROLE_ID = $this->decRoleId ?? null;
        $user->PERIOD_AT = $period->getNowPeriodNum();
        $user->IS_DIRECT_SELLER = 0;
        $user->VERIFIED = 1;
        $user->VERIFIED_AT = Date::nowTime();

        if (!$user->save()) {
            throw new Exception(Form::formatErrorsForApi($user->getErrors()));
        }

        $this->_insertUserId = $user->ID;
        $userForm = new UserForm();
        $this->_userForm = $userForm;
        $userForm->scenario = 'addWithUserName';
        $userForm->userId = $this->_insertUserId;
        $userForm->userName = $this->insertUserName;
        $userForm->zcPv = $this->_decPv;
        $userForm->zcAmount = $this->_decAmount;
        $userForm->conUserName = $this->conUserName;
        $userForm->recUserName = $this->recUserName;
        $userForm->location = $this->location;
        $userForm->idCard = $this->mobile;
        $userForm->allData = $allData;
        if(!$userForm->validate()){
            $this->addErrors($userForm->getErrors());
            return false;
        }
        if($result = $userForm->add()){
            return $result;
        } else {
            return false;
        }
    }

    /**
     * 添加报单订单
     * @return bool|UserInfo|null
     * @throws \yii\db\Exception
     */
    public function addDecOrder(){
        $periodObj = Period::instance();
        $nowPeriodNum = $periodObj->getNowPeriodNum();
        $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);

        $ord = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 10);
        // 加入报单信息
        $decOrderModel = new DecOrder();
        $decOrderModel->DEC_SN = 'DS'.$ord;
        $decOrderModel->ORDER_SN = 'OS'.$ord;
        $decOrderModel->TYPE = $this->type;
        $decOrderModel->USER_ID = \Yii::$app->user->id;
        $decOrderModel->TO_USER_ID = $this->_insertUserId;
        $decOrderModel->DEC_AMOUNT = $this->_decAmount;
        $decOrderModel->DEC_PV = $this->_decPv;
        $decOrderModel->PERIOD_NUM = $nowPeriodNum;
        $decOrderModel->CALC_MONTH = $nowCalcMonth;
        $decOrderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
        $decOrderModel->PAID_WALLET = 'cash';
        $decOrderModel->CON_USER_ID = Info::getUserIdByUserName($this->conUserName);
        $decOrderModel->REC_USER_ID = Info::getUserIdByUserName($this->recUserName);
        $decOrderModel->DEC_ID = $this->_decId;
        $decOrderModel->IS_DEL = 0;
        $decOrderModel->CREATED_AT = Date::nowTime();
        if(!$decOrderModel->save()){
            throw new Exception(Form::formatErrorsForApi($decOrderModel->getErrors()));
        }

        // 加入订单信息
        if($this->province!=1){
            $warehouse = Region::getWarehouseByCode($this->province);//仓库
            if(!$warehouse){
                throw new Exception('Delivery is temporarily not supported in the region. Contact customer service for details');//地区暂时不支持配送，具体联系客服
            }
        }else{
            $warehouse = '01';
        }
        $orderModel = new Order();
        $orderModel->SN = 'OS'.$ord;
        $orderModel->DEC_SN = 'DS'.$ord;
        $orderModel->ORDER_TYPE = $this->type;
        $orderModel->USER_ID = $this->_insertUserId;
        $orderModel->USER_NAME = $this->insertUserName;
        $orderModel->ORDER_AMOUNT = $this->_decAmount;
        $orderModel->PV = $this->_decPv;
        $orderModel->PAY_AMOUNT = $this->_decAmount;
        $orderModel->PAY_PV = $this->_decPv;
        $orderModel->PAY_AT = Date::nowTime();
        $orderModel->PAY_TYPE = 'cash';
        $orderModel->PERIOD_NUM = $nowPeriodNum;
        $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
        $orderModel->FREIGHT = 0;
        $orderModel->PAY_FREIGHT = 0;
        $orderModel->CONSIGNEE = $this->consignee;
        $orderModel->MOBILE = $this->acceptMobile;
        $orderModel->EMAIL = $this->email;
        $orderModel->PROVINCE = $this->province;
        $orderModel->LGA_NAME = $this->lgaName;
        $orderModel->CITY_NAME = $this->cityName;
//        $orderModel->CITY = $this->city;
//        $orderModel->COUNTY = intval($this->county) ?? 0;
        $orderModel->ADDRESS = $this->address;
        $orderModel->WAREHOUSE = $warehouse;
        $orderModel->STATUS = 1;
        $orderModel->CREATED_AT = Date::nowTime();
        $orderModel->CREATE_USER = Info::getUserNameByUserId(\Yii::$app->user->id);
        if($this->province==1){
            $orderModel->EXPRESS_TYPE = 1;
        }
        if(!$orderModel->save()){
            throw new Exception(Form::formatErrorsForApi($orderModel->getErrors()));
        }
        // 加入商品到订单商品表
        foreach($this->_orderGoods as $key=>$value){
            $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
            $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
        }
        OrderGoods::batchInsert($this->_orderGoods);

        //写入收货地址信息，判断province字段，当不为1时，插入收货地址信息
        if($this->province!=1){
            $addressModel = new ReceiveAddress();
            $addressModel->USER_ID = $this->_insertUserId;
            $addressModel->USER_NAME = $this->insertUserName;
            $addressModel->CONSIGNEE = $this->consignee;
            $addressModel->MOBILE = $this->acceptMobile;
            $addressModel->PROVINCE = $this->province;
//            $addressModel->CITY = $this->city;
//            $addressModel->COUNTY = intval($this->county) ?? 0;
            $addressModel->CITY_NAME = $this->cityName;
            $addressModel->LGA_NAME = $this->lgaName;
            $addressModel->ADDRESS = $this->address;
            $addressModel->IS_DEFAULT = 1;
            if(!$addressModel->save()){
                throw new Exception(Form::formatErrorsForApi($addressModel->getErrors()));
            }
            //扣报单人现金钱包
//            Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_decAmount), ['REMARK' =>'为'.$this->insertUserName.'报单']);
            Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_decAmount), ['REMARK' =>'To'.$this->insertUserName.'Entry']);
            return $addressModel;
        }else{
            $addressModel = new ReceiveAddress();
            return $addressModel;
        }
    }



    /**
     * 删单
     * @return bool
     * @throws \yii\db\Exception
     */
    public function delete(){
        if(!$this->validate()){
            return false;
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $oneOrder = $this->_oneOrder;
            // 首购单要删除会员
            if($this->type == self::TYPE_ZC){
                UserInfo::deleteUser($oneOrder['TO_USER_ID']);
            }
            // 如果是复销单的话，还需要考虑给会员的复销池减去金额
            elseif($this->type == self::TYPE_FX){
//                Reconsume::changePoolPV($oneOrder['TO_USER_ID'], -abs($oneOrder['DEC_PV']), ['REMARK'=>'删单扣除', 'DEAL_TYPE'=>Reconsume::TYPE_AUDIT_PV]);
                Reconsume::changePoolPV($oneOrder['TO_USER_ID'], -abs($oneOrder['DEC_PV']), ['REMARK'=>'Deletion deduction', 'DEAL_TYPE'=>Reconsume::TYPE_AUDIT_PV]);
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('delete', $e->getMessage());
            return false;
        }
        return true;
    }

}
