<?php

namespace App\Http\Controllers\Api;

use App\Module\Base;
use App\Module\Project;
use SimpleDingTalk\Config;
use App\Http\Controllers\Controller;
use SimpleDingTalk\User;
use SimpleDingTalk\AccessToken;
use Request;
use DB;
use App\Module\Users;

class DingController extends Controller
{


    public function __construct()
    {

        // 配置信息
        $apps=[
            'miniprogram_app' => [
                'info' => [
                    'AGENT_ID' => '',
                    'APP_KEY' => '',
                    'APP_SECRET' => ''
                ],
                'access_token' => [
                    'expires' => 0,
                    'file_path' => ''
                ],
                'callback_info' => [
                    'aes_key' => '',
                    'token' => ''
                ],
                'login_info' => [
                    'authorize' => [
                        'redirect_uri' => '',
                        'dingtalk_login_uri' => ''
                    ]
                ],
                'v2' => [
                    'access_token' => [
                        'expires' => 0,
                        'file_path' => ''
                    ],

                ],
                'userAccessToken' => [
                    'expires' => 0,
                    'file_path' => ''
                ]
            ],
            'micro_app' => [
                'info' => [
                    'AGENT_ID' => '1602970634',
                    'APP_KEY' => 'dingoduj8nh4jsroanpr',
                    'APP_SECRET' => '9qsEDDVN8sJ96GMe3pqHpiJuEwXnDBHg010kBJJc6GK--HDQ0Cnv5Twuv97ge_JS'
                ],
                'access_token' => [
                    'expires' => 0,
                    'file_path' => base_path('DingTalkToken')
                ],
                'callback_info' => [
                    'aes_key' => '',
                    'token' => ''
                ],
                'page' => [
                    'app' => '',
                    'pc' => '',
                    'management' => ''
                ],
                'login_info' => [
                    'authorize' => [
                        'redirect_uri' => '',
                        'dingtalk_login_uri'=>''
                    ]
                ],
                'v2' => [
                    'access_token' => [
                        'expires' => 0,
                        'file_path' => ''
                    ],
                ],
                'userAccessToken' => [
                    'expires' => 0,
                    'file_path' => base_path('DingTalkToken')
                ]
            ]

        ];

        $robots=[
            'robot1' => [
                'info' => [
                    'AGENT_ID' => 123456,
                    'APP_KEY' => '',
                    'APP_SECRET' => '',
                    'access_token' => '',
                    'SEC' => ''
                ],
                'access_token' => [
                    'expires' => 180,
                    'file_path' => './robot.json'
                ]

            ],
        ];

        Config::setRobot($robots)->
        setApp($apps)->
        setAppType('micro_app')->
        setRobotType('robot1')->
        setCorpId('dingc844bf6147f4d40c35c2f4657eb6378f');

        AccessToken::generateToken();

    }

    public function __invoke($method, $action = '')
    {
        $app = $method ? $method : 'main';
        if ($action) {
            $app .= "__" . $action;
        }
        return (method_exists($this, $app)) ? $this->$app() : Base::ajaxError("404 not found (" . str_replace("__", "/", $app) . ").");
    }


    public function login()
    {
        $code = trim(Request::input('code'));
        $ret = User::code_getuserinfo($code);
        $result = json_decode($ret,true);
        if($result['errcode'] === 0){
            $get_user_ret = User::get($result['result']['userid']);
            $user_result = json_decode($get_user_ret,true);
            if($user_result['errcode'] === 0){
                $user_info = $user_result['result'];
                $user = Base::DBC2A(DB::table('users')->where('username', $user_info['mobile'])->where('nickname', $user_info['name'])->first());
                if($user){
                    $array = [
                        'userid' => $result['result']['userid'],
                        'token' => Users::token($user),
                        'loginnum' => $user['loginnum'] + 1,
                        'lastip' => Base::getIp(),
                        'lastdate' => Base::time(),
                        'lineip' => Base::getIp(),
                        'linedate' => Base::time(),
                    ];
                    Base::array_over($user, $array);
                    DB::table('users')->where('id', $user['id'])->update($array);
                    return Base::retSuccess( "登陆成功!", Users::retInfo($user));
                }else{
                    return Base::retError( "您的姓名为:{$user_info['name']},手机号码为:{$user_info['mobile']},系统里面找不到该用户,请使用账号密码登录!");
                }
            }else{
                return Base::retError( "无法获取钉钉信息,请使用账号密码登录!");
            }
        }else{
            return Base::retError($result['errmsg']);
        }
    }

