<?php

namespace app\agent\controller;

use app\agent\BaseController;
use app\common\model\UserPart as UserPartModel;
use app\common\model\Broker as BrokerModel;
use app\common\model\User as UserModel;
use app\common\model\BrokerIncome as BrokerIncomeModel;

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

class Broker extends BaseController
{

    public function brokerList()
    {
        $agent = $this->access_agent;
        return view('broker/brokerlist', [
            'agent' => $agent,
        ]);
    }

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

    public function editBroker()
    {
        $agent = $this->access_agent;
        $data  = [
            'workerid'    => $agent['workerid'],
            'agentid'     => $agent['id'],
            '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') == 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');
            $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['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()
    {
        $idarr      = input('idarr/a');
        $user_check = UserModel::whereIn('brokerid', $idarr)->find();
        if (!empty($user_check)) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "该经纪人还有下线，请先转移再删除",
            ]));
        }
        $broker = BrokerModel::whereIn('id', $idarr)->select();
        $result = $broker->delete();
        if ($result) {
            exit(json_encode([
                'code' => 0,
                'msg'  => "",
            ]));
        }
        exit(json_encode([
            'code' => 1,
            'msg'  => "删除失败，请稍后重试",
        ]));
    }

    public function listBroker()
    {
        $agentid  = $this->access_agent['id'];
        $limit    = input('limit/d', 20);
        $page     = input('page/d', 1);
        $map      = [];
        $map[]    = ['agentid', '=', $agentid];
        $keywords = input('keywords/s');
        if (!empty($keywords)) {
            $map[] = ['title', 'like', '%' . $keywords . '%'];
        }
        $status = input('status/d');
        if (!empty($status)) {
            $map[] = ['status', '=', $status];
        }
        $list  = BrokerModel::with(['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 transferFrom()
    {
        $broker_id   = input('broker_id/d, 0');
        $agentid     = $this->access_agent['id'];
        $broker_list = BrokerModel::where('agentid', $agentid)->where('id', '<>', $broker_id)->select();
        return view('broker/transferform', [
            'origin_broker_id' => $broker_id,
            'broker_list'      => $broker_list,
        ]);
    }

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

        $origin_broker = BrokerModel::where('id', $origin_broker_id)->find();
        $broker        = BrokerModel::where('id', $broker_id)->find();
        if (empty($origin_broker) || empty($broker)) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "参数错误",
            ]));
        }
        if ($origin_broker['agentid'] != $broker['agentid']) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "只有相同门店的经纪人才可以转移",
            ]));
        }

        UserModel::where('brokerid', $origin_broker_id)->update(['brokerid' => $broker_id]);
        UserPartModel::where('puserid', $origin_broker['userid'])->update(['puserid' => $broker['userid']]);
        exit(json_encode([
            'code' => 0,
        ]));
    }

    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'  => "",
        ]));
    }
}
