<?php

namespace app\admin\controller;

use app\admin\BaseController;
use app\common\model\ResidentLog as ResidentLogModel;
use app\common\model\User as UserModel;
use app\common\model\Worker as WorkerModel;
use app\common\model\Broker as BrokerModel;
use app\common\model\Resident as ResidentModel;

use app\common\validate\Resident as ResidentValidate;
use think\exception\ValidateException;

class Resident extends BaseController
{

    public function residentlist()
    {
        $workerlist = WorkerModel::order(['id' => 'desc'])->select();
        return view('resident/residentlist', [
            'workerlist' => $workerlist,
        ]);
    }

    public function residentForm()
    {
        $id       = input('id/d, 0');
        $resident = ResidentModel::findOrEmpty($id);
        return view('resident/residentform', [
            'resident' => $resident,
        ]);
    }

    public function editresident()
    {
        $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', ""),
            'details'  => input('details/s', ""),
            'status'   => input('status/d') == 1 ? 1 : 2,
        ];
        if (empty($id)) {
            $vdata = [
                'id'     => $id,
                'mobile' => input('mobile/s'),
            ];
            try {
                validate(ResidentValidate::class)->check($vdata);
            } catch (ValidateException $e) {
                exit(json_encode([
                    'code' => 1,
                    'msg'  => $e->getError(),
                ]));
            }

            $user = UserModel::where(['mobile' => input('usermobile/s', '')])->findOrEmpty();
            if ($user->isEmpty()) {
                exit(json_encode([
                    'code' => 1,
                    'msg'  => "关联的用户不存在。",
                ]));
            }
            $broker = BrokerModel::where('userid', $user['id'])->findOrEmpty();
            if (empty($broker)) {
                exit(json_encode([
                    'code' => 1,
                    'msg'  => "只有经纪人才能关联。",
                ]));
            }

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

            $data['userid']     = $user->id;
            $data['workerid']   = $broker['workerid'];
            $data['agentid']    = $broker['agentid'];
            $data['createtime'] = time();
            ResidentModel::create($data);
        } else {
            $resident = ResidentModel::find($id);
            $resident->save($data);
        }

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

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

    public function delresident()
    {
        $access_admin = session('access_admin');
        $password     = input('password');
        if ($access_admin['password'] !== md5($password)) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "操作密码验证失败",
            ]));
        }
        $idarr  = input('idarr/a');
        $result = ResidentModel::whereIn('id', $idarr)->delete();
        if ($result) {
            exit(json_encode([
                'code' => 0,
                'msg'  => "",
            ]));
        }
        exit(json_encode([
            'code' => 1,
            'msg'  => "删除失败，请稍后重试",
        ]));
    }

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

    // 用户跟进记录
    public function follow()
    {
        return view('resident/follow');
    }

    public function listfollow()
    {
        $limit  = input('limit/d', 20);
        $page   = input('page/d', 1);
        $map    = [];
        $mobile = input('mobile/s');
        if (!empty($mobile)) {
            $resident = ResidentModel::where('mobile',$mobile)->findOrEmpty();
            if (empty($resident)) {
                $map[] = ['id','=',0];
            } else {
                $map[] = ['residentid', '=', $resident['id']];
            }
        }
        $list  = ResidentLogModel::with(['resident', 'worker'])->where($map)->order('createtime', 'DESC')->limit($limit)->page($page)->select();
        $count = ResidentLogModel::where($map)->count();
        if ($count == 0) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "未查询到数据",
            ]));
        }
        exit(json_encode([
            'code'  => 0,
            'msg'   => "",
            'count' => $count,
            'data'  => $list,
        ]));
    }
}