    public function notice__push()
    {
        $user = Users::authE();
        if (Base::isError($user)) {
            return $user;
        } else {
            $user = $user['data'];
        }
        $act = trim(Base::getPostValue('act'));
        $taskid = intval(Base::getPostValue('taskid'));
        $task = Base::DBC2A(DB::table('project_task')
            ->where([
                ['delete', '=', 0],
                ['id', '=', $taskid],
            ])
            ->first());
        if (empty($task)) {
            return Base::retError('任务不存在!');
        }
        if ($task['projectid'] > 0) {
            if (!Project::isPersons($task, $user['username'])) {
                $inRes = Project::inThe($task['projectid'], $user['username']);
                if (Base::isError($inRes)) {
                    return $inRes;
                }
            }
            if (!in_array($act, ['comment', 'attention'])) {
                $checkRole = Project::role('edit_role', $task['projectid'], $task['id']);
                if (Base::isError($checkRole)) {
                    return $checkRole;
                }
                switch ($act) {
                    case 'complete':
                    case 'unfinished':
                        $checkRole = Project::role('complete_role', $task['projectid'], $task['id']);
                        if (Base::isError($checkRole)) {
                            return $checkRole;
                        }
                        break;
                    case 'archived':
                    case 'unarchived':
                        $checkRole = Project::role('archived_role', $task['projectid'], $task['id']);
                        if (Base::isError($checkRole)) {
                            return $checkRole;
                        }
                        break;
                    case 'delete':
                        $checkRole = Project::role('del_role', $task['projectid'], $task['id']);
                        if (Base::isError($checkRole)) {
                            return $checkRole;
                        }
                        break;
                }
            }
        } else {
            if (!Project::isPersons($task, $user['username'])) {
                return Base::retError('此操作只允许任务负责人!');
            }
        }
        $content = Base::newTrim(Base::getPostValue('content'));
        $message = "";
        $upArray = [];
        $logArray = [];


        switch ($act) {
            /**
             * 修改标题
             */
            case 'title': {
                $upArray['title'] = $content;
                $logArray[] = [
                    'type' => '日志',
                    'projectid' => $task['projectid'],
                    'taskid' => $task['id'],
                    'username' => $user['username'],
                    'detail' => '修改任务标题',
                    'indate' => Base::time(),
                    'other' => Base::array2string([
                        'type' => 'task',
                        'id' => $task['id'],
                        'title' => $content,
                        'old_title' => $task['title'],
                    ])
                ];
                break;
            }
            /**
             * 修改子任务
             */
            case 'subtask': {
                if (!is_array($content)) {
                    $content = [];
                }
                $subNames = [];
                foreach ($content AS $tmp) {
                    if ($tmp['uname'] && !in_array($tmp['uname'], $subNames)) {
                        $subNames[] = $tmp['uname'];
                    }
                }
                $content = Base::array2string($content);
                if ($content == $task['subtask']) {
                    return Base::retError('子任务未做改变!');
                }
                $upArray['subtask'] = $content;
                //
                $detail = '修改子任务';
                $subtype = 'modify';
                $new_count = count(Base::string2array($content));
                $old_count = count(Base::string2array($task['subtask']));
                if ($new_count > $old_count) {
                    $detail = '添加子任务';
                    $subtype = 'add';
                } elseif ($new_count < $old_count) {
                    $detail = '删除子任务';
                    $subtype = 'del';
                }
                //
                if ($subNames) {
                    DB::transaction(function() use ($task, $subNames) {
                        foreach ($subNames AS $uname) {
                            $row = Base::DBC2A(DB::table('project_users')->where([
                                'type' => '负责人',
                                'taskid' => $task['id'],
                                'username' => $uname,
                            ])->lockForUpdate()->first());
                            if (empty($row)) {
                                DB::table('project_users')->insert([
                                    'type' => '负责人',
                                    'projectid' => $task['projectid'],
                                    'taskid' => $task['id'],
                                    'isowner' => $task['username'] == $uname ? 1 : 0,
                                    'username' => $uname,
                                    'indate' => Base::time()
                                ]);
                            }
                        }
                        DB::table('project_users')->where([
                            'type' => '负责人',
                            'taskid' => $task['id'],
                        ])->whereNotIn('username', $subNames)->delete();
                    });
                } else {
                    DB::table('project_users')->where([
                        'type' => '负责人',
                        'taskid' => $task['id'],
                    ])->delete();
                }
                //
                $logArray[] = [
                    'type' => '日志',
                    'projectid' => $task['projectid'],
                    'taskid' => $task['id'],
                    'username' => $user['username'],
                    'detail' => $detail,
                    'indate' => Base::time(),
                    'other' => Base::array2string([
                        'type' => 'task',
                        'subtype' => $subtype,
                        'id' => $task['id'],
                        'title' => $task['title'],
                        'subtask' => $content,
                        'old_subtask' => $task['subtask'],
                    ])
                ];
                break;
            }

            default: {
                return Base::retError('参数错误!');
            }


        }

    }

    public function transfer(){
        return Base::retSuccess( "登陆成功!");
    }
}