package com.sw.mes.stocktaking;

import com.sw.mes.core.exception.BusinessException;
import com.sw.mes.core.response.ResponsePage;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.core.utils.*;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;

/**
 * @Author：wanjia
 * @Date：2024/3/15 09:17
 */
@RestController
@RequestMapping("/stocktaking")
@Api(description = "盘点接口")
@Slf4j
public class StocktakingController {


    @Autowired
    private StocktakingService stocktakingService;

    @ApiOperation(value = "分页查询籽晶信息列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<Stocktaking>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<Stocktaking> specification = DynamicSpecifications.bySearchFilter(request, Stocktaking.class);
        Page<Stocktaking> seedData = stocktakingService.findByExample(specification, PageUtil.createPageable(requestPage));
        buildNo(seedData.toList());
        ResponsePage<Stocktaking> responsePage = new ResponsePage<>(seedData.toList(), seedData.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "批量创建记录")
    @PostMapping("/create")
    public Result<Integer> create(@RequestBody @Valid @ApiParam(value = "盘账记录对象") List<Stocktaking> stocktakings
            , BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (CollectionUtils.isEmpty(stocktakings)) {
            return ResultGenerator.fail("请扫描后再提交");
        }
        try {
            return ResultGenerator.success(stocktakingService.insert(stocktakings));
        } catch (BusinessException e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }


    @ApiOperation(value = "查询对象")
    @GetMapping("/{sectionNo}")
    public Result<Stocktaking> queryBySectionNo(@RequestBody @Valid @ApiParam(value = "晶编") @PathVariable("sectionNo") String sectionNo) {
        if (StringUtils.isEmpty(sectionNo)) {
            return ResultGenerator.fail("请输入晶编号");
        }
        Stocktaking stocktaking = null;
        try {
            stocktaking = stocktakingService.queryStocktaking(sectionNo);
            if (null == stocktaking) {
                return ResultGenerator.fail("无法查询到相关信息，请核对传入的晶编号：" + sectionNo);
            }
        } catch (BusinessException e) {
            return ResultGenerator.fail(e.getMessage());
        }
        return ResultGenerator.success(stocktaking);
    }


    @ApiOperation(value = "导出")
    @GetMapping("/exportExcel")
    public void export(ServletRequest request, HttpServletResponse response, @ApiIgnore RequestPage requestPage) {
        try {
            Specification<Stocktaking> specification = DynamicSpecifications.bySearchFilter(request, Stocktaking.class);
            //requestPage.setPage(1);
            requestPage.setRows(20000);//最多导出2000行
            Page<Stocktaking> seedData = stocktakingService.findByExample(specification, PageUtil.createPageable(requestPage));
            List<Stocktaking> list = seedData.getContent();
            buildNo(list);
            ExcelUtil.exportExcel(list, "盘点记录", Stocktaking.class, response);
        } catch (Exception e) {
            log.error("export_error", e);
            throw new RuntimeException("导出盘点记录出错，错误信息：" + e.getMessage());
        }
    }


    private void buildNo(List<Stocktaking> list) {
        long tmp = 0;
        long no = 1;
        //根据时间分组进行编号排序
        for (Stocktaking stocktaking : list) {
            if (tmp != stocktaking.getGmtCreate().getTime()) {
                no = 1;
            }
            stocktaking.setNo(no);
            tmp = stocktaking.getGmtCreate().getTime();
            no++;
        }
    }

}
