<?php

namespace app\admin\controller\users;

use app\admin\model\UserMoneyLog;
use app\admin\model\device\Chargedevice;
use app\admin\model\order\Order;

use app\common\controller\Backend;
use think\Db;

/**
 * 用户管理
 *
 * @icon fa fa-users
 */
class Users extends Backend
{

    /**
     * Users模型对象
     * @var \app\admin\model\users\Users
     */
    protected $model = null;
    protected $searchFields = 'id,nickname,mobile,realname';   //里面为搜索的字段
    protected $selectpageFields = "id,nickname,mobile,realname";

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\users\Users;
        $this->view->assign("sexList", $this->model->getSexList());
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("userTypeList", $this->model->getUserTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }




    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        if(!$params['signtime']){
            $params['signtime'] = 0;
        }
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function editMoney($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if ($params) {
                $money = $params['money'];
                $charge_device_sn = $params['charge_device_sn'];
                if ($params['money'] == 0) {
                    $this->error('请输入正确的余额数');
                }
                if (($row['total_money'] + $params['money']) < 0) {
                    $this->error('余额不足！');
                }
                if (!$params['intro']  || empty($params['intro'])) {
                    $this->error('请填写操作备注！');
                }
                $createtime = time();
                //组合订单信息
                $data = [
                    'order_sn' => self::getOrderSn(),
                    'user_id' => $row['id'],
                    'nickname' => '',
                    'mobile' => '',
                    'total_price' => $money,
                    'need_pay' => $money,
                    'device_sign' => $charge_device_sn,
                    'order_type' => $params['order_type'],
                    'status' => 4,
                    'createtime' => $createtime,
                    'endtime' => $createtime,
                    'billingType' => -1,
                    'chargingElec' => 0,
                    'chargingGroupName' => '',
                    'chargingName' => '',
                    'chargingPower' => 0,
                    'chargingTime' => 0,
                    'consumeCount' => 0,
                    'consumeTime' => 0,
                    'socketCode' => 0,
                    'code' => 0
                ];
                $order = Order::create($data);
                //给对应的代理商分佣
                $this->model->where(['id' => $row['id']])->setInc('total_money', $money);
                $data = [
                    'user_id' => $row['id'],
                    'money' => $money,
                    'before' => $row['total_money'],
                    'after' => $row['total_money'] + $money,
                    'memo' => $params['intro'],
                    'type' => $params['order_type'],
                    'createtime' => $createtime,
                    'order_id' => $order['id']
                ];
                UserMoneyLog::create($data);
                $this->success();
            } else {
                $this->error('数据错误，请重新打开窗口！user_id', $row['id']);
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function editShoppingMoney($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if ($params) {
                $money = $params['shopping_money'];
//                $charge_device_sn = $params['charge_device_sn'];
                if ($params['shopping_money'] == 0) {
                    $this->error('请输入正确的购物金数');
                }
                if (($row['shopping_money'] + $params['shopping_money']) < 0) {
                    $this->error('余额不足！');
                }
                if (!$params['intro']  || empty($params['intro'])) {
                    $this->error('请填写操作备注！');
                }
                $createtime = time();
                //组合订单信息
                $data = [
                    'order_sn' => self::getOrderSn(),
                    'user_id' => $row['id'],
                    'nickname' => '',
                    'mobile' => '',
                    'total_price' => $money,
                    'need_pay' => $money,
                    'device_sign' => '',
                    'order_type' => $params['order_type'],
                    'status' => 4,
                    'createtime' => $createtime,
                    'endtime' => $createtime,
                    'billingType' => -1,
                    'chargingElec' => 0,
                    'chargingGroupName' => '',
                    'chargingName' => '',
                    'chargingPower' => 0,
                    'chargingTime' => 0,
                    'consumeCount' => 0,
                    'consumeTime' => 0,
                    'socketCode' => 0,
                    'code' => 0
                ];
                $order = Order::create($data);
                //给对应的代理商分佣
                $this->model->where(['id' => $row['id']])->setInc('shopping_money', $money);
                $data = [
                    'user_id' => $row['id'],
                    'money' => $money,
                    'before' => $row['shopping_money'],
                    'after' => $row['shopping_money'] + $money,
                    'memo' => $params['intro'],
                    'type' => $params['order_type'],
                    'createtime' => $createtime,
                    'order_id' => $order['id']
                ];
                UserMoneyLog::create($data);
                $this->success();
            } else {
                $this->error('数据错误，请重新打开窗口！user_id', $row['id']);
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * @param null $ids
     * 增减股权
     */
    public function editEquity($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if ($params) {
                $equity = $params['equity'];
                if ($params['equity'] == 0) {
                    $this->error('请输入正确的股权数');
                }
                if (((int)$row['equity'] + $params['equity']) < 0) {
                    $this->error('股权余额不足！');
                }
                $info = $this->model->where(['id' => $row['id']])->find();
                if($params['equity'] > 0 && !$params['equity_code']){
                    $this->error('请输入股权代码！');
                }
                $equity_code = $params['equity_code'];
                if($info['equity'] && $equity>0){
                    $info['equity_code'] .= '+'.$params['equity_code'];
                    $equity_code = $info['equity_code'];
                }
                $params['signtime'] = strtotime($params['signtime']);
                if($equity_code && $params['equity'] > 0){
                    $this->model->where(['id' => $row['id']])->update(['equity_code' =>$equity_code,'signtime' =>$params['signtime']]);
                }
                $this->model->where(['id' => $row['id']])->setInc('equity', $equity);
                $data = [
                    'user_id' => $row['id'],
                    'money' => $equity,
                    'before' => (int)$row['equity'],
                    'after' => (int)$row['equity'] + $equity,
                    'memo' => $params['equity_code'],
                    'type' => 13,
                    'heatos' => $params['equity'] > 0 ? 1:-1,
                    'createtime' => time(),
                ];
                UserMoneyLog::create($data);
                $this->success();
            } else {
                $this->error('数据错误，请重新打开窗口！user_id', $row['id']);
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();

    }

    /**
     * @return string
     * 订单编号
     */
    public static function getOrderSn()
    {
        $order_sn = date('YmdHis') . rand(100000000000000000, 999999999999999999);
        return $order_sn;
    }
}
