package cn.gtmap.estateplat.config.core.service.impl;

import cn.gtmap.estateplat.config.core.mapper.config.BdcZjjlMapper;
import cn.gtmap.estateplat.config.core.service.BdcXmService;
import cn.gtmap.estateplat.config.core.service.BdcZdGlService;
import cn.gtmap.estateplat.config.core.service.BdcZjjlService;
import cn.gtmap.estateplat.config.utils.Constants;
import cn.gtmap.estateplat.config.utils.PlatformUtil;
import cn.gtmap.estateplat.config.utils.PublicUtil;
import cn.gtmap.estateplat.core.support.mybatis.mapper.EntityMapper;
import cn.gtmap.estateplat.core.support.mybatis.mapper.Example;
import cn.gtmap.estateplat.model.server.core.BdcXm;
import cn.gtmap.estateplat.model.server.core.BdcZjjl;
import com.google.common.collect.Maps;
import com.gtis.common.util.UUIDGenerator;
import com.gtis.plat.service.SysSignService;
import com.gtis.plat.service.SysWorkFlowInstanceService;
import com.gtis.plat.service.WorkFlowCoreService;
import com.gtis.plat.vo.PfActivityVo;
import com.gtis.plat.vo.PfSignVo;
import com.gtis.plat.vo.PfUserVo;
import com.gtis.plat.vo.PfWorkFlowInstanceVo;
import com.gtis.plat.wf.WorkFlowInfo;
import com.gtis.web.SessionUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BdcZjjlServiceImpl implements BdcZjjlService {
    protected final Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private EntityMapper entityMapper;
    @Autowired
    private BdcXmService bdcXmService;
    @Autowired
    private SysSignService sysSignService;
    @Autowired
    private SysWorkFlowInstanceService sysWorkFlowInstanceService;
    @Autowired
    private BdcZdGlService bdcZdGlService;
    @Autowired
    private BdcZjjlMapper bdcZjjlMapper;
    @Autowired
    WorkFlowCoreService workFlowCoreService;


    public BdcZjjl getBdcZjjlListByWiid(String wiid) {
        BdcZjjl bdcZjjl = null;
        if (StringUtils.isNotBlank(wiid)) {
            Example example = new Example(BdcZjjl.class);
            example.createCriteria().andEqualTo("wiid", wiid);
            List<BdcZjjl> bdcZjjlList = entityMapper.selectByExample(example);
            if (CollectionUtils.isNotEmpty(bdcZjjlList)) {
                bdcZjjl = bdcZjjlList.get(0);
            }
        }
        return bdcZjjl;
    }

    @Override
    public String saveBdczjjl(String wiid, String zjr, String zjyy, String zjzt) {
        String msg = "";
        List<BdcXm> bdcXmList = bdcXmService.getBdcXmListByWiid(wiid);
        BdcZjjl bdcZjjl = getBdcZjjlListByWiid(wiid);
        if (bdcZjjl == null) {
            bdcZjjl = new BdcZjjl();
            bdcZjjl.setZjjlid(UUIDGenerator.generate18());
        }
        if (StringUtils.isBlank(zjzt)) {
            bdcZjjl.setZjzt("0");
        } else {
            bdcZjjl.setZjzt(zjzt);
        }
        if (StringUtils.isBlank(zjr)) {
            bdcZjjl.setZjr(SessionUtil.getCurrentUser().getUsername());
        }
        bdcZjjl.setZjksrq(new Date());


        if (CollectionUtils.isNotEmpty(bdcXmList)) {
            BdcXm bdcXm = bdcXmList.get(0);
            bdcZjjl.setCjr(bdcXm.getCjr());
            bdcZjjl.setWiid(bdcXm.getWiid());
            bdcZjjl.setXmbh(bdcXm.getBh());
            String sqlxdm = "";
            //获取平台的申请类型代码,主要为了合并
            if (StringUtils.isNotBlank(bdcXm.getWiid())) {
                PfWorkFlowInstanceVo pfWorkFlowInstanceVo = sysWorkFlowInstanceService.getWorkflowInstance(bdcXm.getWiid());
                if (pfWorkFlowInstanceVo != null && StringUtils.isNotBlank(pfWorkFlowInstanceVo.getWorkflowDefinitionId())) {
                    sqlxdm = bdcZdGlService.getBdcSqlxdmByWdid(pfWorkFlowInstanceVo.getWorkflowDefinitionId());
                }
            }
            bdcZjjl.setSqlx(sqlxdm);

            HashMap map = Maps.newHashMap();
            map.put("proId", bdcXm.getProid());
            List<PfSignVo> pfSignVoList = sysSignService.getSignListOrderfield(map);
            if (CollectionUtils.isNotEmpty(pfSignVoList)) {
                for (PfSignVo pfSignVo : pfSignVoList) {
                    if (StringUtils.equals(Constants.SIGN_KEY_CSR, pfSignVo.getSignKey())) {
                        bdcZjjl.setSpr(pfSignVo.getSignName());
                    }
                }
            }
        }
        entityMapper.saveOrUpdate(bdcZjjl, bdcZjjl.getZjjlid());
        msg = "success";
        return msg;
    }

    @Override
    public List<PfUserVo> getPfuserByRoleName(String zjjsmc) {
        return bdcZjjlMapper.getPfuserByRoleName(zjjsmc);
    }

    @Override
    public void exportZjjlxx(List<Map> rows, HttpServletRequest request, HttpServletResponse response) {
        //一、从后台拿数据
        if (null == request || null == response) {
            return;
        }
        try {
            //二、 数据转成excel
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/x-download");
            String fileName = "质检记录" + getCurrStrDate() + ".xlsx";
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            // 第一步：定义一个新的工作簿
            XSSFWorkbook wb = new XSSFWorkbook();
            // 第二步：创建一个Sheet页
            XSSFSheet sheet = wb.createSheet("质检记录");
            sheet.setDefaultRowHeight((short) (2 * 256));//设置行高
            sheet.setColumnWidth(0, 4000);//设置列宽
            sheet.setColumnWidth(1, 5500);
            sheet.setColumnWidth(2, 5500);
            sheet.setColumnWidth(3, 5500);
            sheet.setColumnWidth(4, 5500);
            sheet.setColumnWidth(5, 5500);
            sheet.setColumnWidth(6, 5500);
            sheet.setColumnWidth(6, 3000);
            XSSFFont font = wb.createFont();
            font.setFontName("宋体");
            font.setFontHeightInPoints((short) 16);

            XSSFRow row = sheet.createRow(0);
            XSSFCell cell = row.createCell(0);
            cell.setCellValue("受理编号");
            cell = row.createCell(1);
            cell.setCellValue("业务类型 ");
            cell = row.createCell(2);
            cell.setCellValue("创建人");
            cell = row.createCell(3);
            cell.setCellValue("审批人");
            cell = row.createCell(4);
            cell.setCellValue("质检人");
            cell = row.createCell(5);
            cell.setCellValue("质检开始时间 ");
            cell = row.createCell(6);
            cell.setCellValue("质检结束日期 ");
            cell = row.createCell(7);
            cell.setCellValue("状态 ");

            XSSFRow xssfrows;
            XSSFCell cells;
            for (int i = 0; i < rows.size(); i++) {
                // 第三步：在这个sheet页里创建一行
                xssfrows = sheet.createRow(i + 1);
                // 第四步：在该行创建一个单元格
                cells = xssfrows.createCell(0);
                // 第五步：在该单元格里设置值
                cells.setCellValue(PublicUtil.ternaryOperator(rows.get(i).get("XMBH")));
                cells = xssfrows.createCell(1);
                cells.setCellValue(PublicUtil.ternaryOperator(rows.get(i).get("SQLXMC")));
                cells = xssfrows.createCell(2);
                cells.setCellValue(PublicUtil.ternaryOperator(rows.get(i).get("CJR")));
                cells = xssfrows.createCell(3);
                cells.setCellValue(PublicUtil.ternaryOperator(rows.get(i).get("SPR")));
                cells = xssfrows.createCell(4);
                cells.setCellValue(PublicUtil.ternaryOperator(rows.get(i).get("ZJR")));

                cells = xssfrows.createCell(5);
                String zjksrq = PublicUtil.ternaryOperator(rows.get(i).get("ZJKSRQ"));
                cells.setCellValue(zjksrq);
                if (StringUtils.isNotBlank(zjksrq)) {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    Date date = format.parse(zjksrq);
                    zjksrq = format.format(date);
                    cells.setCellValue(zjksrq);
                }

                cells = xssfrows.createCell(6);
                String zjjsrq = PublicUtil.ternaryOperator(rows.get(i).get("ZJJSRQ"));
                cells.setCellValue(zjjsrq);
                if (StringUtils.isNotBlank(zjjsrq)) {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    Date date = format.parse(zjjsrq);
                    zjjsrq = format.format(date);
                    cells.setCellValue(zjjsrq);
                }
                cells = xssfrows.createCell(7);
                if (StringUtils.equalsIgnoreCase(PublicUtil.ternaryOperator(rows.get(i).get("ZJBHG")), "1")) {
                    cells.setCellValue("不合格");
                } else {
                    cells.setCellValue("合格");
                }
            }
            OutputStream out = response.getOutputStream();
            wb.write(out);
            out.close();
        } catch (IOException e) {
            logger.error("质检记录导出错误", e);
        } catch (ParseException e) {
            logger.error("解析错误", e);
        }

    }

    @Override
    public void exportZjtjxx(List<Map> rows, HttpServletRequest request, HttpServletResponse response) {
        //一、从后台拿数据
        if (null == request || null == response) {
            return;
        }
        try {
            //二、 数据转成excel
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/x-download");
            String fileName = "质检统计" + getCurrStrDate() + ".xlsx";
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            // 第一步：定义一个新的工作簿
            XSSFWorkbook wb = new XSSFWorkbook();
            // 第二步：创建一个Sheet页
            XSSFSheet sheet = wb.createSheet("质检统计");
            sheet.setDefaultRowHeight((short) (2 * 256));//设置行高
            sheet.setColumnWidth(0, 5500);//设置列宽
            sheet.setColumnWidth(1, 5500);
            XSSFFont font = wb.createFont();
            font.setFontName("宋体");
            font.setFontHeightInPoints((short) 16);

            XSSFRow row = sheet.createRow(0);
            XSSFCell cell = row.createCell(0);
            cell.setCellValue("质检人");
            cell = row.createCell(1);
            cell.setCellValue("质检数量");
            cell = row.createCell(2);

            XSSFRow xssfrows;
            XSSFCell cells;
            for (int i = 0; i < rows.size(); i++) {
                // 第三步：在这个sheet页里创建一行
                xssfrows = sheet.createRow(i + 1);
                // 第四步：在该行创建一个单元格
                cells = xssfrows.createCell(0);
                // 第五步：在该单元格里设置值
                cells.setCellValue(PublicUtil.ternaryOperator(rows.get(i).get("ZJR")));
                cells = xssfrows.createCell(1);
                cells.setCellValue(PublicUtil.ternaryOperator(rows.get(i).get("ZJSL")));
                cells = xssfrows.createCell(2);
            }
            OutputStream out = response.getOutputStream();
            wb.write(out);
            out.close();
        } catch (IOException e) {
            logger.error("质检统计导出错误", e);
        }
    }


    @Override
    public void updateBdczjjl(BdcZjjl bdcZjjl) {
        if (bdcZjjl != null && StringUtils.isNotBlank(bdcZjjl.getWiid())) {
            BdcZjjl zjjl = getBdcZjjlListByWiid(bdcZjjl.getWiid());
            if (zjjl != null) {
                zjjl.setZjzt(bdcZjjl.getZjzt());
                zjjl.setZjbhg(bdcZjjl.getZjbhg());
                zjjl.setZjr(bdcZjjl.getZjr());
                zjjl.setZjjsrq(bdcZjjl.getZjjsrq());
                entityMapper.saveOrUpdate(zjjl, zjjl.getZjjlid());
            }
        }
    }

    @Override
    public String turnBack(String wiid, String thyj) {
        String result = StringUtils.EMPTY;
        String adids = StringUtils.EMPTY;
        try {
            String taskid = PlatformUtil.getTaskidByWiid(wiid);
            String userid = SessionUtil.getCurrentUserId();
            WorkFlowInfo info = workFlowCoreService.getWorkFlowTurnBackInfo(userid, taskid);
            List<PfActivityVo> backActivitys = info.getTargetActivitys();
            if (CollectionUtils.isNotEmpty(backActivitys)) {
                for (PfActivityVo backActivity : backActivitys) {
                    if (StringUtils.equals(Constants.WORKFLOW_SL, backActivity.getActivityName())) {
                        adids = backActivity.getActivityDefinitionId();
                        break;
                    }
                }
            }
            result = PlatformUtil.turnBack(wiid, taskid, SessionUtil.getCurrentUserId(), adids, thyj);
        } catch (Exception e) {
            logger.error("流程退回错误", e);
        }
        return result;
    }

    public String getCurrStrDate() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        return format.format(new Date());
    }
}
