package cn.palmte.work.controller.backend;

import cn.palmte.work.bean.ResponseMsg;
import cn.palmte.work.model.*;
import cn.palmte.work.service.HumanCostService;
import cn.palmte.work.utils.Utils;
import cn.palmte.work.utils.excel.ExcelUtil;
import cn.palmte.work.utils.excel.ExportUtils;
import com.alibaba.fastjson.JSON;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.poifs.filesystem.OfficeXmlFileException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import top.jfunc.common.db.bean.Page;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 人力成本管理
 * @author Yuanping Zhang
 * @date 2021/11/1
 */
@Controller
@RequestMapping("/humanCost")
public class HumanCostController extends BaseController{
    private static final Logger logger = LoggerFactory.getLogger(HumanCostController.class);

    @Autowired
    private DeptRepository deptRepository;

    @Autowired
    private HumanCostService humanCostService;

    @Autowired
    private AdminRepository adminRepository;

    @Autowired
    private ProjectRepository projectRepository;
    /**
     * 列表
     */
    @RequestMapping("/list")
    public String list(@RequestParam(value = KEYWORDS,required = false) String keywords,
                       @RequestParam(value = PAGE_NUMBER, defaultValue = DEFAULT_PAGE_NUMBER) int pageNumber,
                       @RequestParam(value = PAGE_SIZE, defaultValue = DEFAULT_PAGE_SIZE) int pageSize,
                       Map<String, Object> model) {
        //当前登录人的角色类型
        Admin admin = getAdmin();
        int roleLevel = admin.getRoleLevel();
        List<Project> selfProjects = projectRepository.findByCreator(admin.getId(), new Date());
        if (roleLevel <= 3 || roleLevel == 6) {
            model.put("deptVary", 1);
            model.put("deptList", deptRepository.findAll());
            model.put("projectList", projectRepository.findAll());
            model.put("showSalary", 1);
        } else if (roleLevel == 4 || roleLevel == 5) {
            model.put("deptVary", -1);
            model.put("deptList", new ArrayList<>());
            model.put("projectList", projectRepository.findByDeptId(admin.getDeptId()));
            model.put("showSalary", -1);
        } else if (selfProjects != null) {
            model.put("deptVary", -1);
            model.put("deptList", new ArrayList<>());
            model.put("projectList", selfProjects);
            model.put("showSalary", -1);
        } else {
            keywords = setDate(keywords);
            model.put("keywords",keywords);
            ConcurrentHashMap<String, String> searchInfo = getSearchInfo(keywords,model);
            if (searchInfo.containsKey("time")) {
                String time = searchInfo.get("time");
                if (time.length() == 7) {
                    String individualTime = time.substring(0, 4) + "年" + time.substring(5, 7) + "月";
                    model.put("individualTime", individualTime);
                }
            }
            model.put("pager",humanCostService.individual(searchInfo, admin.getId(), pageNumber, pageSize));
            return "admin/human_cost_individual";
        }
        keywords = setDate(keywords);
        model.put("keywords",keywords);
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo(keywords,model);
        Page<ProjectUserTime> project = humanCostService.project(searchInfo, admin, pageNumber, pageSize);
        List<ProjectUserTime> staff = humanCostService.staff(searchInfo, admin);
        Map<String, BigDecimal> map = humanCostService.map(searchInfo, admin, pageNumber, pageSize);
        BigDecimal total = humanCostService.sum(searchInfo, admin);
        model.put("pager", project);
        model.put("staff", staff);
        model.put("map", map);
        model.put("total", total);
        return "admin/human_cost_list";
    }

    private String setDate(String keywords) {
        if (keywords == null || keywords.length() == 0) {
            Date date = new Date();
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM");
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
            date = calendar.getTime();
            String accDate = sf.format(date);
            keywords = "{time: '" + accDate + "'}";
        }
        return keywords;
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    public void export(@RequestParam(value = KEYWORDS,required = false) String keywords,
                       HttpServletResponse response) throws Exception{
        Admin admin = getAdmin();
        Map<String, String> searchInfo = getSearchInfo(keywords);
        downloadHeader(response , Utils.generateExcelName("人力成本表"));
        Page<ProjectUserTime> project = humanCostService.project((ConcurrentHashMap<String, String>) searchInfo, admin, 1, 5000);
        List<ProjectUserTime> staff = humanCostService.staff((ConcurrentHashMap<String, String>) searchInfo, admin);
        Map<String, BigDecimal> map = humanCostService.map((ConcurrentHashMap<String, String>) searchInfo, admin, 1, 5000);
        String[] headers = humanCostService.getHeaders(staff);
        String[] columns = humanCostService.getColumns(project.getList());
        ExportUtils.exportHumanCost(headers, columns, staff, project.getList(),
                response.getOutputStream() , map);
    }

    /**
     * 下载导入模板
     */
    @RequestMapping("/template")
    public void importTemplate(HttpServletResponse response) throws IOException {
        String[] columns = new String[]{""};
        downloadHeader(response , Utils.generateExcelName("人力成本导入模板"));
        List<String> data = new ArrayList<>();
        data.add("成本");
        String[] headers = humanCostService.template(data);
        ExportUtils exportUtils = new ExportUtils(headers);
        exportUtils.exportTemplate(columns , data, "yyyy-MM-dd HH:mm:ss" , 1);
        exportUtils.write(response.getOutputStream());
    }

    @RequestMapping("/batchImport")
    @ResponseBody
    public String batchImport(MultipartFile file, @RequestParam(value = "date",required = false) String date) {
        try {
            Map<String, String> title = new HashMap<>();
            Collection<Map> maps = ExcelUtil.importHumanCost(Map.class, file.getInputStream(),
                    title,0);
            return JSON.toJSONString(humanCostService.check(maps, title, date));
        } catch (OfficeXmlFileException | EncryptedDocumentException | InvalidFormatException e) {
            logger.error("", e);
            return JSON.toJSONString(ResponseMsg.buildFailedMsg("格式错误，请上传excel 2003/2007格式文件"));
        } catch (Exception e) {
            return JSON.toJSONString(ResponseMsg.buildFailedMsg("导入数据失败,请联系管理员"));
        }
    }
}
