<?php

namespace app\worker\controller;

use app\worker\BaseController;
use app\common\model\Agent as AgentModel;
use app\common\model\Broker as BrokerModel;
use app\common\model\ComjobsReport as ComjobsReportModel;
use app\common\model\User as UserModel;

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

use think\facade\Db;
use think\facade\Request;

class Agent extends BaseController
{

    public function agentList()
    {
        return view('agent/agentlist');
    }

    public function agentForm()
    {
        $workerid = $this->access_worker['id'];
        $id       = input('id/d, 0');
        $agent    = AgentModel::where('workerid', '=', $workerid)->findOrEmpty($id);
        return view('agent/agentform', [
            'agent'  => $agent,
            'worker' => $this->access_worker,
        ]);
    }

    public function editAgent()
    {
        $workerid = $this->access_worker['id'];
        $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'  => $workerid,
            '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', 0),
            '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' => $workerid,
        ], ['agentid' => $agent->id]);
        exit(json_encode([
            'code' => 0,
        ]));
    }

    public function agent_join()
    {
        if (Request::isAjax()) {
            $data['realname']    = trim(input('post.realname/s'));
            $data['mobile']      = trim(input('post.mobile/s'));
            $data['address']     = trim(input('post.province/s')) . trim(input('post.city/s')) . trim(input('post.district/s')) . trim(input('post.address/s'));
            $data['idcard']      = trim(input('post.idcard/s'));
            $data['recommender'] = trim(input('post.recommender/s'));
            $data['createtime']  = time();
            $data['status']      = (int)1;

            $res = Db::name('agent_form')->insert($data);

            if ($res) {
                $rtn['code'] = 0;
                $rtn['msg']  = '您的申请已提交，请静心等待';
            } else {
                $rtn['code'] = 1;
                $rtn['msg']  = '对不起，您的申请失败，请重新申请';
            }
            return $rtn;
        } else {
            return view('agent/agent_join');
        }

    }

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

    public function delAgent()
    {
        $workerid   = $this->access_worker['id'];
        $idarr      = input('idarr/a');
        $broker_ids = BrokerModel::whereIn('agentid', $idarr)->column('id');
        if (!empty($broker_ids)) {
            BrokerModel::destroy($broker_ids,true);
            UserModel::where('brokerid', 'in', $broker_ids)->update(['brokerid' => 0]);
        }
        AgentModel::destroy(function($query)use($workerid,$idarr){
            $query->where('workerid', '=', $workerid)->whereIn('id', $idarr);
        },true);
        exit(json_encode([
            'code' => 0,
            'msg'  => "",
        ]));
    }

    public function listAgent()
    {
        $workerid = $this->access_worker['id'];
        $limit    = input('limit');
        $page     = input('page');
        $map      = [];
        $map[]    = ['workerid', '=', $workerid];
        $keywords = input('keywords/s');
        if (!empty($keywords)) {
            $map[] = ['idnumber', 'like', '%' . $keywords . '%'];
        }
        $status = input('status/d');
        if (!empty($status)) {
            $map[] = ['status', '=', $status];
        }
        $list  = AgentModel::with(['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 transferfrom()
    {
        $agent_id   = input('agent_id/d, 0');
        $agent_list = AgentModel::where('status', 1)->where('id', '<>', $agent_id)->select();
        return view('agent/transferform', [
            'origin_agent_id' => $agent_id,
            'agent_list'      => $agent_list,
        ]);
    }

    public function edittransfer()
    {
        $origin_agent_id = input('origin_agent_id/d, 0');
        $agent_id        = input('agent_id/d, 0');
        if (empty($origin_agent_id) || empty($agent_id)) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "参数错误",
            ]));
        }
        if ($origin_agent_id == $agent_id) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "不可以转移给自己",
            ]));
        }

        $origin_agent = AgentModel::where('id', $origin_agent_id)->find();
        $agent        = AgentModel::where('id', $agent_id)->find();
        if (empty($origin_agent) || empty($agent)) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "参数错误",
            ]));
        }

        BrokerModel::where('agentid', $origin_agent_id)->update(['agent_id' => $agent_id, 'workerid' => $agent['workerid']]);
        ComjobsReportModel::where('agentid', $origin_agent_id)->update(['agent_id' => $agent_id, 'workerid' => $agent['workerid']]);
        exit(json_encode([
            'code' => 0,
        ]));
    }
}
