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

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.config.OSSConfig;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.*;
import com.jpsoft.shinestar.modules.business.dto.ExamineDetailDTO;
import com.jpsoft.shinestar.modules.business.dto.ExaminePersonDetailDTO;
import com.jpsoft.shinestar.modules.business.entity.AdjustShift;
import com.jpsoft.shinestar.modules.business.entity.AdjustShiftPerson;
import com.jpsoft.shinestar.modules.business.service.AdjustShiftPersonService;
import com.jpsoft.shinestar.modules.business.service.AdjustShiftService;
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.common.utils.TypeNameUtil;
import com.jpsoft.shinestar.modules.sys.entity.User;
import com.jpsoft.shinestar.modules.sys.service.UserService;
import com.jpsoft.shinestar.modules.workflow.entity.*;
import com.jpsoft.shinestar.modules.workflow.service.*;
import io.swagger.annotations.ApiOperation;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/business/adjustShift")
public class AdjustShiftController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private OSSConfig ossConfig;

    @Autowired
    private AdjustShiftService adjustShiftService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private PersonPopedomService personPopedomService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private UserService userService;

    @Autowired
    private AdjustShiftPersonService adjustShiftPersonService;

    @Autowired
    private WorkShiftInfoService workShiftInfoService;

    @Autowired
    private ProcinstService procinstService;

    @Autowired
    private ProcinstActivityService procinstActivityService;

    @Autowired
    private ProcinstActUserService procinstActUserService;


    @ApiOperation(value="列表")
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    public MessageResult<Object> pageList(
            String personName,String companyId,String auditStatus,String type,String createTimeRange,String auditTimeRange,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestParam(value = "exportFlag", defaultValue = "false") Boolean exportFlag,
            HttpServletRequest request){
        String subject = (String)request.getAttribute("subject");

        //当前用户ID
        System.out.println(subject);

        MessageResult<Object> msgResult = new MessageResult<>();

        try {

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

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

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

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

            User user = userService.get(subject);

            if (userService.hasRole(subject, "SYSADMIN")) {
                if (StringUtils.isNotEmpty(companyId)) {
                    searchParams.put("companyId", "%" + companyId + "%");
                }
            } else {
                if (StringUtils.isNotEmpty(companyId)) {
                    searchParams.put("companyId", "%" + companyId + "%");
                } else {
                    CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());
                    searchParams.put("companyId", "%" + companyInfo.getId() + "%");
                }
            }

            if (StringUtils.isNotEmpty(auditStatus)) {
                searchParams.put("auditStatus", auditStatus);
            }


            if (StringUtils.isNotEmpty(createTimeRange)) {
                String[] timeRangeArray = createTimeRange.split(",");
                String beginTime = "";
                String endTime = "";
                if (timeRangeArray.length == 1) {
                    beginTime = timeRangeArray[0];
                    beginTime += " 00:00:00";
                } else if (timeRangeArray.length == 2) {
                    beginTime = timeRangeArray[0];
                    endTime = timeRangeArray[1];
                    beginTime += " 00:00:00";
                    endTime += " 23:59:59";
                }

                searchParams.put("beginTime", beginTime);
                searchParams.put("endTime", endTime);
            }

            if (StringUtils.isNotEmpty(auditTimeRange)) {
                String[] timeRangeArray = auditTimeRange.split(",");
                String beginTime = "";
                String endTime = "";
                if (timeRangeArray.length == 1) {
                    beginTime = timeRangeArray[0];
                    beginTime += " 00:00:00";
                } else if (timeRangeArray.length == 2) {
                    beginTime = timeRangeArray[0];
                    endTime = timeRangeArray[1];
                    beginTime += " 00:00:00";
                    endTime += " 23:59:59";
                }

                searchParams.put("beginAuditTime", beginTime);
                searchParams.put("endAuditTime", endTime);
            }


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

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

            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");

            for (AdjustShift adjustShift : page) {
                Map map = new HashMap<>();
                String personNameStr = "";
                String jobNumber = "";
                String companyName = "";

                PersonPopedom personPopedom = personPopedomService.get(adjustShift.getPersonPopedomId());
                if (personPopedom != null) {
                    PersonInfo personInfo = personInfoService.get(personPopedom.getPersonId());
                    if (personInfo != null) {
                        personNameStr = personInfo.getName();
                        jobNumber = personInfo.getJobNumber();

                        CompanyInfo companyInfo = companyInfoService.get(personInfo.getCompanyId());
                        if (companyInfo != null) {
                            companyName = companyInfo.getName();
                        }
                    }
                }

                map.put("id",adjustShift.getId());
                map.put("personName",personNameStr);
                map.put("jobNumber",jobNumber);
                map.put("companyName",companyName);

                List<AdjustShiftPerson> adjustShiftPersonList = adjustShiftPersonService.findByAdjustShiftId(adjustShift.getId());

                //调整前的班次
                // String shifIds = adjustShift.getOldShiftId();
                String shifIds = adjustShiftPersonList.get(0).getOldShiftId();
                List<String> shiftIdList = Arrays.asList(shifIds.split(","));
                String oldShiftName = null;
                for (String shiftId : shiftIdList) {
                    WorkShiftInfo workShiftInfo = workShiftInfoService.get(shiftId);
                    String workShiftName = workShiftInfo.getNumber() + "-" + workShiftInfo.getName();
                    if (StringUtils.isBlank(oldShiftName)) {
                        oldShiftName = workShiftName;
                    } else {
                        oldShiftName = oldShiftName + "," + workShiftName;
                    }

                }

                //调整后的班次
                //   String newShiftIds = adjustShift.getNewShiftId();

                String newShiftIds = adjustShiftPersonList.get(0).getNewShiftId();
                List<String> newShiftIdList = Arrays.asList(newShiftIds.split(","));
                String newShiftName = null;
                for (String shiftId : newShiftIdList) {
                    WorkShiftInfo workShiftInfo = workShiftInfoService.get(shiftId);
                    String workShiftName = workShiftInfo.getNumber() + "-" + workShiftInfo.getName();
                    if (StringUtils.isBlank(newShiftName)) {
                        newShiftName = workShiftName;
                    } else {
                        newShiftName = newShiftName + "," + workShiftName;
                    }

                }

                map.put("oldShiftName",oldShiftName);
                map.put("newShiftName",newShiftName);
                map.put("statusN",TypeNameUtil.getExamineTypeName(adjustShift.getStatus()));

                String createTime="";

                if(adjustShift.getCreateTime()!=null){
                    createTime = sdf.format(adjustShift.getCreateTime());
                }

                map.put("createTime",createTime);

                if(adjustShift.getType().equals("1")){
                    map.put("type","个人申请");
                }
                else{
                    map.put("type","上级安排");
                }

                map.put("adjustDate",adjustShift.getAdjustDate());

                String updateTime="";

                if(adjustShift.getUpdateTime()!=null){
                    updateTime = sdf.format(adjustShift.getUpdateTime());
                }
                map.put("updateTime",updateTime);

                mapList.add(map);
            }

            if (exportFlag) {
                String filePath = exportXls(mapList);
                msgResult.setData(filePath);
            } else {
                Map<String, Object> dataMap = PojoUtils.pageWrapper(page);
                dataMap.put("data", mapList);
                msgResult.setData(dataMap);
            }
            msgResult.setResult(true);
        }
        catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msgResult.setResult(false);
        }

        return msgResult;
    }


    private String exportXls(List<Map> mapList) throws IOException {
        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]);
        }

        for (int i=0;i<mapList.size();i++){
            Map<String,Object> map = mapList.get(i);

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

            int colIndex = 0;
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("createTime"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("personName"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("jobNumber"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("companyName"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("type"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("adjustDate"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("oldShiftName"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("newShiftName"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("statusN"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("updateTime"),""));
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        try {
            workbook.write(output);

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

            downloadUrl = OSSUtil.upload(ossConfig,"adjustShift","调班明细表.xls",input);
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);
        }

        return downloadUrl;
    }


    @ApiOperation(value="审核列表")
    @RequestMapping(value = "flowList",method = RequestMethod.POST)
    public MessageResult<List<ProcinstActivity>> flowList(String id, HttpServletRequest request){

        MessageResult<List<ProcinstActivity>> msgResult = new MessageResult<>();

        try {

            Procinst procinst = procinstService.findByBusinessKey(id);

            List<ProcinstActivity> procinstActivityList = procinstActivityService.findByProcinstId(procinst.getId());

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

            for (ProcinstActivity procinstActivity:procinstActivityList) {

                String auditPersonName = "";
                Date auditTime = null;

                List<ProcinstActUser> procinstActUserList = procinstActUserService.findByProcinstActivityId(procinstActivity.getId());

                for (ProcinstActUser procinstActUser : procinstActUserList) {
                    if (procinstActUser.getType().equals("1")) {
                        PersonInfo personInfo = personInfoService.get(Long.parseLong(procinstActUser.getUserId()));
                        if (personInfo != null) {
                            auditPersonName += personInfo.getName() + ",";
                        }
                        auditTime = procinstActUser.getFinishTime();
                    }
                }

                if (StringUtils.isNotEmpty(auditPersonName)) {
                    auditPersonName = auditPersonName.substring(0, auditPersonName.lastIndexOf(","));
                }

                procinstActivity.setAuditPersonName(auditPersonName);
                if (auditTime != null) {
                    String auditTimeStr = sdf.format(auditTime);
                    procinstActivity.setAuditTime(auditTimeStr);
                }
            }

            msgResult.setResult(true);
            msgResult.setData(procinstActivityList);
        }
        catch(Exception ex){

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

        return msgResult;
    }
}
