<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\web\controller;
use EasyWeChat\Factory;
use model\UserInfo;
use service\DepartmentService;
use service\PositionService;
use service\UserInfoService;

//header('Access-Control-Allow-Origin:https://open.weixin.qq.com');

class NotifyController extends MainController
{

    private $is_debug = true;//上线后设为false;
//    const APPID = 'wx051828c647720b9d';
//    const MCHID = '1502575411';
//    const KEY = 'qazxswedcvfr1456287tgnnyu964236q';

    public function __construct()
    {
        parent::__construct();
        //通知微信已经收到回调了
//        $str = '<xml>' .
//            '<return_code><![CDATA[SUCCESS]]></return_code>' .
//            '<return_msg><![CDATA[OK]]></return_msg>' .
//            '</xml> ';
//        echo $str;
//        require_once CMF_ROOT.'vendor/wxpay/WxPayPubHelper.php';
//        require_once CMF_ROOT.'vendor/wxpay/log.php';
    }


    /**
     * @name 同步
     */
    public function tb(){
        file_put_contents(WEB_ROOT.'qy1.txt',file_get_contents("php://input").date('Y-m-d H:i:s')."\n",FILE_APPEND);
        $app = Factory::work(config('work_wechat.'));
     //   $message=json_decode('{"ToUserName":"wwe32621127cf73e25","FromUserName":"sys","CreateTime":"1592558376","MsgType":"event","Event":"change_contact","ChangeType":"update_user","UserID":"shaoguo","Name":"\u90b5\u679c222"}',true);

        $app->server->push(function ($message) {
            // $message['FromUserName'] // 用户的 openid
            // $message['MsgType'] // 消息类型：event, text....
            file_put_contents(WEB_ROOT.'qy9.txt',json_encode($message)."\n",FILE_APPEND);
            if($message['Event']=="change_contact"){
                $new_data=array_slice($message,7);
                switch ($message['ChangeType']){
                    case 'update_user':
                        $s=array_keys($new_data)[0];
                        if($s=='NewUserID'){$new_data['UserID']==$new_data['NewUserID'];unset($new_data['UserID']);}
                        $new_data=CamelToUnderLineArr($new_data);
                        unset($new_data['ext_attr']);
                        unset($new_data['department']);
                        unset($new_data['is_leader_in_dept']);
                        unset($new_data['status']);
                        unset($new_data['position']);
                        unset($new_data['is_leader']);

                        if(isset($message['Department'])){
                            $message['Department']=explode(',',$message['Department']);
                            $message['IsLeaderInDept']=explode(',',$message['IsLeaderInDept']);
                            if(!empty($message['Department'])){
                                $departments=DepartmentService::get([['work_department_id','in',$message['Department']]],'id')->column('id');
                                $user_info=UserInfoService::getOne([['user_id','=',$message['UserID']],['delete_time','=',0]]);
                                foreach ($departments as $k=>$v){
                                    $department_data[$k]=['department_id'=>$v,'is_leader_in_dept'=>$message['IsLeaderInDept'][$k],'is_default'=>0];
                                }

//                            dump($message);
                                if(!empty($user_info->department))$user_info->department()->detach();
                                dump($department_data);
                                foreach ($department_data as $d){
                                    $user_info->department()->attach($d['department_id'],$d);
                                }


                            }
                        }

                        if(!empty($message['Position'])){
                            $position=PositionService::getOne([['name','=',$message['Position']],['delete_time','=',0]]);
                            $new_data['position_id']=$position['id'];
                        }

                        UserInfoService::update([['user_id','=',$message['UserID']]],$new_data);
                        break;

                    case 'create_user':
                        $new_data=array_slice($message,6);
                        $s=array_keys($new_data)[0];
                        if($s=='NewUserID'){$new_data['UserID']==$new_data['NewUserID'];unset($new_data['UserID']);}
                        $new_data=CamelToUnderLineArr($new_data);
                        unset($new_data['ext_attr']);
                        unset($new_data['department']);
                        unset($new_data['is_leader_in_dept']);
                        unset($new_data['status']);
                        unset($new_data['position']);
                        unset($new_data['is_leader']);
                        unset($new_data['avatar']);

                        $message['Department']=explode(',',$message['Department']);
                        $message['IsLeaderInDept']=explode(',',$message['IsLeaderInDept']);
                        if(!empty($message['Department'])){
                            $departments=DepartmentService::get([['work_department_id','in',$message['Department']]],'id')->column('id');
                            $department_data=array();
                            foreach ($departments as $k=>$v){
                                $department_data[$k]=['department_id'=>$v,'is_leader_in_dept'=>$message['IsLeaderInDept'][$k],'is_default'=>0];
                            }


                        }

                        if(!empty($message['Position'])){
                            $position=PositionService::getOne([['name','=',$message['Position']],['delete_time','=',0]]);
                            $new_data['position_id']=$position['id'];
                        }

                        $new_data['department']=$department_data;
                        $new_data['external_profile']=json_encode(array());
                        $new_data['enable']=1;

                        $user_info=UserInfo::create($new_data);
                        if(!empty($department_data));
                        foreach ($department_data as $v){
                            $user_info->department()->attach($v['department_id'],$v);
                        }
                        break;

                    case 'delete_user':
                        UserInfoService::update([['user_id','=',$message['UserID']],['delete_time','=',0]],['delete_time'=>time()]);
                        break;
                }
            }


//            return "您好！欢迎使用 EasyWeChat";
        });

        $response = $app->server->serve();

        return $response->send();


    }


    public function test(){
//        $worker=work(config('work_wechat.'));
//        dump($worker->department->list());
        $test=json_decode('{"ToUserName":"wwe32621127cf73e25","FromUserName":"sys","CreateTime":"1590978582","MsgType":"event","Event":"change_contact","ChangeType":"update_user","UserID":"shaoguo","Avatar":"http:\/\/wework.qpic.cn\/bizmail\/zLtxaArXppcU07OO4ZjTBBN8hBJfPBKm6ukdf633icInwFI6Av4yz4A\/0","Alias":"\u4e5d\u5343\u4e03","Address":"\u6e56\u5317\u6b66\u6c49"}',true);
        //$test=array_slice($test,7);
        dump(CamelToUnderLineArr($test));

        $department=DepartmentService::get([['work_department_id','in',[1]]])->column('id');
        dump($department);


    }
}
