
package com.ruoyi.web.controller.party;

import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExportExcelUtil;
import com.ruoyi.common.utils.poi.ImportExcelUtil;
import com.ruoyi.party.domain.PartyMember;
import com.ruoyi.party.domain.vo.PartyMemberVo;
import com.ruoyi.party.mapper.PartyMemberMapper;
import com.ruoyi.party.service.api.IPartyMemberService;
import com.ruoyi.system.mapper.system.SysDictDataMapper;
import io.swagger.annotations.Api;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 党员Controller
 *
 * @author ruoyi
 * @date 2024-05-17
 */
@Api(tags = "党建-党员")
@RestController
@RequestMapping("/api/party/partyMember")
public class PartyMemberController extends BaseController
{
    @Autowired
    private IPartyMemberService partyMemberService;

    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    private List<SysDictData> getDataByType(String type){
        return sysDictDataMapper.selectDictDataByType(type);
    }

    /**
     * 查询党员列表
     */
    @GetMapping("/list")
    public TableDataInfo list(PartyMember partyMember)
    {
        startPage();
        List<PartyMember> list = partyMemberService.selectPartyMemberList(partyMember);
        TableDataInfo dataInfo = getDataTable(list);
        if(!org.springframework.util.CollectionUtils.isEmpty(dataInfo.getRows())){
            dataInfo.setRows(partyMemberService.convertToVo((List<PartyMember>) dataInfo.getRows()));
        }
        return dataInfo;
    }

    /**
     * 导出党员列表，有需要在改
     */
//    @Log(title = "党员", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, PartyMember partyMember)
//    {
//        List<PartyMember> list = partyMemberService.selectPartyMemberList(partyMember);
//        ExcelUtil<PartyMember> util = new ExcelUtil<PartyMember>(PartyMember.class);
//        util.exportExcel(response, list, "党员数据");
//    }

    /**
     * 获取党员详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        List<SysDictData> dictDataList = this.getDataByType("party_people_type");
        Map<String, SysDictData>  map = dictDataList.stream().collect(Collectors.toMap(SysDictData::getDictValue, x -> x));
        List<SysDictData> educationDictDataList = this.getDataByType("education_type");
        Map<String, SysDictData>  educationMap = educationDictDataList.stream().collect(Collectors.toMap(SysDictData::getDictValue, x -> x));
        PartyMemberVo partyMemberVo = partyMemberService.selectPartyMemberById(id);
        if(StringUtils.isNotBlank(partyMemberVo.getRylb())){
            SysDictData sysDictData = map.get(partyMemberVo.getRylb());
            partyMemberVo.setRylbName(sysDictData == null?"":sysDictData.getDictLabel());
        }
        if(StringUtils.isNotBlank(partyMemberVo.getXl())){
            SysDictData sysDictData = educationMap.get(partyMemberVo.getXl());
            partyMemberVo.setEducationName(sysDictData == null?"":sysDictData.getDictLabel());
        }
        return success(partyMemberVo);
    }

    /**
     * 新增党员
     */
    @Log(title = "党员", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PartyMember partyMember)
    {
        return toAjax(partyMemberService.insertPartyMember(partyMember));
    }

    /**
     * 修改党员
     */
    @Log(title = "党员", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PartyMember partyMember)
    {
        return toAjax(partyMemberService.updatePartyMember(partyMember));
    }

    /**
     * 删除党员
     */
    @Log(title = "党员", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(partyMemberService.deletePartyMemberByIds(ids));
    }

