<?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\Info;
use common\models\Config;
use common\models\DeclarationLevel;
use common\models\DeclarationPackage;
use common\models\DecLevelLog;
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\Region;
use common\models\ShopGoods;
use common\models\User;
use common\models\UserInfo;
use common\models\UserNetwork;
use yii\base\Exception;

/**
 * 升级管理,进行升级
 */
class DeclarationUpgradeForm extends Model
{
    public $type;
    public $decLv;
    public $decWay;
    public $packageId;
    public $goodsId;
    public $goodsNum;
    public $insertUserName;
    public $consignee;
    public $acceptMobile;
    public $province;
    public $city;
    public $county;
    public $address;
    public $nowPerf;
    public $nextPerf;
    public $decUserName;
    public $remark;
    // 传过来的全部数据
    public $allData;
    private $_decId;
    public $_insertUserId;
    private $_decAmount;
    private $_decPv;
    private $_orderGoods;
    const TYPE_ZC = 'ZC';
    private $_userForm = null;
    // 全部的安置网上级
    private $_tempNetworkParentUser = [];

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['remark','type','decLv','decWay','packageId','goodsId', 'goodsNum', 'insertUserName','consignee','acceptMobile','province','city','county','address','nowPerf','nextPerf'], 'trim'],
            [['type','decLv','decWay','insertUserName','nowPerf','province','city','county','address','acceptMobile'], 'required'],
            [['decUserName'], 'issetDec'], // 必须是报单中心
            [['decWay'], 'hasProduct'],// 必须选择商品
            [['decLv'], 'alreadyMaxDec'], //判断要升级用户是否已经是最高级
        ];
    }

    public function attributeLabels()
    {
        return [
            'type' => '升级类型',
            'decLv' => '升级级别',
            'decWay' => '报单方式',
            'packageId' => '升级套餐',
            'goodsId' => '商品ID',
            'goodsNum' => '商品数量',
            'insertUserName' => '要升级的会员编号',
            'consignee' => '收货人',
            'acceptMobile' => '收货人手机',
            'province' => '收货省',
            'city' => '收货市',
            'county' => '收货区县',
            'address' => '收货详细地址',
        ];
    }

    /**
     * 添加报单
     * @param $allData
     * @return bool|null
     * @throws Exception
     * @throws \yii\db\Exception
     */
    public function add($allData){
        if(!$this->validate()){
            return null;
        }
        $loginUserId = \Yii::$app->user->id;
        // 首购单
        if($this->type == self::TYPE_ZC){
            //报单商品及PV判断
            $decLevelConfig = Cache::getDecLevelConfig();
            $decLevel = $decLevelConfig[$this->decLv];
            $toDecLevel = $this->decLv;
            if(!$this->decLv){
                throw new Exception('请选择升级级别');
            }
            $baseInfo = Info::baseInfoZhByUserName($this->insertUserName);
            $userId = $baseInfo['ID'];
            $userDecPvSum = User::sumDevPvByUserId($userId); // 用户所有报单PV总和
            if ($userDecPvSum != $this->nowPerf) {
                throw new Exception('请联系客服人员核对升级会员业绩');
            }
            // 获取用户是否是观察期
            $observe = Config::getConfigByType('observe'); // 获取观察期配置信息
            $observeLimit = $observe['observePeriodLimit']['value']; // 月份限制
            $isObserve = User::checkIsObserve($baseInfo['CREATED_AT'], $observeLimit); // 判断用户是否再观察期中
            $diffPerf = $isObserve ? $this->nowPerf : 0; // 观察期内升级要加上用户累计的PV,全额则基础PV为0,全额购买
            if ($this->decWay != 2) {
                throw new Exception('升级方式不正确，请联系客服人员');
            }
            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']
                // ];
            } 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) {
                            throw new Exception('商品不存在');
                        }
                        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']
                            ];
                        }
                    }
                }
                // 这里特殊是用户原报单PV之和+用户购买的商品总PV
                $checkPv = $totalPv + $diffPerf;
                if($checkPv < $decLevel['PERF']) {
                    throw new Exception('总PV不能小于所选级别PV');
                }
                foreach ($decLevelConfig as $key=>$val){
                    if($checkPv>=$val['PERF']){
                        $toDecLevel = $key;
                    }
                }
                if($this->decLv!=$toDecLevel){
                    throw new Exception('总PV不能超过已选级别下一个级别的PV值');
                }
                $this->_decAmount = $totalAmount;
                $this->_decPv = $totalPv;
            }
            //看现金余额是否充足
            if (Cash::getAvailableBalance($loginUserId) < $this->_decAmount){
                throw new Exception('报单人现金不足，无法完成报单');
            }
            $baseInfo = Info::baseInfoZhByUserName($this->insertUserName);
            $this->_insertUserId = $baseInfo['ID']; // 被报单人,通过insername 查找用户id
            $insertConId = $baseInfo['CON_UID'];
            $insertRecId = $baseInfo['REC_UID'];
            if(!($decResult = $this->addDecOrder($insertConId,$insertRecId, $baseInfo['DEC_LV'],$isObserve,$this->remark))) {
                throw new Exception("操作失败");
            }
        }
        return true;
    }

    /**
     * 添加报单订单
     * @return bool|UserInfo|null
     * @throws \yii\db\Exception
     */
    public function addDecOrder($insertConId,$insertRecId,$oriDecLv,$isObserve,$remark=''){
        $warehouse = Region::getWarehouseByCode($this->province);//仓库
        if(!$warehouse){
            throw new Exception('地区暂时不支持配送，具体联系客服');
        }

        $upgradeType = $isObserve ? 1 : 2; // 1补差  2全额
        $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);
        // 加入报单信息
        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            $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 = $insertConId;
            $decOrderModel->REC_USER_ID = $insertRecId;
            $decOrderModel->DEC_ID = $this->_decId;
            $decOrderModel->IS_DEL = 0;
            $decOrderModel->DETAIL_TYPE = 2;
            $decOrderModel->CREATED_AT = Date::nowTime();
            $decOrderModel->UPGRADE_TYPE = $upgradeType;
            $decOrderModel->REMARK = $remark;
            $decOrderModel->ORI_LV = $oriDecLv; // 变更前的级别
            $decOrderModel->UPGRADE_LV = $this->decLv; // 变更后的级别
            if(!$decOrderModel->save()){
                $transaction->rollBack();
                throw new Exception(Form::formatErrorsForApi($decOrderModel->getErrors()));
            }

            $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->PROVINCE = $this->province;
            $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(!$orderModel->save()){
                $transaction->rollBack();
                throw new Exception(Form::formatErrorsForApi($orderModel->getErrors()));
            }

            /**
             * 2022-05-10
             * York
             */
            foreach ($this->goodsNum as $k => $v) {
                if ($v) {
                    $goods = ShopGoods::findOneAsArray('ID=:ID',[':ID'=> $this->goodsId[$k]]);
                    if (!$goods) {
                        throw new Exception('商品不存在');
                    }
                    $storenums = $goods['STORE_NUMS'] - $this->goodsNum[$k];
                    if($goods['STATUS']==1){
                        if($goods['STORE_NUMS'] >=$this->goodsNum[$k]){
                            $data = ShopGoods::find()->where(['ID' => $this->goodsId[$k]])->one();
                            $data->STORE_NUMS = $storenums;
                            $data->update();
                            if ($storenums==0){
                                $data->STATUS = 0;
                                $data->UPDATED_AT = Date::nowTime();
                                $data->update();
                            }
                        }else{
                            throw new Exception("商品".$goods['GOODS_NAME']."库存不足");
                        }
                    }else{
                        throw new Exception("商品".$goods['GOODS_NAME']."已下架");
                    }
                }
            }

            // 加入商品到订单商品表
            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);
            //写入收货地址信息
            $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->ADDRESS = $this->address;
            $addressModel->IS_DEFAULT = 0;
            if(!$addressModel->save()){
                $transaction->rollBack();
                throw new Exception(Form::formatErrorsForApi($addressModel->getErrors()));
            }
            // 扣报单人现金钱包
            Cash::changeUserCash(\Yii::$app->user->id, 'CASH', -abs($this->_decAmount), ['REMARK' =>'为'.$this->insertUserName.'升级报单', 'ORDER_SN' => $orderModel->SN]);
            // 为被升级人进行升级操作
            $decLevelLog = new DecLevelLog();
            $decLog = [
                'userId' => $this->_insertUserId,//会员ID
                'fromId' => $oriDecLv, // 变动前的级别
                'levelId' => $this->decLv,// 变动后的级别
                'actionId' => \Yii::$app->user->id,
                'remark' => $this->remark,
                'lvPv' => $this->_decPv
            ];
            $modifyDecLv = $decLevelLog->frontendChange($decLog);
            if (empty($modifyDecLv)) {
                $transaction->rollBack();
                throw new Exception("为会员升级失败");
            }
            $transaction->commit();
        } catch(Exception $e) {
            $transaction->rollBack();
            throw new Exception($e->getMessage());
            return false;
        }

        return $modifyDecLv;
    }

    /**
     * 判断报单中心是否存在
     * @param $attribute
     */
    public function issetDec($attribute){
        $decUser = User::find()
        ->select('ID')
        ->where('IS_DEC=1 AND USER_NAME=:USER_NAME', [':USER_NAME' => $this->decUserName])
        ->asArray()
        ->one();
        if (!$decUser) {
            $this->addError($attribute, '报单中心不存在');
            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]));
