<?php

namespace app\admin\controller;

use app\admin\BaseController;
use app\common\model\User as UserModel;
use app\common\model\Worker as WorkerModel;
use app\common\model\Agent as AgentModel;
use app\common\model\AgentForm as AgentFormModel;
use app\common\model\Broker as BrokerModel;

use app\common\validate\Agent as AgentValidate;
use think\exception\ValidateException;
use think\facade\Db;

class Agent extends BaseController
{

    public function agentList()
    {
        $workerlist = WorkerModel::order(['id' => 'desc'])->select();
        return view('agent/agentlist', [
            'workerlist' => $workerlist,
        ]);
    }

    public function agentForm()
    {
        $id         = input('id/d, 0');
        $agent      = AgentModel::with(['muser'])->findOrEmpty($id);
        $workerlist = WorkerModel::order(['id' => 'desc'])->select();
        return view('agent/agentform', [
            'workerlist' => $workerlist,
            'agent'      => $agent,
        ]);
    }

    public function editAgent()
    {
        $id    = input('id/d');
        $vdata = [
            'id'        => $id,
            'loginname' => input('loginname/s', ""),
            'idnumber'  => input('idnumber/s', ""),
        ];
        try {
            validate(AgentValidate::class)->check($vdata);
        } catch (ValidateException $e) {
            exit(json_encode([
                'code' => 1,
                'msg'  => $e->getError(),
            ]));
        }
        $muser = UserModel::where(['mobile' => input('musermobile/s', '')])->findOrEmpty();
        if ($muser->isEmpty()) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "关联的用户不存在。",
            ]));
        }
        $data     = [
            'userid'    => $muser->id,
            'workerid'  => input('workerid/d', 0),
            'loginname' => input('loginname/s', ""),
            'idnumber'  => input('idnumber/s', ""),
            'title'     => input('title/s', ""),
            'tilpic'    => input('tilpic/s', ""),
            'picall'    => input('picall/a', []),
            'realname'  => input('realname/s', ""),
            'mobile'    => input('mobile/s', ""),
            'telephone' => input('telephone/s', ""),
            'latitude'  => input('latitude/f', 0.00),
            'longitude' => input('longitude/f', 0.00),
            'province'  => input('province/s', ""),
            'city'      => input('city/s', ""),
            'district'  => input('district/s', ""),
            'address'   => input('address/s', ""),
            'details'   => input('details/s', ""),
            'priority'  => input('priority/d', 0),
            'remark'    => input('remark/s', ""),
            'status'    => input('status/d', 1),
            'is_settle' => input('is_settle/d', 1),
        ];
        $password = input('password/s', "");
        if (empty($id)) {
            $data['password']   = empty($password) ? md5("123456789") : md5($password);
            $data['createtime'] = time();
            $agent              = AgentModel::create($data);
        } else {
            if (!empty($password)) {
                $data['password'] = md5($password);
            }
            $agent = AgentModel::find($id);
            $agent->save($data);
        }
        BrokerModel::update([
            'workerid' => input('workerid/d', 0),
        ], ['agentid' => $agent->id]);
        exit(json_encode([
            'code' => 0,
        ]));
    }

    public function fieldAgent()
    {
        $id   = input('id/d', 0);
        $info = AgentModel::findOrEmpty($id);
        if ($info->isEmpty()) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "信息不存在",
            ]));
        } else {
            $info->save([
                input('field/s') => input('value/s', ""),
            ]);
        }
        exit(json_encode([
            'code' => 0,
        ]));
    }

    public function delAgent()
    {
        $access_admin = session('access_admin');
        $password     = input('password');
        if ($access_admin['password'] !== md5($password)) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "操作密码验证失败",
            ]));
        }
        $idarr  = input('idarr/a');
        $result = Db::name('agent')->whereIn('id', $idarr)->update(['deletetime' => time()]);
        if ($result) {
            exit(json_encode([
                'code' => 0,
                'msg'  => "",
            ]));
        }
        exit(json_encode([
            'code' => 1,
            'msg'  => "删除失败，请稍后重试",
        ]));
    }

    public function listAgent()
    {
        $limit    = input('limit');
        $page     = input('page');
        $map      = [];
        $keywords = input('keywords/s');
        if (!empty($keywords)) {
            $map[] = ['idnumber', 'like', '%' . $keywords . '%'];
        }
        $workerid = input('workerid/d');
        if (!empty($workerid)) {
            $map[] = ['workerid', '=', $workerid];
        }
        $status = input('status/d');
        if (!empty($status)) {
            $map[] = ['status', '=', $status];
        }
        $list  = AgentModel::with(['worker', 'muser'])->where($map)->order(['priority' => 'DESC', 'id' => 'DESC'])->limit($limit)->page($page)->append(['status_text'])->select();
        $count = AgentModel::where($map)->count();
        if ($count == 0) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "未查询到数据",
            ]));
        }
        exit(json_encode([
            'code'  => 0,
            'msg'   => "",
            'count' => $count,
            'data'  => $list,
        ]));
    }


    // 申请注册经纪人
    public function fagentList()
    {
        return view('agent/fagentlist');
    }

    public function fagentForm()
    {
        $id     = input('id/d, 0');
        $fagent = AgentFormModel::findOrEmpty($id);
        return view('agent/fagentform', [
            'fagent' => $fagent,
        ]);
    }

    public function editFagent()
    {
        $id     = input('id/d');
        $fagent = AgentFormModel::findOrEmpty($id);
        $fagent->save([
            'realname'    => input('realname/s', ""),
            'mobile'      => input('mobile/s', ""),
            'address'     => input('address/s', ""),
            'idcard'      => input('idcard/s', ""),
            'recommender' => input('recommender/s', ""),
            'status'      => input('status/d', 1),
            'remark'      => input('remark/s', ""),
            'createtime'  => input('createtime/s', ""),
        ]);
        exit(json_encode([
            'code' => 0,
        ]));
    }

    public function fieldFagent()
    {
        $id   = input('id/d', 0);
        $info = AgentFormModel::findOrEmpty($id);
        if ($info->isEmpty()) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "信息不存在",
            ]));
        } else {
            $info->save([
                input('field/s') => input('value'),
            ]);
        }
        exit(json_encode([
            'code' => 0,
        ]));
    }

    public function delFagent()
    {
        $idarr  = input('idarr/a');
        $fagent = AgentFormModel::whereIn('id', $idarr)->select();
        $result = $fagent->delete();
        if ($result) {
            exit(json_encode([
                'code' => 0,
                'msg'  => "",
            ]));
        }
        exit(json_encode([
            'code' => 1,
            'msg'  => "删除失败，请稍后重试",
        ]));
    }

    public function listFagent()
    {
        $limit    = input('limit');
        $page     = input('page');
        $map      = [];
        $keywords = input('keywords/s');
        if (!empty($keywords)) {
            $map[] = ['realname|mobile', 'like', '%' . $keywords . '%'];
        }
        $status = input('status/d');
        if (!empty($status)) {
            $map[] = ['status', '=', $status];
        }
        $list  = AgentFormModel::where($map)->order('id', 'DESC')->limit($limit)->page($page)->append(['status_text'])->select();
        $count = AgentFormModel::where($map)->count();
        if ($count == 0) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "未查询到数据",
            ]));
        }
        exit(json_encode([
            'code'  => 0,
            'msg'   => "",
            'count' => $count,
            'data'  => $list,
        ]));
    }


}
