package com.lz.modules.third.controller;

import com.alibaba.fastjson.JSONObject;
import com.lz.common.utils.DingTalkUtil;
import com.lz.common.utils.R;
import com.lz.modules.job.business.DingtalkBusiness;
import com.lz.modules.luck.entity.Luck;
import com.lz.modules.luck.entity.LuckRecord;
import com.lz.modules.luck.service.LuckRecordService;
import com.lz.modules.luck.service.LuckService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/dtlg")
@Slf4j
public class DingTalkLoginController {
    @Autowired
    DingtalkBusiness dingtalkBusiness;
    @Autowired
    LuckService luckService;
    @Autowired
    LuckRecordService luckRecordService;
    @Value("${dingtalk.appid}")
    private String appid;
    @PostMapping("/login")
    public R login(@RequestBody String body){
        log.info("钉钉免登录luck{}", body);
        JSONObject json = JSONObject.parseObject(body);
        return dingtalkBusiness.login(json.getString("code"), appid);
    }

    @GetMapping("/jump")
    public R jump(@RequestParam String code){
        log.info("钉钉免登录luck{}", code);
        return dingtalkBusiness.jump(code);
    }

    @PostMapping("/luck")
    public R luck(@RequestBody String body){
        log.info("luck{}", body);
        JSONObject json = JSONObject.parseObject(body);
        Luck luck = luckService.selectLuckById(1L);//默认第一个活动
        if(luck.getStopTime().getTime() > System.currentTimeMillis()){
            return dingtalkBusiness.luck(json.getString("code"), appid, luck.getId());
        }
        return R.error("活动已经停止");

    }

    @GetMapping("/look")
    public String look(@RequestParam String luckId){
        List<LuckRecord> luckRecords = luckRecordService.selectLuckRecordByLuckId(luckId);
        String value = "暂无人员报名";
        if(luckRecords.size() > 0){
            value = "";
            for (int i = 0; i < luckRecords.size(); i++){
                LuckRecord luckRecord = luckRecords.get(i);
                value += "<p>" + (i + 1) + "：姓名：<span style=\"color:#000000;\"><strong>" + luckRecord.getName()
                        + "</strong></span> 是否中将：<span style=" +
                        (luckRecord.getIsLuck() == 0 ? "\"color:#000000;\">未中将" : "\"color:#E53333;\">中将") +
                        "</span></p>";
            }
        }
        return value;

    }
}
