package com.jpsoft.shinestar.modules.business.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.util.StringUtil;
import com.jpsoft.shinestar.config.OSSConfig;
import com.jpsoft.shinestar.exception.CustomException;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.CompanyInfoService;
import com.jpsoft.shinestar.modules.base.service.PersonInfoService;
import com.jpsoft.shinestar.modules.base.service.PersonPopedomService;
import com.jpsoft.shinestar.modules.base.service.WorkShiftInfoService;
import com.jpsoft.shinestar.modules.business.dto.UpdatePersonAttendanceDTO;
import com.jpsoft.shinestar.modules.business.entity.SupplementWork;
import com.jpsoft.shinestar.modules.business.entity.SupplementWorkPerson;
import com.jpsoft.shinestar.modules.business.entity.WorkScheduleAttendance;
import com.jpsoft.shinestar.modules.business.service.SupplementWorkPersonService;
import com.jpsoft.shinestar.modules.business.service.SupplementWorkService;
import com.jpsoft.shinestar.modules.business.service.WorkScheduleAttendanceService;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.utils.OSSUtil;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.sys.entity.User;
import com.jpsoft.shinestar.modules.sys.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.joda.time.DateTime;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/business/supplementWork")
@Api(description = "supplementWork")
public class SupplementWorkController {

    @Autowired
    private OSSConfig ossConfig;

    @Autowired
    private SupplementWorkService supplementWorkService;

    @Autowired
    private SupplementWorkPersonService supplementWorkPersonService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private UserService userService;

