package org.jeecg.modules.projectManagement.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.NotDuplicate;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basedata.entity.FdContractClass;
import org.jeecg.modules.projectManagement.entity.*;
import org.jeecg.modules.projectManagement.mapper.FdContractMapper;
import org.jeecg.modules.projectManagement.service.IFdClinicalProjectMilestonesService;
import org.jeecg.modules.projectManagement.service.IFdContractService;
import org.jeecg.modules.projectManagement.service.IFdWorkingHoursItemsService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.projectManagement.service.IFdWorkingHoursService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;

/**
 * @Title: Controller
 * @Description: 工时记录明细
 * @author： jeecg-boot
 * @date： 2019-06-25
 * @version： V1.0
 */
@RestController
@RequestMapping("/projectManagement/fdWorkingHoursItems")
@Slf4j
public class FdWorkingHoursItemsController {
    @Autowired
    private IFdWorkingHoursItemsService fdWorkingHoursItemsService;

    @Resource
    private IFdContractService fdContractService;

    @Resource
    private FdContractMapper fdContractMapper;

    @Resource
    private IFdClinicalProjectMilestonesService fdClinicalProjectMilestonesService;

    @Resource
    private IFdWorkingHoursService iFdWorkingHoursService;

    /**
     * 分页列表查询
     *
     * @param fdWorkingHoursItems
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    public Result<IPage<FdWorkingHoursItems>> queryPageList(FdWorkingHoursItems fdWorkingHoursItems,
                                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                            HttpServletRequest req) {
        Result<IPage<FdWorkingHoursItems>> result = new Result<IPage<FdWorkingHoursItems>>();
        //工时记录id
        String workingId=fdWorkingHoursItems.getPkWokingHour();
        if(!oConvertUtils.isEmpty(fdWorkingHoursItems.getPkWokingHour())){
            fdWorkingHoursItems.setPkWokingHour(null);
        }
        QueryWrapper<FdWorkingHoursItems> queryWrapper = QueryGenerator.initQueryWrapper(fdWorkingHoursItems, req.getParameterMap());
        queryWrapper.orderByAsc("sort");
        if(!oConvertUtils.isEmpty(workingId)){
            // queryWrapper.eq("whi.pk_woking_hour",workingId);
            queryWrapper.lambda().eq(FdWorkingHoursItems::getPkWokingHour,workingId);
        }
        Page<FdWorkingHoursItems> page = new Page<FdWorkingHoursItems>(pageNo, pageSize);
        IPage<FdWorkingHoursItems> pageList = fdWorkingHoursItemsService.page(page, queryWrapper);
        // IPage<FdWorkingHoursItems> pageList = fdWorkingHoursItemsService.findByPage(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
    * @Author chenchuang
    * @Description //TODO 工时查看菜单信息查询
    * @Date 2020/7/23 14:04
    * @Param [fdWorkingHoursItems, pageNo, pageSize, req]
    * @return org.jeecg.common.api.vo.Result<com.baomidou.mybatisplus.core.metadata.IPage<org.jeecg.modules.projectManagement.entity.FdWorkingHoursItems>>
    */
    @GetMapping(value = "/getViewPage")
    public Result<IPage<FdWorkingHoursItems>> getViewPage(FdWorkingHoursItems fdWorkingHoursItems,
                                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                            HttpServletRequest req) {
        Result<IPage<FdWorkingHoursItems>> result = new Result<IPage<FdWorkingHoursItems>>();
        String startDate=fdWorkingHoursItems.getStartDate();//开始时间
        String endDate=fdWorkingHoursItems.getEndDate();//结束时间
        if(StringUtils.isNotBlank(startDate)){
            fdWorkingHoursItems.setStartDate(null);
        }
        if(StringUtils.isNotBlank(endDate)){
            fdWorkingHoursItems.setEndDate(null);
        }
        String contractCode=fdWorkingHoursItems.getContractCode();
        if(StringUtils.isNotBlank(contractCode)){
            fdWorkingHoursItems.setContractCode(null);
        }
        QueryWrapper<FdWorkingHoursItems> queryWrapper = QueryGenerator.initQueryWrapper(fdWorkingHoursItems, req.getParameterMap());
        if(StringUtils.isNotBlank(startDate)&&StringUtils.isNotBlank(endDate)){
            //时间间隔查询
            queryWrapper.between("fwh.actual_hours",startDate,endDate);
        }
        if(StringUtils.isNotBlank(contractCode)){
            queryWrapper.like("fwhi.contract_code",contractCode);
        }
        queryWrapper.orderByAsc("CONVERT ( fwh.hour_filler USING gbk ),fwh.actual_hours");
        Page<FdWorkingHoursItems> page = new Page<FdWorkingHoursItems>(pageNo, pageSize);
        IPage<FdWorkingHoursItems> pageList = fdWorkingHoursItemsService.getViewPage(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 添加
     *
     * @param fdWorkingHoursItems
     * @return
     */
    @PostMapping(value = "/add")
    @NotDuplicate
    public Result<FdWorkingHoursItems> add(@RequestBody @Valid FdWorkingHoursItems fdWorkingHoursItems, BindingResult bindingResult) {
        Result<FdWorkingHoursItems> result = new Result<FdWorkingHoursItems>();
        try {
            StringBuilder sb = new StringBuilder();
            if (bindingResult.hasErrors()) {
                //记录错误信息
                bindingResult.getAllErrors().stream().forEach(error -> sb.append(error.getDefaultMessage() + "<br/>"));
                result.error500(sb.toString());
                return result;
            }
            fdWorkingHoursItemsService.save(fdWorkingHoursItems);
            //查询主表数据
            FdWorkingHours fdWorkingHours=iFdWorkingHoursService.getById(fdWorkingHoursItems.getPkWokingHour());
            //更新总工时
            iFdWorkingHoursService.updateHoursTotal(fdWorkingHours);
            result.success("添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param fdWorkingHoursItems
     * @return
     */
    @PutMapping(value = "/edit")
    @NotDuplicate
    public Result<FdWorkingHoursItems> edit(@RequestBody @Valid FdWorkingHoursItems fdWorkingHoursItems, BindingResult bindingResult) {
        Result<FdWorkingHoursItems> result = new Result<FdWorkingHoursItems>();
        FdWorkingHoursItems fdWorkingHoursItemsEntity = fdWorkingHoursItemsService.getById(fdWorkingHoursItems.getId());
        if (fdWorkingHoursItemsEntity == null) {
            result.error500("未找到对应实体");
        } else {
            StringBuilder sb = new StringBuilder();
            if (bindingResult.hasErrors()) {
                //记录错误信息
                bindingResult.getAllErrors().stream().forEach(error -> sb.append(error.getDefaultMessage() + "<br/>"));
                result.error500(sb.toString());
                return result;
            }

//            fdWorkingHoursItems.setSort("");

            boolean ok = fdWorkingHoursItemsService.updateById(fdWorkingHoursItems);

            //查询主表数据
            FdWorkingHours fdWorkingHours=iFdWorkingHoursService.getById(fdWorkingHoursItems.getPkWokingHour());
            //更新总工时
            iFdWorkingHoursService.updateHoursTotal(fdWorkingHours);
            //TODO 返回false说明什么？
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete")
    public Result<FdWorkingHoursItems> delete(@RequestParam(name = "id", required = true) String id) {
        Result<FdWorkingHoursItems> result = new Result<FdWorkingHoursItems>();
        FdWorkingHoursItems fdWorkingHoursItems = fdWorkingHoursItemsService.getById(id);
        if (fdWorkingHoursItems == null) {
            result.error500("未找到对应实体");
        } else {
            //查询主表数据
            FdWorkingHours fdWorkingHours=iFdWorkingHoursService.getById(fdWorkingHoursItems.getPkWokingHour());
            boolean ok = fdWorkingHoursItemsService.removeById(id);
            //更新总工时
            iFdWorkingHoursService.updateHoursTotal(fdWorkingHours);
            if (ok) {
                result.success("删除成功!");
            }
        }

        return result;
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatch")
    public Result<FdWorkingHoursItems> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<FdWorkingHoursItems> result = new Result<FdWorkingHoursItems>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.fdWorkingHoursItemsService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<FdWorkingHoursItems> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<FdWorkingHoursItems> result = new Result<FdWorkingHoursItems>();
        FdWorkingHoursItems fdWorkingHoursItems = fdWorkingHoursItemsService.getById(id);
        if (fdWorkingHoursItems == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(fdWorkingHoursItems);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
        // Step.1 组装查询条件
        QueryWrapper<FdWorkingHoursItems> queryWrapper = null;
        try {
            String paramsStr = request.getParameter("paramsStr");
            if (oConvertUtils.isNotEmpty(paramsStr)) {
                String deString = URLDecoder.decode(paramsStr, "UTF-8");
                FdWorkingHoursItems fdWorkingHoursItems = JSON.parseObject(deString, FdWorkingHoursItems.class);
                queryWrapper = QueryGenerator.initQueryWrapper(fdWorkingHoursItems, request.getParameterMap());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<FdWorkingHoursItems> pageList = fdWorkingHoursItemsService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "工时记录明细列表");
        mv.addObject(NormalExcelConstants.CLASS, FdWorkingHoursItems.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("工时记录明细列表数据", "导出人:Jeecg", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<FdWorkingHoursItems> listFdWorkingHoursItemss = ExcelImportUtil.importExcel(file.getInputStream(), FdWorkingHoursItems.class, params);
                for (FdWorkingHoursItems fdWorkingHoursItemsExcel : listFdWorkingHoursItemss) {
                    fdWorkingHoursItemsService.save(fdWorkingHoursItemsExcel);
                }
                return Result.ok("文件导入成功！数据行数：" + listFdWorkingHoursItemss.size());
            } catch (Exception e) {
                log.error(e.getMessage());
                return Result.error("文件导入失败！");
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }


    /**
     * @Author gurui
     * @Description //TODO 普通里程碑根据合同id查询
     * @Date 19:02 2019/6/25
     * @Param [id]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdWorkingHoursItems>
     **/
    @GetMapping(value = "/queryByContractId")
    public Result<FdWorkingHoursItems> queryByContractId( String contractId) {
        Result<FdWorkingHoursItems> result = new Result<FdWorkingHoursItems>();
        FdWorkingHoursItems fdContract = fdWorkingHoursItemsService.queryByContractId(contractId);
        if (fdContract == null) {
            result.error500("未找到对应实体");
        } else {
            //根据合同id获取合同项目名称
            LambdaQueryWrapper<FdContract> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(FdContract::getId,contractId);
            List<FdContract> list = fdContractService.list(queryWrapper);
            for (FdContract fdContract1:list){
                fdContract.setProjectDescription(fdContract1.getProjectName());
            }
            //根据合同id获取项目里程碑
            LambdaQueryWrapper<FdClinicalProjectMilestones> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(FdClinicalProjectMilestones::getPkContract,contractId);
            List<FdClinicalProjectMilestones> list1 = fdClinicalProjectMilestonesService.list(queryWrapper1);
            for (FdClinicalProjectMilestones fdClinicalProjectMilestones:list1){
                fdContract.setMilestones(fdClinicalProjectMilestones.getProjectName());
            }
            result.setResult(fdContract);
            result.setSuccess(true);
        }
        return result;
    }

    /***
     * @Title:按部门工时报表数据
            * @Description:TODO
            * @param startDate, endDate]
            * @return org.jeecg.common.api.vo.Result<java.util.List<org.jeecg.modules.projectManagement.entity.FdWorkingHoursItems>>
            * @exception 
            * @author 陈创
            * @date 2019/8/21 16:43
            * @updatehistory:
     *   2019/8/21 16:43 新增
            */
    @GetMapping(value = "/getWorkingReport")
    @RequiresPermissions("url:departMentStatistic:view")
    public Result<List<FdWorkingHoursItems>> getWorkingReport(String startDate,String endDate,@RequestParam(name = "departs", required = true)List<String> departs){
        Result<List<FdWorkingHoursItems>> result=new Result<>();
        try {
            //移除字符“null”的数据
            removeNull(departs);
            List<FdWorkingHoursItems> fdWorkingHoursItemsList=fdWorkingHoursItemsService.getWorkingReport(startDate,endDate,departs);
            result.setResult(fdWorkingHoursItemsList);
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("查询失败"+e.getMessage());
        }
        return result;
    }

    /***
     * @Title:按人员查询报表数据
            * @Description:TODO
            * @param startDate, endDate]
            * @return org.jeecg.common.api.vo.Result<java.util.List<org.jeecg.modules.projectManagement.entity.FdWorkingHoursItems>>
            * @exception 
            * @author 陈创
            * @date 2019/8/21 17:00
            * @updatehistory:
     *   2019/8/21 17:00 新增
            */
    @GetMapping(value = "/getWorkingReportPersonnel")
    @RequiresPermissions("url:peopleStatistic:view")
    public Result<List<FdWorkingHoursItems>> getWorkingReportPersonnel(String startDate,String endDate,@RequestParam(name = "personnelCodes", required = true)List<String> personnelCodes){
        Result<List<FdWorkingHoursItems>> result=new Result<>();
        //移除字符“null”的数据
        removeNull(personnelCodes);
        try {
            List<FdWorkingHoursItems> fdWorkingHoursItemsList=fdWorkingHoursItemsService.getWorkingReportPersonnel(startDate,endDate,personnelCodes);
            result.setResult(fdWorkingHoursItemsList);
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("查询失败"+e.getMessage());
        }
        return result;
    }

    /**
     * 移除为字符“null”的数据
     * @param list
     */
    public void removeNull(List<String> list){
        if(list!=null&&list.size()>0){
            for(int i=0;i<list.size();i++){
                if(list.get(i).equals("null")){
                    list.remove(i);
                }
            }
        }
    }

    /***
     * @Title:档案中审核完的合同数据
            * @Description:TODO
            * @param fdProjectFile
            * @return org.jeecg.common.api.vo.Result<java.util.List<org.jeecg.modules.projectManagement.entity.FdProjectFile>>
            * @exception 
            * @author 陈创
            * @date 2019/9/4 10:43
            * @updatehistory:
     *   2019/9/4 10:43 新增
            */
    @GetMapping(value = "/getContractList")
    public Result<List<FdProjectFile>> getContractList(FdProjectFile fdProjectFile){
        Result<List<FdProjectFile>> result=new Result<>();
        try {
            List<FdProjectFile> fdProjectFileList=fdWorkingHoursItemsService.getContractList(fdProjectFile);
            result.setResult(fdProjectFileList);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败"+e.getMessage());
        }
        return result;
    }

    /***
     * @Title:工时异常报表
            * @Description:TODO
            * @param startDate, endDate]
            * @return org.jeecg.common.api.vo.Result<java.util.List<org.jeecg.modules.projectManagement.entity.FdWorkingHoursItems>>
            * @exception 
            * @author 陈创
            * @date 2019/9/17 15:45
            * @updatehistory:
     *   2019/9/17 15:45 新增
            */
    @GetMapping(value = "/abnormalHoursReport")
    @RequiresPermissions("url:working-abnormal:view")
    public Result<List<FdWorkingHoursItems>> abnormalHoursReport(String startDate,String endDate,String roleId){
        Result<List<FdWorkingHoursItems>> result=new Result<>();
        try {
            List<FdWorkingHoursItems> fdWorkingHoursItemsList=fdWorkingHoursItemsService.abnormalHoursReport(startDate,endDate,roleId);
            result.setResult(fdWorkingHoursItemsList);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败："+e.getMessage());
        }
        return result;
    }

    /**
     * 工时导出个人数据
     * @param fdWorkingHoursItems
     * @return
     */
    @GetMapping(value = "/getWorkingItemsExport")
    @RequiresPermissions("working:exportPersonalData")
    public Result<List<FdWorkingHoursItems>> getWorkingItemsExport(FdWorkingHoursItems fdWorkingHoursItems){
        Result<List<FdWorkingHoursItems>> result=new Result<>();
        try {
            SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();//当前登录用户信息
            fdWorkingHoursItems.setMainCreateBy(user.getUsername());//获取当前人的编码
            result.setResult(fdWorkingHoursItemsService.getWorkingItemsExport(fdWorkingHoursItems));
            result.success("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败："+e.getMessage());
        }
        return result;
    }

    /**
    * @Author chenchuang
    * @Description //TODO 工时导出按项目统计总工时按月
    * @Date 2020/6/4 14:57
    * @Param [fdWorkingHoursItems]
    * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdWorkingHours>
    */
    @GetMapping(value = "/getDateExport")
    public Result<FdWorkingHours> getDateExport(FdWorkingHoursItems fdWorkingHoursItems){
        Result<FdWorkingHours> result=new Result<>();
        try {
            FdWorkingHours fdWorkingHoursItemsList=fdWorkingHoursItemsService.getDateExport(fdWorkingHoursItems);
            result.setResult(fdWorkingHoursItemsList);
            result.success("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败："+e.getMessage());
        }
        return result;
    }

    /**
     * @Author chenchuang
     * @Description //TODO 工时导出按项目统计工时按天
     * @Date 2020/6/4 14:57
     * @Param [fdWorkingHoursItems]
     * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.projectManagement.entity.FdWorkingHours>
     */
    @GetMapping(value = "/getDayDateExport")
    public Result<FdWorkingHours> getDayDateExport(FdWorkingHoursItems fdWorkingHoursItems){
        Result<FdWorkingHours> result=new Result<>();
        try {
            FdWorkingHours fdWorkingHoursItemsList=fdWorkingHoursItemsService.getDayDateExport(fdWorkingHoursItems);
            result.setResult(fdWorkingHoursItemsList);
            result.success("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("操作失败："+e.getMessage());
        }
        return result;
    }
}
