package com.lz.modules.app.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.lz.common.utils.*;
import com.lz.common.utils.excel.ExcelSheet;
import com.lz.modules.app.dto.*;
import com.lz.modules.app.entity.DepartmentsEntity;
import com.lz.modules.app.entity.StaffEntity;
import com.lz.modules.app.enums.ExcelStaffHeardEnum;
import com.lz.modules.app.model.RoleModel;
import com.lz.modules.app.req.StaffReq;
import com.lz.modules.app.resp.StaffRoleModel;
import com.lz.modules.app.service.*;
import com.lz.modules.flow.service.StaffRoleService;
import io.swagger.annotations.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 员工基本信息表
 *
 * @author fumeiai
 * @email fumeiai@linzikg.com
 * @date 2020-04-29 20:59:20
 */
@RestController
@RequestMapping("staff/info")
@Api(tags = "人员相关")
public class StaffController {

    @Autowired
    private StaffService staffService;

    @Autowired
    private DepartmentsService departmentsService;

    @Autowired
    private StaffEducationService staffEducationService;

    @Autowired
    private StaffOccupationService staffOccupationService;

    @Autowired
    private StaffProjectExperienceService staffProjectExperienceService;

    @Autowired
    private StaffWorkTransferRecordService staffWorkTransferRecordService;

    @Autowired
    private StaffRoleService staffRoleService;

    /**
     * 列表
     */
    @RequestMapping("/list")
//    @RequiresPermissions("staff:info:list")
    public R list(@RequestParam Map<String, Object> params) {
        //当前页
        int currentPage = 0;
        //默认每页返回数量
        int limit = 10;
        //部门Id
        String departmentId = "";
        //员工姓名
        String name = "";
        //人员状态【1：离职；0：在职】
        Integer staffStatus = 0;

        if (params.containsKey("page")) {
            currentPage = Integer.parseInt(params.get("page").toString());
        }

        if (params.containsKey("limit")) {
            limit = Integer.parseInt(params.get("limit").toString());
        }

        if (params.containsKey("departmentId")) {
            departmentId = params.get("departmentId").toString();
        }

        if (params.containsKey("name")) {
            name = params.get("name").toString();
        }

        if (params.containsKey("staffStatus")) {
            staffStatus = Integer.parseInt(params.get("staffStatus").toString());
        }
        List<StaffDto> staffInfos = staffService.getStaffInfos(currentPage, limit, departmentId, name, staffStatus);
        //总页码
        int maxCount = staffService.getStaffInfoCount(departmentId, name, staffStatus);

        R ret = R.ok();
        PageUtils pageInfo = new PageUtils(staffInfos, maxCount, limit, currentPage);
        ret.put("page", pageInfo);
        return ret;
    }

    /**
     * 列表
     */
    @PostMapping("/stafflist")
//    @RequiresPermissions("staff:info:list")
    @ApiOperation("获取人员列表")
    @ApiResponses({@ApiResponse(code = 200, message = "成功", response = StaffDto.class)})
    public R stafflist(@RequestBody @ApiParam StaffReq staffReq) {
        //当前页
        Map<String, Object> map = new HashMap<>();
        if(staffReq.getCurrPage() > 0){
            map.put("page", staffReq.getCurrPage());
        }

        if(staffReq.getPageSize() > 0){
            map.put("limit", staffReq.getPageSize());
        }

        if(staffReq.getDepartmentId() != null){
            map.put("departmentId", staffReq.getDepartmentId());
        }

        if(staffReq.getName() != null && staffReq.getName().length() > 0){
            map.put("name", staffReq.getName());
        }
        return list(map);
    }


    /**
     * 信息
     */
    @RequestMapping("/query/{staffId}")
//    @RequiresPermissions("staff:info:query")
    public R info(@PathVariable("staffId") Long id) {
//        StaffEntity staff = staffService.getById(id);
        Map data = new HashMap();
        data.put("staffId", id);
        StaffBaseInfoDto staffBaseInfoDto = staffService.getBaseInfo(id);
        StaffEducationInfoDto staffEducationInfoDto = staffEducationService.getInfoByStaffId(id);
        StaffOccupationInfoDto staffOccupationInfoDto = staffOccupationService.getOccupationByStaffId(id);
        if (staffOccupationInfoDto != null) {
            List<StaffProjectExperienceDto> staffProjectExperiences = staffProjectExperienceService.getProjectInfoByStaffId(id);
            if (staffProjectExperiences.size() > 0) {
                staffOccupationInfoDto.setProjectExperiences(staffProjectExperiences);
            }
            List<StaffWorkTransferDto> staffWorkTransfers = staffWorkTransferRecordService.getWorkInfoByStaffId(id);
            if (staffWorkTransfers.size() > 0) {
                staffOccupationInfoDto.setWorkTransfers(staffWorkTransfers);
            }
        }
        data.put("baseInfo", staffBaseInfoDto);
        data.put("educationInfo", staffEducationInfoDto);
        data.put("occupationInfo", staffOccupationInfoDto);
        return R.ok().put("data", data);
    }

