<?php

namespace app\worker\controller;

use app\common\model\ComjobsCate;
use app\common\model\RensheCode;
use app\common\model\UserTags;
use app\common\model\UserWill;
use app\common\model\WorkerGroup;
use think\facade\Session;
use app\worker\BaseController;
use app\common\model\User as UserModel;
use app\common\model\UserAuths as UserAuthsModel;
use app\common\model\UserFollow as UserFollowModel;
use app\common\model\UserGroups as UserGroupsModel;
use app\common\model\Agent as AgentModel;
use app\common\model\Broker as BrokerModel;

use app\common\validate\User as UserValidate;
use think\exception\ValidateException;

use PHPExcel_IOFactory;
use PHPExcel;

class User extends BaseController
{

    // 用户跟进记录
    public function follow()
    {
        $userid     = input('userid/d');
        $user       = UserModel::findOrEmpty($userid);
        $followlist = UserFollowModel::where('userid', $userid)->order('id', 'desc')->limit(100)->select();
        return view('user/follow', [
            'user'       => $user,
            'followlist' => $followlist,
        ]);
    }

    public function editFollow()
    {
        $userid = input('userid/d', 0);
        $user   = UserModel::findOrEmpty($userid);
        if ($user->isEmpty()) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "用户信息不存在。",
            ]));
        }
        $worker = $this->access_worker;
        $broker = BrokerModel::where('workerid', '=', $worker['id'])->findOrEmpty($user->brokerid);
        if ($broker->isEmpty()) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "你无权限上报该用户跟进记录。",
            ]));
        }
        UserFollowModel::create([
            'userid'     => $userid,
            'ftype'      => input('ftype/s', ""),
            'remark'     => input('remark/s', ""),
            'createtime' => time(),
        ]);
        $followstatus = input('followstatus/d', 1);
        $user->save([
            'followstatus' => $followstatus,
        ]);
        exit(json_encode([
            'code' => 0,
        ]));
    }


    // 用户授权
    public function authsList()
    {
        $userid = input('userid/d');
        return view('user/authslist', [
            'userid' => $userid,
        ]);
    }

    public function listAuths()
    {
        $userid = input('userid/d');
        $list   = UserAuthsModel::where('userid', $userid)->order('id', 'asc')->append(['identitytype_text'])->select();
        $count  = UserAuthsModel::where('userid', $userid)->count();
        if ($count == 0) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "未查询到数据",
            ]));
        }
        exit(json_encode([
            'code'  => 0,
            'msg'   => "",
            'count' => $count,
            'data'  => $list,
        ]));
    }

    public function delAuths()
    {
        $id    = input('id/d');
        $auths = UserAuthsModel::find($id);
        if ($auths->identitytype == 'mobile') {
            exit(json_encode([
                'code' => 1,
                'msg'  => "手机号授权方式不允许删除",
            ]));
        }
        $result = $auths->delete();
        if ($result) {
            exit(json_encode([
                'code' => 0,
            ]));
        }
        exit(json_encode([
            'code' => 1,
            'msg'  => "删除失败，请稍后重试",
        ]));
    }

    // 用户
    public function userList()
    {
        $workerid   = $this->access_worker['id'];
        $groupslist = UserGroupsModel::order(['isdefault' => 'desc', 'id' => 'asc'])->select();
        $agentlist  = AgentModel::with('broker')->where('workerid', '=', $workerid)->order(['id' => 'desc'])->select();
        $grouplist  = WorkerGroup::where('workerid', $workerid)->select();
        return view('user/userlist', [
            'grouplist'  => $grouplist,
            'groupslist' => $groupslist,
            'agentlist'  => $agentlist,
        ]);
    }

    public function userForm()
    {
        $workerid  = $this->access_worker['id'];
        $agentlist = AgentModel::with('broker')->where('workerid', '=', $workerid)->order(['id' => 'desc'])->select();
        if (empty($agentlist)) {
            return '没有权限';
        }
        $agentidarr = $agentlist->column('id');
        $brokerlist = BrokerModel::whereIn('agentid', $agentidarr)->select();
        if (empty($brokerlist)) {
            return '没有权限';
        }
        $id            = input('id/d', 0);
        $brokeridarr   = $brokerlist->column('id');
        $user          = UserModel::whereIn('brokerid', $brokeridarr)->findOrEmpty($id);
        $groupslist    = UserGroupsModel::order(['isdefault' => 'desc', 'id' => 'asc'])->select();
        $willlist      = UserWill::select();
        $usertags      = UserTags::select();
        $emptimelist   = RensheCode::getList('emp_time');
        $communitylist = RensheCode::getList('community')->toArray();
        $grouplist     = WorkerGroup::where('workerid', $workerid)->select();
        array_push($communitylist, ['code' => 0, 'id' => 0, 'name' => "不限"]);
        $comlist = ComjobsCate::select();
        return view('user/userform', [
            'brokerlist'    => $brokerlist,
            'agentlist'     => $agentlist,
            'groupslist'    => $groupslist,
            'user'          => $user,
            'willlist'      => $willlist,
            'usertags'      => $usertags,
            'emptimelist'   => $emptimelist,
            'communitylist' => $communitylist,
            'comlist'       => $comlist,
            'grouplist'     => $grouplist,
        ]);
    }

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

    public function listUser()
    {
        $workerid    = $this->access_worker['id'];
        $limit       = input('limit');
        $page        = input('page');
        $map         = [];
        $brokeridarr = BrokerModel::where('workerid', '=', $workerid)->column('id');
        $map[]       = ['brokerid', 'in', $brokeridarr];
        $map[]       = ['brokerid', '<>', 0];
        $keywords    = input('keywords/s');
        if (!empty($keywords)) {
            $map[] = ['nickname|realname', 'like', '%' . $keywords . '%', 'or'];
        }
        $agentid = input('agentid/d');
        if (!empty($agentid)) {
            $brokeridarr = BrokerModel::where('agentid', '=', $agentid)->column('id');
            $map[]       = ['brokerid', 'in', $brokeridarr];
        }
        $status = input('status/d');
        if (!empty($status)) {
            $map[] = ['status', '=', $status];
        }
        $groupsid = input('groupsid/d');
        if (!empty($groupsid)) {
            $map[] = ['groupsid', '=', $groupsid];
        }
        $groupid = input('groupid/d');
        if (!empty($groupid)) {
            $map[] = ['groupid', '=', $groupid];
        }
        $list  = UserModel::with(['userGroups', 'workerGroup', 'broker' => ['agent', 'worker']])->where($map)->order('id', 'desc')->limit($limit)->page($page)->append(['status_text', 'isvip_text', 'authstatus_text', 'followstatus_text'])->select();
        $count = UserModel::where($map)->count();
        if ($count == 0) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "未查询到数据",
            ]));
        }
        exit(json_encode([
            'code'  => 0,
            'msg'   => "",
            'count' => $count,
            'data'  => $list,
        ]));
    }


    public function exportUser()
    {
        $workerid    = $this->access_worker['id'];
        $map         = [];
        $brokeridarr = BrokerModel::where('workerid', '=', $workerid)->column('id');
        $map[]       = ['brokerid', 'in', $brokeridarr];
        $map[]       = ['brokerid', '<>', 0];
        $keywords    = input('keywords/s');
        if (!empty($keywords)) {
            $map[] = ['nickname|realname', 'like', '%' . $keywords . '%', 'or'];
        }
        $agentbrokerarr = explode(",", input('agentbroker/s'));
        $agentid        = isset($agentbrokerarr[0]) ? $agentbrokerarr[0] : 0;
        if (!empty($agentid)) {
            $brokeridarr = BrokerModel::where('agentid', '=', $agentid)->column('id');
            $map[]       = ['brokerid', 'in', $brokeridarr];
        }
        $brokerid = isset($agentbrokerarr[1]) ? $agentbrokerarr[1] : 0;
        if (!empty($brokerid)) {
            $map[] = ['brokerid', '=', $brokerid];
        }
        $status = input('status/d');
        if (!empty($status)) {
            $map[] = ['status', '=', $status];
        }
        $authstatus = input('authstatus/d');
        if (!empty($authstatus)) {
            $map[] = ['authstatus', '=', $authstatus];
        }
        $followstatus = input('followstatus/d');
        if (!empty($followstatus)) {
            $map[] = ['followstatus', '=', $followstatus];
        }
        $xlsData = UserModel::with(['userGroups', 'broker' => ['agent', 'worker']])->where($map)->order('id', 'desc')->select()->append(['status_text', 'isvip_text', 'authstatus_text', 'followstatus_text'])->toArray();
        $xlsCell = [
            ['id', '表ID'],
            ['nickname', '昵称'],
            ['realname', '姓名'],
            ['mobile', '手机号'],
            ['integral', '可用积分'],
            ['inttotal', '累计积分'],
            ['status_text', '状态'],
            ['isvip_text', '是否VIP'],
            ['authstatus_text', '是否实名认证'],
            ['idcard', '身份证号'],
            ['gender', '性别', [1 => '男', 2 => '女']],
            ['birthday', '出生日期'],
            ['address', '现居住地'],
            ['education', '学历'],
            ['bankcard.openbank', '开户行'],
            ['bankcard.account', '账户名'],
            ['bankcard.number', '账户号'],
            ['followstatus_text', '跟进状态'],
            ['userGroups.title', '用户组'],
            ['broker.agent.title', '代理门店'],
            ['broker.title', '经纪人'],
            ['createtime', '注册时间'],
        ];
        export_excel("系统用户", $xlsCell, $xlsData);
    }

    public function editUser()
    {
        $id     = input('id/d');
        $mobile = input('mobile/s');
        $vdata  = [
            'id'     => $id,
            'mobile' => $mobile,
        ];
        try {
            validate(UserValidate::class)->check($vdata);
        } catch (ValidateException $e) {
            exit(json_encode([
                'code' => 1,
                'msg'  => $e->getError(),
            ]));
        }
        $agentbrokerarr = explode(",", input('agentbroker/s'));
        $brokerid       = isset($agentbrokerarr[1]) ? $agentbrokerarr[1] : 0;
        $data           = [
            'groupsid'       => input('groupsid/d', 0),
            'groupid'        => input('groupid/d', 0),
            'brokerid'       => $brokerid,
            'nickname'       => input('nickname/s', ""),
            'avatar'         => input('avatar/s', ""),
            'realname'       => input('realname/s', ""),
            'mobile'         => $mobile,
            'status'         => input('status/d', 1),
            'isvip'          => input('isvip/d', 1),
            'authstatus'     => input('authstatus/d', 1),
            'authremark'     => input('authremark/s', ""),
            'idcardzpic'     => input('idcardzpic/s', ""),
            'idcardfpic'     => input('idcardfpic/s', ""),
            'idcard'         => input('idcard/s', ""),
            'gender'         => input('gender/d', 1),
            'birthday'       => input('birthday/s', ""),
            'address'        => input('address/s', ""),
            'education'      => input('education/s', ""),
            'jobintention'   => input('jobintention/s', ""),
            'workexperience' => input('workexperience/s', ""),
            'eduexperience'  => input('eduexperience/s', ""),
            'followstatus'   => input('followstatus/d', 1),
            'bankcard'       => input('bankcard/a', []),
            'emp_time'       => array_values(input('emp_time/a', [])),
            'user_tags'      => array_values(input('user_tags/a', [])),
            'work_place'     => array_values(input('work_place/a', [])),
            'com_cate_type'  => input('com_cate_type/d', 1),
            'com_cate'       => array_values(input('com_cate/a', [])),
            'com_cate_other' => input('com_cate_other/s', ""),
            'skill_cert'     => array_values(input('skill_cert/a', [])),
        ];
        $password       = input('password/s');
        if (empty($id)) {
            $data['integral']   = 0;
            $data['inttotal']   = 0;
            $data['createtime'] = time();
            $user               = UserModel::create($data);
            UserAuthsModel::create([
                'userid'       => $user->id,
                'identitytype' => "mobile",
                'identifier'   => $mobile,
                'password'     => empty($password) ? md5("123456789") : md5($password),
                'logintime'    => time(),
                'loginip'      => $_SERVER['SERVER_ADDR'],
                'wxampcode'    => "",
            ]);
        } else {
            $data['id'] = $id;
            UserModel::update($data);
            $adata = ['identifier' => $mobile];
            if (!empty($password)) {
                $adata['password'] = md5($password);
            }
            UserAuthsModel::update($adata, ['userid' => $id, 'identitytype' => 'mobile']);
        }
        exit(json_encode([
            'code' => 0,
        ]));
    }


}