<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\model\Agent  as AgentModel;
use think\facade\Db;

class Agent extends AdminBase
{
    public function index()
    {
        return '您好！这是一个[Agent]示例应用';
    }
    
    /* 
     * 获取代理列表
     */
    public function getAgentList()
    {
        $name   = input('name', '');
        $mobile = input('mobile','', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $offset = input('pageSize',20, ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $order  = 'id desc';
        if(!empty($name))   $where[] = ['name'  ,'=', $name];
        if(!empty($mobile)) $where[] = ['mobile','=', $mobile];
        $where[] = ['is_del' ,'=', 0];
        $where[] = ['agent_id' ,'=', 1];
        $res = AgentModel::getAgentList($where,$order,$offset);
        if($res){
            return ajaxmsg('操作成功',200, $res); 
        }else {
            return ajaxmsg('操作失败',0);
        }
    }
    /* 
     * 修改代理信息
     */
    public function editAgent()
    {
        $data = input();
        unset($data['id']);
        unset($data['create_time']);
        unset($data['agent_time']);
        if(empty($data['id'])) $data['agent_id'] = 1;
        $res = AgentModel::strict(false)->where(['mobile'=>$data['mobile']])->save($data);
		if($res) {
            return ajaxmsg('操作成功',200);
        } else {
            return ajaxmsg('操作失败',0);
        }
    }
    /*
     * 禁用代理
     */
    public function doDisable()
    {
        $id     = input('id','', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $status = input('agent_pro','', ['trim', FILTER_SANITIZE_NUMBER_INT]);
		$res = AgentModel::where('id', $id)->save(['agent_pro'=> $status]);
        if ($res) {
            return ajaxmsg('操作成功',200);
        } else {
            return ajaxmsg('操作失败',0);
        }
    }
    /*
     * 删除会员
     */
    public function delAgent()
    {
        $id     = input('id','', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $agent = AgentModel::where(['id' => $id,'agent_id' => 1,'agent_pro' => 1])->find();
        if(empty($agent)) return ajaxmsg('查询失败',0);
        $member  = AgentModel::where(['agent_far' => $id, 'is_del' => 0])->find();
		//print_r($member);exit;
		if(!empty($member)) {
			return ajaxmsg('操作失败，请先转移该代理的下级会员',0);
		}
		$result = AgentModel::where('id', $id)->save(['agent_id' => 0,'agent_pro'=> 0]);
        if($result) {
            return ajaxmsg('操作成功',200);
        } else {
            return ajaxmsg('操作失败',0);
        }
    }
}