package com.ruoyi.web.controller.index;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.KaoqinConfig;
import com.ruoyi.system.domain.KaoqinRecord;
import com.ruoyi.system.service.IKaoqinRecordService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.Size;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.common.utils.SecurityUtils.checkStrongPwd;

/**
 * @Author: tjf
 * @Date: 2023/2/8 13:46
 * @Describe:
 */
@RestController
@RequestMapping("/index")
public class IndexController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IKaoqinRecordService kaoqinRecordService;

    /**
     * app新增用户
     */
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        String phonenumber = user.getPhonenumber();
        user.setUserName(phonenumber);
        if (!user.getCode().equals(redisCache.getCacheObject(CacheConstants.SMS_CODE_KEY+user.getPhonenumber()))) {
            return error("新增用户'" + user.getUserName() + "'失败，短信验证码错误");
        }
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user))) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if ("1".equals(checkStrongPwd(user.getPassword()))) {
            return AjaxResult.error("密码必须包含数字、大小写字母、特殊符号且大于8位");
        }
        user.setCreateBy("APP");
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUserApp(user));
    }

    /**
     * 重置密码app
     */
    @PostMapping("/resetPwdAPP")
    public AjaxResult resetPwdAPP(@RequestBody SysUser user) {
        String verifyKey = CacheConstants.SMS_CODE_KEY + user.getPhonenumber();

        String codeApp = redisCache.getCacheObject(verifyKey);
        if (StringUtils.isBlank(codeApp)) {
            return AjaxResult.error("短信验证码已过期");
        }
        String code = user.getCode();
        if (!codeApp.equals(code)) {
            return AjaxResult.error("验证码不正确");
        }
        if ("1".equals(checkStrongPwd(user.getPassword()))) {
            return AjaxResult.error("密码必须包含数字、大小写字母、特殊符号且大于8位");
        }
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.resetPwdAPP(user));
    }

    /**
     * app修改用户手机号
     */
    @PostMapping("/updatePhone")
    public AjaxResult updatePhone(@RequestBody SysUser user) {

        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 后台管理首页统计
     *
     * @param kaoQinRecord
     * @return
     */
    @PostMapping("/backstage")
    public AjaxResult backstage(@RequestBody KaoqinRecord kaoQinRecord) {
        //查询该部门所有人员
        Integer total = userService.selectUserCount(kaoQinRecord);
        //查询打卡人员
        List<KaoqinRecord> kaoqinRecords = kaoqinRecordService.selectKaoqinRecordList(kaoQinRecord);
        int daKaNum = 0;
        if (kaoqinRecords != null) {
            daKaNum = kaoqinRecords.size();
        }
        int weidaka = 0;
        if (total > 0) {
            weidaka = total - daKaNum;
        }
        if (weidaka < 0) {
            weidaka = 0;
        }
        Map map = new HashMap(2);
        map.put("weidaka", weidaka);
        map.put("yidaka", daKaNum);
        return AjaxResult.success(map);
    }


    /**
     * 后台管理首页统计-折线图
     *
     * @param kaoQinRecord
     * @return
     */
    @PostMapping("/brokenLine")
    public AjaxResult brokenLine(@RequestBody KaoqinRecord kaoQinRecord) {
        //1.创建一个放所有日期的集合
        List<String> dates = new ArrayList();
        //4.将格式化后的第一天添加进集合
        for (int i = 6; i >= 0; i--) {
            LocalDate localDate = LocalDate.now().minusDays(i);
            String date = localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            dates.add(date);
        }
        //获取当前日期的前7天日期
        Map map = new HashMap(2);
        map.put("x", dates);

        Map yMpa = new HashMap(2);
        List<Integer> normal = new ArrayList();
        List<Integer> abnormal = new ArrayList();
        yMpa.put("normal",normal);
        yMpa.put("abnormal",abnormal);

        for (String date : dates) {
            kaoQinRecord.setKaTime(date);
            List<KaoqinRecord> kaoqinRecords = kaoqinRecordService.selectKaoqinRecordList(kaoQinRecord);
            Map<String, List<KaoqinRecord>> collect = kaoqinRecords.stream().collect(Collectors.groupingBy(KaoqinRecord::getKaStatus));
            if (collect != null){
                //正常
                List<KaoqinRecord> kaoqinRecordsNormal = collect.get("1");
                //异常
                List<KaoqinRecord> kaoqinRecordsAbnormal = collect.get("2");
                if (kaoqinRecordsNormal != null){
                    normal.add(kaoqinRecordsNormal.size());
                }
                if (kaoqinRecordsAbnormal != null){
                    abnormal.add(kaoqinRecordsAbnormal.size());
                }
            }
        }
        map.put("y", yMpa);
        return AjaxResult.success(map);
    }
}