//            if (!isset($flipParent[$this->decUserName])) {
//                $this->addError($attribute, '为' . $this->insertUserName . '升级报单，报单中心' . $this->decUserName . '不在' . $this->insertUserName . '的安置网上级中');
//                return ;
//            }
            $this->_decId = $decUser['ID'];
        }
    }


    // 判断是否已选择商品或套餐
    public function hasProduct($attribute) {
        if ($this->decWay==1 && empty($this->packageId)) {
            $this->addError($attribute, '购买套餐升级，请选择套餐');
            return false;
        }
        if ($this->decWay!=1 && empty($this->goodsId)) {
            $this->addError($attribute, '购买商品升级，请选择商品');
            return false;
        }

        return true;
    }

    // 判断要升级的会员,是否已是最高级别
    public function alreadyMaxDec($attribute) {
        $baseInfo = Info::baseInfoZhByUserName($this->insertUserName);
        $userDecId = $baseInfo['DEC_LV'];// 用户当前的级别
        $maxPerfInfo = DeclarationLevel::getMaxDecPref();
        $maxDecId = $maxPerfInfo['ID']; // 级别配置中最高级别ID
        if ($maxDecId == $userDecId) {
            $this->addError($attribute, '已是最高级别，无需升级');
            return false;
        }

        return true;
    }

    /**
     * 寻找被升级人的上级
     * @param null $conUserName
     * @return bool
     */
    private function loopFindParentToNetwork($conUserName = null) {
        if($conUserName == null ){
            $conUserName = $this->insertUserName;
        }
        $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
    //  * @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]);
    //         }
    //         $transaction->commit();
    //     } catch (Exception $e) {
    //         $transaction->rollBack();
    //         $this->addError('delete', $e->getMessage());
    //         return false;
    //     }
    //     return true;
    // }

}
