package cn.wise.sc.cement.business.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.wise.sc.cement.business.entity.NormProduction;
import cn.wise.sc.cement.business.entity.NormProductionStatistics;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.LoginUser;
import cn.wise.sc.cement.business.model.PageQuery;
import cn.wise.sc.cement.business.model.vo.NormProductionVo;
import cn.wise.sc.cement.business.model.vo.ProductionVo;
import cn.wise.sc.cement.business.model.vo.WorkloadStatisticsVo;
import cn.wise.sc.cement.business.service.INonStandardValueService;
import cn.wise.sc.cement.business.service.INormProductionService;
import cn.wise.sc.cement.business.service.IPrecipriceService;
import cn.wise.sc.cement.business.service.ISysUserService;
import cn.wise.sc.cement.business.util.PageUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ztw
 * @since 2020-09-23
 */
@RestController
@Api(tags = "人员产值统计-标准产值")
@RequestMapping("/business/norm/production")
public class NormProductionController {

    final
    INormProductionService iNormProductionService;
    final
    IPrecipriceService iPrecipriceService;
    final
    INonStandardValueService inonStandardValueService;
    final
    ISysUserService iSysUserService;

    public NormProductionController(INormProductionService iNormProductionService, IPrecipriceService iPrecipriceService, INonStandardValueService inonStandardValueService, ISysUserService iSysUserService) {
        this.iNormProductionService = iNormProductionService;
        this.iPrecipriceService = iPrecipriceService;
        this.inonStandardValueService = inonStandardValueService;
        this.iSysUserService = iSysUserService;
    }

    @PostMapping("/create")
    @ApiOperation("新增标准产值配置")
    public BaseResponse<NormProduction> addObj(@RequestBody NormProduction normProduction) {
        return iNormProductionService.addObj(normProduction);
    }

    @GetMapping("/page")
    @ApiOperation("分页查询")
    public BaseResponse<IPage<NormProductionVo>> page(PageQuery pageQuery) {
        return iNormProductionService.getPage(pageQuery);
    }

