<?php

namespace app\admin\controller;

use app\BaseController;
use app\admin\model\IpConfig as IpConfigModel;
use app\admin\validate\IpConfigValidate;
use Exception;
use think\facade\DB;

class IpConfig extends BaseController
{
    /**
     * @api {post} /ip/delete IP黑名单 删除
     *
     */
    function delete()
    {

        DB::startTrans();
        try {
            $params = (new IpConfigValidate())->post()->goCheck('id');
            $count = IpConfigModel::where('id', $params['id'])->delete();
            if ($count < 1) throw new Exception('操作失败');
            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }
        return $this->success();
    }


    /**
     * @api {post} /ip/update IP 更新
     */
    function update()
    {
        DB::startTrans();
        try {

            $params = (new IpConfigValidate())->post()->goCheck('edit');
            $id = $this->request->param('id',0);
            $params['operator_id'] = $this->admin_id;
            if (!$id) {
                $ip = IpConfigModel::where('ip', $params['ip'])->find();
                if ($ip) {
                    return $this->error('IP已存在');
                }
                IpConfigModel::create($params);
            } else {
                $ip = IpConfigModel::where('id', $id)->find();
                if (!$ip) {
                    return $this->error('IP不存在');
                }
                IpConfigModel::where('id', $id)->update($params);
            }
            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }
        return $this->success();
    }

    /**
     * @api {get} /ip/index IP查询
     */
    function index()
    {
        try {
            $params = $this->request->param();
            $page = $params['page'] ?? 1;
            $limit = $params['limit'] ?? 15;
            $query = IpConfigModel::join('kefu', 'kefu.id = ip_config.operator_id', 'left');
            if (!empty($params['type'])) {
                $query->where('ip_config.type', $params['type']);
            }
            if (!empty($params['status'])) {
                $query->where('ip_config.status', $params['status']);
            }
            if (!empty($params['operator'])) {
                $query->where('kefu.name', 'like', '%'.$params['operator'].'%');
            }
            $count = $query->count();
            $list = $query
                ->field(['ip_config.*', 'kefu.name as operator_name'])
                ->order('updated_at','desc')
                ->limit($limit)
                ->page($page)
                ->select();
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success(['count' => $count, 'list' => $list]);
    }
}