package com.bonus.system.wechat.controller;

import com.bonus.common.core.utils.poi.MultiSheetExcelExporter;
import com.bonus.common.core.web.controller.BaseController;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.core.web.page.TableDataInfo;
import com.bonus.common.log.annotation.Log;
import com.bonus.common.log.annotation.SysLog;
import com.bonus.common.log.enums.BusinessType;
import com.bonus.common.log.enums.OperaType;
import com.bonus.common.security.annotation.RequiresPermissions;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.system.api.domain.MapVo;
import com.bonus.system.api.domain.SysUser;
import com.bonus.system.basic.dao.SysOrgDao;
import com.bonus.system.dept.dao.ProDeptRoleDao;
import com.bonus.system.holiday.entity.WorkReportBean;
import com.bonus.system.wechat.entity.WechatBean;
import com.bonus.system.wechat.service.WechatService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 小程序打卡数据
 *
 * @author lsun
 */
@RestController
@RequestMapping("/wechat")
@Slf4j
public class WechatController extends BaseController {

    @Resource(name = "WechatService")
    private WechatService wechatService;

    @Resource(name = "ProDeptRoleDao")
    private ProDeptRoleDao proDeptRoleDao;

    @Resource
    private SysOrgDao sysOrgDao;

    /**
     * 获取小程序打卡数据列表(表格)
     */
    @RequiresPermissions("flow:wechat:list")
    @GetMapping("/list")
    @Log(title = "流程管理->小程序打卡数据->列表查询", businessType = BusinessType.QUERY)
    public TableDataInfo list(WechatBean bean) {
        try{
            SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
            List<String> roleId = sysUser.getRoleList();
            //管理员与人资角色可以看到所有
            if (roleId != null && !roleId.isEmpty()) {
                if (Collections.frequency(roleId, "1") == 0 && Collections.frequency(roleId, "16") == 0) {
                    // 根据用户id查询是否是管理员或帮忙负责人
                    Long userId = SecurityUtils.getUserId();
                    List<MapVo> orgList = sysOrgDao.getOrgIdList(userId);
                    if (!orgList.isEmpty()) {
                        // 使用 LinkedHashSet 来保证顺序并自动去重
                        Set<String> idsSet = new LinkedHashSet<>();
                        for (MapVo mapVo : orgList) {
                            String id = proDeptRoleDao.getOrgChildById(mapVo.getId());
                            if (id != null && !id.trim().isEmpty()) { // 防止空或仅含空白字符的字符串
                                // 将分割后的数组添加到 Set 中，自动去重
                                Collections.addAll(idsSet, id.split(","));
                            }
                        }
                        // 如果需要转换回 List 类型
                        List<String> uniqueIds = new ArrayList<>(idsSet);
                        bean.setOrgList(uniqueIds);
                    }else {
                        bean.setUserId(userId);
                    }
                }
            }
            startPage();
            return getDataTable(wechatService.getWechatList(bean));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return getDataTableError(new ArrayList<>());
    }

    /**
     * 获取小程序打卡数据单用户列表(审核表格)
     */
    @RequiresPermissions("flow:wechat:list")
    @GetMapping("/userList")
    @Log(title = "流程管理->小程序打卡数据->单用户列表查询", businessType = BusinessType.QUERY)
    public TableDataInfo userList(WechatBean bean) {
        try{
            startPage();
            return getDataTable(wechatService.getWechatUserList(bean));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return getDataTableError(new ArrayList<>());
    }


    @GetMapping("/export")
    @SysLog(title = "小程序打卡数据", businessType = OperaType.EXPORT,module = "小程序打卡数据")
    public void export(HttpServletResponse response, WechatBean bean) {
        try {
            SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
            List<String> roleId = sysUser.getRoleList();
            //管理员与人资角色可以看到所有
            if (roleId != null && !roleId.isEmpty()) {
                if (Collections.frequency(roleId, "1") == 0 && Collections.frequency(roleId, "16") == 0) {
                    // 根据用户id查询是否是管理员或帮忙负责人
                    Long userId = SecurityUtils.getUserId();
                    List<MapVo> orgList = sysOrgDao.getOrgIdList(userId);
                    if (!orgList.isEmpty()) {
                        // 使用 LinkedHashSet 来保证顺序并自动去重
                        Set<String> idsSet = new LinkedHashSet<>();
                        for (MapVo mapVo : orgList) {
                            String id = proDeptRoleDao.getOrgChildById(mapVo.getId());
                            if (id != null && !id.trim().isEmpty()) { // 防止空或仅含空白字符的字符串
                                // 将分割后的数组添加到 Set 中，自动去重
                                Collections.addAll(idsSet, id.split(","));
                            }
                        }
                        // 如果需要转换回 List 类型
                        List<String> uniqueIds = new ArrayList<>(idsSet);
                        bean.setOrgList(uniqueIds);
                    }else{
                        bean.setUserId(userId);
                    }
                }
            }
            //先查询小程序打卡数据
            List<WechatBean> list = wechatService.getWechatList(bean);
            //轮休数据
            List<WechatBean> listUser=new ArrayList<>();
            MultiSheetExcelExporter exporter = new MultiSheetExcelExporter();
            // 创建第一个sheet：员工信息
            Sheet employeeSheet = exporter.createSheet("小程序打卡数据");
            List<String> employeeHeaders = Arrays.asList("序号", "姓名", "打卡天数", "今日是否考勤");
            exporter.addHeaderRow(employeeSheet, employeeHeaders);

            List<Map<String, Object>> employeeData = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> map = new LinkedHashMap<>();
                map.put("序号", i + 1);
                map.put("姓名", list.get(i).getUserName());
                map.put("打卡天数", list.get(i).getDays());
                map.put("今日是否考勤", list.get(i).getIsToday());
                employeeData.add(map);
            }
            exporter.addDataRows(employeeSheet, employeeData, employeeHeaders);

            //查询用户数据
            List<WechatBean> list1 = wechatService.getWechatUserList(bean);
            listUser.addAll(list1);
            // 创建第二个sheet：查询用户数据
            Sheet departmentSheet = exporter.createSheet("查询用户数据");
            List<String> departmentHeaders = Arrays.asList("序号", "姓名", "日期", "上班打卡时间", "考勤状态", "备注","下班打卡时间", "考勤状态", "备注");
            exporter.addHeaderRow(departmentSheet, departmentHeaders);
            List<Map<String, Object>> departmentData = new ArrayList<>();
            for (int i = 0; i < listUser.size(); i++) {
                Map<String, Object> map = new LinkedHashMap<>();
                map.put("序号", i + 1);
                map.put("姓名", listUser.get(i).getUserName());
                map.put("日期", listUser.get(i).getAttCurrentDay());
                map.put("上班打卡时间", listUser.get(i).getToWorkAttCurrentTime());
                String toWorkAttStatus =getAttStatus(listUser.get(i).getToWorkAttStatus());
                map.put("考勤状态",toWorkAttStatus);
                map.put("备注",listUser.get(i).getToErrorRemake());
                map.put("下班打卡时间", listUser.get(i).getOffWorkAttCurrentTime());
                String offWorkAttStatus =getAttStatus(listUser.get(i).getOffWorkAttStatus());
                map.put("考勤状态",offWorkAttStatus);
                map.put("备注",listUser.get(i).getOffErrorRemake());
                departmentData.add(map);
            }
            exporter.addDataRows(departmentSheet, departmentData, departmentHeaders);
            // 导出Excel文件
            exporter.exportToResponse(response, "小程序打卡数据报表");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String getAttStatus(String attStatus) {
        switch (attStatus) {
            case "1":
                attStatus = "正常";
                break;
            case "2":
                attStatus = "迟到";
                break;
            case "3":
                attStatus = "旷工";
                break;
            case "4":
                attStatus = "早退";
                break;
            case "5":
                attStatus = "轮休";
                break;
            case "6":
                attStatus = "请假";
                break;
            case "7":
                attStatus = "临时外出";
                break;
            case "8":
                attStatus = "出入异常";
                break;
            case "9":
                attStatus = "打卡地异常";
                break;
            case "10":
                attStatus = "出差";
                break;
            case "19":
                attStatus = "育儿假";
                break;
            default:
                attStatus = "休假";
                break;
        }
        return attStatus;
    }

}
