package com.bonus.bracelet.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.alibaba.fastjson2.JSON;
import com.bonus.bracelet.mapper.BaseProjectMapper;
import com.bonus.bracelet.service.IBaseProjectService;
import com.bonus.common.core.utils.ExcelStyleUtil;
import com.bonus.common.core.utils.poi.ExcelUtil;
import com.bonus.common.core.web.controller.BaseController;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.core.web.page.TableDataInfo;
import com.bonus.common.entity.bracelet.exportVo.ProjectExportVo;
import com.bonus.common.entity.bracelet.vo.BaseProject;
import com.bonus.common.entity.bracelet.vo.PersonVo;
import com.bonus.common.log.annotation.SysLog;
import com.bonus.common.log.enums.OperaType;
import com.bonus.common.security.annotation.RequiresPermissions;
import com.bonus.common.security.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 岗位信息操作处理
 * 
 * @author bonus
 */
@RestController
@RequestMapping("/project")
@Slf4j
public class BaseProjectController extends BaseController
{
    @Autowired
    private IBaseProjectService projectService;

    @Autowired
    private BaseProjectMapper projectMapper;
    /**
     * 获取项目列表
     */
    @RequiresPermissions("bracelet:project:list")
    @GetMapping("/list")
    @SysLog(title = "项目部管理", businessType = OperaType.QUERY,module = "基础管理->项目部管理")
    public TableDataInfo list(BaseProject project) {
        startPage();
        List<BaseProject> list = projectService.selectProjectList(project);
        return getDataTable(list);
    }



    /**
     * 根据项目id获取详细信息
     */
    @RequiresPermissions("bracelet:project:query")
    @GetMapping(value = "/{projectId}")
    public AjaxResult getInfo(@PathVariable Integer projectId) {
        return projectService.selectProjectById(projectId);
    }

    /**
     * 新增项目
     */
    @RequiresPermissions("bracelet:project:add")
    @PostMapping("/addtemp")
    @SysLog(title = "项目部管理", businessType = OperaType.INSERT,module = "基础管理->项目部管理",details ="新增项目" )
    public AjaxResult addtemp(@RequestParam(value = "file", required = false) MultipartFile[] file, String params) {
        try{
            BaseProject project = JSON.parseObject(params, BaseProject.class);
            if (!projectService.checkProjectDeptNameUniqueAdd(project)) {
                return error("新增项目部'" + project.getProjectDepartName() + "'失败，项目部名称已存在");
            }
//            project.setCreateBy(SecurityUtils.getUsername());
         //   project.setDelFlag(0);
            return projectService.insertProject(file,params);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }


    /**
     * 修改项目
     */
    @PostMapping("/update")
    @SysLog(title = "项目部管理", businessType = OperaType.UPDATE,module = "基础管理->项目管理")
    public AjaxResult edit(@RequestParam(value = "file", required = false) MultipartFile[] file, String params,@RequestParam(value = "delFileIdList", required = false) String[] delFileIdList) {
            BaseProject project = JSON.parseObject(params, BaseProject.class);
            if (!projectService.checkProjectDeptNameUnique(project)) {
                return error("修改项目部失败，项目部名称已存在");
            }
//            project.setUpdateBy(SecurityUtils.getUsername());
            return projectService.updateProject(file,params,delFileIdList);

    }

    /**
     * 删除项目
     */
    @RequiresPermissions("bracelet:project:remove")
    @DeleteMapping("/{projectIds}")
    @SysLog(title = "项目部管理", businessType = OperaType.UPDATE,module = "基础管理->项目部管理")
    public AjaxResult remove(@PathVariable int[] projectIds) {
        try{
            return toAjax(projectService.deleteProjectByIds(projectIds));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    @RequiresPermissions("bracelet:project:export")
    @PostMapping("/export")
    @SysLog(title = "项目部管理", businessType = OperaType.EXPORT,module = "基础管理->项目部管理")
    public void export(HttpServletResponse response, BaseProject project) {
        try{
            List<BaseProject> list = projectService.selectProjectList(project);
            ExcelUtil<BaseProject> util = new ExcelUtil<BaseProject>(BaseProject.class);
            util.exportExcel(response, list, "项目部数据");
        }catch (Exception e){
            log.error(e.toString(),e);
        }
    }

    @GetMapping("exportProjectSome")
    public void exportProjectSome(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "ids") String ids) {
        try {
            List<ProjectExportVo> projectExportVoList = new ArrayList<>();
            String[] idAll = ids.split(",");
            int[] num = new int[idAll.length];
            for (int i = 0; i < idAll.length; i++) {
                num[i] = Integer.parseInt(idAll[i]);
            }
            List<BaseProject> projectLists = projectMapper.getProjectSomeLists(num);
            for (int i = 0; i < projectLists.size(); i++) {
                ProjectExportVo exportVo = new ProjectExportVo();
                BaseProject vo = projectLists.get(i);
                BeanUtils.copyProperties(vo, exportVo);
                exportVo.setId((i + 1) + "");
                projectExportVoList.add(exportVo);
            }
            ExportParams exportParams = new ExportParams("项目部管理表", "项目部管理表", ExcelType.XSSF);
            exportParams.setStyle(ExcelStyleUtil.class);
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, ProjectExportVo.class, projectExportVoList);
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode("项目部管理表" + ".xlsx", "UTF-8"));
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.close();
            workbook.close();
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }
}
