<?php


namespace JinDouYun\Controller\Shop;


use JinDouYun\Controller\BaseController;
use JinDouYun\Controller\DingController;
use JinDouYun\Model\Department\MStaff;
use JinDouYun\Model\Shop\MShop;
use JinDouYun\Model\Shop\MShopRostering;
use JinDouYun\Model\Shop\MShopTemplate;
use Mall\Framework\Core\ErrorCode;

class ApiRostering extends BaseController
{

    public function __construct()
    {
        $this->checkToken = false;
    }

    public function clock()
    {
        $data = $_GET;
        $encrypt = file_get_contents("php://input");
        $encrypt = json_decode($encrypt);

        $crypt = new DingController("dingtoken", "SiB4UpWsOTjNvL1aHXGL2NnId4uk2BDdercxCTEhK0s", "dingxipi1agktpmfqfsn");
//        $crypt = new DingController("4dmWAL5kRd", "4gS9bzCXdujudDqQTzssi5rG9aMJp88PlnbMYUsOiA4", "dingz0cy4rdbwijahce9");
        $text = $crypt->getDecryptMsg($data['msg_signature'], $data['timestamp'], $data['nonce'], $encrypt->encrypt);
        if (isset($text['ErrorCode'])){
            file_put_contents('./5.txt',$text['ErrorCode']);
        }

        $EnterpriseId = $data['EnterpriseId'];

        $Mstaff = new MStaff($EnterpriseId);
        $Mrostering = new MShopRostering($EnterpriseId);
        $MTem= new MShopTemplate($EnterpriseId);
        $text = json_decode($text);
        $res = $crypt->getEncryptedMap("success");
        if ($text->EventType == 'check_url'){
            echo $res;
            exit();
        }else{

            $userId = $text->DataList[0]->userId;

            if ($text->EventType == 'attendance_check_record' || $text->EventType == 'attendance_schedule_change'){
                $today = date('Y-m-d', strtotime('today'));

                $url = 'https://oapi.dingtalk.com/attendance/listRecord?access_token='.$this->voucher('', $EnterpriseId);

                $staff = $Mstaff->getStaffInfo(['userId' => $userId])->getData();


                $rostering = $Mrostering->details([['time', 'like', '%'.$today.'%'], ['uid', '=' , $staff['id']]]);
                if (empty($rostering)){
                    echo $res;
                    exit();
                }
                $rostering = $rostering->getData();
                $data['userIds'] = [$userId];
                $data['checkDateFrom'] = date('Y-m-d H:i:s', strtotime('today'));
                $data['checkDateTo'] = date('Y-m-d H:i:s', strtotime('tomorrow'));


                $res = $this->post_json($url, json_encode($data));

                $res = json_decode($res);

                $recordresult = $res->recordresult;

                $time_slot = json_decode($rostering['time_slot']);

                $clock = $rostering['clock']? json_decode( $rostering['clock']) : [];

                $num = 0;
                foreach ($time_slot as $item)
                {

                    foreach ($item as $vo)
                    {
                        $times = strtotime($vo) * 1000;
                        $count = count($recordresult);
                        $time = [];
                        for ($i=0;$i < $count; $i++){
                            if (!isset($recordresult[$i]->invalidRecordType)){
                                if ($times == $recordresult[$i]->baseCheckTime){
                                    if (!$time) $time = $recordresult[$i];
                                }
                            }
                        }
                        if ($time){
                            if (isset($clock[$num])){
                                if ($clock[$num]->timeResult == 'NotSigned'){
                                    $clock[$num]->userCheckTime = date('Y-m-d H:i:s', $time->userCheckTime/1000);
                                    $clock[$num]->timeResult = $time->timeResult;
                                }
                            }else{
                                $clock[] = json_decode(json_encode(['baseCheckTime' => date('Y-m-d H:i:s', strtotime($vo)),'userCheckTime' => date('Y-m-d H:i:s', $time->userCheckTime/1000), 'timeResult' => $time->timeResult]));
                            }
                        }else{
                            if (strtotime($vo) < time() and !isset($clock[$num])){
                                $clock[] = json_decode(json_encode(['baseCheckTime' => date('Y-m-d H:i:s', strtotime($vo)), 'userCheckTime' => '','timeResult' => 'NotSigned']));
                            }
                        }
                        $num++;
                    }
                }
                $status = 0;
                $price = 0;//打卡金额
                $go_to_work = 1;
                if ($num == count($clock)){
                    foreach ($clock as $item){
                        if ($rostering['status'] == 0){
                            if ($item->timeResult == 'Normal'){
                                $tem_price = $MTem->details(['shift_id' => $rostering['template_id']])->getData();
                                $price += $tem_price['single_time'];
                            }

                        }
                        if ($item->timeResult != 'Normal') $status = -1;// 不正常今天的打卡未完成
                    }
                    if ($status == 0) $status = 1;// 如果都打卡正常那么打完完成

                }
                if (count($clock) == 2 or count($clock) == 4){
                    $go_to_work = 0;
                }
                if ($price > 0 and $staff['is_clock'] == 1){
                    $balance = $staff['reward'] + $price;
                    $rewardTotal = $staff['rewardTotal'] + $price;
                    $Mstaff->clockReward($price, $balance,  $staff['userCenterId'], $staff['id'], $this->shopId, $rewardTotal);
                }
                $Mrostering->update(['status' => $status, 'clock' => json_encode($clock)], $rostering['id']);
                $Mstaff->updateStaff(['go_to_work' => $go_to_work], $staff['id']);
            }
        }
        $res = $crypt->getEncryptedMap("success");
        echo $res;

    }

}