package com.ruoyi.project.plant.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;

import com.ruoyi.common.utils.document.DocumentHandler;
import com.ruoyi.common.utils.document.PDFTemplateUtil;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.project.plant.domain.*;
import com.ruoyi.project.plant.service.*;
import freemarker.template.Template;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 目标措施Controller
 *
 * @author ruoyi
 * @date 2021-07-05
 */
@RestController
@RequestMapping("/plant/targetmeasures")
public class TTargetmeasuresController extends BaseController
{
    @Autowired
    private ITTargetmeasuresService tTargetmeasuresService;

    @Autowired
    private ITTargetlistService tTargetlistService;

    @Autowired
    private ITStaffmgrService tStaffmgrService;

    @Autowired
    private ITTargetagreementService tTargetagreementService;

    @Autowired
    private ITTargetyardstickService tTargetyardstickService;

    /**
     * 查询目标措施列表
     */
    @PreAuthorize("@ss.hasPermi('plant:targetmeasures:list')")
    @GetMapping("/list")
    public AjaxResult list(TTargetmeasures tTargetmeasures)
    {
        List<TTargetmeasures> list = tTargetmeasuresService.selectTTargetmeasuresList(tTargetmeasures);
        return AjaxResult.success(list);
    }

    /**
     * 导出目标措施列表
     */
    @PreAuthorize("@ss.hasPermi('plant:targetmeasures:export')")
    @Log(title = "目标措施", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TTargetmeasures tTargetmeasures)
    {
        List<TTargetmeasures> list = tTargetmeasuresService.selectTTargetmeasuresList(tTargetmeasures);
        ExcelUtil<TTargetmeasures> util = new ExcelUtil<TTargetmeasures>(TTargetmeasures.class);
        return util.exportExcel(list, "targetmeasures");
    }

    /**
     * 获取目标措施详细信息
     */
    @PreAuthorize("@ss.hasPermi('plant:targetmeasures:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tTargetmeasuresService.selectTTargetmeasuresById(id));
    }

    /**
     * 新增目标措施
     */
    @PreAuthorize("@ss.hasPermi('plant:targetmeasures:add')")
    @Log(title = "目标措施", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TTargetmeasures tTargetmeasures)
    {
        //单元格背景颜色状态整改
        if (tTargetmeasures.getFirstquarter() == "" || tTargetmeasures.getFirstquarter() == null) {
            tTargetmeasures.setFirstquarterStatus(null);
        }else if (tTargetmeasures.getFirstquarterStatus() != null) {
        }else {
            tTargetmeasures.setFirstquarterStatus("2");
        }
        if (tTargetmeasures.getHalfyear() == "" || tTargetmeasures.getHalfyear() == null) {
            tTargetmeasures.setHalfyearStatus(null);
        }else if (tTargetmeasures.getHalfyearStatus() != null) {
        }else {
            tTargetmeasures.setHalfyearStatus("2");
        }
        if (tTargetmeasures.getThreequarter() == "" || tTargetmeasures.getThreequarter() == null) {
            tTargetmeasures.setThreequarterStatus(null);
        }else if (tTargetmeasures.getThreequarterStatus() != null) {
        }else {
            tTargetmeasures.setThreequarterStatus("2");
        }
        if (tTargetmeasures.getAnnual() == "" || tTargetmeasures.getAnnual() == null) {
            tTargetmeasures.setAnnualStatus(null);
        }else if (tTargetmeasures.getAnnualStatus() != null) {
        }else {
            tTargetmeasures.setAnnualStatus("2");
        }
        agreement(tTargetmeasures);
        return toAjax(tTargetmeasuresService.insertTTargetmeasures(tTargetmeasures));
    }

    /**
     * 修改目标措施
     */
    @PreAuthorize("@ss.hasPermi('plant:targetmeasures:edit')")
    @Log(title = "目标措施", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TTargetmeasures tTargetmeasures)
    {
        //单元格背景颜色状态整改
        if (tTargetmeasures.getFirstquarter() == "" || tTargetmeasures.getFirstquarter() == null) {
            tTargetmeasures.setFirstquarterStatus(null);
        }else if (tTargetmeasures.getFirstquarterStatus() != null) {
        }else {
            tTargetmeasures.setFirstquarterStatus("2");
        }
        if (tTargetmeasures.getHalfyear() == "" || tTargetmeasures.getHalfyear() == null) {
            tTargetmeasures.setHalfyearStatus(null);
        }else if (tTargetmeasures.getHalfyearStatus() != null) {
        }else {
            tTargetmeasures.setHalfyearStatus("2");
        }
        if (tTargetmeasures.getThreequarter() == "" || tTargetmeasures.getThreequarter() == null) {
            tTargetmeasures.setThreequarterStatus(null);
        }else if (tTargetmeasures.getThreequarterStatus() != null) {
        }else {
            tTargetmeasures.setThreequarterStatus("2");
        }
        if (tTargetmeasures.getAnnual() == "" || tTargetmeasures.getAnnual() == null) {
            tTargetmeasures.setAnnualStatus(null);
        }else if (tTargetmeasures.getAnnualStatus() != null) {
        }else {
            tTargetmeasures.setAnnualStatus("2");
        }
        agreement(tTargetmeasures);
        return toAjax(tTargetmeasuresService.updateTTargetmeasures(tTargetmeasures));
    }

