package com.ruoyi.project.plant.controller;

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

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.StringUtils;
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.TStaffmgr;
import com.ruoyi.project.plant.domain.TTargetlist;
import com.ruoyi.project.plant.domain.TTargetyardstick;
import com.ruoyi.project.plant.service.ITStaffmgrService;
import com.ruoyi.project.plant.service.ITTargetlistService;
import com.ruoyi.project.plant.service.ITTargetyardstickService;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.service.ISysDeptService;
import com.ruoyi.project.system.service.ISysDictTypeService;
import freemarker.template.Template;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
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.project.plant.domain.TTargetagreement;
import com.ruoyi.project.plant.service.ITTargetagreementService;
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-08-16
 */
@RestController
@RequestMapping("/plant/targetagreement")
public class TTargetagreementController extends BaseController
{
    @Autowired
    private ITTargetagreementService tTargetagreementService;

    @Autowired
    private ITTargetyardstickService tTargetyardstickService;

    @Autowired
    private ITTargetlistService tTargetlistService;

    @Autowired
    private ITStaffmgrService tStaffmgrService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    @Autowired
    private ISysDeptService iSysDeptService;

    /**
     * 查询目标协议列表
     */
    @PreAuthorize("@ss.hasPermi('plant:targetagreement:list')")
    @GetMapping("/list")
    public TableDataInfo list(TTargetagreement tTargetagreement)
    {
        startPage();
        List<TTargetagreement> list;
        if (StringUtils.isEmpty(tTargetagreement.getYear())) {
            Calendar calendar = Calendar.getInstance();
            tTargetagreement.setYear(String.valueOf(calendar.get(Calendar.YEAR)));
            list = tTargetagreementService.selectTTargetagreementList(tTargetagreement);
            if (CollectionUtils.isEmpty(list)){
                tTargetagreement.setYear(String.valueOf(calendar.get(Calendar.YEAR)-1));
                list = tTargetagreementService.selectTTargetagreementList(tTargetagreement);
            }
        } else {
            list = tTargetagreementService.selectTTargetagreementList(tTargetagreement);
        }
        List<SysDictData> partnersDict = iSysDictTypeService.selectDictDataByType("PARTNERS");
        for (TTargetagreement t : list) {
            List<TTargetyardstick> tTargetyardsticks = tTargetyardstickService.selectTTargetyardstickByAgreementId(t.getId());
            if (!"24".equals(t.getActualpost())) {
                for (TTargetyardstick y : tTargetyardsticks) {
                    if (y.getPartners() != null) {
                        String[] partners = y.getPartners().split(",");
                        int i = 0;
                        String partnersName = "";
                        for (String p : partners) {
                            for (SysDictData a : partnersDict) {
                                if (a.getDictValue().equals(p)) {
                                    if (i != 0) {
                                        partnersName = partnersName + "," + a.getDictLabel();
                                    }else {
                                        partnersName = a.getDictLabel();
                                    }
                                }
                            }
                            i++;
                        }
                        y.setPartners(partnersName);
                    }
                }
            }
            t.settTargetyardsticks(tTargetyardsticks);
        }
        return getDataTable(list);
    }

    /**
     * 导出目标协议列表
     */
    @PreAuthorize("@ss.hasPermi('plant:targetagreement:export')")
    @Log(title = "目标协议", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TTargetagreement tTargetagreement)
    {
        List<TTargetagreement> list = tTargetagreementService.selectTTargetagreementList(tTargetagreement);
        ExcelUtil<TTargetagreement> util = new ExcelUtil<TTargetagreement>(TTargetagreement.class);
        return util.exportExcel(list, "targetagreement");
    }

    /**
     * 获取目标协议详细信息
     */
    @PreAuthorize("@ss.hasPermi('plant:targetagreement:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tTargetagreementService.selectTTargetagreementById(id));
    }

    /**
     * 新增目标协议
     */
    @PreAuthorize("@ss.hasPermi('plant:targetagreement:add')")
    @Log(title = "目标协议", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TTargetagreement tTargetagreement)
    {
        return toAjax(tTargetagreementService.insertTTargetagreement(tTargetagreement));
    }

    /**
     * 修改目标协议
     */
    @PreAuthorize("@ss.hasPermi('plant:targetagreement:edit')")
    @Log(title = "目标协议", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TTargetagreement tTargetagreement)
    {
        return toAjax(tTargetagreementService.updateTTargetagreement(tTargetagreement));
    }

