<?php

namespace app\worker\controller;

use app\common\service\IncomeService;
use app\worker\BaseController;
use app\common\model\Agent as AgentModel;
use app\common\model\Broker as BrokerModel;
use app\common\model\User as UserModel;
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()
    {
        $workerid  = $this->access_worker['id'];
        $agentlist = AgentModel::where('workerid', '=', $workerid)->order(['id' => 'desc'])->select();
        return view('broker/brokerlist', [
            'agentlist' => $agentlist,
        ]);
    }

    public function brokerForm()
    {
        $workerid  = $this->access_worker['id'];
        $id        = input('id/d', 0);
        $broker    = BrokerModel::where('workerid', '=', $workerid)->findOrEmpty($id);
        $agentlist = AgentModel::where('workerid', '=', $workerid)->order(['id' => 'desc'])->select();
        $townlist  = file_get_contents(root_path('public/static/jscss') . 'village.json');
        return view('broker/brokerform', [
            'townlist'  => $townlist,
            'agentlist' => $agentlist,
            'broker'    => $broker,
            'worker'    => $this->access_worker,
        ]);
    }

    public function editBroker()
    {
        $workerid = $this->access_worker['id'];
        $data     = [
            'agentid'     => input('agentid/d', 0),
            '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', ""),
            'region'      => input('region/s', ""),
            'details'     => input('details/s', ""),
            'powerreport' => input('powerreport/d', 0) == 1 ? 1 : 2,
            'status'      => input('status/d', 0) == 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)) {
            $id    = input('id/d', 0);
            $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'  => "关联的用户不存在。",
                ]));
            }

            $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['createtime'] = time();
            $broker             = BrokerModel::create($data);

            event('brokerAdd', $broker);
        } else {
            $broker = BrokerModel::find($id);
            $broker->save($data);
        }
        $muser->save([
            'brokerid' => $broker->id,
        ]);
        exit(json_encode([
            'code' => 0,
        ]));
    }

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

    public function delBroker()
    {
        $workerid = $this->access_worker['id'];
        $password = input('password');
        if ($this->access_worker['password'] !== md5($password)) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "操作密码验证失败",
            ]));
        }
        $idarr      = input('idarr/a');
        $user_check = UserModel::whereIn('brokerid', $idarr)->find();
        if (!empty($user_check)) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "该经纪人还有下线，请先转移再删除",
            ]));
        }
        $broker = BrokerModel::where('workerid', '=', $workerid)->whereIn('id', $idarr)->select();
        $result = $broker->delete();
        if ($result) {
            exit(json_encode([
                'code' => 0,
                'msg'  => "",
            ]));
        }
        exit(json_encode([
            'code' => 1,
            'msg'  => "删除失败，请稍后重试",
        ]));
    }

    public function listBroker()
    {
        $workerid = $this->access_worker['id'];
        $limit    = input('limit/d', 20);
        $page     = input('page/d', 1);
        $map      = [];
        $map[]    = ['workerid', '=', $workerid];
        $keywords = input('keywords/s');
        if (!empty($keywords)) {
            $map[] = ['title', 'like', '%' . $keywords . '%'];
        }
        $status = input('status/d');
        if (!empty($status)) {
            $map[] = ['status', '=', $status];
        }
        $agentid = input('agentid/d');
        if (!empty($agentid)) {
            $map[] = ['agentid', '=', $agentid];
        }
        $list  = BrokerModel::with(['muser', 'worker', 'agent'])->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 incomeList()
    {
        $brokerid = input('brokerid');
        if (empty($brokerid)) {
            exit("未查询到数据");
        }

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

    public function listIncome()
    {
        $brokerid = input('brokerid');
        if (empty($brokerid)) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "未查询到数据",
            ]));
        }

        $limit = input('limit/d', 20);
        $page  = input('page/d', 1);
        $map   = [
            ['brokerid', '=', $brokerid],
        ];
        $list  = BrokerIncomeModel::where($map)->order('id', 'DESC')->limit($limit)->page($page)->append(['status_text', 'powerreport_text'])->select();
        $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 settleIncome()
    {
        $brokerid = input('brokerid');
        $value    = input('value');

        if (empty($brokerid) || $value <= 0) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "参数错误",
            ]));
        }

        $broker = BrokerModel::find($brokerid);
        if (empty($broker)) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "未查询到数据",
            ]));
        }
        if ($broker['income'] < $value) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "经纪人收益不足",
            ]));
        }

        $incomeService = new IncomeService();
        $incomeService->add($brokerid, -$value, '商家结算', '劳务公司与经纪人线下结算');

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