package com.ssm.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.github.pagehelper.PageInfo;
import com.ssm.manage.entity.AbnormalClockInRecord;
import com.ssm.manage.entity.RegionThreeLevel;
import com.ssm.manage.entity.StaffTemporary;
import com.ssm.manage.excelEntity.ExcelAbnormalClockInRecord;
import com.ssm.manage.excelEntity.ExcelAbnormalClockInRecordDetail;
import com.ssm.manage.excelEntity.ExcelJobContentList;
import com.ssm.manage.mapper.RegionListMapper;
import com.ssm.manage.mapper.StaffTemporaryMapper;
import com.ssm.manage.query.AbnormalClockInRecordPageQuery;
import com.ssm.manage.response.BlackListVo;
import com.ssm.manage.response.JobContentListVo;
import com.ssm.manage.response.PageResponse;
import com.ssm.manage.service.AbnormalClockInRecordService;
import com.ssm.manage.vo.AbnormalClockInRecordDetail;
import com.ssm.manage.vo.AbnormalClockInRecordsVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/clock-in-record/abnormal")
public class AbnormalClockInRecordController {
    private final AbnormalClockInRecordService abnormalClockInRecordService;

    @Autowired
    private RegionListMapper regionListMapper;
    @Autowired
    private StaffTemporaryMapper staffTemporaryMapper;


    @PostMapping("/page")
    public PageResponse<AbnormalClockInRecord> page(@RequestBody AbnormalClockInRecordPageQuery pageQuery) {

        PageResponse<AbnormalClockInRecord> pageResponse = new PageResponse<>();

        PageInfo<AbnormalClockInRecord> resultPage = abnormalClockInRecordService.page(pageQuery);

        pageResponse.setPageInfo(resultPage);
        return pageResponse;
    }

    @PostMapping("/export")
    public void export(@RequestBody AbnormalClockInRecordPageQuery pageQuery) throws IOException {
        PageResponse<AbnormalClockInRecord> pageResponse = new PageResponse<>();
        PageInfo<AbnormalClockInRecord> resultPage;
        resultPage = abnormalClockInRecordService.page(pageQuery);
        List<AbnormalClockInRecord> list = resultPage.getList();
        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
        // {} 代表普通变量 {.} 代表是list的变量 {前缀.} 前缀可以区分不同的list
        ExcelWriter excelWriter = null;
        OutputStream out = null;
        InputStream inputStream =null;
        try {
            String fileName = "projectType";
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1") + ".xlsx");
            out = response.getOutputStream();
           inputStream = this.getClass().getClassLoader().getResourceAsStream("config/AbnormalList.xlsx");
            List<ExcelAbnormalClockInRecord> excelBaseProjectTypeList = new ArrayList<>();

            if(list!=null && list.size()>0) {
                for (AbnormalClockInRecord jobContentListVo : list) {
                    ExcelAbnormalClockInRecord excelAbnormalClockInRecord = new ExcelAbnormalClockInRecord();
                    BeanUtils.copyProperties(jobContentListVo, excelAbnormalClockInRecord);

                    //TODO 添加在这里
                    //服务类型（1代表月结，0代表日结）
                    Integer type = jobContentListVo.getType();
                    if(type != null){
                        if(type == 1){
                            excelAbnormalClockInRecord.setType("月结");
                        }else {
                            excelAbnormalClockInRecord.setType("日结");
                        }
                    }
                    //考勤日期形式（yyyy-MM-dd）
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String date = sdf.format(excelAbnormalClockInRecord.getAttendanceTime());
                    excelAbnormalClockInRecord.setAttendanceTime1(date);

                    //三级部门
                    StaffTemporary staffTemporary = staffTemporaryMapper.selectByStaffNum(excelAbnormalClockInRecord.getStaffNum());
                    if(staffTemporary != null){
                        RegionThreeLevel regionThreeLevel = regionListMapper.selectParentById(staffTemporary.getZhongkongDeptId());
                        // 三级部门以中控的为准
                        Integer zhongkongDeptId = staffTemporary.getZhongkongDeptId();
                        if (zhongkongDeptId != null) {
                            String secondDeptName = regionThreeLevel.getSecondDeptName();
                            if (StringUtils.isBlank(secondDeptName)) {  // 二级为空, 说明当前部门只有一级
                                // 将三级提到一级
                                excelAbnormalClockInRecord.setFirstDeptName(staffTemporary.getZhongkongDeptName());
                            } else {    // 二级不为空, 说明当前部门有可能有 一二两个级别
                                String firstDeptName = regionThreeLevel.getFirstDeptName();
                                if (StringUtils.isBlank(firstDeptName)) {   // 一级为空, 说明当前部门只有前两级
                                    // 将二级提到一级
                                    excelAbnormalClockInRecord.setFirstDeptName(secondDeptName);
                                    // 将三级提到二级
                                    excelAbnormalClockInRecord.setSecondDeptName(staffTemporary.getZhongkongDeptName());
                                    // 设置三级为空
                                } else {    // 一级不为空, 说明当前部门有完整的三个级别
                                    // 设置一、二、三级别
                                    excelAbnormalClockInRecord.setFirstDeptName(firstDeptName);
                                    excelAbnormalClockInRecord.setSecondDeptName(secondDeptName);
                                    excelAbnormalClockInRecord.setThreeDeptName(staffTemporary.getZhongkongDeptName());
                                }
                            }
                        }
                    }

                    excelBaseProjectTypeList.add(excelAbnormalClockInRecord);
                }
            }




//            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
            //EasyExcel.write(out, LiveRoomData.class).sheet("模板").doWrite(list);
            excelWriter = EasyExcel.write(out).withTemplate(inputStream).build();
            //FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            excelWriter.fill(excelBaseProjectTypeList, writeSheet);


        } catch (Exception e) {
            log.error("SsmProjectTypeController.export:",e);
        } finally {
            //destFile.delete();
            // 别忘记关闭流
            excelWriter.finish();
            out.flush();
            out.close();
            inputStream.close();
        }
    }
}