    //获取党员总数
    @RequestMapping(value="getPartyCounts",method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getPartyCounts(){
        return success(partyMemberService.getPartyCount());
    }


    //学历分布
    @RequestMapping(value="getXLFB",method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getXLFB(String orgId){
        List<Map<String,String>> list= partyMemberService.getXLFB(orgId);
        List<SysDictData> educationDictDataList = this.getDataByType("education_type");
        Map<String, SysDictData> educationMap = educationDictDataList.stream().collect(Collectors.toMap(SysDictData::getDictValue, x -> x));
        List<Map<String,Object>> rlist=new ArrayList<>();
        if(CollectionUtils.isNotEmpty(list)){
            for(Map<String,String> map : list){
                Map<String,Object> rmap=new HashMap<>();
                String dictType = map.get("xl");
                if(educationMap.containsKey(dictType)){
                    SysDictData sysDictData = educationMap.get(dictType);
                    rmap.put("xl", sysDictData.getDictLabel());
                    rmap.put("count", map.get("counts"));
                    rlist.add(rmap);
                }
            }
        }
        return success(rlist);
    }

    //党龄
    @RequestMapping(value="getDl",method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getDl(String orgId) {
        List<Map<String, String>> list = partyMemberService.getDl(orgId);
        List<Object> rlist = new ArrayList<Object>();
        int wnyxCountsMan = 0;  //5年以下
        int wnyxCountsWoman = 0;  //5年以下
        int wdsnCountsMan = 0;  //5到10年
        int wdsnCountsWoman = 0;  //5到10年
        int sdswCountsMan = 0;  //10-15
        int sdswCountsWoman = 0;  //10-15
        int swdesCountsMan = 0;  //15-20
        int swdesCountsWoman = 0;  //15-20
        int esysCountsMan = 0;  //>20
        int esysCountsWoman = 0;  //>20
        if (CollectionUtils.isNotEmpty(list)) {
            for (Map<String, String> map : list) {
                int dYear = 0;
                if (map.get("dyear") != null) {
                    String d = String.valueOf(map.get("dyear")); //党龄
                    dYear = Integer.parseInt(d);
                }
                String sex = String.valueOf(map.get("xb"));
                if (dYear < 5) {
                    if (sex.equals("男")) {
                        wnyxCountsMan++;
                        continue;
                    }
                    if (sex.equals("女")) {
                        wnyxCountsWoman++;
                        continue;
                    }

                }
                if (dYear <= 10) {
                    if (sex.equals("男")) {
                        wdsnCountsMan++;
                        continue;
                    }
                    if (sex.equals("女")) {
                        wdsnCountsWoman++;
                        continue;
                    }
                }
                if (dYear <= 15) {
                    if (sex.equals("男")) {
                        sdswCountsMan++;
                        continue;
                    }
                    if (sex.equals("女")) {
                        sdswCountsWoman++;
                        continue;
                    }
                }
                if (dYear <= 20) {
                    if (sex.equals("男")) {
                        swdesCountsMan++;
                        continue;
                    }
                    if (sex.equals("女")) {
                        swdesCountsWoman++;
                        continue;
                    }
                }
                if (dYear > 20) {
                    if (sex.equals("男")) {
                        esysCountsMan++;
                        continue;
                    }
                    if (sex.equals("女")) {
                        esysCountsWoman++;
                    }
                }

            }
        }
        String rString = "[{\"time\":\"5年以下\",\"type\":\"女\",\"value\":" + wnyxCountsWoman + "},"
                + "{\"time\":\"5-10年\",\"type\":\"女\",\"value\":" + wdsnCountsWoman + "},"
                + "{\"time\":\"10-15年\",\"type\":\"女\",\"value\":" + sdswCountsWoman + "},"
                + "{\"time\":\"15-20年\",\"type\":\"女\",\"value\":" + swdesCountsWoman + "},"
                + "{\"time\":\"20年以上\",\"type\":\"女\",\"value\":" + esysCountsWoman + "}]";
        JSONArray rj = JSONArray.parseArray(rString);
        rlist.add(rj);
        String rStringMan = "[{\"time\":\"5年以下\",\"type\":\"男\",\"value\":" + wnyxCountsMan + "},"
                + "{\"time\":\"5-10年\",\"type\":\"男\",\"value\":" + wdsnCountsMan + "},"
                + "{\"time\":\"10-15年\",\"type\":\"男\",\"value\":" + sdswCountsMan + "},"
                + "{\"time\":\"15-20年\",\"type\":\"男\",\"value\":" + swdesCountsMan + "},"
                + "{\"time\":\"20年以上\",\"type\":\"男\",\"value\":" + esysCountsMan + "}]";
        JSONArray r = JSONArray.parseArray(rStringMan);
        rlist.add(r);
        return success(rlist);
    }

    @PostMapping(value = "/readExcel", headers = "content-type=multipart/form-data")
    public AjaxResult readExcel(@RequestParam(value = "file") MultipartFile file) {
        if (null == file) {
            return AjaxResult.error("文件不存在");
        }
        String fileName = file.getOriginalFilename();
        InputStream is;
        Workbook workbook;
        try {
            is = file.getInputStream();//创建文件流
            if ("xls".equals(ImportExcelUtil.getPostFix(fileName))) {
                workbook = new HSSFWorkbook(is);  //xls对应的HSSFWorkbook工作簿对象
            } else if ("xlsx".equals(ImportExcelUtil.getPostFix(fileName))) {
                workbook = new XSSFWorkbook(is); //xlsx对应的XSSFWorkbook工作簿对象
            } else {
                return AjaxResult.error("文件格式不正确");
            }
        } catch (Exception e) {
            e.printStackTrace();
            //msg+=e.getMessage();
            return AjaxResult.error("系统错误");
        }

        Sheet sheet = workbook.getSheetAt(0);
        if (sheet == null) {
            //空判断
            return AjaxResult.error("文件内容为空");
        }
        List<SysDictData> partyPeopleTypes = sysDictDataMapper.selectDictDataByType("party_people_type");
        List<SysDictData> educationTypes = sysDictDataMapper.selectDictDataByType("education_type");
        Map<String, SysDictData> treeMap = partyPeopleTypes.stream().collect(Collectors.toMap(SysDictData::getDictLabel, x -> x));
        Map<String, SysDictData> educationMap = educationTypes.stream().collect(Collectors.toMap(SysDictData::getDictLabel, x -> x));
        partyMemberService.importExcel(workbook, treeMap, educationMap);

        return AjaxResult.success();
    }

    @GetMapping("/downloadTemplate")
    public String readExcel(HttpServletRequest request, HttpServletResponse response) {
        HSSFWorkbook sheets = partyMemberService.exportTemplate();
        try {
            return ExportExcelUtil.downloadExcel(request, response, sheets);
        } catch (IOException e) {
            logger.info("下载党员导入模版出错");
            throw new RuntimeException("下载党员导入模版出错" + e.getMessage());
        }
    }
}

