<?php
namespace common\models\forms;

use common\helpers\Date;
use common\components\Model;
use common\helpers\Form;
use common\helpers\user\Info;
use common\libs\logging\operate\AdminOperate;
use common\models\Period;
use common\models\Region;
use common\models\User;
use common\models\UserClose;
use common\models\UserInfo;
use common\models\UserNetwork;
use common\models\UserRelation;
use common\models\UserSystem;
use yii\base\Exception;

/**
 * Class CloseDecForm
 * @package common\models\forms
 */
class CloseDecForm extends Model
{
    public $userIds;
    public $userName;
    public $remark;
    public $type;  // 1:单独关闭个人，2:按推荐网络关闭，3:按安置网络关闭，4:按体系关闭
    public $isClose; // 0: 允许报单, 1:禁止报单
    public $areaSelected; //地区选择

    private $_userId;
    private $_userSystem;

    public static $types = [
        1 => '按指定会员',
        2 => '按开拓网络',
        3 => '按安置网络',
        4 => '按体系',
        5 => '按地区',
    ];

    public static $closeSwitch = [
        0 => '允许报单',
        1 => '禁止报单',
    ];

    public function init()
    {
        parent::init();
        $this->adminOperateLogger = new AdminOperate([
            'fetchClass' => User::class,
        ]);
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['userIds', 'userName', 'type', 'isClose', 'areaSelected', 'remark'], 'trim'],
            [['userIds', 'userName', 'type', 'isClose', 'areaSelected'], 'required'],
            [['userName'], 'initUserId'],
            [['type'], 'isType'],
        ];
    }

    /**
     * 指定校验场景
     * @return array
     */
    public function scenarios()
    {
        $parentScenarios =  parent::scenarios();
        $customScenarios = [
            // 单独禁止报单
            'single' => ['userName', 'type', 'isClose', 'remark'],
            // 批量禁止
            'batch' => ['userIds', 'type', 'isClose', 'remark'],
            // 按地区关闭
            'area' => ['isClose', 'type', 'areaSelected', 'remark'],
        ];
        return array_merge($parentScenarios, $customScenarios);
    }

    public function attributeLabels()
    {
        return [
            'userName' => '会员编号',
            'type' => '类型',
            'remark' => '备注',
        ];
    }

    /**
     * 初始化会员ID
     * @param $attribute
     */
    public function initUserId($attribute){
        $this->_userId = Info::getUserIdByUserName($this->userName);
        if(!$this->_userId){
            $this->addError($attribute, 'Member does not exist'); // 会员不存在
        }
    }


    /**
     * 状态类型校验
     * @param $attribute
     */
    public function isType($attribute){
        if($this->type == 4){
            $this->_userSystem = UserSystem::getSystemByUserId($this->_userId);
            if($this->_userSystem){
                if($this->_userSystem['LEADER_UID'] != $this->_userId){
                    $this->addError($attribute, '按体系管理报单必须是体系领导人');
                }
            }  else {
                $this->addError($attribute, '体系不存在');
            }
        }
    }

    /**
     * 批量处理
     * @return array|null
     * @throws \yii\db\Exception
     */
    public function batch(){
        if(!$this->validate()){
            return null;
        }
        $this->adminOperateLogger->setIsBatch(true)->beforeUpdate($this->userIds, 'ID',['select'=>'ID,DEC_CLOSED,DEC_CLOSED_AT']);
        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            if($this->isClose){
                $closedAt = Date::nowTime();
            } else {
                $closedAt = 0;
            }
            $allUidIn = implode("','", $this->userIds);
            User::updateAll(['DEC_CLOSED'=> $this->isClose ? $this->isClose : 0,'DEC_CLOSED_AT'=>$closedAt], "ID IN ('".$allUidIn."')");
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('batch', $e->getMessage());
            return null;
        }
        $this->adminOperateLogger->setIsBatch(true)->afterUpdate($this->userIds, 'ID',['select'=>'ID,DEC_CLOSED,DEC_CLOSED_AT']);
        $this->adminOperateLogger->setBatchField('ID')->setOptObjField('ID')->clean()->save([
            'optType' => self::$types[$this->type].self::$closeSwitch[$this->isClose],
            'remark' => $this->remark,
        ]);
        return $this->userIds;
    }

    /**
     * 按照地区关闭
     * @return bool|null
     * @throws \yii\db\Exception
     */
    public function area(){
        if(!$this->validate()){
            return null;
        }
        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            if($this->isClose){
                $closedAt = Date::nowTime();
            } else {
                $closedAt = 0;
            }
            $where = '';
            $params = [];
            if(isset($this->areaSelected[0]) && $this->areaSelected[0]){
                $where .= 'PROVINCE=:PROVINCE';
                $params[':PROVINCE'] = $this->areaSelected[0];
            }
            if(isset($this->areaSelected[1]) && $this->areaSelected[1]){
                $where .= ' AND CITY=:CITY';
                $params[':CITY'] = $this->areaSelected[1];
            }
            if(isset($this->areaSelected[2]) && $this->areaSelected[1]){
                $where .= ' AND COUNTY=:COUNTY';
                $params[':COUNTY'] = $this->areaSelected[2];
            }

            $allUser = User::findAllAsArray($where,$params,'ID');
            $allUserIds = array_column($allUser, 'ID');
            $this->adminOperateLogger->setIsBatch(true)->beforeUpdate($allUserIds, 'ID',['select'=>'ID,DEC_CLOSED,DEC_CLOSED_AT']);

            User::updateAll(['DEC_CLOSED'=> $this->isClose ? $this->isClose : 0,'DEC_CLOSED_AT'=>$closedAt], $where,$params);
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('area', $e->getMessage());
            return null;
        }

        $this->adminOperateLogger->setIsBatch(true)->afterUpdate($allUserIds, 'ID', ['select' => 'ID,DEC_CLOSED,DEC_CLOSED_AT']);
        $province = isset($this->areaSelected[0]) ? Region::getCnName($this->areaSelected[0]) : '';
        $city = isset($this->areaSelected[1]) ? Region::getCnName($this->areaSelected[1]) : '';
        $county = isset($this->areaSelected[2]) ? Region::getCnName($this->areaSelected[2]) : '';
        $this->adminOperateLogger->setBatchField('ID')->setOptObjField('ID')->clean()->save([
            'optType' => self::$types[$this->type] . $province . $city . $county . self::$closeSwitch[$this->isClose],
            'remark' => $this->remark,
        ]);

        return true;
    }


}
