package com.jisco.dynamicweight.dynamicworkupdata.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Snowflake;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.jisco.dynamicweight.dynamicworkupdata.dto.CalNewCokeDto;
import com.jisco.dynamicweight.dynamicworkupdata.dto.CokeComputeDto;
import com.jisco.dynamicweight.dynamicworkupdata.dto.InbatchDto;
import com.jisco.dynamicweight.dynamicworkupdata.dto.ReturnedDustDto;
import com.jisco.dynamicweight.dynamicworkupdata.model.DynamicWorkUpdata;
import com.jisco.dynamicweight.dynamicworkupdata.service.IDynamicWorkUpdataService;
import com.jisco.dynamicweight.dynamicworkupdata.vo.AuditDataVO;
import com.jisco.dynamicweight.dynamicworkupdata.vo.DailyReportVO;
import com.jisco.dynamicweight.util.ExcelUtil;
import com.jisco.dynamicweight.util.UserUtil;
import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.framework.utils.collection.ListUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * DynamicWorkUpdata RESTful接口：
 *
 * @author generator
 * @version 1.0-SNAPSHORT 2022-01-18 10:14
 * 类描述
 * 修订历史：
 * 日期：2022-01-18
 * 作者：generator
 * 参考：
 * 描述：DynamicWorkUpdata RESTful接口
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 * @see null
 */
@RestController
@RequestMapping("/${api.version}/dynamicworkupdatas")
public class DynamicWorkUpdataController extends BaseRESTfulController {

    @Autowired
    IDynamicWorkUpdataService dynamicWorkUpdataService;

    @ApiOperation(value = "获取列表", notes = "分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("dynamicworkupdata:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas, Integer pageNum, Integer pageSize) {
        dynamicWorkUpdataService.recalc();
        PageList<DynamicWorkUpdata> list = dynamicWorkUpdataService.queryForPage(parmas, pageNum, pageSize);
        return success(list);
    }

    @ApiOperation(value = "获取列表", notes = "分页模糊查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("dynamicworkupdata:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas, Integer pageNum, Integer pageSize) {
//        dynamicWorkUpdataService.recalc();
        PageList<DynamicWorkUpdata> list = dynamicWorkUpdataService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }

