<?php

namespace app\admin\controller;

use app\admin\BaseController;
use app\common\model\Config;
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\Broker as BrokerModel;
use app\common\model\Resident as ResidentModel;
use app\common\model\BrokerForm as BrokerFormModel;
use app\common\model\BrokerIncome as BrokerIncomeModel;

use app\common\validate\Broker as BrokerValidate;
use think\exception\ValidateException;

class Broker extends BaseController
{

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

    public function brokerForm()
    {
        $id         = input('id/d, 0');
        $broker     = BrokerModel::findOrEmpty($id);
        $workerlist = WorkerModel::with(['agent', 'muser'])->order(['id' => 'desc'])->select();
        $townlist   = file_get_contents(root_path('public/static/jscss') . 'village.json');
        return view('broker/brokerform', [
            'townlist'   => $townlist,
            'workerlist' => $workerlist,
            'broker'     => $broker,
        ]);
    }

    public function editBroker()
    {
        $id          = input('id/d');
        $data        = [
            'title'       => input('title/s', ""),
            'mobile'      => input('mobile/s', ""),
            'weixin'      => input('weixin/s', ""),
            'qq'          => input('qq/s', ""),
            'province'    => input('province/s', ""),
            'city'        => input('city/s', ""),
            'district'    => input('district/s', ""),
            'town'        => input('town/s', ""),
            'details'     => input('details/s', ""),
            'powerreport' => input('powerreport/d') == 1 ? 1 : 2,
            'status'      => input('status/d') == 1 ? 1 : 2,
        ];

        //镇街
        $townvillage = input('townvillage');
        if (empty($townvillage)) {
            exit(json_encode([
                'code' => 1,
                'msg'  => '请选择镇街',
            ]));
        }
        $townvillage     = explode(',', $townvillage);
        $data['town']    = $townvillage[0];
        $data['village'] = $townvillage[1];

        if (empty($id)) {
            $vdata = [
                'id'     => $id,
                'mobile' => input('mobile/s'),
            ];
            try {
                validate(BrokerValidate::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'  => "关联的用户不存在。",
                ]));
            }
            $workeragentarr = explode(",", input('workeragent/s'));
            $workerid       = isset($workeragentarr[0]) ? $workeragentarr[0] : 0;
            $agentid        = isset($workeragentarr[1]) ? $workeragentarr[1] : 0;
            if (empty($workerid) || empty($agentid)) {
                exit(json_encode([
                    'code' => 1,
                    'msg'  => "请选择劳务公司和代理门店。",
                ]));
            }

            $broker_user = BrokerModel::where('userid', $muser->id)->find();
            if (!empty($broker_user)) {
                exit(json_encode([
                    'code' => 1,
                    'msg'  => "该用户已是经纪人。",
                ]));
            }

            $data['userid']     = $muser->id;
            $data['workerid']   = $workerid;
            $data['agentid']    = $agentid;
            $data['createtime'] = time();
            $broker             = BrokerModel::create($data);

