package com.qianhe.controller;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.qianhe.common.constant.HttpStatus;
import com.qianhe.common.core.domain.entity.SysUser;
import com.qianhe.common.utils.SecurityUtils;
import com.qianhe.domain.*;
import com.qianhe.service.IGgFjbService;
import com.qianhe.service.ISjBzxxService;
import com.qianhe.util.LogUtil;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.qianhe.common.annotation.Log;
import com.qianhe.common.core.controller.BaseController;
import com.qianhe.common.core.domain.AjaxResult;
import com.qianhe.common.enums.BusinessType;
import com.qianhe.service.ISjGfjsXjbzService;
import com.qianhe.common.utils.poi.ExcelUtil;
import com.qianhe.common.core.page.TableDataInfo;

/**
 * 三基 规范建设 星级班组Controller
 *
 * @author qianhe
 * @date 2025-11-28
 */
@RestController
@RequestMapping("/system/sjGfjsXjbz")
public class SjGfjsXjbzController extends BaseController
{
    @Autowired
    private ISjGfjsXjbzService sjGfjsXjbzService;
    @Autowired
    private ISjBzxxService sjBzxxService;
    @Autowired
    private IGgFjbService fjbService;

    /**
     * 查询三基 规范建设 星级班组列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SjGfjsXjbz sjGfjsXjbz)
    {

        //日志
        SysUser u = SecurityUtils.getLoginUser().getUser();
        LogUtil.mkrzsc(u, "三基考核", "三基考核-星级班组", "查询星级班组", "查询");

        startPage();
        List<SjGfjsXjbz> list = sjGfjsXjbzService.selectSjGfjsXjbzList(sjGfjsXjbz);
        return getDataTable(list);
    }
    /**
     * 查询 星级班组 单位下 指定年
     */
    @GetMapping("/listAll")
    public Map<String,Object> listAll(SjGfjsXjbz sjGfjsXjbz){

        //日志
        SysUser u = SecurityUtils.getLoginUser().getUser();
        LogUtil.mkrzsc(u, "三基考核", "三基考核-星级班组", "查询星级班组", "查询");


        Map<String,Object> map=new HashMap<>();
        Long deptId = sjGfjsXjbz.getDeptId();
        String nd = sjGfjsXjbz.getNd();


        //查询附件
        List<GgFjb> fjlist = fjbService.selectFj(deptId,"规范建设-星级班组");
        Map<String, List<GgFjb>> map2 = fjlist.stream().collect(Collectors.groupingBy(GgFjb::getFJLX));
        if(map2.get(nd)!=null){
            List<GgFjb> fileData = map2.get(nd).stream().collect(Collectors.toList());
            //rt.setFileList1(fileData);
            map.put("khpjFjs", fileData);
        }


        //查询 指定单位下 指定年 已保存的 班组星级 数据
        List<SjGfjsXjbz> list = sjGfjsXjbzService.selectSjGfjsXjbzList(sjGfjsXjbz);
        if(list.size()<=0){//没有需要插入一个初始的
            SjBzxx qry = new SjBzxx();
            qry.setDeptId(deptId);
            List<SjBzxx> bzsList = sjBzxxService.selectSjBzxxList(qry);
            List<SjGfjsXjbz> xjbzsList = new ArrayList<>();
            for (SjBzxx bz:bzsList) {
                SjGfjsXjbz xj = new SjGfjsXjbz();
                xj.setBzId(bz.getId());
                xj.setDeptId(bz.getDeptId());
                xj.setNd(nd);
                xj.setBzlx(bz.getBzlx());
                xj.setBzmc(bz.getBzmc());
                xj.setFdjb(bz.getRs());//班组人数
                xj.setZt("0");
                xjbzsList.add(xj);
            }
            if (xjbzsList.size() > 0) {
                sjGfjsXjbzService.batchSave(xjbzsList);
            }

        }
        if(isBeforeNextYearFeb1(nd)){
            sjGfjsXjbzService.updateBzxx_xjbz(nd);
        }
        list = sjGfjsXjbzService.selectSjGfjsXjbzList(sjGfjsXjbz);

        map.put("code", HttpStatus.SUCCESS);
        map.put("msg","查询成功");
        map.put("khpjData", list);
        return map;
    }