    @ApiOperation(value = "创建", notes = "根据DynamicWorkUpdata对象创建")
    @ApiImplicitParam(name = "dynamicWorkUpdata", value = "详细实体dynamicWorkUpdata", required = true, dataType = "DynamicWorkUpdata")
    //@RequiresPermissions("dynamicworkupdata:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@RequestBody DynamicWorkUpdata model) {
        Assert.isTrue(StringUtils.isNotBlank(model.getStationCode()), "站点编码不能为空!");
        Assert.isTrue(StringUtils.isNotBlank(model.getStationName()), "站点名称不能为空!");
        Assert.isTrue(StringUtils.isNotBlank(model.getMaterialCode()), "物料编码不能为空!");
        Assert.isTrue(StringUtils.isNotBlank(model.getMaterialName()), "物料名称不能为空!");
        Assert.isTrue(StringUtils.isNotBlank(model.getRecieverCode()), "收货库房编码不能为空!");
        Assert.isTrue(StringUtils.isNotBlank(model.getRecieverName()), "收货库房名称不能为空!");
        Assert.isTrue(StringUtils.isNotBlank(model.getRecieverType()), "收货点类型不能为空!");
        Assert.isTrue(StringUtils.isNotBlank(model.getSenderCode()), "发货库房编码不能为空!");
        Assert.isTrue(StringUtils.isNotBlank(model.getSenderName()), "发货库房名称不能为空!");
        Assert.isTrue(StringUtils.isNotBlank(model.getSenderType()), "发货点类型不能为空!");
        Assert.isTrue(Objects.nonNull(model.getStartTime()), "开始时间不能为空!");
        Assert.isTrue(Objects.nonNull(model.getEndTime()), "结束时间不能为空!");
        Assert.isTrue(Objects.nonNull(model.getWeight()), "重量不能为空!");
        model.setUpdataNo(null);
        model.setValidFlag("1");
        model.setUploaded("0");
        model.setAuditingFlag("0");
        model.setCreateManNo(UserUtil.getCurrentUserId());
        model.setCreateManName(UserUtil.getCurrentUserName());
        model.setCreateTime(new Date());
        DynamicWorkUpdata dynamicWorkUpdata = dynamicWorkUpdataService.add(model);
        return success(dynamicWorkUpdata);
    }

    @ApiOperation(value = "获取详细信息", notes = "根据url的id来获取详细信息")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("dynamicworkupdata:view")
    @GetMapping(value = "/{id}")
    public RESTfulResult get(@PathVariable String id) {
        DynamicWorkUpdata dynamicWorkUpdata = dynamicWorkUpdataService.getById(id);
        return success(dynamicWorkUpdata);
    }

    @ApiOperation(value = "更新详细信息", notes = "根据url的id来指定更新对象，并根据传过来的dynamicWorkUpdata信息来更新详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String"),
            @ApiImplicitParam(name = "dynamicWorkUpdata", value = "详细实体dynamicWorkUpdata", required = true, dataType = "DynamicWorkUpdata")
    })
    //@RequiresPermissions("dynamicworkupdata:update")
    @PutMapping(value = "/{id}", produces = "application/json;charset=UTF-8")
    public RESTfulResult update(@PathVariable String id, @RequestBody DynamicWorkUpdata model) {
        Assert.isTrue(StringUtils.isNotBlank(model.getStationCode()), "站点编码不能为空!");
        Assert.isTrue(StringUtils.isNotBlank(model.getStationName()), "站点名称不能为空!");
        Assert.isTrue(StringUtils.isNotBlank(model.getMaterialCode()), "物料编码不能为空!");
        Assert.isTrue(StringUtils.isNotBlank(model.getMaterialName()), "物料名称不能为空!");
        Assert.isTrue(StringUtils.isNotBlank(model.getRecieverCode()), "收货库房编码不能为空!");
        Assert.isTrue(StringUtils.isNotBlank(model.getRecieverName()), "收货库房名称不能为空!");
        Assert.isTrue(StringUtils.isNotBlank(model.getRecieverType()), "收货点类型不能为空!");
        Assert.isTrue(StringUtils.isNotBlank(model.getSenderCode()), "发货库房编码不能为空!");
        Assert.isTrue(StringUtils.isNotBlank(model.getSenderName()), "发货库房名称不能为空!");
        Assert.isTrue(StringUtils.isNotBlank(model.getSenderType()), "发货点类型不能为空!");
        Assert.isTrue(Objects.nonNull(model.getStartTime()), "开始时间不能为空!");
        Assert.isTrue(Objects.nonNull(model.getEndTime()), "结束时间不能为空!");
        Assert.isTrue(Objects.nonNull(model.getWeight()), "重量不能为空!");
        Assert.isTrue(StringUtils.isNotBlank(model.getValidFlag()), "有效标识不能为空!");
        model.setUpdateManNo(UserUtil.getCurrentUserId());
        model.setUpdateManName(UserUtil.getCurrentUserName());
        model.setUpdateTime(new Date());
        model.setId(id);
        DynamicWorkUpdata dynamicWorkUpdata = dynamicWorkUpdataService.modify(model);
        return success(dynamicWorkUpdata);
    }

    @ApiOperation(value = "删除", notes = "根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("dynamicworkupdata:delete")
    @DeleteMapping(value = "/{id}")//String
    public RESTfulResult delete(@PathVariable String id) {
        List<String> list = Arrays.asList(id.split(","));
        if (ListUtils.isNotEmpty(list)) {
            List<String> ids = ListUtils.convertList(list);
            dynamicWorkUpdataService.delete(ids);
        }
        return success();
    }

    @ApiOperation(value = "导出Excel", notes = "导出Excel")
    @PostMapping(value = "/exportExcel")//String
    public void exportExcel(@RequestBody HashMap parmas, HttpServletResponse response) throws IOException {
        List<DynamicWorkUpdata> list = dynamicWorkUpdataService.query(parmas);
        ExcelUtil.exportExcel(response, list, DynamicWorkUpdata.class, "动态秤称重数据");
    }

//    @ApiOperation(value = "重新获取动态秤称重数据", notes = "重新获取动态秤称重数据")
//    @GetMapping(value = "/recalc")//String
//    public RESTfulResult recalc(){
//        dynamicWorkUpdataService.recalc();
//        return success();
//    }

    @ApiOperation(value = "数据分批总重量", notes = "数据分批总重量")
    @GetMapping(value = "/inbatchsTotalWeight/{updataNo}/{date1}/{date2}")
    public RESTfulResult inbatchsTotalWeight(@PathVariable String updataNo, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime date1, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime date2) {
        Assert.isTrue(StringUtils.isNotBlank(updataNo), "记录编号不能为空！");
        Assert.notNull(date1, "开始时间不能为空！");
        Assert.notNull(date2, "结束时间不能为空！");
        Date startTime = Date.from(date1.atZone(ZoneId.systemDefault()).toInstant());
        Date endTime = Date.from(date2.atZone(ZoneId.systemDefault()).toInstant());
        BigDecimal weight = dynamicWorkUpdataService.inbatchsTotalWeight(updataNo, startTime, endTime);
        return success(weight);
    }

    @ApiOperation(value = "数据分批", notes = "数据分批")
    @PostMapping(value = "/inbatchs/{updataNo}/{date1}/{date2}")
    public RESTfulResult inbatchs(@PathVariable String updataNo, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime date1, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime date2, @RequestBody List<InbatchDto> list) {
        Assert.isTrue(StringUtils.isNotBlank(updataNo), "记录编号不能为空！");
        Assert.notNull(date1, "开始时间不能为空！");
        Assert.notNull(date2, "结束时间不能为空！");
        Date startTime = Date.from(date1.atZone(ZoneId.systemDefault()).toInstant());
        Date endTime = Date.from(date2.atZone(ZoneId.systemDefault()).toInstant());
        dynamicWorkUpdataService.inbatchs(updataNo, startTime, endTime, list);
        return success();
    }

    @ApiOperation(value = "返粉总重量", notes = "返粉总重量")
    @GetMapping(value = "/returnedDustTotalWeight/{updataNo}/{date1}/{date2}")
    public RESTfulResult returnedDustWeight(@PathVariable String updataNo, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime date1, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime date2) {
        Assert.isTrue(StringUtils.isNotBlank(updataNo), "记录编号不能为空！");
        Assert.notNull(date1, "开始时间不能为空！");
        Assert.notNull(date2, "结束时间不能为空！");
        Date startTime = Date.from(date1.atZone(ZoneId.systemDefault()).toInstant());
        Date endTime = Date.from(date2.atZone(ZoneId.systemDefault()).toInstant());
        BigDecimal weight = dynamicWorkUpdataService.returnedDustWeight(updataNo, startTime, endTime);
        return success(weight);
    }

    @ApiOperation(value = "返粉", notes = "返粉")
    @PostMapping(value = "/returnedDust/{updataNo}/{date1}/{date2}")
    public RESTfulResult returnedDust(@PathVariable String updataNo, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime date1, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime date2, @RequestBody List<ReturnedDustDto> list) {
        Assert.isTrue(StringUtils.isNotBlank(updataNo), "记录编号不能为空！");
        Assert.notNull(date1, "开始时间不能为空！");
        Assert.notNull(date2, "结束时间不能为空！");
        Date startTime = Date.from(date1.atZone(ZoneId.systemDefault()).toInstant());
        Date endTime = Date.from(date2.atZone(ZoneId.systemDefault()).toInstant());
        dynamicWorkUpdataService.returnedDust(updataNo, startTime, endTime, list);
        return success();
    }

    @ApiOperation(value = "重新计算焦炭量", notes = "重新计算焦炭量")
    @PostMapping(value = "recalcCoke")
    public RESTfulResult recalcCoke(@RequestBody CokeComputeDto model) {
        dynamicWorkUpdataService.recalcCoke(model);
        return success();
    }


    @ApiOperation(value = "动态秤日报表", notes = "动态秤日报表")
    @ApiImplicitParam(paramType = "path", name = "date", value = "date", required = true, dataType = "Date")
    @GetMapping(value = "dailyReport/{date}")
    public RESTfulResult dailyReport(@PathVariable String date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            sdf.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
            throw new RuntimeException("日期格式不正确(yyyy-MM-dd)");
        }
        List<DailyReportVO> list = dynamicWorkUpdataService.dailyReport(date);
        return success(list);
    }

    @ApiOperation(value = "动态秤日报表导出Excel", notes = "动态秤日报表导出Excel")
    @PostMapping(value = "/dailyReport/exportExcel/{date}")
    public void dailyReportExportExcel(HttpServletResponse response, @PathVariable String date) throws IOException {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        df.parse(date);
        List<DailyReportVO> list = dynamicWorkUpdataService.dailyReport(date);
        ExcelUtil.exportExcel(response, list, DailyReportVO.class, "动态秤称重数据");
    }

    @ApiOperation(value = "查询待审核数据", notes = "查询待审核数据")
    @ApiImplicitParam(paramType = "path", name = "date", value = "date", required = true, dataType = "Date")
    @GetMapping(value = "getAuditData/{date}")
    public RESTfulResult getAuditData(@PathVariable String date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            sdf.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
            throw new RuntimeException("日期格式不正确(yyyy-MM-dd)");
        }
        List<AuditDataVO> list = dynamicWorkUpdataService.getAuditData(date);
        return success(list);
    }

    @ApiOperation(value = "待审核数据导出Excel", notes = "待审核数据导出Excel")
    @PostMapping(value = "/exportAuditDataExcel/{date}")
    public void exportAuditDataExcel(HttpServletResponse response, @PathVariable String date) throws IOException {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        df.parse(date);
        List<AuditDataVO> list = dynamicWorkUpdataService.getAuditData(date);
        ExcelUtil.exportExcel(response, list, AuditDataVO.class, "待审核数据");
    }

    @ApiOperation(value = "启用", notes = "启用")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    @GetMapping(value = "/enable/{id}")
    public RESTfulResult enable(@PathVariable String id) {
        boolean flag = dynamicWorkUpdataService.enable(id);
        return flag ? success(null, "操作成功") : failed(null, "操作失败");
    }

    @ApiOperation(value = "禁用", notes = "禁用")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    @GetMapping(value = "/disable/{id}")
    public RESTfulResult disable(@PathVariable String id) {
        boolean flag = dynamicWorkUpdataService.disable(id);
        return flag ? success(null, "操作成功") : failed(null, "操作失败");
    }

    @ApiOperation(value = "批量启用", notes = "批量启用")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    @PutMapping(value = "/enableBatch")
    public RESTfulResult enableBatch(@RequestBody List<DynamicWorkUpdata> list) {
        if (ListUtils.isNotEmpty(list)) {
            for (DynamicWorkUpdata updata : list) {
                boolean flag = dynamicWorkUpdataService.enable(updata.getId());
                Assert.isTrue(flag, "操作失败");
            }
        }
        return success();
    }

    @ApiOperation(value = "批量禁用", notes = "批量禁用")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    @PutMapping(value = "/disableBatch")
    public RESTfulResult disableBatch(@RequestBody List<DynamicWorkUpdata> list) {
        if (ListUtils.isNotEmpty(list)) {
            for (DynamicWorkUpdata updata : list) {
                boolean flag = dynamicWorkUpdataService.disable(updata.getId());
                Assert.isTrue(flag, "操作失败");
            }
        }
        return success();
    }

    @ApiOperation(value = "批量删除", notes = "批量删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("dynamicworkupdata:delete")
    @PutMapping(value = "/deleteBatch")//String
    public RESTfulResult deleteBatch(@RequestBody List<DynamicWorkUpdata> list) {
        if (ListUtils.isNotEmpty(list)) {
            List<String> ids = list.stream().map(item -> item.getId()).collect(Collectors.toList());
            dynamicWorkUpdataService.delete(ids);
        }
        return success();
    }

    @ApiOperation(value = "重新生成数据", notes = "删除上传数据表中的数据，并修改采集数据表中的过期标识expire_flag为0，重新生成上传数据表的数据")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    @GetMapping(value = "/reGenerate/{id}")
    public RESTfulResult reGenerate(@PathVariable String id) {
        dynamicWorkUpdataService.reGenerate(id);
        return success(null, "操作成功");
    }

    @ApiOperation(value = "重新采集数据", notes = "删除上传数据表中的数据和采集数据表中的数据，重新采集数据")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    @GetMapping(value = "/reCollect/{id}")
    public RESTfulResult reCollect(@PathVariable String id) {
        dynamicWorkUpdataService.reCollect(id);
        return success(null, "操作成功");
    }

    @ApiOperation(value = "新焦炭计算", notes = "新焦炭计算")
    @PostMapping(value = "/calNewCoke")
    public RESTfulResult calNewCoke(@RequestBody CalNewCokeDto calNewCokeDto) throws IOException {
        try {
            dynamicWorkUpdataService.calNewCoke(calNewCokeDto);
//            Integer a = null;
//            int i = 1 / a;
            return success(null, "操作成功");
        } catch (Exception e) {
            return failed(null, "操作失败：" + e.getMessage());
        }
    }
}