Staff.php 35.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
<?php

namespace addons\qingdong\controller;


use addons\qingdong\model\AttendanceStatisc;
use addons\qingdong\model\Attendance;
use addons\qingdong\model\Contacts;
use addons\qingdong\model\Contract;
use addons\qingdong\model\Customer;
use addons\qingdong\model\Flow;
use addons\qingdong\model\Leads;
use addons\qingdong\model\Receivables;
use addons\qingdong\model\Remind;
use addons\qingdong\model\Staff as StaffModel;
use app\admin\model\qingdong\customer\Mainbody;
use addons\qingdong\model\StaffDepartment;
use addons\qingdong\library\Wechat;
use addons\qingdong\model\Achievement;
use addons\qingdong\model\Record;
use addons\qingdong\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use fast\Http;
use think\Db;
use think\Exception;
use think\Log;
use think\Validate;

/**
 *  * 操作文档:https://doc.fastadmin.net/qingdong
 * 软件介绍:https://www.fastadmin.net/store/qingdong.html
 * 售后微信:qingdong_crm
 * 员工登录 注册接口
 */
class Staff extends StaffApi
{
    protected $noNeedLogin = ['test', 'wxLogin', 'login','logintest','register','listStaff','addTime','listStaff2','detailStaff','getDepartment','getDepartment2','getDepartment3','getStaff102'];
    protected $noNeedRight = ['getInfo', 'editInfo', "use_phone"];


    public function _initialize()
    {
        parent::_initialize();
    }

    //是否登录
    public function isLogin()
    {
        $this->success('已登录', ['userinfo' => $this->auth->getUserinfo()]);
    }


    public function getStaff102(){
        
        $groupIds = \addons\qingdong\model\Staff::getLowerId(102, true);
        $uids = AuthGroupAccess::where(['group_id' => ['in', $groupIds]])->column('uid');
        $ids = StaffModel::where('admin_id','in',$uids)->column('id');
        $this->success('重庆公司的人员id',$ids);
    }


    public function addTime(){

            $param = $this->request->param();

            $startTime= strtotime($param['startTime']);
            $endTime= strtotime($param['endTime']);

            $statisc = (new AttendanceStatisc())->where('staff_id',$param['employeeId'])->where('time',date('Y-m-d',$startTime))->find();

            $data = [
                'clock_in'=>date('Y-m-d H:i:s',$startTime),
                'clock_in_status'=>'0',
                'late_time'=>'0',
                'clock_out'=>date('Y-m-d H:i:s',$endTime),
                'clock_out_status'=>'0',
                'leaver_time'=>'0',
            ];

            $statisc->save($data);

            $staff = StaffModel::where(['id' => $param['employeeId']])->with(['department', 'parent'])->find();

		  (new Attendance())->where('statisc_id',$statisc['id'])->delete();
            $data2 = [
                [
                'staff_id'=>$param['employeeId'],
                'nickname'=>$staff['openid'],
                'statisc_id'=>$statisc['id'],
                'type'=>'0',
                'time'=>date('Y-m-d H:i:s',$startTime),
                'address'=>'汇锦广场A座',
                'lng'=>'104.05304714627',
                'lat'=>'30.557355143229',
                'createtime'=>$startTime,
                'updatetime'=>$startTime,
                ],
                [
                    'staff_id'=>$param['employeeId'],
                    'nickname'=>$staff['openid'],
                    'statisc_id'=>$statisc['id'],
                    'type'=>'0',
                    'time'=>date('Y-m-d H:i:s',$endTime),
                    'address'=>'汇锦广场A座',
                    'lng'=>'104.05304714627',
                    'lat'=>'30.557355143229',
                    'createtime'=>$endTime,
                    'updatetime'=>$endTime,

                ]
            ];

            (new Attendance())->insertAll($data2);

            $this->success();

        }


