package com.ruoyi.kaohe.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ruoyi.kaohe.domain.KhKhrwResult;
import com.ruoyi.kaohe.service.IKhKhrwResultService;
import com.ruoyi.kaohe.service.IKhVoteEmpService;
import com.ruoyi.kaohe.service.IKhVoteService;
import com.ruoyi.kaohe.util.EnhancedJsonExporter;
import com.ruoyi.kaohe.util.JsonDeepMerge;
import com.ruoyi.kaohe.util.PinYinUtil;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.kaohe.domain.KhGather;
import com.ruoyi.kaohe.service.IKhGatherService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 生成汇总Controller
 *
 * @author hs
 * @date 2025-07-10
 */
@RestController
@RequestMapping("/kaohe/gather")
public class KhGatherController extends BaseController {
    @Autowired
    private IKhKhrwResultService khKhrwResultService;
    @Autowired
    private IKhVoteEmpService voteEmpService;
    @Autowired
    private IKhVoteService khVoteService;
    @Autowired
    private IKhGatherService khGatherService;

    /**
     * 生成汇总列表
     */
    //@PreAuthorize("@ss.hasPermi('kaohe:gather:list')")
    @PostMapping("/generateSum")
    public AjaxResult generateSum(@RequestBody String json) throws JsonProcessingException {
        // 将String转换为JSONObject
        JSONObject jsonObject = new JSONObject(json);
        String hz_name = jsonObject.getString("title");
        String pyhz_name = PinYinUtil.getPinyinInitials(hz_name);
        JSONArray datas = jsonObject.getJSONArray("data");
        //拼接表头数据
        JSONArray header = new JSONArray();//存放表头的最终数据
        //----------------------------------------------------------------------------------------------
        //循环主标题下的每一个子节点
        Map<String, Object> nodes = parseJson(datas, hz_name, null);
        //获取并拼接表头
        JSONObject btKhdx = (JSONObject) nodes.get("btKhdx");
        JSONObject head = (JSONObject) nodes.get("head");
        JSONArray oldchildren = head.getJSONArray("children");
        JSONArray newChildren = new JSONArray();
        newChildren.put(btKhdx);
        for (Object oldchild : oldchildren) {
            newChildren.put(oldchild);
        }
        JSONObject zongfen = new JSONObject();
        zongfen.put("name", pyhz_name + "_df");
        zongfen.put("label", "总分");
        newChildren.put(zongfen);
        head.put("children", newChildren);
        header.put(head);

        //获取并整合数据
        JSONArray tabledata = new JSONArray((JSONArray) nodes.get("alldatas"));
        JSONArray hz_df = new JSONArray((JSONArray) nodes.get("title_df"));
        for (Object zf : hz_df) {
            JSONObject chulizf = (JSONObject) zf;
            BigDecimal yijidf = chulizf.getBigDecimal(pyhz_name + "_df");
            JSONObject newDf = new JSONObject();
            newDf.put(pyhz_name + "_df", yijidf);
            chulizf.put(pyhz_name, newDf);
            chulizf.remove(pyhz_name + "_df");
            zf = chulizf;
        }
        tabledata.putAll(hz_df);
        //根据被考核对象名分组数据到map中   得到表格内容的最终数据
        JSONArray endTableData = JsonDeepMerge.mergeByKey(tabledata, "khdx");
        //把数据结果中的khdx这个键值对———放到汇总主题拼音的key值里面
        for (Object endData : endTableData) {
            JSONObject jsonData = (JSONObject) endData;
            String khdx = jsonData.getString("khdx");
            JSONObject hzData = jsonData.getJSONObject(pyhz_name);
            hzData.put("khdx", khdx);
            jsonData.remove("khdx");
            jsonData.put(pyhz_name, hzData);
            endData = jsonData;
        }

        KhGather gather = new KhGather();
        gather.setHzName(hz_name);
        gather.setTableHeader(header.toString());
        gather.setTableData(endTableData.toString());
        gather.setCreateBy(getUsername());
        gather.setTitleStr(json);
        khGatherService.insertKhGather(gather);
        return AjaxResult.success();
    }