    public static boolean isBeforeNextYearFeb1(String inputYear) {
        // 1. 校验输入年份的合法性（必须是4位数字）
        if (inputYear == null || !inputYear.matches("^\\d{4}$")) {
            throw new IllegalArgumentException("输入年度必须是4位数字（如2025），当前输入：" + inputYear);
        }

        try {
            // 2. 解析输入年份，计算次年2月1日00:00:00（东八区时区，避免系统时区偏差）
            int year = Integer.parseInt(inputYear);
            int nextYear = year + 1;
            // 构建次年2月1日0点的截止时间（指定东八区）
            LocalDateTime nextFeb1 = LocalDateTime.of(nextYear, 2, 1, 0, 0, 0)
                    .atZone(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            // 3. 获取当前东八区时间，对比是否在截止时间之前
            LocalDateTime now = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
            return now.isBefore(nextFeb1);

        } catch (NumberFormatException | DateTimeParseException e) {
            throw new IllegalArgumentException("年份解析失败：" + inputYear, e);
        }
    }

    /**
     * 导出三基 规范建设 星级班组列表
     */
    @Log(title = "三基 规范建设 星级班组", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SjGfjsXjbz sjGfjsXjbz)
    {

        //日志
        SysUser u = SecurityUtils.getLoginUser().getUser();
        LogUtil.mkrzsc(u, "三基考核", "三基考核-星级班组", "导出星级班组", "导出");

        List<SjGfjsXjbz> list = sjGfjsXjbzService.selectSjGfjsXjbzList(sjGfjsXjbz);
        ExcelUtil<SjGfjsXjbz> util = new ExcelUtil<SjGfjsXjbz>(SjGfjsXjbz.class);
        util.exportExcel(response, list, "三基 规范建设 星级班组数据");
    }

    /**
     * 获取三基 规范建设 星级班组详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {

        //日志
        SysUser u = SecurityUtils.getLoginUser().getUser();
        LogUtil.mkrzsc(u, "三基考核", "三基考核-星级班组", "查询星级班组", "查询");

        return success(sjGfjsXjbzService.selectSjGfjsXjbzById(id));
    }

    /**
     * 新增三基 规范建设 星级班组
     */
    @Log(title = "三基 规范建设 星级班组", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SjGfjsXjbz sjGfjsXjbz)
    {

        //日志
        SysUser u = SecurityUtils.getLoginUser().getUser();
        LogUtil.mkrzsc(u, "三基考核", "三基考核-星级班组", "新增星级班组", "新增");

        return toAjax(sjGfjsXjbzService.insertSjGfjsXjbz(sjGfjsXjbz));
    }

    /**
     * 修改三基 规范建设 星级班组
     */
    @Log(title = "三基 规范建设 星级班组", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SjGfjsXjbz sjGfjsXjbz)
    {

        //日志
        SysUser u = SecurityUtils.getLoginUser().getUser();
        LogUtil.mkrzsc(u, "三基考核", "三基考核-星级班组", "修改星级班组", "修改");

        return toAjax(sjGfjsXjbzService.updateSjGfjsXjbz(sjGfjsXjbz));
    }

    /**
     * 删除三基 规范建设 星级班组
     */
    @Log(title = "三基 规范建设 星级班组", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {

        //日志
        SysUser u = SecurityUtils.getLoginUser().getUser();
        LogUtil.mkrzsc(u, "三基考核", "三基考核-星级班组", "删除星级班组", "删除");

        return toAjax(sjGfjsXjbzService.deleteSjGfjsXjbzByIds(ids));
    }

    @PutMapping("/pledit")
    public AjaxResult pledit(@RequestBody List<SjGfjsXjbz> list)
    {

        //日志
        SysUser u = SecurityUtils.getLoginUser().getUser();
        LogUtil.mkrzsc(u, "三基考核", "三基考核-星级班组", "修改星级班组", "修改");

        return toAjax(sjGfjsXjbzService.pledit(list));
    }
    //批量提交 ids
    @PostMapping("/pltj")
    public AjaxResult pltj(@RequestBody SjGfjsXjbz fjx)
    {

        //日志
        SysUser u = SecurityUtils.getLoginUser().getUser();
        LogUtil.mkrzsc(u, "三基考核", "三基考核-星级班组", "修改星级班组", "修改");

        fjx.setZt("1");
        return toAjax(sjGfjsXjbzService.plxg(fjx));
    }


    //上传附件
    @PostMapping("/scfj")
    public AjaxResult scfj(@RequestBody SjGfjsXjbz sjZdsc)
    {

        String fileListStr1 = sjZdsc.getFileListStr1();
        int i1 = fjbService.batchSaveFj(sjZdsc.getDeptId()+"", sjZdsc.getNd(), "规范建设-星级班组", fileListStr1);

        return toAjax(i1);
    }
}