    @PutMapping("/edit")
    @ApiOperation("编辑标注产值配置")
    public BaseResponse<Boolean> edit(@RequestBody NormProduction production) {
        return iNormProductionService.edit(production);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据id获取标准产值配置")
    public BaseResponse<NormProduction> getById(@PathVariable("id") Integer id) {
        if (id == null || id <= 0) {
            return BaseResponse.errorMsg("id不能为空!");
        }
        NormProduction rts = iNormProductionService.getById(id);

        if (rts != null) {
            return BaseResponse.okData(rts);
        } else {
            return BaseResponse.errorMsg("没找着符合要求的信息!");
        }
    }

    @PutMapping("/status/{id}")
    @ApiOperation("启用/禁用")
    public BaseResponse<Integer> activeOrForbidden(@PathVariable("id") Integer id) {

        if (id == null || id <= 0) {
            return BaseResponse.errorMsg("编号id不能为空!");
        }
        return iNormProductionService.activeOrForbidden(id);
    }


    @GetMapping("/statistics")
    @ApiOperation("标准产值统计")
    public BaseResponse<Page<NormProductionStatistics>> normProductionStatistics(String start, String end, String name, Integer groupId, PageQuery pageQuery) {

        Long startTime = null;
        Long endTime = null;
        if (StrUtil.isNotBlank(start) && StrUtil.isNotBlank(end)) {
            startTime = DateUtil.parseDate(start).getTime();
            endTime = DateUtil.parseDate(end).offsetNew(DateField.DAY_OF_MONTH, 1).getTime();
        }

        //将list拆分成分页
        BaseResponse<List<NormProductionStatistics>> baseResponse = iPrecipriceService
                .normProductionStatistics(startTime, endTime, name, groupId);
        if (baseResponse.getCode() == 200) {
            List<NormProductionStatistics> data = baseResponse.getData();
            if (data.size() != 0) {
                Page<NormProductionStatistics> rts = PageUtil.listConvertToPage(data, pageQuery);
                return BaseResponse.okData(rts);
            }
        }

        return BaseResponse.okData(new Page<>());
    }

    @GetMapping("/statistics/detail")
    @ApiOperation("标准产值详情")
    public BaseResponse<Page<NormProduction.NormProductionDetail>> normProductionDetails(Integer userId, String start,
                                                                                         String end, PageQuery pageQuery) {

        Assert.notNull(userId, "用户id是必填的!");
        Long startTime = null;
        Long endTime = null;
        if (StrUtil.isNotBlank(start) && StrUtil.isNotBlank(end)) {
            startTime = DateUtil.parseDate(start).getTime();
            endTime = DateUtil.parseDate(end).offsetNew(DateField.DAY_OF_MONTH, 1).getTime();
        }
        List<NormProduction.NormProductionDetail> data = iPrecipriceService.normProductionDetails(userId, startTime, endTime);

        List<NormProduction.NormProductionDetail> collect = data
                .stream()
                .filter(arg -> arg.getUserId().intValue() == userId)
                .collect(Collectors.toList());
        if (collect.size() != 0) {
            Page<NormProduction.NormProductionDetail> rts = PageUtil.listConvertToPage(collect, pageQuery);
            return BaseResponse.okData(rts);
        }
        return BaseResponse.okData(new Page<>());
    }

    @GetMapping("/total/production")
    @ApiOperation("总产值统计")
    public BaseResponse<Page<ProductionVo>> production(PageQuery pageQuery, String name, String start, String end, Integer groupId) {

        Long startTime = null;
        Long endTime = null;
        if (StrUtil.isNotBlank(start) && StrUtil.isNotBlank(end)) {
            startTime = DateUtil.parseDate(start).getTime();
            endTime = DateUtil.parseDate(end).offsetNew(DateField.DAY_OF_MONTH, 1).getTime();
        }

        List<ProductionVo> rts = iPrecipriceService.production(name, startTime, endTime, groupId);
        if (!CollectionUtil.isEmpty(rts)) {
            Set<Integer> ids = new HashSet<>();
            for (ProductionVo productionVo : rts) {
                Integer groupId1 = productionVo.getGroupId();
                ids.add(groupId1);
            }
            List<ProductionVo> newRts = new ArrayList<>();
            for (Integer groupId1 : ids) {
                for (ProductionVo productionVo : rts) {
                    ProductionVo finalNormProduction = new ProductionVo();
                    if (productionVo.getGroupId().intValue() == groupId1) {
                        finalNormProduction.setUserId(productionVo.getUserId());
                        finalNormProduction.setUserName(productionVo.getUserName());
                        finalNormProduction.setAccount(productionVo.getAccount());
                        finalNormProduction.setPositionId(productionVo.getPositionId());
                        finalNormProduction.setPosition(productionVo.getPosition());
                        finalNormProduction.setTime(productionVo.getTime());
                        finalNormProduction.setGroupId(productionVo.getGroupId());
                        finalNormProduction.setGroupName(productionVo.getGroupName());

                        Double newFinalValue = productionVo.getProductionTotalValue() + finalNormProduction.getProductionTotalValue();
                        finalNormProduction.setProductionTotalValue(newFinalValue);

                        Double newNonProductionValue = productionVo.getNonProductionValue() + finalNormProduction.getNonProductionValue();
                        finalNormProduction.setProductionValue(newNonProductionValue);

                        Double newProductionValue = productionVo.getProductionValue() + finalNormProduction.getProductionValue();
                        finalNormProduction.setNonProductionValue(newProductionValue);
                    }
                    newRts.add(finalNormProduction);
                }
            }
            rts = newRts;
        }

        return BaseResponse.okData(PageUtil.listConvertToPage(rts, pageQuery));
    }

    @PostMapping("/export/statistics")
    @ApiOperation("导出标准产值列表")
    public void exportNormProductionStatistics(String start, String end, String name, Integer groupId, HttpServletResponse response) {
        Long startTime = null;
        Long endTime = null;
        if (StrUtil.isNotBlank(start) && StrUtil.isNotBlank(end)) {
            startTime = DateUtil.parseDate(start).getTime();
            endTime = DateUtil.parseDate(end).offsetNew(DateField.DAY_OF_MONTH, 1).getTime();
        }
        iNormProductionService.exportNormProductionStatistics(startTime, endTime, name, groupId, response);
    }

    @PostMapping("/export/statistics/detail")
    @ApiOperation("导出个人标准产值详情列表")
    public void exportNormProductionDetails(Integer userId, String start,
                                            String end, HttpServletResponse response) {
        Long startTime = null;
        Long endTime = null;
        if (StrUtil.isNotBlank(start) && StrUtil.isNotBlank(end)) {
            startTime = DateUtil.parseDate(start).getTime();
            endTime = DateUtil.parseDate(end).offsetNew(DateField.DAY_OF_MONTH, 1).getTime();
        }
        iPrecipriceService.exportNormProductionDetail(userId, startTime, endTime, response);
    }

    @PostMapping("/export/total/production")
    @ApiOperation("导出总产值")
    public void exportProduction(String name, String start, String end, Integer groupId, HttpServletResponse response) {
        Long startTime = null;
        Long endTime = null;
        if (StrUtil.isNotBlank(start) && StrUtil.isNotBlank(end)) {
            startTime = DateUtil.parseDate(start).getTime();
            endTime = DateUtil.parseDate(end).offsetNew(DateField.DAY_OF_MONTH, 1).getTime();
        }

        iNormProductionService.exportProduction(name, startTime, endTime, groupId, response);
    }


    @GetMapping("/workload/statistics")
    @ApiOperation("工作量统计")
    public BaseResponse<List<WorkloadStatisticsVo>> workloadStatistics(String start, String end, Integer userId) {

        LoginUser loginUser = iSysUserService.getLoginUser();
        if (BeanUtil.isEmpty(loginUser)) {
            return BaseResponse.errorMsg("请登录!");
        }

        if (!loginUser.getRoleList().getName().equals("系统管理员")) {
            userId = loginUser.getId();
        }

        Date startTime = null;
        Date endTime = DateUtil.date();
        if (StrUtil.isNotBlank(start) && StrUtil.isNotBlank(end)) {
            startTime = DateUtil.parseDate(start);
            endTime = DateUtil.parseDate(end).offsetNew(DateField.DAY_OF_MONTH, 1);
        }

        return BaseResponse.okData(iPrecipriceService.workloadStatistics(startTime, endTime, userId));
    }
}