    /**
     * 递归解析json
     *
     * @param datas
     * @param titleP
     * @param z_zb
     * @return
     */
    private Map<String, Object> parseJson(JSONArray datas, String titleP, BigDecimal z_zb) throws JsonProcessingException {

        Map<String, Object> result = new HashMap<>();
        JSONArray title_df = new JSONArray();//处理标题占比时的得分
        String pyTitle = PinYinUtil.getPinyinInitials(titleP);//父级表头
        JSONObject btKhdx = new JSONObject(true);  //表头考核对象存储
        JSONObject btTitle = new JSONObject(true);
        btTitle.put("name", pyTitle);
        btTitle.put("label", titleP);
        JSONArray btchildren = new JSONArray();
//---------------------------------------------------------------------
        JSONArray bd = new JSONArray();//表数据拼接
        JSONArray alldatas = new JSONArray();//表格数据拼接

        //循环考核任务或标题
        for (int i = 0; i < datas.length(); i++) {
            JSONObject jobj = (JSONObject) datas.get(i);
            String type = jobj.getString("type");
            String title = jobj.getString("title");
            String erjiPyTitle = PinYinUtil.getPinyinInitials(title);
            BigDecimal zb = null;
            if (jobj.has("zb")) {
                zb = jobj.getBigDecimal("zb");
            }
            //标题--------------------------------------------------------------
            if (type.equals("0")) {
                JSONArray data2 = jobj.getJSONArray("data");
                //递归获取下一级数据
                Map<String, Object> childmap = parseJson(data2, title, zb);
                JSONObject head = (JSONObject) childmap.get("head");
                JSONObject defen = new JSONObject(true);
                defen.put("name", erjiPyTitle + "_df");
                defen.put("label", "得分");
                JSONObject zb1 = new JSONObject(true);
                zb1.put("name", erjiPyTitle + "_zb");
                zb1.put("label", "占比");
                JSONObject zsfs = new JSONObject(true);
                zsfs.put("name", erjiPyTitle + "_zsfs");
                zsfs.put("label", "折算分数");
                btchildren.put(head);
                btchildren.put(defen);
                btchildren.put(zb1);
                btchildren.put(zsfs);
                //-------------------------获取表格数据------------------------------

                JSONArray alldatas1 = (JSONArray) childmap.get("alldatas");
                JSONArray title_df1 = (JSONArray) childmap.get("title_df");
                btKhdx = (JSONObject) childmap.get("btKhdx");
                if (title_df1 == null) {//代表它下面还是标题，没有数据   多级标题的
                    BigDecimal erjidf = BigDecimal.ZERO;
                    JSONObject outsideTitle = new JSONObject();
                    JSONObject newDf = new JSONObject();
                    newDf.put(erjiPyTitle + "_df", erjidf);
                    if (z_zb != null) {  //如果传递过来的标题占比不为null
                        BigDecimal erjizsfs = z_zb.multiply(erjidf);
                        newDf.put(erjiPyTitle + "_zb", z_zb);
                        newDf.put(erjiPyTitle + "_zsfs", erjizsfs);
                    }
                    outsideTitle.put(pyTitle, newDf);
                    title_df1.put(outsideTitle);
                } else {
                    //循环处理后的标题得分  加上层级及   占比、折算分数
                    for (Object df : title_df1) {
                        JSONObject dfobj = (JSONObject) df;
                        BigDecimal erjidf = dfobj.getBigDecimal(erjiPyTitle + "_df");
                        JSONObject newDf = new JSONObject();
                        newDf.put(erjiPyTitle + "_df", erjidf);
                        BigDecimal erjizsfs = BigDecimal.ZERO;
                        if (zb != null) {  //如果标题占比不为null
                            erjizsfs = zb.multiply(erjidf);
                            newDf.put(erjiPyTitle + "_zb", zb);
                            newDf.put(erjiPyTitle + "_zsfs", erjizsfs);
                        }

                        //标题递归来得分数据按格式 //{"khdx":"",pyTitle _df:defen}存储到title_df中
                        JSONObject hzdf = new JSONObject();
                        hzdf.put("khdx", dfobj.get("khdx"));
                        if (zb != null) {
                            hzdf.put(pyTitle + "_df", erjizsfs);
                        } else {
                            hzdf.put(pyTitle + "_df", erjidf);
                        }
                        title_df.put(hzdf);


                        dfobj.remove(erjiPyTitle + "_df");//删除原来的数据项
                        dfobj.put(pyTitle, newDf);//删除原来的数据项
                        df = dfobj;//更改df结构，添加外层主题嵌套 如：{"khdx":"",pyTitle:{erjiPyTitle_df:defen}}
                    }
                    alldatas.putAll(title_df1);
                }


                //循环改变内部层级关系
                for (Object tabledatum : alldatas1) {
                    JSONObject obj = (JSONObject) tabledatum;
                    JSONObject yiji = new JSONObject(true);
                    yiji.put(erjiPyTitle, obj.get(erjiPyTitle));
                    obj.remove(erjiPyTitle);//删除原来的数据项
                    obj.put(pyTitle, yiji);
                    tabledatum = obj;
                }
                alldatas.putAll(alldatas1);

            } else {  //引用考核任务
                Long pcId = jobj.getLong("id");
                //根据pcId获取考核任务结果
                KhKhrwResult khrwResult = new KhKhrwResult();
                khrwResult.setPcId(pcId);
                List<KhKhrwResult> khrw = khKhrwResultService.selectKhKhrwResultList(khrwResult);
                String khrwName = jobj.getString("title");
                String pykhrwName = PinYinUtil.getPinyinInitials(khrwName);
                if (khrw != null && khrw.size() > 0) {
                    //----------------------从这把title从考核任务名改为对应模板名称-----------------
                    khrwName=khrw.get(0).getTemName();
                    pykhrwName = PinYinUtil.getPinyinInitials(khrwName);

                    //----------组合表头数据---------
                    JSONArray tableHeader = new JSONArray(khrw.get(0).getTableHeader());
                    btKhdx = tableHeader.getJSONObject(0);//下标0 单位/姓名
                    JSONObject head1 = tableHeader.getJSONObject(1); //整体数据
                    JSONObject head2 = tableHeader.getJSONObject(2);//得分
                    btchildren.put(head1);
                    btchildren.put(head2);
                    if (zb != null) {  //当考核任务不占比时
                        JSONObject head3 = new JSONObject(true);                   //占比
                        head3.put("name", pykhrwName + "_zb");
                        head3.put("label", "占比");
                        JSONObject head4 = new JSONObject(true);                  //折算分数
                        head4.put("name", pykhrwName + "_zsfs");
                        head4.put("label", "折算分数");
                        btchildren.put(head3);
                        btchildren.put(head4);
                    }

                    //---------------组合表格数据------------------------------------------------
                    JSONArray tabledata = new JSONArray(khrw.get(0).getTableData());
                    String pinyinKhrw = PinYinUtil.getPinyinInitials(khrwName);
                    for (Object tabledatum : tabledata) {
                        JSONObject obj = (JSONObject) tabledatum;
                        JSONObject erji = new JSONObject(true);
                        //------------------------------------
                        erji.put(pinyinKhrw, obj.get(pinyinKhrw));
                        //------------------------------------
                        erji.put(pinyinKhrw + "_df", obj.get(pinyinKhrw + "_df"));
                        if (zb != null) {   //代表当前引用考核任务有占比
                            BigDecimal zsfs = zb.multiply((BigDecimal) obj.get(pinyinKhrw + "_df"));
                            erji.put(pinyinKhrw + "_zb", zb);
                            erji.put(pinyinKhrw + "_zsfs", zsfs);

                            //获取上一级标题得分数组
                            JSONObject khdx = new JSONObject();
                            khdx.put("khdx", obj.get("khdx"));//存储当前考核对象名称
                            khdx.put(pyTitle + "_df", zsfs);//存储当前考核对象最后折算分数
                            title_df.put(khdx);                    //{"khdx":"",pyTitle _df:defen}

                        } else { //当前考核任务无占比   上面只存储了得分
                            //获取上一级标题得分数组
                            JSONObject khdx = new JSONObject();
                            khdx.put("khdx", obj.get("khdx"));//存储当前考核对象名称
                            khdx.put(pyTitle + "_df", obj.get(pinyinKhrw + "_df"));///存储当前考核对象最后得分
                            title_df.put(khdx);                   //{"khdx":"",pyTitle _df:defen}
                        }
                        obj.remove(pinyinKhrw);//删除原来的数据项
                        obj.remove(pinyinKhrw + "_df");//删除原来的得分
                        obj.put(pyTitle, erji);
                        tabledatum = obj;
                    }
                    alldatas.putAll(tabledata);
                }
            }
        }
        title_df = new JSONArray(JsonDeepMerge.jsonGroupSum(title_df, "khdx", pyTitle + "_df"));

        btTitle.put("children", btchildren);
        result.put("head", btTitle);
        result.put("data", bd);
        result.put("alldatas", alldatas);
        result.put("title_df", title_df);
        result.put("btKhdx", btKhdx);
        return result;
    }

/*
    {"title":"教学单位领导班子考核总分","data":[{"zb":0.9,"type":"0","title":"二级单位目标管理与绩效考核成绩","data":[{"type":"1","title":"党建与行政目标任务","id":1,"zb":0.1},{"type":"1","title":"事业发展","id":6,"zb":0.9}]},{"type":"1","title":"民主测评","id":2,"zb":0.3},{"type":"2","title":"创新","id":7}]}
*/