            event('brokerAdd', $broker);
        } else {
            $broker = BrokerModel::find($id);
            $broker->save($data);
        }

        exit(json_encode([
            'code' => 0,
        ]));
    }

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

    public function delBroker()
    {
        $access_admin = session('access_admin');
        $password     = input('password');
        if ($access_admin['password'] !== md5($password)) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "操作密码验证失败",
            ]));
        }
        $idarr      = input('idarr/a');
        $user_check = UserModel::whereIn('brokerid', $idarr)->findOrEmpty();
        if (!empty($user_check)) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "该经纪人还有下线，请先转移再删除",
            ]));
        }
        $user_ids       = BrokerModel::whereIn('id', $idarr)->column('userid');
        $resident_check = ResidentModel::whereIn('userid', $user_ids)->findOrEmpty();
        if (empty($resident_check)) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "该经纪人是驻场老师，请取消驻场老师资格",
            ]));
        }

        $result = BrokerModel::whereIn('id', $idarr)->delete();
        if ($result) {
            exit(json_encode([
                'code' => 0,
                'msg'  => "",
            ]));
        }
        exit(json_encode([
            'code' => 1,
            'msg'  => "删除失败，请稍后重试",
        ]));
    }

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


    // 申请注册经纪人
    public function fbrokerList()
    {
        return view('broker/fbrokerlist');
    }

    public function fbrokerForm()
    {
        $id      = input('id/d, 0');
        $fbroker = BrokerFormModel::findOrEmpty($id);
        return view('broker/fbrokerform', [
            'fbroker' => $fbroker,
        ]);
    }

    public function editFbroker()
    {
        $id      = input('id/d');
        $fbroker = BrokerFormModel::findOrEmpty($id);
        $fbroker->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 fieldFbroker()
    {
        $id   = input('id/d', 0);
        $info = BrokerFormModel::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 delFbroker()
    {
        $idarr   = input('idarr/a');
        $fbroker = BrokerFormModel::whereIn('id', $idarr)->select();
        $result  = $fbroker->delete();
        if ($result) {
            exit(json_encode([
                'code' => 0,
                'msg'  => "",
            ]));
        }
        exit(json_encode([
            'code' => 1,
            'msg'  => "删除失败，请稍后重试",
        ]));
    }

    public function listFbroker()
    {
        $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  = BrokerFormModel::where($map)->order('id', 'DESC')->limit($limit)->page($page)->append(['status_text', 'powerreport_text'])->select();
        $count = BrokerFormModel::where($map)->count();
        if ($count == 0) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "未查询到数据",
            ]));
        }
        exit(json_encode([
            'code'  => 0,
            'msg'   => "",
            'count' => $count,
            'data'  => $list,
        ]));
    }

    public function brokerdefault()
    {
        $broker_id = Config::getConfigValue("default_broker");
        $broker    = [];
        if (!empty($broker_id)) {
            $broker = BrokerModel::where('id', $broker_id)->find();
        }

        return view('broker/brokerdefault', [
            'broker' => $broker,
        ]);
    }

    public function brokerajax()
    {
        $keyword = input('keyword');
        $list    = BrokerModel::where('title|mobile', 'like', "%{$keyword}%")->limit(10)->select();
        exit(json_encode([
            'code' => 0,
            'msg'  => "",
            'data' => $list,
        ]));
    }

    public function editdefault()
    {
        $brokerid = input('brokerid/d', 0);
        if (empty($brokerid)) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "请选择经纪人",
            ]));
        }

        Config::setConfigValue('default_broker', $brokerid);
        exit(json_encode(['code' => 0]));
    }

    public function cashList()
    {
        return view('broker/cashlist');
    }

    public function listCash()
    {
        $limit  = input('limit/d', 20);
        $page   = input('page/d', 1);
        $map    = [
            ['type', '=', 2],
        ];
        $status = input('status/d');
        if (!empty($status)) {
            $map[] = ['status', '=', $status];
        }
        $list = BrokerIncomeModel::with(['broker'])->where($map)->order('status', 'ASC')->limit($limit)->page($page)->append(['status_text'])->select();
        foreach ($list as $v) {
            $v['value'] = abs($v['value']);
        }
        $count = BrokerIncomeModel::where($map)->count();
        if ($count == 0) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "未查询到数据",
            ]));
        }
        exit(json_encode([
            'code'  => 0,
            'msg'   => "",
            'count' => $count,
            'data'  => $list,
        ]));
    }

    public function examineCash()
    {
        $id     = input('id/d', 0);
        $income = BrokerIncomeModel::findOrEmpty($id);
        if ($income->isEmpty()) {
            exit('未查询到数据');
        }
        if ($income->status != 1) {
            exit('该记录无需审核');
        }

        return view('broker/examinecash', [
            'id' => $id,
        ]);
    }

    public function cashExamine()
    {
        $id     = input('id/d', 0);
        $income = BrokerIncomeModel::findOrEmpty($id);
        if ($income->isEmpty()) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "未查询到数据",
            ]));
        }

        //更改状态
        $status = input('status/d', 0);
        if (empty($status)) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "请选择状态",
            ]));
        }
        $remark         = input('remark', '');
        $income->status = $status;
        $income->remark = $remark;
        $income->save();

        //审核失败，退钱
        if ($status == 3) {
            $broker         = BrokerModel::where('id', $income['brokerid'])->find();
            $broker->income += abs($income['value']);
            $broker->save();
        }

        exit(json_encode([
            'code' => 0,
        ]));
    }

    public function applyList()
    {
        return view('broker/applylist');
    }

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

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

    public function statusApply()
    {
        $id      = input('id');
        $status  = input('status', 1);
        $fbroker = BrokerFormModel::where('id', $id)->find();
        if ($fbroker['status'] != 1) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "请不要重复审核",
            ]));
        }

        $fbroker->status = $status;
        $fbroker->save();

        if ($status == 2) {
            $broker_user = BrokerModel::where('userid', $fbroker['userid'])->find();
            if (!empty($broker_user)) {
                exit(json_encode([
                    'code' => 0,
                    'msg'  => "",
                ]));
            }

            $data['userid']     = $fbroker['userid'];
            $data['workerid']   = $fbroker['workerid'];
            $data['agentid']    = $fbroker['agentid'];
            $data['title']      = $fbroker['title'];
            $data['avatar']     = $fbroker['avatar'];
            $data['mobile']     = $fbroker['mobile'];
            $data['province']   = $fbroker['province'];
            $data['city']       = $fbroker['city'];
            $data['town']       = $fbroker['town'];
            $data['village']    = $fbroker['village'];
            $data['district']   = $fbroker['district'];
            $data['region']     = $fbroker['region'];
            $data['createtime'] = time();
            $broker             = BrokerModel::create($data);

            event('brokerAdd', $broker);
        }

        exit(json_encode([
            'code' => 0,
            'msg'  => "",
        ]));
    }
}