    /**
     * 列表
     */
    @RequestMapping("/statistical")
//    @RequiresPermissions("staff:info:statistical")
    public R statistical(@RequestParam Map<String, Object> params) {
        Map data = new HashMap();
        String departmentName = "浙江霖梓控股有限公司";
        //部门Id
        String departmentId = "";
        //统计时间起
        String beginDate = "2017-01-01";
        //统计时间止
        String endDate = DateUtils.format(DateUtils.getCurrentDate(), DateUtils.DATE_PATTERN);

        if (params.containsKey("departmentId")) {
            departmentId = params.get("departmentId").toString();
        }

        if (params.containsKey("beginDate")) {
            beginDate = params.get("beginDate").toString();
        }

        if (params.containsKey("endDate")) {
            endDate = params.get("endDate").toString();
        }

        StaffStatisticalDto staffStatisticals = staffService.getStatisticalData(departmentId, beginDate, endDate);
        data = JSON.parseObject(JSON.toJSONString(staffStatisticals), Map.class);

        data.put("beginDate", beginDate);
        data.put("endDate", endDate);
        if (departmentId != "") {
            DepartmentsEntity department = departmentsService.getOne(new QueryWrapper<DepartmentsEntity>().eq("department_id", departmentId));
            if (department != null) {
                departmentName = department.getDepartmentName();
            }
        }
        data.put("departmentName", departmentName);

        List<GraphicsStatisticalDto> genderRows = staffService.getGenderData(departmentId, beginDate, endDate);
        GraphicsDto genderDistribution = new GraphicsDto();
        genderDistribution.setRows(genderRows);
        data.put("genderDistribution", genderDistribution);

        List<GraphicsStatisticalDto> ageRows = staffService.getAgeData(departmentId, beginDate, endDate);
        GraphicsDto ageDistribution = new GraphicsDto();
        ageDistribution.setRows(ageRows);
        data.put("ageDistribution", ageDistribution);

        List<GraphicsStatisticalDto> jobSeniorityRows = staffService.getJobSeniorityData(departmentId, beginDate, endDate);
        GraphicsDto jobSeniorityDistribution = new GraphicsDto();
        jobSeniorityDistribution.setRows(jobSeniorityRows);
        data.put("jobSeniorityDistribution", jobSeniorityDistribution);

        List<GraphicsStatisticalDto> educationRows = staffService.getEducationData(departmentId, beginDate, endDate);
        GraphicsDto educationDistribution = new GraphicsDto();
        educationDistribution.setRows(educationRows);
        data.put("educationDistribution", educationDistribution);

        R ret = R.ok();
        ret.put("data", data);
        return ret;
    }


    /**
     * 上传Excel,读取Excel中内容
     *
     * @param file 文件
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/batchImport")
//    @RequiresPermissions("user:ltuserrewardlog:upload")
    public R batchImport(@RequestParam(value = "file") MultipartFile file) {

        InputStream inputStream;
        try {
            //判断文件是否为空
            if (file == null) {
                return R.error("文件不能为空");
            }

            //获取文件名
            String name = file.getOriginalFilename();

            //进一步判断文件是否为空（即判断其大小是否为0或其名称是否为null）验证文件名是否合格
            long size = file.getSize();
            if (StringUtil.isBlank(name) || size == 0 || !ExcelUtil.validateExcel(name)) {
                return R.error("文件格式不正确！请使用.xls或.xlsx后缀文档。");
            }

            if (name.lastIndexOf(".csv") != -1 || name.lastIndexOf(".CSV") != -1) {
                inputStream = new ByteArrayInputStream(file.getBytes());
            } else {
                inputStream = file.getInputStream();
            }
            List<Map<String, String>> sheet12List = Lists.newArrayList();
            List<Map<String, String>> sheet3List = Lists.newArrayList();
            List<Map<String, String>> sheet4List = Lists.newArrayList();

            ExcelUtil.getExcelData(inputStream, sheet12List, sheet3List, sheet4List);

            staffService.enterDatabase(sheet12List, sheet3List, sheet4List);

            return R.ok();
        } catch (IOException e) {
            return R.error();
        }
    }

    /**
     * 模板下载
     *
     * @param params   请求参数集合
     * @param response
     */
    @RequestMapping("/downloadTemplate")
//    @RequiresPermissions("staff:info:download")
    public void download(@RequestParam Map<String, Object> params, HttpServletResponse response) {

        List<ExcelSheet<HashMap<String, Object>>> list = new ArrayList<>();

        try {
            ExcelSheet<HashMap<String, Object>> sheet = new ExcelSheet<>();
            sheet.setSheetName("员工档案表-在职");
            sheet.setHeaders(ExcelUtil.getExcelHeaderMap());
            List<HashMap<String, Object>> dataList = new ArrayList<>();
            HashMap<String, Object> data = (HashMap<String, Object>) ExcelUtil.getExcelDataMap();
            dataList.add(data);

            sheet.setDataset(dataList);
            list.add(sheet);

            ExcelSheet<HashMap<String, Object>> sheet2 = new ExcelSheet<>();
            sheet2.setSheetName("员工档案表-离职");
            Map<String, String> headMap = ExcelUtil.getExcelHeaderMap();
            headMap.put(ExcelStaffHeardEnum.findFieldByName("离职日期"), "离职日期");
            headMap.put(ExcelStaffHeardEnum.findFieldByName("离职原因"), "离职原因");
            sheet2.setHeaders(headMap);
            list.add(sheet2);

            ExcelSheet<HashMap<String, Object>> sheet3 = new ExcelSheet<>();
            sheet3.setSheetName("员工项目经历");
            sheet3.setHeaders(ExcelUtil.getExcelSheet2HeaderMap());
            list.add(sheet3);

            ExcelSheet<HashMap<String, Object>> sheet4 = new ExcelSheet<>();
            sheet4.setSheetName("工作调转记录");
            sheet4.setHeaders(ExcelUtil.getExcelSheet3HeaderMap());
            list.add(sheet4);

            ExcelUtil.exportExcel(list, "员工信息模版" + DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN), response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("staff:info:save")
    public R save(@RequestBody StaffEntity staff) {
        staffService.save(staff);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("staff:info:update")
    public R update(@RequestBody StaffEntity staff) {
        staffService.updateById(staff);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("staff:info:delete")
    public R delete(@RequestBody Long[] ids) {
        staffService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }



}