    /**
     * 查询生成汇总列表
     */
    @PreAuthorize("@ss.hasPermi('kaohe:gather:list')")
    @GetMapping("/list")
    public TableDataInfo list(KhGather khGather) {
        startPage();
        List<KhGather> list = khGatherService.selectKhGatherList(khGather);
        return getDataTable(list);
    }

    /**
     * 导出生成汇总列表
     */
    /*@PreAuthorize("@ss.hasPermi('kaohe:gather:export')")
    @Log(title = "生成汇总", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, KhGather khGather) {
        List<KhGather> list = khGatherService.selectKhGatherList(khGather);
        ExcelUtil<KhGather> util = new ExcelUtil<KhGather>(KhGather.class);
        util.exportExcel(response, list, "生成汇总数据");
    }*/
    @PreAuthorize("@ss.hasPermi('kaohe:gather:export')")
    @Log(title = "生成汇总", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Long id) throws Exception {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("汇总数据.xlsx", "UTF-8"));
        KhGather gather = khGatherService.selectKhGatherById(id);
        String tableHeader = gather.getTableHeader();
        String tableData = gather.getTableData();
        EnhancedJsonExporter.exportWithMergedHeader(tableHeader, tableData, response);
    }

    /**
     * 获取生成汇总详细信息
     */
    @PreAuthorize("@ss.hasPermi('kaohe:gather:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(khGatherService.selectKhGatherById(id));
    }

    /**
     * 新增生成汇总
     */
    @PreAuthorize("@ss.hasPermi('kaohe:gather:add')")
    @Log(title = "生成汇总", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody KhGather khGather) {
        return toAjax(khGatherService.insertKhGather(khGather));
    }

    /**
     * 修改生成汇总
     */
    @PreAuthorize("@ss.hasPermi('kaohe:gather:edit')")
    @Log(title = "生成汇总", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody KhGather khGather) {
        return toAjax(khGatherService.updateKhGather(khGather));
    }

    /**
     * 删除生成汇总
     */
    @PreAuthorize("@ss.hasPermi('kaohe:gather:remove')")
    @Log(title = "生成汇总", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(khGatherService.deleteKhGatherByIds(ids));
    }
}