    @Autowired
    private PersonPopedomService personPopedomService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private WorkScheduleAttendanceService workScheduleAttendanceService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @ApiOperation(value="删除")
    @PostMapping("delete/{id}")
    public MessageResult<Integer> delete(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            SupplementWork supplementWork = supplementWorkService.get(id);
            supplementWork.setDelFlag(true);
            supplementWork.setUpdateBy(subject);
            supplementWork.setUpdateTime(new Date());

            int affectCount = supplementWorkService.update(supplementWork);

            if (affectCount > 0) {
                List<SupplementWorkPerson> supplementWorkPeopleList = supplementWorkPersonService.findBySupplementWorkId(supplementWork.getId());

//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//                Date attendanceDate = sdf.parse(supplementWork.getAttendanceDate());

                for (SupplementWorkPerson supplementWorkPerson : supplementWorkPeopleList) {
                    supplementWorkPerson.setDelFlag(true);
                    supplementWorkPerson.setUpdateTime(new Date());
                    supplementWorkPersonService.update(supplementWorkPerson);

                    WorkScheduleAttendance workScheduleAttendance  = workScheduleAttendanceService.findOneBySupplementWorkPersonId(supplementWorkPerson.getId());

                    if(workScheduleAttendance!=null){
                        workScheduleAttendance.setResult("0");
                        workScheduleAttendance.setRemark("取消补卡");
                        workScheduleAttendance.setSupplementWorkPersonId("");
                        workScheduleAttendance.setUpdateTime(new Date());
                        workScheduleAttendance.setUpdateBy(subject);

                        workScheduleAttendanceService.update(workScheduleAttendance);
                    }

//                  PersonPopedom personPopedom = personPopedomService.get(supplementWorkPerson.getPersonPopedomId());
//
//                  UpdatePersonAttendanceDTO updatePersonAttendanceDTO = new UpdatePersonAttendanceDTO(
//                            personPopedom.getPersonId(), attendanceDate, attendanceDate);
//
//                  rabbitTemplate.convertAndSend("updatePersonAttendanceQueue", updatePersonAttendanceDTO);
                }

                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        }
        catch(Exception ex){
            log.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @Autowired
    private WorkShiftInfoService workShiftInfoService;
    private String exportXls(List<SupplementWork> mapList) {
        String downloadUrl = "";

        Workbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet();

        //表头
        Row rowTitle = sheet.createRow(0);

        String[] titles = new String[]{"序号","申请单位","申请人","申请类型","补卡班次",
                "补卡时间","补卡理由","申请时间","审批状态"};

        for (int i=0;i<titles.length;i++) {
            Cell cell = rowTitle.createCell(i);
            cell.setCellValue(titles[i]);
        }
        String[] typeList= new String[]{"","个人申请","批量申请"};
        String[] statusList= new String[]{"审核中","同意","退回","拒绝","无需审核"};
        for (int i=0;i<mapList.size();i++){
            SupplementWork map = mapList.get(i);

            Row row = sheet.createRow(i+1);

            int colIndex = 0;
            row.createCell(colIndex++).setCellValue(i+1);
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.getCompanyName(),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.getPersonName(),""));

            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue( getN(typeList,map.getType()),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.getShiftName(),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.getAttendanceDate(),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.getReason(),""));

            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.getSubmitTime()==null?"":map.getSubmitTime().toLocaleString(),""));

            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(getN(statusList,map.getStatus()),""));

        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        try {
            workbook.write(output);

            byte[] buffer = output.toByteArray();
            ByteArrayInputStream input = new ByteArrayInputStream(buffer);

            downloadUrl = OSSUtil.upload(ossConfig,"supplementWork","补卡记录.xls",input);
        }
        catch (Exception ex){

            log.error(ex.getMessage(),ex);
        }

        return downloadUrl;
    }
    private  String getN( String[] typeList,String value){

        for(int i =0;i<typeList.length;i++){
            if((i+"").equals(value)){
                return typeList[i];
            }
        }

        return "";
    }

    @ApiOperation(value="列表")
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    public MessageResult<Object> pageList(
            @RequestParam(value="companyId",defaultValue="") String companyId,
            @RequestParam(value="subordinate",defaultValue="false") Boolean subordinate,
            @RequestParam(value="hqCompanyId",defaultValue="") String hqCompanyId,
            @RequestParam(value="hqSubordinate",defaultValue="false") Boolean hqSubordinate,
            @RequestParam(value = "personName", defaultValue = "") String personName,
            @RequestParam(value = "swPersonName", defaultValue = "") String swPersonName,
            @RequestParam(value = "status", defaultValue = "") String status,
            @RequestParam(value = "type", defaultValue = "") String type,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime,
            @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "20") int pageSize,
            @RequestParam(value = "exportFlag", defaultValue = "false") Boolean exportFlag,
            @RequestAttribute String subject){
        MessageResult<Object> msgResult = new MessageResult<>();

        try {
            Map<String, Object> searchParams = new HashMap<>();

            List<Sort> sortList = new ArrayList<>();
            sortList.add(new Sort("attendance_date", "desc"));

            //当前用户ID
            User user = userService.get(subject);

            if(!userService.hasRole(user.getId(),"SYSADMIN")) {
                //非系统管理员
                CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());
                searchParams.put("companyCode", companyInfo.getCode() + "%");
            }

            if (StringUtils.isNotEmpty(companyId)){
                CompanyInfo companyInfo = companyInfoService.get(companyId);

                if(subordinate){
                    searchParams.put("companyCode", companyInfo.getCode() + "%");
                }
                else {
                    searchParams.put("companyCode", companyInfo.getCode());
                }
            }

            if (StringUtils.isNotEmpty(hqCompanyId)){
                if("hq1".equals(hqCompanyId)){
                    //后勤1
                    searchParams.put("hqStatus", "1");
                }
                else if("hq2".equals(hqCompanyId)){
                    //后勤2
                    searchParams.put("hqStatus", "2");
                }
                else {
                    CompanyInfo companyInfo = companyInfoService.get(hqCompanyId);

                    if (hqSubordinate) {
                        searchParams.put("hqCompanyCode", companyInfo.getCode() + "%");
                    } else {
                        searchParams.put("hqCompanyCode", companyInfo.getCode());
                    }
                }

                searchParams.put("hqPerson",true);
            }

            if (StringUtils.isNotEmpty(personName)) {
                searchParams.put("personName", "%" + personName + "%");
            }

            if (StringUtils.isNotEmpty(swPersonName)) {
                searchParams.put("swPersonName", "%" + swPersonName + "%");
            }

            if (StringUtil.isNotEmpty(status)) {
                searchParams.put("status", status);
            }

            if (StringUtil.isNotEmpty(type)) {
                searchParams.put("type", type);
            }

            if (startTime != null) {
                searchParams.put("startTime", startTime);
            }

            if (endTime != null) {
                searchParams.put("endTime", new DateTime(endTime).plusDays(1).plusSeconds(-1).toDate());
            }

            Page<SupplementWork> page = supplementWorkService.pageSearch(searchParams, pageIndex, pageSize, true, sortList);

            for (SupplementWork supplementWork : page.getResult()) {
                WorkShiftInfo workShift = workShiftInfoService.get(supplementWork.getWorkShiftId());

                if(workShift!=null){
                    supplementWork.setShiftName(workShift.getNumber() + "."  + workShift.getName());

                    if ("1".equals(supplementWork.getClassify())){
                        supplementWork.setSupplementTime(workShift.getWorkTime());
                    }
                    else{
                        supplementWork.setSupplementTime(workShift.getClosingTime());
                    }
                }

                List<SupplementWorkPerson> personList = supplementWorkPersonService.findBySupplementWorkId(supplementWork.getId());

                List<Map> members = new ArrayList<>();

                for (SupplementWorkPerson supplementWorkPerson : personList) {
                    Map<String,Object> member = new HashMap<>();

                    member.put("id", supplementWorkPerson.getId());

                    //补卡人
                    member.put("name", supplementWorkPerson.getPersonName());

                    //当前补卡对应考勤记录
                    WorkScheduleAttendance wsa = workScheduleAttendanceService.findOneBySupplementWorkPersonId(supplementWorkPerson.getId());

                    member.put("wsa", wsa);

                    members.add(member);
                }

                supplementWork.setMembers(members);
            }

            if(exportFlag) {
                String filePath = exportXls(page);
                msgResult.setData(filePath);
                msgResult.setResult(true);

            }
            else{
                msgResult.setData(PojoUtils.pageWrapper(page));

                msgResult.setResult(true);
            }

        }
        catch (Exception ex){
            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());

            log.error(ex.getMessage(),ex);
        }

        return msgResult;
    }

    @ApiOperation(value="查看补卡当天缺卡记录列表")
    @RequestMapping(value = "missAttendanceList",method = RequestMethod.GET)
    public MessageResult<List> missAttendanceList(String supplementWorkPersonId){
        MessageResult<List> messageResult = new MessageResult<>();

        try {
            SupplementWorkPerson supplementWorkPerson = supplementWorkPersonService.get(supplementWorkPersonId);
            PersonPopedom personPopedom = personPopedomService.get(supplementWorkPerson.getPersonPopedomId());
            PersonInfo personInfo = personInfoService.get(personPopedom.getPersonId());

            SupplementWork supplementWork = supplementWorkService.get(supplementWorkPerson.getSupplementWorkId());

            String attendanceDate = supplementWork.getAttendanceDate().substring(0, 10);

            List<WorkScheduleAttendance> attendanceList = workScheduleAttendanceService.findByPersonIdAttendanceDateResult(personInfo.getId(), attendanceDate, "0");

            messageResult.setResult(true);
            messageResult.setData(attendanceList);
        }
        catch (Exception ex){
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());

            log.error(ex.getMessage(),ex);
        }

        return messageResult;
    }

    @ApiOperation(value="补卡")
    @RequestMapping(value = "patchAttendance",method = RequestMethod.POST)
    public MessageResult<String> patchAttendance(String supplementWorkPersonId,String workAttendanceId){
        MessageResult<String> messageResult = new MessageResult<>();

        try {
            WorkScheduleAttendance workScheduleAttendance = workScheduleAttendanceService.findOneBySupplementWorkPersonId(supplementWorkPersonId);

            if(workScheduleAttendance!=null){
                throw new CustomException("当前补卡申请已生效!不能重复补卡!");
            }

//          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            workScheduleAttendance = workScheduleAttendanceService.get(workAttendanceId);

            SupplementWorkPerson supplementWorkPerson = supplementWorkPersonService.get(supplementWorkPersonId);
//            PersonPopedom personPopedom = personPopedomService.get(supplementWorkPerson.getPersonPopedomId());
//            PersonInfo personInfo = personInfoService.get(personPopedom.getPersonId());

            //更新补卡记录
            supplementWorkPerson.setScheduleAttendanceId(workScheduleAttendance.getId());
            supplementWorkPerson.setUpdateTime(new Date());
            supplementWorkPersonService.update(supplementWorkPerson);

            //更新考勤记录
            workScheduleAttendance.setResult("1");
            workScheduleAttendance.setRemark("补卡");
            workScheduleAttendance.setSupplementWorkPersonId(supplementWorkPerson.getId());
            workScheduleAttendance.setUpdateTime(new Date());

            workScheduleAttendanceService.update(workScheduleAttendance);

            messageResult.setResult(true);
        }
        catch (Exception ex){
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());

            log.error(ex.getMessage(),ex);
        }

        return messageResult;
    }
}