    /**
     * 删除目标协议
     */
    @PreAuthorize("@ss.hasPermi('plant:targetagreement:remove')")
    @Log(title = "目标协议", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tTargetagreementService.deleteTTargetagreementByIds(ids));
    }

    @RequestMapping("/exportPDF")
    public String exportPDF(@RequestParam String id, HttpServletRequest request, HttpServletResponse response) {
        OutputStream out= null;
        try {
            out = response.getOutputStream();
            //获取信息，就是上面的结构
            HashMap<String, Object> map = new HashMap<>();
            DocumentHandler dh = new DocumentHandler();
            TTargetagreement tTargetagreement = tTargetagreementService.selectTTargetagreementById(Long.parseLong(id));
            map.put("tTargetagreement", tTargetagreement);
            //考核人姓名拼音
            String appraiserEN = "";
            if (tTargetagreement.getActualpost() == "24") {
                appraiserEN = spell(tTargetagreement.getAppraiserName());
            }else {
                appraiserEN = spell(tTargetagreement.getAppraiser());
            }
            map.put("appraiserEN", appraiserEN);
            //人员信息查询
            TStaffmgr staffmgr = tStaffmgrService.selectTStaffmgrByStaffId(tTargetagreement.getEmployeeid());
            //人员姓名拼音
            String employeeEN = spell(staffmgr.getName());
            map.put("employeeEN", employeeEN);
            //字典查询
            List<SysDictData> actualpost = iSysDictTypeService.selectDictDataByType("ACTUALPOST_EN");
            String post = "";
            for (SysDictData a : actualpost) {
                if (a.getDictValue().equals(staffmgr.getActualpost())) {
                    post = a.getDictLabel();
                }
            }
            map.put("actualPost", post);
            //部门查询
            List<SysDept> depts = iSysDeptService.selectDeptList(new SysDept());
            String dept = "";
            for (SysDept d : depts) {
                if (d.getDeptId().equals(staffmgr.getDeptId())) {
                    dept = d.getDeptName();
                }
            }
            map.put("dept", dept);
            List<SysDictData> partners = iSysDictTypeService.selectDictDataByType("PARTNERS");
            List<TTargetyardstick> tTargetyardsticks = tTargetyardstickService.selectTTargetyardstickByAgreementId(Long.parseLong(id));
            if (!tTargetagreement.getActualpost().equals("24")) {
                for (TTargetyardstick y : tTargetyardsticks) {
                    if (y.getPartners() != null) {
                        String[] partner = y.getPartners().split(",");
                        String partnerLabel = "";
                        for (int i = 0; i < partner.length; i++) {
                            String pLabel = "";
                            for (SysDictData p : partners) {
                                if (p.getDictValue().equals(partner[i])) {
                                    pLabel = p.getDictLabel();
                                }
                            }
                            if (i == 0) {
                                partnerLabel = pLabel;
                            }else {
                                partnerLabel = partnerLabel + "," + pLabel;
                            }
                        }
                        y.setPartners(partnerLabel);
                    }
                }
            }

            map.put("TTargetyardstick", tTargetyardsticks);
            logger.info(JSON.toJSONString(tTargetyardsticks));
            String year = tTargetagreement.getYear().toString();
            map.put("year", year);
            PDFTemplateUtil.exportPdf("agreemenetFMaker.ftl", staffmgr.getName() + tTargetagreement.getYear() + "年目标协议.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;
    }

    /**
     * 获取字符串内的所有汉字的汉语拼音并大写每个字的首字母
     *
     * @param chinese
     * @return
     */
    public static String spell(String chinese) {
        if (chinese == null) {
            return null;
        }
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);// 小写
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);// 不标声调
        format.setVCharType(HanyuPinyinVCharType.WITH_V);// u:的声母替换为v
        try {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < chinese.length(); i++) {
                String[] array = PinyinHelper.toHanyuPinyinStringArray(chinese
                        .charAt(i), format);
                if (array == null || array.length == 0) {
                    continue;
                }
                String s = array[0];// 不管多音字,只取第一个
                char c = s.charAt(0);// 大写第一个字母
                String pinyin = String.valueOf(c).toUpperCase().concat(s
                        .substring(1));
                sb.append(pinyin);
            }
            return sb.toString();
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成经理目标协议
     */
    @PreAuthorize("@ss.hasPermi('plant:targetagreement:edit')")
    @Log(title = "目标协议", businessType = BusinessType.UPDATE)
    @PutMapping("/generate")
    public int generate(@RequestBody TTargetagreement tTargetagreement)
    {
        //返回值
        int returnNum = 2;
        //判断是否存在当年数据
        TTargetagreement agreement = new TTargetagreement();
        agreement.setYear(tTargetagreement.getYear());
        List<TTargetagreement> tTargetagreements = tTargetagreementService.selectTTargetagreementList(agreement);
        //装置经理
        TStaffmgr staffmgr = new TStaffmgr();
        staffmgr.setActualpost("24");
        List<TStaffmgr> s = tStaffmgrService.selectTStaffmgrList(staffmgr);
        TStaffmgr manager = s.get(0);
        //判断是否存在此人的目标协议(0为无）
        int m = 0;
        for (TTargetagreement a : tTargetagreements) {
            if (manager.getStaffid().equals(a.getEmployeeid())) {
                m = 1;
            }
        }
        if (m == 0) {
            logger.info("此人暂无目标协议");
            //生成经理的目标协议
            tTargetagreement.setEmployeeid(manager.getStaffid());
            tTargetagreement.setDeptId(manager.getDeptId());
            tTargetagreementService.insertTTargetagreement(tTargetagreement);
            Long agreementId = tTargetagreement.getId();
            //选择年份,一级菜单的目标列表
            TTargetlist tTargetlist = new TTargetlist();
            tTargetlist.setYear(tTargetagreement.getYear());
            tTargetlist.setParentId(Long.parseLong("0"));
            List<TTargetlist> tTargetlists = tTargetlistService.selectTTargetlistList(tTargetlist);
            for (TTargetlist t : tTargetlists) {
                TTargetyardstick tTargetyardstick = new TTargetyardstick();
                tTargetyardstick.setAgreementId(agreementId);
                tTargetyardstick.setTarget(t.getDescription());
                //查询二级目录列表
                TTargetlist l = new TTargetlist();
                l.setParentId(t.getId());
                List<TTargetlist> targetlists = tTargetlistService.selectTTargetlistList(l);
                String yardstick = "";
                for (int i = 0; i < targetlists.size(); i++) {
                    if (i == 0) {
                        yardstick = "-" + targetlists.get(i).getYardstick();
                    }else {
                        yardstick = yardstick + "\n" +  "-" + targetlists.get(i).getYardstick();
                    }
                }
                tTargetyardstick.setYardstick(yardstick);
                /*tTargetyardstick.setAchieveDate(t.getExpectedDate());*/
                tTargetyardstickService.insertTTargetyardstick(tTargetyardstick);
            }
            returnNum = 1;
        }else {
            logger.info("此人存在目标协议");
        }
        return returnNum;
    }

}