        public function listStaff2(){

            $param = $this->request->param();
            $list = StaffModel::with(['department', 'parent'])->where(function ($query)use($param){
                if(isset($param['name']) && !empty($param['name'])) {
                    $query->where('name','LIKE','%'.$param['name'].'%');
                }
            })->select();

            $this->success('请求成功', $list);

        }




    //跟进记录排行榜
    public function getRank(){


        //$list = $RecordModel->group('create_staff_id')->select();
        $records = Db::name('qingdong_record')->field('staff_id, COUNT(*) as count')->group('staff_id')->order('count', 'desc')->limit(3)->select();
        foreach ($records as &$item){
            $item['staff']  = StaffModel::where(['id' => $item['staff_id']])->with(['department', 'parent','staffrole'])->find();
        }


        $records2 = Db::name('qingdong_record')->field('staff_id, COUNT(*) as count')->group('staff_id')->order('count', 'asc')->limit(3)->select();
        foreach ($records2 as &$item){
            $item['staff']  = StaffModel::where(['id' => $item['staff_id']])->with(['department', 'parent','staffrole'])->find();
        }

        $this->success('',['data1'=>$records,'data2'=>$records]);

    }

    public function test()
    {
        sendNotice(['title'=>'测试通知消息','time'=>'2024-10-29']);

        halt(11);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account 账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        $code = $this->request->post('code');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $userinfo = $this->auth->getUserinfo();


            if ($account !== 'admin' || $account !== 'admin2' || $account !== 'admin11') {
//halt($code);
                if (isset($code) && !empty($code)) {
                    // 从缓存中获取openId,如果不存在则调用微信接口获取
                    $openId = \think\Cache::get($code); 
                    $openId = null;
                    if (!$openId) {
                        $url = sprintf(
                            'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code',
                            'wx6b03340a69904f8b',
                            '',
                            $code
                        );
                        $result = Http::get($url);
                        $wxResult = json_decode($result, true);
                        $openId = $wxResult['openid'] ?? null;
                        $unionid = $wxResult['unionid'] ?? null;
                        \think\Cache::set('log',$wxResult);
//                        halt($openId);

                        if ($openId) {
                            \think\Cache::set($code, $openId,600);
                        }
                    }

                    if (isset($openId)) {
                        // 检查特定openId
                        if (in_array($openId, ['olaiW6wP1uwTCM_heWdGRuFb_UUY', 'olaiW625OKTceu0ELsWwu1xIh6s8','olaiW669OHa2pS60kTvkHa4v65DI'])) {
//                        	$staffModel->where('id', $userinfo['id'])->update(['openid' => $openId]);
                            // 处理特定openId的逻辑,如果有的话
                        } else {
                            // 检查用户是否已经绑定了其他的openId
                            if (!empty($userinfo['openid']) && $userinfo['openid'] !== $openId) {
                                $this->error('您的员工账号已绑定其他微信号,如有疑问,请与人事联系');
                            }

                            // 检查微信是否已经绑定了其他员工账号
                            $staffModel = new \addons\qingdong\model\Staff();
                            $find = $staffModel->where('mobile', '<>', $account)->where('openid', $openId)->find();
                            if ($find) {
                                if(!in_array($account,['test1','test2','test3','test4','admin'])){
                                    $this->error('您的微信已绑定其他员工账号,如有疑问,请与人事联系');
                                }
                            }

                            // 更新员工账号的openId
                            if (empty($userinfo['openid'])) {
                                $staffModel->where('id', $userinfo['id'])->update(['openid' => $openId,'unionid'=>$unionid]);
                            }
                            $staffModel->where('id', $userinfo['id'])->update(['unionid'=>$unionid]);
                        }
                    }
                }
            }

            
            \think\Session::set("admin", $this->auth->getUserinfo());
            
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 用户注册
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $password_confirm 确认密码
     */
    public function register()
    {
        $username = $this->request->post('username', '');
        $password = $this->request->post('password', '');
        $password_confirm = $this->request->post('password_confirm', '');
        
        // 参数验证
        if (!$username || !$password || !$password_confirm) {
            $this->error('请填写完整信息');
        }
        
        // 用户名格式验证(3-30个字符)
        if (strlen($username) < 3 || strlen($username) > 30) {
            $this->error('用户名长度为3-30个字符');
        }
        
        // 密码格式验证(6-30个字符)
        if (strlen($password) < 6 || strlen($password) > 30) {
            $this->error('密码长度为6-30个字符');
        }
        
        // 确认密码验证
        if ($password !== $password_confirm) {
            $this->error('两次输入的密码不一致');
        }
        
        // 检查用户名是否已存在
        $staffModel = new StaffModel();
        $existStaff = $staffModel->where('mobile', $username)->find();
        if ($existStaff) {
            $this->error('用户名已存在,请使用其他用户名');
        }
        
        // 生成密码盐
        $salt = substr(md5(uniqid(true)), 0, 6);
        $encryptPassword = $this->auth->getEncryptPassword($password, $salt);
        
        // 准备注册数据
        $data = [
            'mobile' => $username,
            'password' => $encryptPassword,
            'salt' => $salt,
            'name' => $username, // 默认姓名为用户名
            'nickname' => $username, // 默认昵称为用户名
            'status' => 0, // 默认状态为待审核
            'img' => '', // 头像字段(注册时为空)
            'email' => '', // 邮箱字段(注册时为空)
            'group_ids' => '', // 角色组字段(注册时为空,避免模型钩子报错)
        ];
        
        // 开启事务
        Db::startTrans();
        try {
            // 创建员工记录
            $staff = $staffModel->save($data);
            if (!$staff) {
                throw new Exception('注册失败,请稍后重试');
            }
            
            // 注册成功后自动登录
            $staffId = $staffModel->id;
            $ret = $this->auth->direct($staffId);
            
            if ($ret) {
                $userinfo = $this->auth->getUserinfo();
                $data = ['userinfo' => $userinfo];
                Db::commit();
                $this->success('注册成功', $data);
            } else {
                throw new Exception('注册成功,但自动登录失败,请手动登录');
            }
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    public function listStaff(){

        $param = $this->request->param();
        $list = StaffModel::with(['department', 'parent'])->where(function ($query)use($param){
            if(isset($param['grouprlue']) && !empty($param['grouprlue'])) {

                $rule_id = $param['grouprlue'];
                $query->where("find_in_set($rule_id, group_ids)");
            }
		if(isset($param['name']) && !empty($param['name'])) {
                 $query->where('name','LIKE','%'.$param['name'].'%');
             }
            
        })->select();

        foreach ($list as &$item){

            $group_ids = $item['group_ids'];
            $datas = (new AuthGroup())->where("find_in_set( id,'$group_ids')")->column('is_status');

            $is_status = 2; // 假设所有都是2,先将$is_status设置为2
            foreach ($datas as $v) {
                if ($v != '2' || $v==null) {
                    $is_status = 1; // 一旦发现有一个不是2,就将$is_status设置为1,并跳出循环
                    break; // 因为只要有一个不是2,就不需要再检查剩下的元素了
                }
            }
            $item['is_status'] = $is_status;



            $group_ids=explode(',',$item['group_ids']);
            $item['role_type'] = 1;//基础和团队
            if (in_array(1, $group_ids)) {//超级管理员
                $item['role_type'] = 9;
            }
        }
        $this->success('请求成功', $list);


    }

    public function detailStaff(){
        $param = $this->request->param();

        $staff = StaffModel::where(['id' => $param['id']])->with(['department', 'parent'])->find();
        $group_ids = explode(',',$staff['group_ids']);
        // halt($group_ids);
        $staff['role_type'] = 1;//基础和团队
        if (in_array(1, $group_ids)) {//超级管理员
            $staff['role_type'] = 9;
        }

        $ids = $staff['group_ids'];
        $datas = (new AuthGroup())->where("find_in_set( id,'$ids')")->column('is_status');
        $is_status = 2; // 假设所有都是2,先将$is_status设置为2
        foreach ($datas as $v) {
            if ($v != '2' || $v == null) {
                $is_status = 1; // 一旦发现有一个不是2,就将$is_status设置为1,并跳出循环
                break; // 因为只要有一个不是2,就不需要再检查剩下的元素了
            }
        }
        $staff['is_status'] = $is_status;
        $this->success('请求成功', $staff);


    }

    //获取个人基本信息
    public function getInfo()
    {
        $staff = StaffModel::where(['id' => $this->auth->id])->with(['department', 'parent','staffrole'])->find();
        $group_ids=explode(',',$staff['group_ids']);

		foreach ($group_ids as $groupId){
            $arr[] = \app\admin\model\AuthGroup::where('id',$groupId)->value('company');
        }
        if(!empty($arr)){
            if(in_array('博西尼信息科技有限公司',$arr)){
                $data = (new Mainbody())->where('name','博西尼信息科技有限公司')->find();
            }else{
                $data = (new Mainbody())->where('name','in',$arr[0])->find();
            }
        }else{
            $data = '';
        }
        $staff['mainbody'] = $data;

        $staff['role_type'] = 1;//基础和团队
        if ($staff['is_attendance'] == '1') {//有考勤权限
            $staff['role_type'] = 9;
        }
        $this->success('请求成功', $staff);
    }



    //获取当前用户的下级组织架构 部门人员

    public function getStaffgroupList(){

        //下级员工
        $ids = StaffModel::getLowerStaffId2(5);


        //halt($this->auth->id);
        $staff = StaffModel::where([
            'id' => ['in', $ids],
            'status' => 1
        ])->with(['parent'])->field('id,name,nickname,img,num,mobile,post,parent_id')->select();

        $data = StaffModel::where(['id' => $this->auth->id])->with(['department', 'parent','staffrole'])->find();
        $pid = $data['group_ids'];

        $gorup_ids = AuthGroup::getDepartmentLowerId(explode(',',$pid));
        $gorup = AuthGroup::where('id','in',$gorup_ids)->field('id,name,pid,is_status')->select();

        $pid = AuthGroupAccess::where('uid',$this->auth->id)->order('group_id asc')->value('group_id');

        $gorup = AuthGroup::getStaffgroupList2($gorup,$pid);

        //$gorup = AuthGroup::where("find_in_set(pid,'$pid')")->field('id,name,pid,is_status')->select();

        $this->success('请求成功', ['staff'=>$staff,'gorup'=>$gorup]);

    }


    //获取当前用户的下级组织架构 部门人员
    public function getStaffgroupList2(){


        //下级员工
        $ids = StaffModel::getLowerStaffId2(4);

        $staff = StaffModel::where([
            'id' => ['in', $ids],
            'status' => 1
        ])->with(['parent'])->field('id,name,nickname,img,num,mobile,post,parent_id')->select();


        $data = StaffModel::where(['id' => $this->auth->id])->with(['department', 'parent','staffrole'])->find();

        $pid = $data['group_ids'];
        //$gorup_ids = AuthGroup::getDepartmentLowerId(explode(',',$pid));
        //$gorup = AuthGroup::where('id','in',$gorup_ids)->field('id,name,pid,is_status')->select();
        $gorup = AuthGroup::where("find_in_set(pid,'$pid')")->field('id,name,pid,is_status')->select();

        $this->success('请求成功', ['staff'=>$staff,'gorup'=>$gorup]);




    }






    //员工绑定信息
    public function staffBind(){
        $staff=StaffModel::get($this->auth->id);
        $data=[
            'is_bind_wechat'=>$staff['openid']?1:($staff['wx_openid']?1:0)
        ];
        $this->success('请求成功',$data);
    }

    //绑定微信
    public function wechatBind(){
        $code = $this->request->post('code');
        $wechat = new Wechat('wxMiniProgram');
        if(empty($wechat->config['app_id'])){
            $this->error('微信小程序appid未设置');
        }
        if(empty($wechat->config['secret'])){
            $this->error('微信小程序secret未设置');
        }
        $decryptSession = $wechat->code($code);

        if (isset($decryptSession['errcode']) && $decryptSession['errcode'] != 0) {
            $this->error(__('解析失败!'));
        }
        $openid = $decryptSession['openid'];
        $unionid = $decryptSession['unionid'] ?? '';
        $staffModel=new StaffModel();
        $result=$staffModel->save(['openid'=>$openid,'unionid'=>$unionid],['id'=>$this->auth->id]);
        if($result){
            $this->success('绑定成功');
        }
        $this->error('绑定失败');




        $type=input('type');//applet小程序   web 网页授权
        $code = input('code');
        if($type == 'web'){
            $wechat = new Wechat('wxOfficialAccount');
            if(empty($wechat->config['app_id'])){
                $this->error('微信公众号appid未设置');
            }
            if(empty($wechat->config['secret'])){
                $this->error('微信公众号secret未设置');
            }
            $decryptSession = $wechat->getOfficialAccessToken($code);

            if (isset($decryptSession['errcode']) && $decryptSession['errcode'] != 0) {
                $this->error(__('解析失败!'));
            }
            $openid = $decryptSession['openid'];
            $unionid = $decryptSession['unionid'] ?? '';

            Log::info(json_encode($decryptSession,JSON_UNESCAPED_UNICODE));
            //判断用户是否存在
            $staff = StaffModel::where(['wx_openid' => $openid])->find();
            if($staff){
                $this->error('该微信号已绑定账号');
            }
            $staffModel=new StaffModel();
            $result=$staffModel->save(['wx_openid'=>$openid,'unionid'=>$unionid],['id'=>$this->auth->id]);
            if($result){
                $this->success('绑定成功');
            }
            $this->error('绑定失败');
        }elseif($type == 'applet'){
            $wechat = new Wechat('wxMiniProgram');
            if(empty($wechat->config['app_id'])){
                $this->error('微信小程序appid未设置');
            }
            if(empty($wechat->config['secret'])){
                $this->error('微信小程序secret未设置');
            }
            $decryptSession = $wechat->code($code);

            if (isset($decryptSession['errcode']) && $decryptSession['errcode'] != 0) {
                $this->error(__('解析失败!'));
            }
            $openid = $decryptSession['openid'];
            $unionid = $decryptSession['unionid'] ?? '';
            //判断用户是否存在
            // $staff = StaffModel::where(['openid' => $openid])->find();
            // if($staff){
            //     $this->error('该微信号已绑定账号');
            // }
            $staffModel=new StaffModel();
            $result=$staffModel->save(['openid'=>$openid,'unionid'=>$unionid],['id'=>$this->auth->id]);
            if($result){
                $this->success('绑定成功');
            }
            $this->error('绑定失败');
        }
    }

    //解绑微信
    public function unboundWechat()
    {
        $staffId = $this->auth->id;
        $model = new StaffModel();
        $staff = $model->where(['id' => $staffId])->find();
        if (empty($staff)) {
            $this->error('员工不存在');
        }
        if ($model->isUpdate(true)->save(['id' => $staffId, 'wx_openid' => null,
            'unionid' => null, 'openid' => null])) {
            $this->success('解绑微信成功');
        }
        $this->error('操作失败');
    }
    //修改个人基本信息
    public function editInfo()
    {
        $name = input('name');
        $img = input('img');
        $email = input('email');
        $sex = input('sex');
        $num = input('num');
        $post = input('post');
        $mobile = input('mobile');
        $autograph = input('autograph');
        $staffs = StaffModel::where(array('id' => $this->auth->id))->find();
        $staffs->mobile = $mobile;
        $staffs->img = $img;
        $staffs->email = $email;
        $staffs->sex = $sex;
        $staffs->num = $num;
        $staffs->post = $post;
        $staffs->autograph = $autograph;
        $staffs->updatetime = time();
        $result = $staffs->save();
        if (!$result) {
            $this->error('修改失败');
        }
        $this->success('修改成功');
    }


    //授权手机号
    public function use_phone()
    {
        $code = $this->request->post('code','',null);
        $encryptedData = $this->request->post('encryptedData','',null);
        $iv = $this->request->post('iv','',null);
        $config = new Wechat('wxMiniProgram');
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $config->config['app_id'] . "&secret=" . $config->config['secret'] . "&js_code=" . $code . "&grant_type=authorization_code";
        $user = curl_getinfo($url);
        $arr = json_decode($user, true);
        if (isset($arr['errcode']) && $arr['errcode'] != 0) {
            $this->error('操作失败!');
        }
        if (!isset($arr['openid']) || !isset($arr['session_key'])) {
            $this->error('授权失败,请重新授权!');
        }
        $openId = $arr['openid'];
        $pc = new Wxbizdatacrypt($config->config['app_id'], $arr['session_key']);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        if ($errCode != 0) {
            $this->error('授权失败,请重新授权!');
        }
        $decryptUserInfo = json_decode($data, true);
        if (isset($decryptUserInfo['phoneNumber']) && !empty($decryptUserInfo['phoneNumber'])) {
            $user_id = $this->auth->id;
            $userInfo = StaffModel::where(array('id' => $user_id))->update(array('mobile' => $decryptUserInfo['phoneNumber']));
            if ($userInfo === false) {
                $this->error('绑定失败!');
            }
            $data = ['mobile' => $decryptUserInfo['phoneNumber']];
            $this->success('绑定成功', $data);
        } else {
            $this->error('授权失败!');
        }
    }


    //获取下级员工列表
    public function getStaffList()
    {
        $ids = StaffModel::getLowerStaffId();
        $staff = StaffModel::where([
            'id' => ['in', $ids],
            'status' => 1
        ])->with(['parent'])->field('id,name,nickname,img,num,mobile,post,parent_id')->select();
        $this->success('请求成功', $staff);
    }


    //获取员工详情
    public function getStaffDetail()
    {
        $id = input('id');
        if (empty($id)) {
            $this->error('员工不存在');
        }
        $staff = StaffModel::with(['department', 'parent'])->where([
            'id' => $id,
        ])->find();
        $this->success('请求成功', $staff);
    }


    //待审核员工列表
    public function getCheckStaffList()
    {
        $staff = StaffModel::where([
            'status' => 0,
            'name' => ['neq', '']
        ])->field('id,name,nickname,img,num,mobile,post,status')->select();
        $this->success('请求成功', $staff);
    }

    //修改员工信息
    public function updateStaff()
    {
        $name = input('name', '');
        $img = input('img', '');
        $password = input('password', '');
        $mobile = input('mobile', '');
        $id = input('id', 0, 'intval');

        $data = [
            'name' => $name,
            'img' => $img,
            'mobile' => $mobile,
            'status' => 1,
            'updatetime' => time()
        ];

        if(isset($password) && !empty($password)){
            $newSalt = substr(md5(uniqid(true)), 0, 6);
            $newPassword = md5(md5($password) . $newSalt);

            $data['salt'] = $newSalt;
            $data['password'] = $newPassword;
        }

        if (StaffModel::where(['id' => $id])->update($data) == false) {
            $this->error('修改失败');
        }
        $this->success('修改成功');
    }

    //审核员工成功
    public function checkStaffSuccess()
    {
        $name = input('name', '');
        $img = input('img', '');
        $email = input('email', '');
        $sex = input('sex', 0);
        $role = input('role', 0);
        $num = input('num', '');
        $post = input('post', '');
        $mobile = input('mobile', '');
        $department_id = input('department_id', 0);
        $parent_id = input('parent_id', 0);
        $id = input('id', 0, 'intval');
        if (StaffModel::where(['id' => $id, 'status' => 0])->find() == false) {
            $this->error('待审核员工不存在');
        }
        if (empty($department_id)) {
            $this->error('请选择员工部门!');
        }
        if (StaffModel::where(['id' => $id])->update([
                'name' => $name,
                'img' => $img,
                'email' => $email,
                'sex' => $sex,
                'num' => $num,
                'role' => $role,
                'mobile' => $mobile,
                'post' => $post,
                'parent_id' => $parent_id,
                'department_id' => $department_id,
                'status' => 1,
                'updatetime' => time()
            ]) == false) {
            $this->error('审核失败');
        }
        $this->success('审核成功');
    }

    //审核员工拒绝
    public function checkStaffError(){
        $id = input('id');
        if (StaffModel::where(['id' => $id, 'status' => 0])->find() == false) {
            $this->error('待审核员工不存在');
        }
        if (StaffModel::where(['id' => $id, 'status' => 0])->update(['deletetime' => time()]) == false) {
            $this->error('拒绝失败');
        }
        $this->success('审核成功');
    }

    //获取员工统计
    public function getStaffStatistics()
    {
        $id = input('id');
        if (empty($id)) {
            $this->error('员工不存在');
        }
        $date = input('date', date('Y-m'));
        //月底
        $endDate = strtotime('+1 month', strtotime(date($date . '-1')));
        $date = strtotime($date);
        //客户 线索 联系人 合同 回款 跟进次数 处理审批
        $leads = Leads::where([
            'create_staff_id' => $id,
            'createtime' => ['between', [$date, $endDate]],
        ])->count();
        $customer = Customer::where([
            'create_staff_id' => $id,
            'createtime' => ['between', [$date, $endDate]],
        ])->count();
        $contacts = Contacts::where([
            'create_staff_id' => $id,
            'createtime' => ['between', [$date, $endDate]],
        ])->count();
        $contract = Contract::where([
            'create_staff_id' => $id,
            'createtime' => ['between', [$date, $endDate]],
            'check_status' => 2
        ])->count();
        $contract_money = Contract::where([
            'create_staff_id' => $id,
            'createtime' => ['between', [$date, $endDate]],
            'check_status' => 2
        ])->sum('money');
        $receivables = Receivables::where([
            'create_staff_id' => $id,
            'createtime' => ['between', [$date, $endDate]],
            'check_status' => 2
        ])->count();
        $receivables_money = Receivables::where([
            'create_staff_id' => $id,
            'createtime' => ['between', [$date, $endDate]],
            'check_status' => 2
        ])->sum('money');
        $record = Record::where([
            'create_staff_id' => $id,
            'createtime' => ['between', [$date, $endDate]],
        ])->count();

        $field = Achievement::getMonthField(date('Y-m', $date));
        $contractAchievement = Achievement::where([
            'year' => date('Y', $date),
            'type' => 3,
            'obj_id' => $id,
            'status' => 1
        ])->value($field);

        $receivablesAchievement = Achievement::where([
            'year' => date('Y', $date),
            'type' => 3,
            'obj_id' => $id,
            'status' => 2
        ])->value($field);

        $this->success('请求成功', [
            'leads' => $leads,
            'customer' => $customer,
            'contacts' => $contacts,
            'contract' => $contract,
            'contract_money' => $contract_money,
            'receivables' => $receivables,
            'receivables_money' => $receivables_money,
            'record' => $record,
            'contractAchievement' => $contractAchievement ?: 0,
            'receivablesAchievement' => $receivablesAchievement ?: 0,
        ]);
    }

    //获取员工所属客户
    public function getStaffCustomer()
    {
        $id = input('id');
        $limit = input("limit/d", 10);
        $row = StaffModel::get($id);
        if (empty($row)) {
            $this->error('员工不存在');
        }
        $where = [];
        $where['owner_staff_id'] = $id;
        $list = Customer::where($where)->with([
            'ownerStaff',
            'contacts'
        ])->field('id,name,next_time,owner_staff_id,level,follow')->order('id desc')->paginate($limit);

        $this->success('请求成功', $list);
    }

    //获取部门列表
    public function getDepartment()
    {

        $this->success('请求成功', StaffDepartment::getDepartmentList());
    }


    //获取部门列表
    public function getDepartment2()
    {

        $this->success('请求成功', AuthGroup::getDepartmentList());
    }


    //通过pid获取下级部门列表
    public function getDepartment3()
    {

        $param = $this->request->param();

        $this->success('请求成功', AuthGroup::getDepartmentList2($param['p_id']));
    }


    //获取上级列表
    public function getParentList()
    {
        $id = input('id');
        if (empty($id)) {
            $this->error('参数错误');
        }
        $this->success('请求成功', StaffModel::getList([$id]));
    }


    /**
     * 获取用户上级IDs
     */
    public function getStaffIds()
    {
        // record 跟进  contract 合同  consume 费用  receivables 回款
        $type = input('type');
        $remind=Remind::where(['type'=>$type])->find();
        if($remind){
            $staff = StaffModel::where(['id' => ['in', $remind['staff_ids']]])->field('id,name,img')->select();
            $this->success('请求成功', $staff);
        }
        $pid = StaffModel::where(['id' => $this->auth->id])->value('parent_id');
        $pids = [$pid];
        $staff = StaffModel::where(['id' => ['in', $pids]])->field('id,name,img')->select();
        $this->success('请求成功', $staff);
    }

    /**
     * 获取审批列表
     */
    public function getsteplist()
    {
        // record 跟进  contract 合同  consume 费用  receivables 回款 formapproval_1 审批
        $type = input('type');

        //获取审批
        $data = Flow::getsteplist($type);
        if (empty($data)) {
            $this->error('无可用审批流,请联系管理员');
        }
        $this->success('请求成功', $data);
    }
    /**
     * 获取审批详情
     */
    public function getstepdetail()
    {
        // record 跟进  contract 合同  consume 费用  receivables 回款
        $type = input('type');
        $relation_id=input('relation_id');
        $data = Flow::getstepdetail($type,$relation_id);
        if (empty($data)) {
            $this->error('无可用审批流,请联系管理员');
        }
        $this->success('请求成功', $data);
    }


    //禁用账号
    public function disable_user()
    {
        $id = input('id');
        $status = 2;
        $model = new StaffModel();
        $staff = $model->where(['id' => $id])->find();
        if (empty($staff)) {
            $this->error('员工不存在');
        }
        if ($model->isUpdate(true)->save(['id' => $id, 'status' => $status])) {
            $this->success('操作成功');
        }
        $this->error('操作失败');
    }
    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }
    /**
     * 修改密码
     */
    public function changepwd()
    {
        if ($this->request->isPost()) {
            $oldpassword = $this->request->post("oldpassword");
            $newpassword = $this->request->post("newpassword");
            $renewpassword = $this->request->post("renewpassword");
            $rule = [
                'oldpassword'   => 'require|length:6,30',
                'newpassword'   => 'require|length:6,30',
                'renewpassword' => 'require|length:6,30|confirm:newpassword',
            ];

            $msg = [
                'renewpassword.confirm' =>'两次输入的密码不一致'
            ];
            $data = [
                'oldpassword'   => $oldpassword,
                'newpassword'   => $newpassword,
                'renewpassword' => $renewpassword,
            ];
            $field = [
                'oldpassword'   => '旧密码',
                'newpassword'   => '新密码',
                'renewpassword' => '确认密码'
            ];
            $validate = new Validate($rule, $msg, $field);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()));
                return false;
            }

            $ret = $this->auth->changepwd($newpassword, $oldpassword);
            if ($ret) {
                $this->success('修改密码成功');
            } else {
                $this->error($this->auth->getError());
            }
        }
    }
    //直接体验
    public function logintest()
    {
        $staff = StaffModel::where([])->order('id asc')->find();
        if(!$staff){
            $this->error('员工不存在');
        }
        $stafflogin= $this->auth->direct($staff['id']);
        if ($stafflogin) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error('登录失败');
        }

    }

}