<?php

namespace app\mainapp\controller;

use app\common\model\BrokerIncome;
use app\common\service\IncomeService;
use app\mainapp\BaseController;

use app\common\model\Param as ParamModel;

use app\common\model\User as UserModel;
use app\common\model\UserFollow as UserFollowModel;
use app\common\model\Broker as BrokerModel;
use app\common\model\BrokerForm as BrokerFormModel;
use app\common\model\DemandSnatch as DemandSnatchModel;
use app\common\model\DemandReport as DemandReportModel;
use app\common\model\Agent as AgentModel;
use app\common\model\Worker as WorkerModel;

use app\common\validate\DemandReport as DemandReportValidate;
use think\exception\ValidateException;

class Broker extends BaseController
{


    public function getListBroker()
    {
        $ppage     = input('ppage/d', 1);
        $psize     = input('psize/d', 20);
        $map       = [];
        $map[]     = ['status', '=', 1];
        $searchval = input('searchval/s', "");
        if (!empty($searchval)) {
            $map[] = ['title|region', 'like', '%' . $searchval . '%'];
        }
        $district = input('district/s', "");
        if (!empty($district)) {
            $map[] = ['district', '=', $district];
        }
        $plist = BrokerModel::with(['muser'])->where($map)->order(['id' => 'desc'])->page($ppage)->limit($psize)->select();
        page_result(0, "", [
            'plist'   => $plist,
            'pstatus' => $psize > count($plist) ? 'noMore' : 'more',
        ]);
    }


    // 申请注册经纪人
    public function pageForm()
    {
        $param = ParamModel::where(1)->find();
        page_result(0, "", [
            'param' => $param,
        ]);
    }

    public function regBroker()
    {
        $realname    = input('realname/s', "");
        $mobile      = input('mobile/s', "");
        $address     = input('address/s', "");
        $idcard      = input('idcard/s', "");
        $recommender = input('recommender/s', "");
        if (empty($realname) || empty($mobile) || empty($address) || empty($idcard)) {
            page_result(1, "姓名、手机号、当前住址、身份证号均不能为空。");
        }
        $form = new BrokerFormModel;
        $form->save([
            'realname'    => $realname,
            'mobile'      => $mobile,
            'address'     => $address,
            'idcard'      => $idcard,
            'recommender' => $recommender,
            'status'      => 1,
            'remark'      => "",
            'createtime'  => time(),
        ]);
        page_result(0, "", []);
    }

    // 订单信息
    public function listOrder()
    {
        $brokerid = input('brokerid/d', 0);
        if (empty($brokerid)) {
            page_result(0, "", [
                'plist'   => [],
                'pstatus' => 'noMore',
            ]);
        }
        $broker = BrokerModel::find($brokerid);
        if (empty($broker)) {
            page_result(0, "", [
                'plist'   => [],
                'pstatus' => 'noMore',
            ]);
        }
        $workerid = $broker->workerid;
        $ppage    = input('ppage/d', 1);
        $psize    = input('psize/d', 20);
        $map      = [];
        $map[]    = ['status', '>=', 2];
        $map[]    = ['worker_id', '=', $workerid];
        $plist    = DemandSnatchModel::with(['demand' => ['worker']])->where($map)->order(['status' => 'ASC', 'id' => 'DESC'])->page($ppage)->limit($psize)->append(['status_text'])->select();
        foreach ($plist as $v) {
            $snatch_num      = DemandReportModel::where('snatchid', $v['id'])->count();
            $v['snatch_num'] = $snatch_num;
        }
        page_result(0, "", [
            'plist'   => $plist,
            'pstatus' => $psize > count($plist) ? 'noMore' : 'more',
        ]);
    }

    // 报备信息
    public function getOrder()
    {
        $id        = input('id/d', 0);
        $brokerid  = input('brokerid/d', 0);
        $order     = DemandSnatchModel::with(['demand' => ['worker']])->where(['id' => $id])->append(['status_text'])->find();
        $order_log = DemandReportModel::where('brokerid', $brokerid)->where('snatchid', $id)->select();
        page_result(0, "", [
            'order'     => $order,
            'order_log' => $order_log,
        ]);
    }