    /**
     * 删除目标措施
     */
    @PreAuthorize("@ss.hasPermi('plant:targetmeasures:remove')")
    @Log(title = "目标措施", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tTargetmeasuresService.deleteTTargetmeasuresByIds(ids));
    }

    //目标协议关联
    public void agreement(TTargetmeasures tTargetmeasures) {
        TTargetlist targetlist = tTargetlistService.selectTTargetlistById(tTargetmeasures.getTargetlistId());
        TTargetlist tTargetlist = tTargetlistService.selectTTargetlistById(targetlist.getParentId());
        TTargetagreement agreement = new TTargetagreement();
        agreement.setYear(tTargetlist.getYear());
        List<TTargetagreement> tTargetagreements = tTargetagreementService.selectTTargetagreementList(agreement);
        if (tTargetmeasures.getResponsible() != null) {
            String[] responsible = tTargetmeasures.getResponsible().split(",");
            for (String r : responsible) {
                //判断此人是否为经理（0为不是）
                int p = 0;
                if (tStaffmgrService.selectTStaffmgrByStaffId(r).getActualpost().equals("24")) {
                    p = 1;
                }
                if (p == 0) {
                    logger.info("此人不是经理");
                    logger.info("responsible:" + r);
                    //判断是否存在此人的目标协议(0为无）
                    int m = 0;
                    for (TTargetagreement a : tTargetagreements) {
                        if (r.equals(a.getEmployeeid())) {
                            m = 1;
                        }
                    }
                    if (m == 0) {
                        logger.info("此人暂无目标协议");
                        TTargetagreement tTargetagreement = new TTargetagreement();
                        tTargetagreement.setYear(tTargetlist.getYear());
                        tTargetagreement.setEmployeeid(r);
                        tTargetagreement.setDeptId(tTargetlist.getDeptId());
                        tTargetagreementService.insertTTargetagreement(tTargetagreement);
                        TTargetyardstick tTargetyardstick = new TTargetyardstick();
                        tTargetyardstick.setAgreementId(tTargetagreement.getId());
                        tTargetyardstick.setTarget(targetlist.getYardstick());
                        String[] insertYardsticks = tTargetmeasures.getMeasures().split("\\.");
                        // 王子文 2022年8月10日
                        // 生产环境新增时，抛出ArrayOutOfBondsException
                        // 解决方案：暂时将setYardstick()方法中数组参数的下标修改为0
//                        tTargetyardstick.setYardstick("-" + insertYardsticks[1]);
                        tTargetyardstick.setYardstick("-" + insertYardsticks[0]);
                        tTargetyardstick.setAchieveDate(tTargetmeasures.getExpectedDate());
                        tTargetyardstick.setPartners(targetlist.getPartners());
                        tTargetyardstickService.insertTTargetyardstick(tTargetyardstick);
                    }else {
                        logger.info("此人存在目标协议");
                        // 王子文 2022年8月10日
                        // 生产环境新增时，抛出TooManyResultsException
                        // 数据库中存在不同年份数据，导致selectTTargetagreementByEmployeeid(r)的resultType与结果数据类型不一致
                        // 解决方案：重写接口，将年份加入检索条件
//                        TTargetagreement tTargetagreement = tTargetagreementService.selectTTargetagreementByEmployeeid(r);
                        TTargetagreement queryParams = new TTargetagreement();
                        queryParams.setEmployeeid(r);
                        queryParams.setYear(tTargetlist.getYear());
                        TTargetagreement tTargetagreement = tTargetagreementService.selectTTargetagreementByEmployeeidAndYear(queryParams);
                        List<TTargetyardstick> tTargetyardsticks = tTargetyardstickService.selectTTargetyardstickByAgreementId(tTargetagreement.getId());
                        //判断是否存在此条判定标准(0为无,若存在判定标准targetyardstick为此条判定标准）
                        int n = 0;
                        TTargetyardstick targetyardstick = new TTargetyardstick();
                        for (TTargetyardstick y : tTargetyardsticks) {
                            if (y.getTarget().equals(targetlist.getYardstick())) {
                                n = 1;
                                targetyardstick = y;
                            }
                        }
                        if (n == 0) {
                            logger.info("此人暂无此条判定标准");
                            TTargetyardstick tTargetyardstick = new TTargetyardstick();
                            tTargetyardstick.setAgreementId(tTargetagreement.getId());
                            tTargetyardstick.setTarget(targetlist.getYardstick());
                            String[] insertYardsticks = tTargetmeasures.getMeasures().split("\\.");
//                            tTargetyardstick.setYardstick("-" + insertYardsticks[1]);
                            tTargetyardstick.setYardstick("-" + insertYardsticks[0]);
                            tTargetyardstick.setAchieveDate(tTargetmeasures.getExpectedDate());
                            tTargetyardstick.setPartners(targetlist.getPartners());
                            tTargetyardstickService.insertTTargetyardstick(tTargetyardstick);
                        }else {
                            logger.info("此人存在此条判定标准");
                            String[] yardstick = targetyardstick.getYardstick().split("\n");
                            //判断是否存在此条具体标准(0为无）
                            int o = 0;
                            String newY = "";
                            for (String y : yardstick) {
                                String[] insertYardsticks = tTargetmeasures.getMeasures().split("\\.");
//                                newY = "-" + insertYardsticks[1];
                                newY = "-" + insertYardsticks[0];
                                if (y.equals(newY)) {
                                    o = 1;
                                }
                            }
                            if (o == 0) {
                                logger.info("此人暂无此条具体标准");
                                String newYardstick = targetyardstick.getYardstick() + "\n" + newY;
                                targetyardstick.setYardstick(newYardstick);
                                tTargetyardstickService.updateTTargetyardstick(targetyardstick);
                            }else {
                                logger.info("此人存在此条具体标准");
                            }
                        }
                    }
                }else {
                    logger.info("此人是经理");
                }
            }
        }
    }

    @RequestMapping("/exportPDF")
    public String exportPDF(@RequestParam String year, HttpServletRequest request, HttpServletResponse response) {
        OutputStream out= null;
        try {
            out = response.getOutputStream();
            //获取信息，就是上面的结构
            HashMap<String, Object> map = new HashMap<>();
            DocumentHandler dh = new DocumentHandler();
            Template t = dh.getTemplate();
            map.put("year", year);
            TTargetlist targetlist = new TTargetlist();
            targetlist.setYear(year);
            targetlist.setParentId(Long.parseLong("0"));
            List<TTargetlist> tTargetlists = tTargetlistService.selectTTargetlistList(targetlist);
            for (TTargetlist list : tTargetlists) {
                targetlist.setParentId(list.getId());
                //次级targetlist数据
                List<TTargetlist> targetlists = tTargetlistService.selectTTargetlistList(targetlist);
                for (TTargetlist l : targetlists) {
                    TTargetmeasures selectMeasure = new TTargetmeasures();
                    selectMeasure.setTargetlistId(l.getId());
                    List<TTargetmeasures> measures = tTargetmeasuresService.selectTTargetmeasuresList(selectMeasure);
                    for (TTargetmeasures m : measures) {
                        String[] responsibles={};
                        if(m.getResponsible()!=null){
                            responsibles= m.getResponsible().split(",");
                            m.setResponsiblesNum(responsibles.length * 16);
                        }

                        String responsiblesName = "";
                        for (int i = 0; i < responsibles.length; i++) {
                            String name ="";
                    name = tStaffmgrService.selectTStaffmgrByStaffId(responsibles[i]).getName();
                            if (i == 0) {
                                responsiblesName = name;
                            }else {
                                responsiblesName = responsiblesName + "," + name;
                            }
                        }
                        m.setResponsible(responsiblesName);
                    }
                    if(measures != null && measures.size() > 0){
                        l.setMeasure(measures.get(0));
                        l.setMeasuresNum(measures.size());
                        measures.remove(0);
                        l.setTargetmeasures(measures);
                    }
                }
                list.setSecondaryList(targetlists);
            }
            map.put("targetlists", tTargetlists);
            PDFTemplateUtil.exportPdf("measuresFMaker.ftl", year + "年CBP/C目标跟踪表.pdf","file:/"+ RuoYiConfig.getProfile(), map, response);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(out!=null)
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return null;
    }
}
