<?php
// +----------------------------------------------------------------------
// | Description: CRM工作台
// +----------------------------------------------------------------------
// | Author: Michael_xu | gengxiaoxu@5kcrm.com 
// +----------------------------------------------------------------------

namespace app\crm\controller;

use app\common\wework\api\Api;
use app\common\wework\callback\WXBizMsgCrypt;
use think\Controller;
use think\Log;
use think\Request;
use think\Session;

class Callback extends Controller
{
    public function index()
    {
        $wxcpt = new WXBizMsgCrypt(config('wework.token'), config('wework.encodingAesKey'), config('wework.corpId'));
        if (Request::instance()->isPost()) {
            $sReqMsgSig = Request::instance()->get('msg_signature');
            $sReqTimeStamp = Request::instance()->get('timestamp');
            $sReqNonce = Request::instance()->get('nonce');

            $sReqData =Request::instance()->getContent();
            $sMsg = "";  // 解析之后的明文

            $errCode = $wxcpt->DecryptMsg($sReqMsgSig, $sReqTimeStamp, $sReqNonce, $sReqData, $sMsg);
            if ($errCode == 0) {
                // 解密成功,sMsg即为xml格式的明文
                $simpleXMLElement = simplexml_load_string($sMsg,'SimpleXMLElement', LIBXML_NOCDATA);
                switch ($simpleXMLElement->Event->__toString()) {
                    case 'change_external_contact':
                        $api = new Api(config('wework.corpId'), config('wework.corpSecret'));
                        $contactInfo = $api->contactInfo($simpleXMLElement->ExternalUserID->__toString());
                        foreach ($contactInfo['follow_user'] as $contactUserInfo) {
                            if ($contactUserInfo['userid'] == $simpleXMLElement->UserID->__toString()) {
                                $customerInfo = model('Customer')->where('name', $contactUserInfo['remark_corp_name'])->find();
                                if ($customerInfo) {
                                    $wxwork = db('admin_wxwork')->where("user_id", $contactUserInfo['userid'])->find();
                                    if (!$wxwork) {
                                        $userGet = $api->userGet($contactUserInfo['userid']);
                                        $wxwork = [
                                            'user_id' => $userGet['userid'],
                                            'name' => $userGet['name'],
                                            'create_time' => time(),
                                            'update_time' => time(),
                                        ];
                                        db('admin_wxwork')->insert($wxwork);
                                        $wxwork = db('admin_wxwork')->where("user_id", $contactUserInfo['userid'])->find();
                                        if (!$wxwork) {
                                            Log::record('联系人添加失败');
                                            return;
                                        }
                                    }
                                    if ($wxwork['update_time']+86400*3 < time()) {
                                        db('admin_wxwork')->where("id", $wxwork['id'])->update([
                                            'name' => $userGet['name'],
                                            'update_time' => time(),
                                        ]);
                                    }

                                    $contactsInfo = model('Contacts')->where([
                                        'external_userid' => $simpleXMLElement->ExternalUserID->__toString(),
                                        'customer_id' => $customerInfo['customer_id'],
                                        'wxwork_id' => $wxwork['id']
                                    ])->find();
                                    $mobile = '';
                                    if ($contactUserInfo['remark_mobiles']) {
                                        $mobile = $contactUserInfo['remark_mobiles'][0];
                                    }
                                    if (!$contactsInfo) {
                                        $param = [
                                            'business_id' => null,
                                            'create_user_id' => 1,
                                            'owner_user_id' => 1,
                                            'customer_id' => $customerInfo['customer_id'],
                                            'name' => $contactUserInfo['remark'],
                                            'mobile' => $mobile,
                                            'external_userid' => $simpleXMLElement->ExternalUserID->__toString(),
                                            'wxwork_id' => $wxwork['id']
                                        ];
                                        if (model('Contacts')->createData($param)) {
                                            Log::record('联系人添加成功');
                                        } else {
                                            Log::record('联系人添加失败');
                                        }
                                    } else {
                                        $param = [
                                            'name' => $contactUserInfo['remark'],
                                            'mobile' => $mobile
                                        ];
                                        model('Contacts')->where('contacts_id', $contactsInfo['contacts_id'])->update($param);
                                        Log::record('联系人更新成功');
                                    }
                                }
                            }
                        }
                        break;
                }
            } else {
                print("ERR: " . $errCode . "\n\n");
            }
        } else {
            $sVerifyMsgSig = Request::instance()->get('msg_signature');
            $sVerifyTimeStamp = Request::instance()->get('timestamp');
            $sVerifyNonce = Request::instance()->get('nonce');
            $sVerifyEchoStr = Request::instance()->get('echostr');
            // 需要返回的明文
            $sEchoStr = "";

            $errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);
            if ($errCode == 0) {
                echo ($sEchoStr);
                // 验证URL成功,将sEchoStr返回
                // HttpUtils.SetResponce($sEchoStr);
            } else {
                print("ERR: " . $errCode . "\n\n");
            }
        }
    }

    public function work() {
        $code = Request::instance()->get('code');
        $api = new Api(config('wework.corpId'), config('wework.corpSecret'));
        $userInfo = $api->getUserInfo($code);
        if ($userInfo) {
            Session::set('wxuser_id', $userInfo['userid']);
            $adminUser = db('admin_user')->where('wxwork_id', $userInfo['userid'])->find();
            if ($adminUser) {
                Session::set('user_id', $adminUser['id']);
                return redirect('http://web.lbschem.com:8088/?authkey=wxwork&sessionid='.session_id());
            } elseif (Session::get('user_id')) {
                db('admin_user')->where('id', Session::get('user_id'))->update([
                    'wxwork_id' => $userInfo['userid']
                ]);
                return redirect('http://web.lbschem.com:8088/?authkey=wxwork&sessionid='.session_id());
            }
        }
        return redirect('http://web.lbschem.com:8088/');
    }
}