    public function addReport()
    {
        $snatchid = input('snatchid/d', 0);
        $snatch   = DemandSnatchModel::where('id', '=', $snatchid)->findOrEmpty();
        if ($snatch->isEmpty()) {
            page_result(1, "订单不存在。");
        }
        if ($snatch['status'] != 2) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "该订单暂时无法报备",
            ]));
        }
        $brokerid = input('brokerid/d', 0);
        $broker   = BrokerModel::where('id', '=', $brokerid)->findOrEmpty();
        if ($broker->isEmpty()) {
            page_result(1, "经纪人信息不存在。");
        }

        $snatch_num = DemandReportModel::where('snatchid', $snatchid)->count();
        if ($snatch_num >= $snatch['num']) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "人数已满",
            ]));
        }

        //数据检验
        $data = [
            'demandid'   => $snatch['demand_id'],
            'snatchid'   => $snatchid,
            'workerid'   => $broker['workerid'],
            'agentid'    => $broker['agentid'],
            'brokerid'   => $broker['id'],
            'realname'   => input('realname/s', ""),
            'mobile'     => input('mobile/s', ""),
            'idcard'     => input('idcard/s', ""),
            'arrivetime' => input('arrivetime/s', ""),
            'remark'     => input('remark/s', ""),
            'retremark'  => "",
            'createtime' => date("Y-m-d H:i:s"),
        ];
        try {
            validate(DemandReportValidate::class)->check($data);
        } catch (ValidateException $e) {
            page_result(1, $e->getError());
        }

        $mobile_check = DemandReportModel::where('snatchid', $snatchid)->where('mobile', $data['mobile'])->find();
        if (!empty($mobile_check)) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "该手机号已报备，请勿重复",
            ]));
        }

        $idcard_check = DemandReportModel::where('snatchid', $snatchid)->where('idcard', $data['idcard'])->find();
        if (!empty($idcard_check)) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "该身份证号已报备，请勿重复",
            ]));
        }

        DemandReportModel::create($data);
        if ($snatch_num + 1 == $snatch['num']) {
            $snatch->status == 3;
            $snatch->save();
        }
        page_result(0, "", []);
    }

    // 报备信息
    /*public function getOrder()
    {
        $orderid = input('orderid/d',0);
        $agentid = input('agentid/d',0);
        $order = ReportOrderModel::with(['reportFactory'])->where(['id'=>$orderid])->find();
        $orderlog = ReportOrderlogModel::where(['agentid'=>$agentid,'orderid'=>$orderid])->order(['id'=>"DESC"])->select();
        ReportOrderlogModel::update(['status' => 2], ['agentid'=>$agentid,'orderid'=>$orderid]);
        page_result(0, "", array(
            'order'			=> $order,
            'orderlog'		=> $orderlog
        ));
    }

    // 订单信息
    public function listOrder()
    {
        $brokerid = input('brokerid/d',0);
        $broker = BrokerModel::findOrEmpty($brokerid);
        $agentid = $broker->agentid;
        $ppage = input('ppage/d', 1);
        $psize = input('psize/d', 20);
        $map = array();
        $map[] = ['ReportOrder.status', '>', 1];
        $plist = ReportOrderModel::hasWhere('reportOrderlog',['agentid'=>$agentid])->with(['reportFactory'])->where($map)->order(['status'=>'ASC','id'=>'DESC'])->page($ppage)->limit($psize)->select()->toArray();
        foreach($plist as $key=>$val){
            $plist[$key]['log'] = ReportOrderlogModel::where(['agentid'=>$agentid,'orderid'=>$val['id']])->order(['id'=>'DESC'])->findOrEmpty()->toArray();
        }
        page_result(0, "", array(
            'plist' => $plist,
            'pstatus' => $psize > count($plist) ? 'noMore' : 'more'
            ));
    }



    // 数据信息
    public function pageBroker()
    {
        $brokerid = input('brokerid/d', 0);
        $stime = strtotime(date("Y-m-d"),time());

        $tuserCount = UserModel::where('brokerid', '=', $brokerid)->where('createtime','between',[$stime,$stime+86400])->count();
        $userCount = UserModel::where('brokerid', '=', $brokerid)->count();

        $tentryCount = ReportEntryModel::where('brokerid', '=', $brokerid)->where('createtime','between',[$stime,$stime+86400])->count();
        $entryCount = ReportEntryModel::where('brokerid', '=', $brokerid)->count();

        page_result(0, "", array('countobj' => array(
            'tuser'		=> $tuserCount,
            'user'		=> $userCount,
            'tentry'	=> $tentryCount,
            'entry'		=> $entryCount
            )));
    }

    // 报备信息
    public function getEntry()
    {
        $entryid = input('entryid/d',0);
        $brokerid = input('brokerid/d',0);
        $entry = ReportEntryModel::with(['reportFactory'])->where(['brokerid'=>$brokerid,'id'=>$entryid])->find();
        $broker = BrokerModel::with('agent')->findOrEmpty($brokerid);
        $factorylist = ReportFactoryModel::order(['priority'=>'desc','id'=>'desc'])->select()->toArray();
        $factoryidarr = ReportFactoryModel::order(['priority'=>'desc','id'=>'desc'])->column('title');
        page_result(0, "", array(
            'entry'			=> $entry,
            'broker'		=> $broker,
            'factorylist'	=> $factorylist,
            'factoryidarr'	=> array_values($factoryidarr),
            'today'			=> date("Y-m-d")
        ));
    }

    public function statusEntry()
    {
        $entryid = input('entryid/d',0);
        $brokerid = input('brokerid/d',0);
        $entry = ReportEntryModel::with(['reportFactory'])->where('brokerid','=',$brokerid)->findOrEmpty($entryid);
        if ($entry->isEmpty()){
            page_result(1, "报备信息不存在。");
        }
        if ($entry->status > 1){
            page_result(1, "报备信息已确认过。");
        }
        $entry->save(['status'=>2]);
        page_result(0, "", array(
            'entry'		=> $entry
        ));
    }

    public function deleteEntry()
    {
        $entryid = input('entryid/d',0);
        $brokerid = input('brokerid/d',0);
        $entry = ReportEntryModel::with(['reportFactory'])->where('brokerid','=',$brokerid)->findOrEmpty($entryid);
        if ($entry->isEmpty()){
            page_result(1, "报备信息不存在。");
        }
        if ($entry->status > 1){
            page_result(1, "报备信息已确认过，不能删除。");
        }
        $entry->delete();
        page_result(0, "", array());
    }

    public function addEntry()
    {
        $brokerid = input('brokerid/d',0);
        $broker = BrokerModel::with('agent')->findOrEmpty($brokerid);
        if ($broker->isEmpty()){
            page_result(1, "经纪人信息不存在。");
        }
        $data = array(
            'workerid'			=> $broker->workerid,
            'agentid'			=> $broker->agentid,
            'brokerid'			=> $brokerid,
            'factoryid'			=> input('factoryid/d', 0),
            'realname'			=> input('realname/s', ""),
            'mobile'			=> input('mobile/s', ""),
            'idcard'			=> input('idcard/s', ""),
            'gender'			=> input('gender/s', ""),
            'nation'			=> input('nation/s', ""),
            'address'			=> input('address/s', ""),
            'startdate'			=> input('startdate/s', ""),
            'enddate'			=> input('enddate/s', ""),
            'reftype'			=> input('reftype/s', ""),
            'refpolicy'			=> input('refpolicy/s', ""),
            'agentremark'		=> input('agentremark/s', ""),
            'status'			=> input('status/d', ""),
            'remark'			=> "",
            'createtime'		=> time()
        );
        $entry = new ReportEntryModel;
        $entry->save($data);
        $newentry = ReportEntryModel::with(['reportFactory'])->where('brokerid','=',$brokerid)->find($entry->id);
        page_result(0, "", array(
            'entry'		=> $newentry
        ));
    }*/

    public function setIdcard()
    {
        $picpath = input('picpath/s', "");
        $picpath = root_path() . "public" . $picpath;
        $idcard  = aliyun_ocr_idcard($picpath);
        if ($idcard == false) {
            page_result(1, "身份证信息识别失败。");
        }
        page_result(0, "", [
            'idcard' => $idcard,
        ]);
    }

    /*public function pageEntry()
    {
        $brokerid = input('brokerid/d',0);
        $statuslist = array(
            array('value'=>"", 'title'=>'状态不限'),
            array('value'=>1, 'title'=>'待确认'),
            array('value'=>2, 'title'=>'已确认'),
            array('value'=>3, 'title'=>'已入职'),
            array('value'=>4, 'title'=>'未通过')
            );
        $factorylist = ReportFactoryModel::field('id as value, title, priority')->order(['priority'=>'desc','id'=>'desc'])->select()->toArray();
        array_unshift($factorylist, array('value'=>"", 'title'=>'工厂不限'));
        page_result(0, "", array(
            'statuslist' => $statuslist,
            'factorylist' => $factorylist
            ));
    }

    public function listEntry()
    {
        $ppage = input('ppage/d', 1);
        $psize = input('psize/d', 20);
        $map = array();
        $brokerid = input('brokerid/d', 0);
        $map[] = ['brokerid', '=', $brokerid];
        $status = input('status/d', 0);
        if (!empty($status)){
            $map[] = ['status', '=', $status];
        }
        $factoryid = input('factoryid/d', 0);
        if (!empty($factoryid)){
            $map[] = ['factoryid', '=', $factoryid];
        }
        $searchval = input('searchval/s', "");
        if (!empty($searchval)){
            $map[] =['realname|mobile', 'like', '%'.$searchval.'%', 'OR'];
        }
        $plist = ReportEntryModel::with(['reportFactory'])->where($map)->order(['id'=>'desc'])->page($ppage)->limit($psize)->select();
        page_result(0, "", array(
            'plist' => $plist,
            'pstatus' => $psize > count($plist) ? 'noMore' : 'more'
            ));
    }*/


    // 我的邀请
    public function getMyuser()
    {
        $userid   = input('userid/d', 0);
        $brokerid = input('brokerid/d', 0);
        $user     = UserModel::with(['userFollow'])->where('brokerid', '=', $brokerid)->findOrEmpty($userid);
        if ($user->isEmpty()) {
            page_result(1, "用户信息不存在");
        }
        page_result(0, "", [
            'user' => $user,
        ]);
    }

    public function sendFollow()
    {
        $userid = input('userid/d', 0);
        $ftype  = input('ftype/s', "");
        $remark = input('remark/s', "");
        if (empty($remark)) {
            page_result(1, "请输入跟进的具体内容。");
        }
        $followstatus = input('followstatus/d', 1);
        UserModel::update(['followstatus' => $followstatus], ['id' => $userid]);
        $data   = [
            'userid'     => $userid,
            'ftype'      => $ftype,
            'remark'     => $remark,
            'createtime' => time(),
        ];
        $follow = new UserFollowModel;
        $follow->save($data);

        $user = UserModel::with(['userFollow'])->findOrEmpty($userid);
        page_result(0, "", [
            'user' => $user,
        ]);
    }

    public function listUser()
    {
        $ppage        = input('ppage/d', 1);
        $psize        = input('psize/d', 20);
        $map          = [];
        $brokerid     = input('brokerid/d', 0);
        $map[]        = ['brokerid', '=', $brokerid];
        $followstatus = input('followstatus/d', 0);
        if (!empty($followstatus)) {
            $map[] = ['followstatus', '=', $followstatus];
        }
        $keyword = input('keyword', '');
        if (!empty($keyword)) {
            $map[] = ['nickname|mobile', 'like', "%{$keyword}%"];
        }
        $plist = UserModel::with(['userFollow'])->where($map)->order(['id' => 'desc'])->page($ppage)->limit($psize)->select();
        page_result(0, "", [
            'plist'   => $plist,
            'pstatus' => $psize > count($plist) ? 'noMore' : 'more',
        ]);
    }


    /**
     * 获取收益列表
     */
    public function getIncome()
    {
        $ppage    = input('ppage/d', 1);
        $psize    = input('psize/d', 20);
        $brokerid = input('brokerid/d', 0);
        if ($brokerid != 0) {
            $map[] = ['brokerid', '=', $brokerid];
        }
        $plist = BrokerIncome::where($map)
            ->order(['id' => 'desc'])
            ->page($ppage)
            ->limit($psize)
            ->append(['status_text'])
            ->select();
        page_result(0, "", [
            'plist'   => $plist,
            'pstatus' => $psize > count($plist) ? 'noMore' : 'more',
        ]);
    }

    public function brokerIncome()
    {
        $brokerid = input('brokerid/d', 0);
        $broker   = BrokerModel::findOrEmpty($brokerid);
        if ($broker->isEmpty()) {
            page_result(1, "用户信息不存在。");
        }
        $month_time   = date('Ym', strtotime('-1 month'));
        $month_income = BrokerIncome::where(['monthtime' => $month_time, 'brokerid' => $brokerid])->sum('value');
        page_result(0, "", [
            'broker'       => $broker,
            'month_income' => $month_income,
        ]);
    }

    public function cash()
    {
        $brokerid = input('brokerid/d', 0);
        $value    = input('value/d', 0);
        $broker   = BrokerModel::findOrEmpty($brokerid);
        if ($broker->isEmpty()) {
            page_result(1, "用户信息不存在。");
        }
        $agent = AgentModel::findOrEmpty($broker['agentid']);
        if ($agent['is_settle'] == 1) {
            page_result(1, "请线下与门店结算。");
        }
        if ($value <= 0) {
            page_result(1, "提现金额必须大于0。");
        }
        if ($value > $broker['income']) {
            page_result(1, "收益不足。");
        }

        $service = new IncomeService();
        $service->add($brokerid, -$value, '经纪人发起提现', '', 2);

        page_result();
    }

    public function agent()
    {
        $agentid = input('agentid/d', 0);
        $agent   = AgentModel::findOrEmpty($agentid);

        page_result(0, '', $agent);
    }

    public function center()
    {
        $brokerid = input('brokerid/d', 0);
        empty($brokerid) && page_result(1, "用户不存在。");

        $broker = BrokerModel::find($brokerid);
        empty($broker) && page_result(1, "用户不存在。");

        $user_ids     = UserModel::where('brokerid', $brokerid)->column('id');
        $worker_count = WorkerModel::where('userid', 'in', $user_ids)->where('status', 5)->count();

        $statistics = [
            'income_total' => $broker['income_total'],
            'income'       => $broker['income'],
            'user'         => count($user_ids),
            'worker'       => $worker_count,
        ];

        page_result(0, '', $statistics);
    }

    public function listWorker()
    {
        $ppage    = input('ppage/d', 1);
        $psize    = input('psize/d', 20);
        $map      = [];
        $brokerid = input('brokerid/d', 0);
        $user_ids = UserModel::where('brokerid', $brokerid)->column('id');
        if (empty($user_ids)) {
            page_result(0, "", [
                'plist'   => [],
                'pstatus' => 'noMore',
            ]);
        }

        $map[]   = ['userid', 'in', $user_ids];
        $map[]   = ['status', '=', 5];
        $keyword = input('keyword', '');
        if (!empty($keyword)) {
            $map[] = ['title|mobile', 'like', "%{$keyword}%"];
        }
        $plist = WorkerModel::where($map)->page($ppage)->limit($psize)->select();
        page_result(0, "", [
            'plist'   => $plist,
            'pstatus' => $psize > count($plist) ? 'noMore' : 'more',
        ]);
    }

    public function apply()
    {
        $data = input('param.');

        $broker = BrokerModel::where('userid', $data['userid'])->find();
        if (!empty($broker)) {
            page_result(1, "您已经是经纪人了！", $data);
        }

        $check = BrokerFormModel::where('userid', $data['userid'])->find();
        if (!empty($check)) {
            page_result(1, "请勿重复申请", $data);
        }

        $data['province']   = '福建省';
        $data['city']       = '泉州市';
        $data['district']   = '晋江市';
        $data['createtime'] = time();
        BrokerFormModel::create($data);
        page_result();
    }
}