package com.ruoyi.web.controller.party;

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.bean.BeanCopyUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.poi.ExportExcelUtil;
import com.ruoyi.common.utils.poi.ImportExcelUtil;
import com.ruoyi.party.domain.PartyOrganization;
import com.ruoyi.party.domain.vo.PartyOrganizationVo;
import com.ruoyi.party.service.api.IPartyOrganizationService;
import com.ruoyi.system.mapper.system.SysDictDataMapper;
import io.swagger.annotations.Api;
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.util.CollectionUtils;
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.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 党组织管理Controller
 *
 * @author ruoyi
 * @date 2024-05-17
 */
@Api(tags = "党组织管理")
@RestController
@RequestMapping("/api/party/partyOrganization")
public class PartyOrganizationController extends BaseController
{
    @Autowired
    private IPartyOrganizationService partyOrganizationService;

    @Autowired
    private SysDictDataMapper sysDictDataMapper;

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

    /**
     * 查询党组织管理列表
     */
    @GetMapping("/list")
    public TableDataInfo list(PartyOrganization partyOrganization)
    {
        List<SysDictData> ortTypeList = getDataByType("party_org_type");
        Map<String, SysDictData>  orgMap = ortTypeList.stream().collect(Collectors.toMap(SysDictData::getDictValue, x -> x));
        startPage();
        List<PartyOrganization> list = partyOrganizationService.selectPartyOrganizationList(partyOrganization);
        TableDataInfo dataInfo = getDataTable(list);
        List<PartyOrganizationVo> voList = BeanCopyUtil.bathToBean(dataInfo.getRows(), PartyOrganizationVo.class);
        if(!CollectionUtils.isEmpty(voList)){
            voList.forEach(e ->{
                if(StringUtils.isNotBlank(e.getZzlb())){
                    SysDictData zzlb = orgMap.get(e.getZzlb());
                    e.setZzlbName(zzlb == null?"":zzlb.getDictLabel());
                }
            });
        }
        dataInfo.setRows(voList);
        return dataInfo;
    }

    /**
     * 导出党组织管理列表
     */
    @Log(title = "党组织管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PartyOrganization partyOrganization)
    {
        List<PartyOrganization> list = partyOrganizationService.selectPartyOrganizationList(partyOrganization);
        ExcelUtil<PartyOrganization> util = new ExcelUtil<PartyOrganization>(PartyOrganization.class);
        util.exportExcel(response, list, "党组织管理数据");
    }

    /**
     * 获取党组织管理详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        List<SysDictData> ortTypeList = getDataByType("party_org_type");
        List<SysDictData> sdgxTypeList = getDataByType("sdgx_type");
        PartyOrganizationVo partyOrganizationVo = partyOrganizationService.selectPartyOrganizationById(id);
        Map<String, SysDictData>  orgMap = ortTypeList.stream().collect(Collectors.toMap(SysDictData::getDictValue, x -> x));
        Map<String, SysDictData>  sdgxMap = sdgxTypeList.stream().collect(Collectors.toMap(SysDictData::getDictValue, x -> x));
        if(StringUtils.isNotBlank(partyOrganizationVo.getSdgx())){
            SysDictData sdgx = sdgxMap.get(partyOrganizationVo.getSdgx());
            partyOrganizationVo.setSdgxName(sdgx == null?"":sdgx.getDictLabel());
        }
        if(StringUtils.isNotBlank(partyOrganizationVo.getZzlb())){
            SysDictData zzlb = orgMap.get(partyOrganizationVo.getZzlb());
            partyOrganizationVo.setZzlbName(zzlb == null?"":zzlb.getDictLabel());
        }
        return success(partyOrganizationVo);
    }

    /**
     * 新增党组织管理
     */
    @Log(title = "党组织管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PartyOrganization partyOrganization)
    {
        return toAjax(partyOrganizationService.insertPartyOrganization(partyOrganization));
    }

    /**
     * 修改党组织管理
     */
    @Log(title = "党组织管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PartyOrganization partyOrganization)
    {
        return toAjax(partyOrganizationService.updatePartyOrganization(partyOrganization));
    }

    /**
     * 删除党组织管理
     */
    @Log(title = "党组织管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(partyOrganizationService.deletePartyOrganizationByIds(ids));
    }


    @RequestMapping(value = "countPartyOrganization",method = RequestMethod.GET)
    public AjaxResult countPartyOrganization() {
        int count=partyOrganizationService.countOrg();
        return success(count);
    }


    //党组织构成情况
    @RequestMapping(value="getPartyOrgBuild",method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getPartyOrgBuild(){
        List<SysDictData> sysDictDataList = getDataByType("party_org_type");
        List<Map<String,String>> list =partyOrganizationService.getPartyOrgBuild(sysDictDataList);
        return success(list);
    }


    /**
     * 党组织树
     * @param partyOrganization
     * @return
     */
    @GetMapping("/listTree")
    public TableDataInfo listTree(PartyOrganization partyOrganization) {
        return getDataTable(partyOrganizationService.partyOrganizationTree(partyOrganization));
    }

    @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("文件内容为空");
        }

        partyOrganizationService.importExcel(workbook, getDataByType("party_org_type"), getDataByType("sdgx_type"));

        return AjaxResult.success();
    }

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