<?php
namespace common\models\forms;

use common\components\Model;
use common\helpers\Cache;
use common\helpers\Date;
use common\helpers\Form;
use common\helpers\LoggerTool;
use common\helpers\user\Cash;
use common\helpers\user\Reconsume;
use common\helpers\user\Info;
use common\models\DeclarationPackage;
use common\models\BaDecOrder;
use common\models\EmployLevel;
use common\models\BaOrder;
use common\models\BaOrderGoods;
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\BaUser;
use common\models\UserInfo;
use common\models\BaUserInfo;
use common\models\UserNetwork;
use common\models\UserRelation;
use yii\base\Exception;

/**
 * Login form
 */
class BaDeclarationForm 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','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', // 报单类型
            'goodsId' => 'product ID', // 商品ID
            'goodsNum' => 'Product quantity', // 商品数量
            'insertUserName' => 'Member user name', // 会员用户名
            'password' => 'Login password', // 登陆密码
            'payPassword' => 'Payment password', // 支付密码
            'realName' => 'Member name', // 会员姓名
            'mobile' => 'Phone Number', // 手机号
            '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',//收货省
            'address' => 'Receiving detailed address',//收货详细地址
        ];
    }

    /**
     * 指定场景
     * @return array
     */
    public function scenarios()
    {
        $parentScenarios =  parent::scenarios();
        $customScenarios = [
            'userDec' => ['type','allData', 'decLv','decWay','insertUserName','password','payPassword', 'realName', 'mobile', 'address', 'consignee','acceptMobile','province','decUserName', 'location', 'email'],
        ];
        return array_merge($parentScenarios, $customScenarios);
    }

    /**
     * 判断报单中心是否存在
     * @param $attribute
     */
    public function issetDec($attribute){
        if (!$decUser = BaUser::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->_decId = $decUser['ID'];
        }
    }

    /**
     * 判断开拓人
     * @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 $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'); // 请选择报单级别
//            }

            $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');//报单人现金不足，无法完成报单
            }
//            print_r($allData);exit;
            if(!($zcResult = $this->addBaUser($allData))) {
                throw new Exception(Form::formatErrorsForApi($this->_userForm->getErrors()));
            }
//            print_r($allData);exit;
            if(!($decResult = $this->addBaDecOrder())) {
                throw new Exception(Form::formatErrorsForApi($decResult->getErrors()));
            }
        }
        return true;
    }

    /**
     * 添加会员
     * @param $allData
     * @return bool|UserInfo|null
     * @throws \yii\db\Exception
     * @throws \Exception
     */
    public function addBaUser($allData){
        $period = Period::instance();

        try {
            // 增加会员
            $user = new BaUser();
            $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->AVATAR = 'avatar/1.png';
            $user->IS_DEC = 0;
            $user->DEC_ID = $this->_decId ?? '';
            $user->DEC_ROLE_ID = $this->decRoleId ?? '';
            $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 BaUserForm();
            $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;
            //        print_r($userForm);exit;
            if (!$userForm->validate()) {
                $this->addErrors($userForm->getErrors());
                return false;
            }
            if ($result = $userForm->add()) {
                return $result;
            } else {
                return false;
            }
        } catch (\Exception $e) {
            LoggerTool::info($e->getMessage());
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 添加报单订单
     * @return bool|UserInfo|null
     * @throws \yii\db\Exception
     */
    public function addBaDecOrder(){
        $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 BaDecOrder();
        $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 BaOrder();
        $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->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);
        }
        BaOrderGoods::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_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()));
            }
        }else{
            $addressModel = new ReceiveAddress();
        }
        //扣报单人现金钱包
        Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_decAmount), ['REMARK' =>'To'.$this->insertUserName.'Entry']); // 报单
        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){
                BaUserInfo::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;
    }

}
