package com.yeejoin.amos.boot.module.jcs.biz.service.impl;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Sequence;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPTable;
import com.yeejoin.amos.boot.biz.common.utils.PdfUtils;
import com.yeejoin.amos.boot.module.common.api.entity.DynamicFormInstance;
import com.yeejoin.amos.boot.module.common.biz.service.impl.DynamicFormInstanceServiceImpl;
import com.yeejoin.amos.boot.module.jcs.api.dto.ShiftChangeDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.ShiftChangeDutyDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.ShiftChangeInfoDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.ShiftChangePowerDto;
import com.yeejoin.amos.boot.module.jcs.api.entity.ShiftChange;
import com.yeejoin.amos.boot.module.jcs.api.mapper.ShiftChangeMapper;
import com.yeejoin.amos.boot.module.jcs.api.service.IShiftChangeService;

/**
 * 交接班记录表服务实现类
 *
 * @author system_generator
 * @date 2021-07-13
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ShiftChangeServiceImpl extends BaseService<ShiftChangeDto, ShiftChange, ShiftChangeMapper> implements IShiftChangeService {

    @Autowired
    DynamicFormInstanceServiceImpl dynamicFormInstanceService;

    @Autowired
    Sequence sequence;

    private final String GROUP_CODE = "shiftChanges";

    @Override
    public Map<String, Object> createFormAndEntry(Map<String, Object> model) {
        Long instanceId = dynamicFormInstanceService.commonSave(GROUP_CODE, model);
        ShiftChange shiftChange = (ShiftChange) Bean.mapToBean(model, ShiftChange.class);
        shiftChange.setInstanceId(instanceId);
        shiftChange.setDutyJson(shiftChange.getDutyJson() == null ? new JSONObject() : shiftChange.getDutyJson());
        shiftChange.setPowerJson(shiftChange.getPowerJson() == null ? new JSONObject() : shiftChange.getPowerJson());
        this.save(shiftChange);
        return model;
    }

    @Override
    public Boolean removeOneById(Long sequenceNbr) {
        ShiftChangeDto shiftChange = this.queryBySeq(sequenceNbr);
        if (shiftChange != null) {
            dynamicFormInstanceService.remove(new LambdaQueryWrapper<DynamicFormInstance>().eq(DynamicFormInstance::getInstanceId, shiftChange.getInstanceId()));
            this.removeById(sequenceNbr);
        }
        return null;
    }

    @Override
    public Map<String, Object> getOneBySeq(Long sequenceNbr) {
        ShiftChangeDto shiftChange = this.queryBySeq(sequenceNbr);
        if (shiftChange == null) {
            throw new BadRequest("指定数据不存在");
        }
        Map<String, Object> baseInfo = dynamicFormInstanceService.getOneMap(shiftChange.getInstanceId(), GROUP_CODE);
        Map<String, Object> cxc = Bean.BeantoMap(shiftChange);
        baseInfo.putAll(cxc);
        return baseInfo;
    }

    @Override
    public IPage<Map<String, Object>> queryForShiftChangePage(int current, int size) {
        IPage<Map<String, Object>> page = dynamicFormInstanceService.pageList(current,size,GROUP_CODE);
        List<ShiftChange> shiftChanges = this.list();
        Map<Long,ShiftChange> shiftChangeMap = shiftChanges.stream().collect(Collectors.toMap(ShiftChange::getInstanceId, Function.identity()));
        page.getRecords().forEach(r->{
            //instanceId 必输 所以未进行 null判断
            ShiftChange shiftChange = shiftChangeMap.get(Long.parseLong(r.get("instanceId").toString()));
            r.putAll(Bean.BeantoMap(shiftChange));
        });
        return page;
    }

    @Override
    public List<Map<String, Object>> queryForShiftChangeList() {
        List<Map<String, Object>> list = dynamicFormInstanceService.listAll(GROUP_CODE);
        List<ShiftChange> shiftChanges = this.list();
        Map<Long,ShiftChange> shiftChangeMap = shiftChanges.stream().collect(Collectors.toMap(ShiftChange::getInstanceId, Function.identity()));
        list.forEach(r -> {
            //instanceId 必输 所以未进行 null判断
            ShiftChange shiftChange = shiftChangeMap.get(Long.parseLong(r.get("instanceId").toString()));
            r.putAll(Bean.BeantoMap(shiftChange));
        });
        return list;
    }

    @Override
    public Map<String, Object> lastRecord() {
        List<Map<String, Object>> list = dynamicFormInstanceService.listAll(GROUP_CODE);
        list = list.stream().sorted(Comparator.comparing(e->e.get("instanceId"), Comparator.comparingLong(s -> -Long.parseLong(s.toString())))).collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>();
        map = list.isEmpty() ? map : list.get(0);
        return map;
    }

    @Override
    public void exportPdfById(HttpServletResponse response, Long shiftChangeId) throws IOException, DocumentException {
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/pdf;charset=UTF-8");
        // 下载文件的默认名称
        String fileName = "交接班记录表.pdf";
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName,
                StandardCharsets.UTF_8.name()));
        // 创建document对象
        Document document = PdfUtils.createFile(response);
        // 获取pdf文件数据
        ShiftChangeDto shiftChange = this.queryBySeq(shiftChangeId);
        ShiftChangeInfoDto ShiftChangeInfoDto = new ShiftChangeInfoDto();
        if (shiftChange != null) {
            Map<String, Object> baseInfo = dynamicFormInstanceService.getOneMap(shiftChange.getInstanceId(), GROUP_CODE);
            ShiftChangeInfoDto = (ShiftChangeInfoDto)  Bean.mapToBean(baseInfo, ShiftChangeInfoDto.class);
        } else {
            shiftChange = new ShiftChangeDto();
        }
        // 创建pdf格式
        createPDFReport(document,ShiftChangeInfoDto,shiftChange);
    }

    /**
     * 创建pdf文件样式数据
     */
    public  void createPDFReport(Document document,ShiftChangeInfoDto shiftChangeInfoDto,ShiftChangeDto shiftChange) throws IOException, DocumentException {
        document.open();
        // 基本样式参数
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font cellContent = new Font(bfChinese, 11, Font.NORMAL);
        Font cellTitle = new Font(bfChinese, 11, Font.BOLD);
        Font title = new Font(bfChinese, 20, Font.BOLD);
        int size = 30;
        int smallSize = 0;

        // 表头
        Paragraph docTitle = new Paragraph("119接警坐席交接班记录\n", title);
        docTitle.setAlignment(Element.ALIGN_CENTER);

        // 表格内容
        PdfPTable table1 = PdfUtils.createTable(8);
        int[] widths = { 12, 25, 25, 25, 25, 20, 25, 25 };
        table1.setWidthPercentage(100);
        table1.setSpacingBefore(10);
        table1.setWidths(widths);

        SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss" );
        String recDare = shiftChange.getRecDate() != null ? sdf.format(shiftChange.getRecDate()) : "";

        // 第一行
        table1.addCell(PdfUtils.createCell("时间", cellTitle,Element.ALIGN_CENTER,1,1,
                size,1,1,0,1));
        table1.addCell(PdfUtils.createCell(recDare, cellContent,Element.ALIGN_CENTER,3,1,
                size,1,1,0,0));
        table1.addCell(PdfUtils.createCell("值班领导", cellTitle,Element.ALIGN_CENTER,1,1,
                size,1,1,0,0));
        table1.addCell(PdfUtils.createCell(shiftChangeInfoDto.getJsDutyLeader(), cellContent,Element.ALIGN_CENTER,3,1,
                size,1,1,0,0));

        // 第二行
        table1.addCell(PdfUtils.createCell("值\n班\n员", cellTitle,Element.ALIGN_CENTER,1,3,
                size,1,1,0,1));
        table1.addCell(PdfUtils.createCell("正班", cellTitle,Element.ALIGN_CENTER,1,1,
                size,1,1,0,0));
        table1.addCell(PdfUtils.createCell(shiftChangeInfoDto.getDutyPersonOne(), cellContent,Element.ALIGN_CENTER,1,1,
                size,1,1,0,0));
        table1.addCell(PdfUtils.createCell("值班开始时间", cellContent,Element.ALIGN_CENTER,1,1,size,1,1,0,0));
        table1.addCell(PdfUtils.createCell("交接班时间", cellContent,Element.ALIGN_CENTER,1,1,size,1,1,0,0));
        table1.addCell(PdfUtils.createCell("接班员", cellTitle,Element.ALIGN_CENTER,1,3,size,1,1,0,0));
        table1.addCell(PdfUtils.createCell("正班", cellTitle,Element.ALIGN_CENTER,1,1,size,1,1,0,0));
        table1.addCell(PdfUtils.createCell(shiftChangeInfoDto.getSucceedPersonOne(), cellContent,Element.ALIGN_CENTER,1,1,size,1,1,0,0));

        // 第三行
        table1.addCell(PdfUtils.createCell("副班", cellTitle,Element.ALIGN_CENTER,1,1,size,1,1,0,0));
        table1.addCell(PdfUtils.createCell(shiftChangeInfoDto.getDutyPersonTwo(), cellContent,Element.ALIGN_CENTER,1,1,size,1,1,0,0));
        table1.addCell(PdfUtils.createCell(shiftChangeInfoDto.getBeginDate(), cellContent,Element.ALIGN_CENTER,1,1,size,1,1,0,0));
        table1.addCell(PdfUtils.createCell(shiftChangeInfoDto.getEndDate(), cellContent,Element.ALIGN_CENTER,1,1,size,1,1,0,0));
        table1.addCell(PdfUtils.createCell("副班", cellTitle,Element.ALIGN_CENTER,1,1,size,1,1,0,0));
        table1.addCell(PdfUtils.createCell(shiftChangeInfoDto.getSucceedPersonTwo(), cellContent,Element.ALIGN_CENTER,1,1,size,1,1,0,0));

        // 第四行
        table1.addCell(PdfUtils.createCell("经理", cellTitle,Element.ALIGN_CENTER,1,1,size,1,1,0,0));
        table1.addCell(PdfUtils.createCell(shiftChangeInfoDto.getDutyPersonLeader(), cellContent,Element.ALIGN_CENTER,3,1,size,1,1,0,0));
        table1.addCell(PdfUtils.createCell("经理", cellTitle,Element.ALIGN_CENTER,1,1,size,1,1,0,0));
        table1.addCell(PdfUtils.createCell(shiftChangeInfoDto.getSucceedPersonLeader(), cellContent,Element.ALIGN_CENTER,1,1,size,1,1,0,0));

        JSONObject dutyJson = shiftChange.getDutyJson();
        JSONObject powerJson = shiftChange.getPowerJson();
        ShiftChangeDutyDto dutyDto = new ShiftChangeDutyDto();
        ShiftChangePowerDto powerDto = new ShiftChangePowerDto();

        if (dutyJson != null) {
            dutyDto = JSONObject.toJavaObject(dutyJson, ShiftChangeDutyDto.class);
        }
        if (powerJson != null) {
            powerDto = JSONObject.toJavaObject(powerJson, ShiftChangePowerDto.class);
        }

        List<String> infoList = dutyDto.getAlertInfoList();
        List<String> powerList = powerDto.getTransferContent();
        int infoSize = infoList != null ? infoList.size() : 0;
        int powerSize = powerList != null ? powerList.size() : 0;
        String alarmRemark = dutyDto.getAlarmRemark() == null ? "无" : dutyDto.getAlarmRemark();
        String powerRemark = powerDto.getPowerRemark() == null ? "无" : powerDto.getPowerRemark();

        // 值班情况
        table1.addCell(PdfUtils.createCell("值\n班\n情\n况", cellTitle,Element.ALIGN_CENTER,1,6+powerSize+infoSize,size,1,1,0,1));
        table1.addCell(PdfUtils.createCell("接警情况:", cellTitle,Element.ALIGN_LEFT,7,1,size,1,1,0,0));
        table1.addCell(PdfUtils.createCell("接警"+ dutyDto.getCalledCount() +"起", cellContent, Element.ALIGN_CENTER,1,1,smallSize,0,0,0,0));
        table1.addCell(PdfUtils.createCell("未结案" + dutyDto.getUnFinishedCount() + "起", cellContent,Element.ALIGN_CENTER,2,1,smallSize,0,0,0,0));
        table1.addCell(PdfUtils.createCell("已结案" + dutyDto.getFinishedCount() + "起", cellContent,Element.ALIGN_CENTER,2,1,smallSize,0,0,0,0));
        table1.addCell(PdfUtils.createCell("重大警情" + dutyDto.getMajorAlertCount() + "起", cellContent,Element.ALIGN_CENTER,2,1,smallSize,0,1,0,0));
        if (!ObjectUtils.isEmpty(infoList)) {
            for (String info : infoList) {
                table1.addCell(PdfUtils.createCell(info, cellContent,Element.ALIGN_LEFT,7,1,smallSize,0,1,0,0));
            }
        }
        table1.addCell(PdfUtils.createCell("备注:"+alarmRemark, cellContent,Element.ALIGN_LEFT,7,1,smallSize,0,1,0,0));
        table1.addCell(PdfUtils.createCell("力量出动:", cellTitle,Element.ALIGN_LEFT,7,1,size,0,1,0,0));
        table1.addCell(PdfUtils.createCell("调派任务"+ powerDto.getTransfer_count() +"起", cellContent,Element.ALIGN_CENTER,1,1,smallSize,0,0,0,0));
        table1.addCell(PdfUtils.createCell("调派车辆" + powerDto.getCar_count() + "辆次", cellContent,Element.ALIGN_CENTER,2,1,smallSize,0,0,0,0));
        table1.addCell(PdfUtils.createCell("已完成任务" + powerDto.getEnd_count() + "起", cellContent,Element.ALIGN_CENTER,2,1,smallSize,0,0,0,0));
        table1.addCell(PdfUtils.createCell("未归队车辆" + powerDto.getNo_return_car_count() + "辆", cellContent,Element.ALIGN_CENTER,2,1,smallSize,0,1,0,0));
        if (!ObjectUtils.isEmpty(powerList)) {
            for (String powerInfo : powerList) {
                table1.addCell(PdfUtils.createCell(powerInfo, cellContent,Element.ALIGN_LEFT,7,1,smallSize,0,1,0,0));
            }
        }
        table1.addCell(PdfUtils.createCell("备注:"+powerRemark, cellContent,Element.ALIGN_LEFT,7,1,smallSize,0,1,0,0));

        // 移交事宜
        table1.addCell(PdfUtils.createCell("移\n交\n事\n宜", cellTitle,Element.ALIGN_CENTER,1,1,size,1,1,1,1));
        table1.addCell(PdfUtils.createCell(shiftChange.getRemark(), cellContent,Element.ALIGN_LEFT,7,1,120,1,1,1,0));

        /*bug3413 交接班，下载的交接班记录表中缺少日常工作项 陈召 2021-11-08*/
        // 日常工作
        table1.addCell(PdfUtils.createCell("日\n常\n工\n作", cellTitle,Element.ALIGN_CENTER,1,1,size,1,1,1,1));
        table1.addCell(PdfUtils.createCell(shiftChange.getDutyWork(), cellContent,Element.ALIGN_LEFT,7,1,120,1,1,1,0));
        /*bug3413 交接班，下载的交接班记录表中缺少日常工作项 陈召 2021-11-08*/
        try{
            document.add(docTitle);
            document.add(table1);;
        }catch (DocumentException E){
            throw  new RuntimeException("PDF写入文件报错");
        }
        document.close();
    }
}
