郑永安
2023-06-19 f65443d8abeaedc9d102324565e8368e7c9d90c8
src/main/java/com/gk/firework/Controller/StockController.java
对比新文件
@@ -0,0 +1,904 @@
package com.gk.firework.Controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gk.firework.Controller.Base.BaseController;
import com.gk.firework.Domain.*;
import com.gk.firework.Domain.Enum.ErrorCode;
import com.gk.firework.Domain.Extension.StockTotal;
import com.gk.firework.Domain.Log.JsonParams;
import com.gk.firework.Domain.Utils.BeanUtils;
import com.gk.firework.Domain.Utils.Msg;
import com.gk.firework.Domain.Utils.PageInfo;
import com.gk.firework.Domain.Utils.StringUtils;
import com.gk.firework.Domain.Vo.*;
import com.gk.firework.Service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import static com.gk.firework.Domain.Enum.ErrorCode.*;
/**
 * @author : jingjy
 * @date : 2021/3/19 11:06
 */
@Api(tags = "库存接口")
@RestController
@RequestMapping("/stock")
public class StockController extends BaseController {
    @Autowired
    private ProductService productService;
    @Autowired
    private UserService userService;
    @Autowired
    private EntryService entryService;
    @Autowired
    private EntryDetailService entryDetailService;
    @Autowired
    private StockService stockService;
    @Autowired
    private ProductLocusService productLocusService;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private StaticStockService staticStockService;
    @PostMapping("/entrySingle")
    @JsonParams
    public Msg entrySingle(@RequestBody JSONObject jsonObject){
        Msg msg = new Msg(true);
        String userId = jsonObject.getString("id");
        String type = jsonObject.getString("type");
        String date = jsonObject.getString("time");
        String rfids = jsonObject.getString("rfids");
        String transport = jsonObject.getString("cert");
        UserInfo userInfo = userService.getById(userId);
        Date datetime;
        DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            datetime = dateFormat1.parse(date);
        } catch (ParseException e) {
            msg.setCode(ERROR_10003.getCode());
            msg.setMessage(ERROR_10003.getMsg()+":入库日期类型错误!");
            return msg;
        }
        String auth = getAuth();
        auth = StringUtils.isBlank(auth) ? "NOAUTH" : auth;
        EntryOrderInfo orderInfo = entryService.generateEntryOrderInfo(type,userInfo,datetime,transport, auth);
        if (StringUtils.isBlank(userId) || StringUtils.isBlank(rfids)){
            msg.setCode(ERROR_10001.getCode());
            msg.setMessage(ERROR_10001.getMsg()+":用户信息或者流向码为空,无法入库");
            return msg;
        }
        if (EntryUtils.RK_ENTRY.equals(type)){
            //一般入库
            List<String>directionCodes = StringUtils.toList(rfids);
            List<ProductVo> productVos = new ArrayList<>();
            List<EntryDetailInfo>detailInfos = new ArrayList<>();
            List<ProductLocusInfo>locusInfos = new ArrayList<>();
            //入库数量
            int entryNum = 0;
            for (String dire:directionCodes) {
                if (FireworkDeal.isNotDirectionCode(dire)){
                    msg.setCode(ERROR_10004.getCode());
                    msg.setMessage(ERROR_10004.getMsg()+":流向码:"+dire+" 不符合规则,无法识别!");
                    return msg;
                }
                DirectionDetail detail = FireworkDeal.dealDirectionCode(dire);
                if (productService.hasProductByDire(dire)){
                    msg.setCode(ERROR_50001.getMsg());
                    msg.setMessage(ERROR_50001.getMsg()+":流向码:"+dire+" 未找到相应产品信息!");
                    return msg;
                }
                ProductVo productVo = productService.selectVoByDirection(dire);
                EntryDetailInfo detailInfo = new EntryDetailInfo(orderInfo.getCode(),dire,productVo.getItemCode(),
                        productVo.getName(),productVo.getManufacturer(),new Date(),userInfo.getCompanynumber());
                if (detail.getLength() == FireworkDeal.DIRECTION_OUTSIDE){
                    ProductLocusInfo productLocusInfo = new ProductLocusInfo(dire,new Date(),datetime, userInfo.getCompany(),
                            null,ProductLocusInfo.ENTRY_STATUS,productVo.getBoxNumber().toString());
                    locusInfos.add(productLocusInfo);
                }
                detailInfos.add(detailInfo);
                if (detail.getBoxNo() == null){
                    entryNum += 1;
                }else {
                    entryNum += Integer.parseInt(detail.getBoxNo());
                }
                if (detail.getLength() == FireworkDeal.DIRECTION_OUTSIDE){
                    FireworkDeal.getProductVos(dire, detail, detail, productVos, productVo);
                }else if (detail.getLength() == FireworkDeal.DIRECTION_INSIDE){
                    ProductInfo productVo1 = productService.selectByDirection(dire);
                    productVo1.setDirectionCode(dire);
                    ProductVo productVo2 = BeanUtils.copy(productVo1,ProductVo.class);
                    FireworkDeal.setProductVosAttribute(productVo2);
                    productVos.add(productVo2);
                }
            }
            boolean flag = stockService.putInStorage(userInfo,productVos,datetime, type);
            if (flag){
                orderInfo.setNum(entryNum);
                entryService.save(orderInfo);
                entryDetailService.saveBatch(detailInfos);
                productLocusService.insertBatch(locusInfos);
            }else {
                msg.setCode(ERROR_40001.getCode());
                msg.setMessage(ERROR_40001.getMsg()+"库存入库失败");
                return msg;
            }
        }
        return msg;
    }
    @PostMapping("/entryBatch")
    @JsonParams
    public List<Msg> entryBatch(@RequestBody JSONArray jsonArray){
        List<Msg> msgList = new ArrayList<>();
        if (jsonArray.size() < 1){
            return null;
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            msgList.add(entrySingle(jsonObject));
        }
        return msgList;
    }
    @ApiOperation(value = "通用入库",response = Msg.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "JSONArray",value = "json数组,json对象为:{id:'用户ID',rfids:'流向码',time:'入库时间',cert:'运输证',type:'入库类型'}"),
    })
    @PostMapping("/entry")
    @JsonParams
    public Msg entryStock(@RequestBody JSONArray jsonArray){
        if (jsonArray.size() > 0)
        {
            for (int i = 0; i < jsonArray.size(); i++) {
                // 遍历 jsonArray 数组,把每一个对象转成 json 对象
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String userId = jsonObject.getString("id");
                String directionCodeStr = jsonObject.getString("rfids");
                String datetime = jsonObject.getString("time");
                String transport = jsonObject.getString("cert");
                Date date;
                DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    date = dateFormat.parse(datetime);
                } catch (ParseException e) {
                    return new Msg(ERROR_10003,"入库日期类型错误!");
                }
                //type 1.常规入库; 2.退货入库
                String type = jsonObject.getString("type");
                if (StringUtils.isBlank(type)){
                    return new Msg(ERROR_10001,"入库类型不能为空");
                }
                if (StringUtils.isBlank(directionCodeStr)){
                    return new Msg(ERROR_10001,"流向码不能为空");
                }
                boolean isUser = userService.checkUserById(userId);
                if (!isUser){
                    return new Msg(ERROR_50001,"未找到相关用户信息,不能入库!");
                }
                UserInfo userInfo = userService.getById(userId);
                //判断是否存在同时间同操作人入库记录
                boolean exist = entryService.isEntryExist(datetime,userInfo);
                if (exist){ continue; }
                String auth = getAuth();
                auth = StringUtils.isBlank(auth) ? "NOAUTH" : auth;
                List<String> directionCodes = StringUtils.toList(directionCodeStr);
                EntryOrderInfo orderInfo = entryService.generateEntryOrderInfo(type,userInfo,date,transport, auth);
                int boxNum = 0;
                List<EntryDetailInfo>detailInfos = new ArrayList<>();
                List<ProductLocusInfo>locusInfos = new ArrayList<>();
                List<ProductVo> productVos = new ArrayList<>();
                for (String dire:directionCodes) {
                    if (FireworkDeal.isNotDirectionCode(dire)){
                        return new Msg(ERROR_10004,"流向码:"+dire+" 不符合规则,无法识别!");
                    }
                    DirectionDetail detail = FireworkDeal.dealDirectionCode(dire);
                    if (productService.hasProductByDire(dire)){
                        return new Msg(ERROR_50001,":流向码:"+dire+" 未找到相应产品信息!");
                    }
                    ProductVo productVo = productService.selectVoByDirection(dire);
                    EntryDetailInfo detailInfo = new EntryDetailInfo(orderInfo.getCode(),dire,productVo.getItemCode(),
                            productVo.getName(),productVo.getManufacturer(),new Date(),userInfo.getCompanynumber());
                    if (detail.getLength() == FireworkDeal.DIRECTION_OUTSIDE){
                        ProductLocusInfo productLocusInfo = new ProductLocusInfo(dire,new Date(),date, userInfo.getCompany(),
                                null,ProductLocusInfo.ENTRY_STATUS,productVo.getBoxNumber().toString());
                        locusInfos.add(productLocusInfo);
                    }
                    if (detail.getLength() == FireworkDeal.DIRECTION_OUTSIDE){
                        FireworkDeal.getProductVos(dire, detail, detail, productVos, productVo);
                        detailInfo.setBoxcode(detail.getOriginalCode());
                        detailInfo.setNum(Integer.parseInt(detail.getBoxNo()));
                        boxNum += Integer.parseInt(detail.getBoxNo());
                    }else if (detail.getLength() == FireworkDeal.DIRECTION_INSIDE){
                        ProductInfo productVo1 = productService.selectByDirection(dire);
                        ProductVo productVo2 = BeanUtils.copy(productVo1,ProductVo.class);
                        productVo2.setItemCode(dire.substring(0,10));
                        productVo2.setDirectionCode(dire);
                        productVos.add(productVo2);
                        detailInfo.setNum(1);
                        boxNum +=1;
                    }
                    detailInfos.add(detailInfo);
                }
                orderInfo.setNum(boxNum);
                entryService.save(orderInfo);
                entryDetailService.saveBatch(detailInfos);
                productLocusService.insertBatch(locusInfos);
                boolean flag = stockService.putInStorage(userInfo,productVos,date,type);
            }
        }
        return success();
    }
    /**
     *
     * @param jsonArray [{"id":"用户ID","type":"快速入库填1","time":"时间","cert":"运输证编号","rfidfirst":"第一箱的流向码","rfidlast":"最后一箱的流向码"}]
     * @return msg
     */
    @ApiOperation(value = "快速入库",response = Msg.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "JSONArray",value = "json数组,json对象为:{\"id\":\"用户ID\",\"type\":\"快速入库填1\",\"time\":\"时间\",\"cert\":\"运输证编号\",\"rfidfirst\":\"第一箱的流向码\",\"rfidlast\":\"最后一箱的流向码\"}"),
    })
    @PostMapping("/entryQuick")
    @JsonParams
    public Msg entryQuick(@RequestBody JSONArray jsonArray){
        Msg msg = new Msg(true);
        if (jsonArray.size() > 0)
        {
            for (int i = 0; i < jsonArray.size(); i++) {
                // 遍历 jsonArray 数组,把每一个对象转成 json 对象
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String userId = jsonObject.getString("id");
                String directionCodeFirst = jsonObject.getString("rfidfirst");
                String directionCodeLast = jsonObject.getString("rfidlast");
                String datetime = jsonObject.getString("time");
                String transport = jsonObject.getString("cert");
                //type 1.常规入库; 2.退货入库
                String type = "1";
                Date date;
                DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    date = dateFormat.parse(datetime);
                } catch (ParseException e) {
                    msg.setCode(ERROR_10003.getCode());
                    msg.setMessage(ERROR_10003.getMsg()+":入库日期类型错误!");
                    return msg;
                }
                if (!(FireworkDeal.is22Characters(directionCodeFirst) && FireworkDeal.is22Characters(directionCodeLast))){
                    msg.setCode(ERROR_10004.getCode());
                    msg.setMessage(ERROR_10004.getMsg()+":流向码首尾不符合规则,无法快速入库!");
                    return msg;
                }
                boolean isUser = userService.checkUserById(userId);
                if (!isUser){
                    msg.setCode(ERROR_50001.getCode());
                    msg.setMessage(ERROR_50001.getMsg()+":未找到相关用户信息,不能入库!");
                    return msg;
                }
                UserInfo userInfo = userService.getById(userId);
                //判断是否存在同时间同操作人入库记录
                boolean exist = entryService.isEntryExist(datetime,userInfo);
                if (exist){
                    continue;
                }
                String auth = getAuth();
                auth = StringUtils.isBlank(auth) ? "NOAUTH" : auth;
                EntryOrderInfo orderInfo = entryService.generateEntryOrderInfo(type,userInfo,date,transport, auth);
                List<EntryDetailInfo>detailInfos = new ArrayList<>();
                List<ProductLocusInfo>locusInfos = new ArrayList<>();
                List<ProductVo> productVos = new ArrayList<>();
                DirectionDetail detailFirst = FireworkDeal.dealDirectionCode(directionCodeFirst);
                DirectionDetail detailLast = FireworkDeal.dealDirectionCode(directionCodeLast);
                if (!detailFirst.getItemCode().equals(detailLast.getItemCode())){
                    msg.setCode(ERROR_10004.getCode());
                    msg.setMessage(ERROR_10004.getMsg()+":首尾商品编码不一致,无法快速入库");
                    return msg;
                }
                if (Integer.parseInt(detailFirst.getSerialNo()) > Integer.parseInt(detailLast.getSerialNo())){
                    msg.setCode(ERROR_10004.getCode());
                    msg.setMessage(ERROR_10004.getMsg()+":首位商品序号大于末位,无法快速入库");
                    return msg;
                }
                ProductVo productVo = productService.selectVoByDirection(directionCodeFirst);
                Integer firstNo = Integer.parseInt(detailFirst.getSerialNo());
                Integer lastNo = Integer.parseInt(detailLast.getSerialNo());
                int perBoxNum = Integer.parseInt(detailFirst.getBoxNo());
                int boxNum = ((lastNo-firstNo)/perBoxNum)+1;
                int totalNum = 0;
                for (int j=1;j<= boxNum;j++){
                    String dire = detailFirst.getItemCode()+detailFirst.getDateCode()+ String.format("%05d", firstNo)+String.format("%03d", perBoxNum);
                    EntryDetailInfo detailInfo = new EntryDetailInfo(orderInfo.getCode(),dire,productVo.getItemCode(),
                            productVo.getName(),productVo.getManufacturer(),new Date(),userInfo.getCompanynumber());
                    detailInfo.setNum(perBoxNum);
                    detailInfos.add(detailInfo);
                    ProductLocusInfo productLocusInfo = new ProductLocusInfo(dire,new Date(),date, userInfo.getCompany(),
                            null,ProductLocusInfo.ENTRY_STATUS,productVo.getBoxNumber().toString());
                    locusInfos.add(productLocusInfo);
                    firstNo+=perBoxNum;
                    totalNum += perBoxNum;
                }
                FireworkDeal.getProductVos(directionCodeFirst,detailFirst,detailLast,productVos,productVo);
                orderInfo.setNum(totalNum);
                entryService.save(orderInfo);
                entryDetailService.saveBatch(detailInfos);
                productLocusService.insertBatch(locusInfos);
                boolean flag = stockService.putInStorage(userInfo,productVos,date, type);
            }
        }
        return msg;
    }
    @GetMapping("/info")
    public Msg getList(@RequestParam(value = "name", required = false) String name,
                       @RequestParam(value = "directionCode", required = false) String directionCode,
                       @RequestParam(value = "manufacturer", required = false) String manufacturer,
                       @RequestParam(value = "type", required = false) String type,
                       @RequestParam(value = "secondaryType", required = false) String secondaryType,
                       @RequestParam(value = "beginDate") String beginDate,
                       @RequestParam(value = "endDate") String endDate,
                       @RequestParam(value = "owner")String owner,
                       @RequestParam(defaultValue = "0") Integer pageIndex,
                       @RequestParam(defaultValue = "10") Integer pageSize,
                       String sort, String order){
        Msg msg = new Msg(true);
        PageInfo pageInfo = new PageInfo(pageIndex, pageSize,sort,order);
        Map<String, Object> condition = new HashMap<>(8);
        if (StringUtils.isNotBlank(name)) {
            condition.put("name", name);
        }
        if (StringUtils.isNotBlank(directionCode)) {
            condition.put("directionCode", directionCode);
        }
        if (StringUtils.isNotBlank(manufacturer)) {
            condition.put("manufacturer", manufacturer);
        }
        if (StringUtils.isNotBlank(type)) {
            condition.put("type", type);
        }
        if (StringUtils.isNotBlank(secondaryType)) {
            condition.put("secondaryType", secondaryType);
        }
//        if (getUser().getCompanyid() != null){
//            owner = getUser().getCompanyid().toString();
//        }
        condition.put("owner",owner);
        condition.put("beginDate",beginDate);
        condition.put("endDate",endDate);
        pageInfo.setCondition(condition);
        stockService.selectDataGrid(pageInfo);
        msg.setResult(pageInfo);
        return msg;
    }
    @GetMapping("/info-app")
    public Msg getList2() {
        PageInfo pageInfo = new PageInfo();
        Map<String, Object> condition = new HashMap<>();
        UserInfo user = getUser();
        UserInfo userInfo = userService.getById(user);
        condition.put("owner",userInfo.getCompanyid());
        pageInfo.setCondition(condition);
        PageInfoExtension<StockTotal> extension = stockService.selectDataGridExtensions(pageInfo);
        return success(extension);
    }
    @GetMapping("/enterpriseStock")
    public Msg getEnterpriseStockList(@RequestParam(value = "name", required = false) String name,
                                      @RequestParam(value = "province", required = false) String province,
                                      @RequestParam(value = "city", required = false) String city,
                                      @RequestParam(value = "area", required = false) String area,
                                      @RequestParam(value = "town", required = false) String town,
                                      @RequestParam(value = "community", required = false) String community,
                                      @RequestParam(value = "enterpriseType", required = false) String type,
                                      @RequestParam(defaultValue = "0") Integer pageIndex,
                                      @RequestParam(defaultValue = "10") Integer pageSize,
                                      String sort, String order){
        Msg msg = new Msg(true);
        PageInfo pageInfo = new PageInfo(pageIndex, pageSize,sort,order);
        Map<String, Object> condition = new HashMap<>(16);
        if (StringUtils.isNotBlank(name)) {
            condition.put("name", name);
        }
        if (StringUtils.isNotBlank(type)) {
            condition.put("type", type);
        }
        if (StringUtils.isNotBlank(province)) {
            condition.put("province", province);
        }
        if (StringUtils.isNotBlank(city)) {
            condition.put("city", city);
        }
        if (StringUtils.isNotBlank(area)) {
            condition.put("district", area);
        }
        if (StringUtils.isNotBlank(town)) {
            condition.put("town", town);
        }
        if (StringUtils.isNotBlank(community)) {
            condition.put("community", community);
        }
        UserInfo userInfo = userService.getById(getUser().getId());
        assert userInfo != null;
        if (userInfo.getCompanynumber() != null){
            condition.put("operator",userInfo.getCompanynumber());
            List<Enterprise> subs = enterpriseService.selectSubEnterprise(userInfo.getCompanyid());
            List<String> subList = subs.stream().map(Enterprise::getEnterprisenumber).collect(Collectors.toList());
            if (subList.size() > 0)
                condition.put("subList", subList);
        }
        //根据用户省市区权限添加/修改查询条件
        if (userInfo.getCompanyid() == null && userInfo.getType() == 3){
            boolean provinceNull = StringUtils.isBlank(userInfo.getProvince());
            boolean cityNull = !provinceNull && StringUtils.isBlank(userInfo.getCity()) ;
            boolean districtNull = !provinceNull && StringUtils.isNotBlank(userInfo.getCity())
                    && StringUtils.isBlank(userInfo.getArea());
            boolean streetNull = !provinceNull && StringUtils.isNotBlank(userInfo.getCity())
                    && StringUtils.isNotBlank(userInfo.getArea()) && StringUtils.isBlank(userInfo.getTown());
            boolean committeeNull = !provinceNull && StringUtils.isNotBlank(userInfo.getCity())
                    && StringUtils.isNotBlank(userInfo.getArea()) && StringUtils.isNotBlank(userInfo.getTown())
                    && StringUtils.isBlank(userInfo.getCommunity());
            if (cityNull){
                condition.put("province", userInfo.getProvince());
            }else if (districtNull){
                condition.put("province", userInfo.getProvince());
                condition.put("city", userInfo.getCity());
            }else if (streetNull){
                condition.put("province", userInfo.getProvince());
                condition.put("city", userInfo.getCity());
                condition.put("district", userInfo.getArea());
            }else if (committeeNull){
                condition.put("province", userInfo.getProvince());
                condition.put("city", userInfo.getCity());
                condition.put("district", userInfo.getArea());
                condition.put("street", userInfo.getTown());
            }else {
                condition.put("province", userInfo.getProvince());
                condition.put("city", userInfo.getCity());
                condition.put("district", userInfo.getArea());
                condition.put("street", userInfo.getTown());
                condition.put("committee", userInfo.getCommunity());
            }
        }
        pageInfo.setCondition(condition);
        condition.put("index",(pageIndex-1)*pageSize);
        condition.put("size",pageSize);
//        stockService.selectEnterpriseStockDataGrid(pageInfo);
//        Integer count = enterpriseService.getEnterpriseByLimitCount(condition);
//        limit #{condition.index},#{condition.size}
        List<StockVo>stockVos = stockService.selectEnterpriseStocks(condition);
        int index = (pageIndex-1)*pageSize;
        int count = stockVos.size();
        int size = index+pageSize;
        if (size > count){
            size = count;
        }
        //总计
        BigDecimal stockNum = new BigDecimal("0");
        BigDecimal firecracker = new BigDecimal("0");
        BigDecimal spray = new BigDecimal("0");
        BigDecimal rotation = new BigDecimal("0");
        BigDecimal bead = new BigDecimal("0");
        BigDecimal toy = new BigDecimal("0");
        BigDecimal combined = new BigDecimal("0");
        if (stockVos.size() > 0) {
            for (StockVo stockVo : stockVos) {
                stockNum = stockNum.add(stockVo.getStockNum());
                firecracker = firecracker.add(stockVo.getFirecracker());
                spray = spray.add(stockVo.getSpray());
                rotation = rotation.add(stockVo.getRotation());
                bead = bead.add(stockVo.getBead());
                toy = toy.add(stockVo.getToy());
                combined = combined.add(stockVo.getCombined());
            }
        }
        Map<String, Object> totalRow = new HashMap<>();
        totalRow.put("name", "总计");
        totalRow.put("stockNum", stockNum);
        totalRow.put("firecracker", firecracker);
        totalRow.put("spray", spray);
        totalRow.put("rotation", rotation);
        totalRow.put("bead", bead);
        totalRow.put("toy", toy);
        totalRow.put("combined", combined);
        pageInfo.setResult(stockVos.subList(index,size));
        pageInfo.setTotalCount((long) count);
        PageInfoExtension<Map> extension = new PageInfoExtension<>(pageInfo);
        extension.setExtension(totalRow);
        msg.setResult(extension);
        return msg;
    }
    @GetMapping("/enterpriseStaticStock")
    public Msg enterpriseStaticStock(@RequestParam(value = "name", required = false) String name,
                                      @RequestParam(value = "province", required = false) String province,
                                      @RequestParam(value = "city", required = false) String city,
                                      @RequestParam(value = "area", required = false) String area,
                                      @RequestParam(value = "town", required = false) String town,
                                      @RequestParam(value = "community", required = false) String community,
                                      @RequestParam(value = "enterpriseType", required = false) String type,
                                      @RequestParam(defaultValue = "0") Integer pageIndex,
                                      @RequestParam(defaultValue = "10") Integer pageSize,
                                      String sort, String order){
        Msg msg = new Msg(true);
        PageInfo pageInfo = new PageInfo(pageIndex, pageSize,sort,order);
        Map<String, Object> condition = new HashMap<>(16);
        if (StringUtils.isNotBlank(name)) {
            condition.put("name", name);
        }
        if (StringUtils.isNotBlank(type)) {
            condition.put("type", type);
        }
        if (StringUtils.isNotBlank(province)) {
            condition.put("province", province);
        }
        if (StringUtils.isNotBlank(city)) {
            condition.put("city", city);
        }
        if (StringUtils.isNotBlank(area)) {
            condition.put("district", area);
        }
        if (StringUtils.isNotBlank(town)) {
            condition.put("town", town);
        }
        if (StringUtils.isNotBlank(community)) {
            condition.put("community", community);
        }
        UserInfo userInfo = userService.getById(getUser().getId());
        assert userInfo != null;
        if (userInfo.getCompanynumber() != null){
            condition.put("operator",userInfo.getCompanynumber());
            List<Enterprise> subs = enterpriseService.selectSubEnterprise(userInfo.getCompanyid());
            List<String> subList = subs.stream().map(Enterprise::getEnterprisenumber).collect(Collectors.toList());
            if (subList.size() > 0)
                condition.put("subList", subList);
        }
        //根据用户省市区权限添加/修改查询条件
        if (userInfo.getCompanyid() == null && userInfo.getType() == 3){
            boolean provinceNull = StringUtils.isBlank(userInfo.getProvince());
            boolean cityNull = !provinceNull && StringUtils.isBlank(userInfo.getCity()) ;
            boolean districtNull = !provinceNull && StringUtils.isNotBlank(userInfo.getCity())
                    && StringUtils.isBlank(userInfo.getArea());
            boolean streetNull = !provinceNull && StringUtils.isNotBlank(userInfo.getCity())
                    && StringUtils.isNotBlank(userInfo.getArea()) && StringUtils.isBlank(userInfo.getTown());
            boolean committeeNull = !provinceNull && StringUtils.isNotBlank(userInfo.getCity())
                    && StringUtils.isNotBlank(userInfo.getArea()) && StringUtils.isNotBlank(userInfo.getTown())
                    && StringUtils.isBlank(userInfo.getCommunity());
            if (cityNull){
                condition.put("province", userInfo.getProvince());
            }else if (districtNull){
                condition.put("province", userInfo.getProvince());
                condition.put("city", userInfo.getCity());
            }else if (streetNull){
                condition.put("province", userInfo.getProvince());
                condition.put("city", userInfo.getCity());
                condition.put("district", userInfo.getArea());
            }else if (committeeNull){
                condition.put("province", userInfo.getProvince());
                condition.put("city", userInfo.getCity());
                condition.put("district", userInfo.getArea());
                condition.put("street", userInfo.getTown());
            }else {
                condition.put("province", userInfo.getProvince());
                condition.put("city", userInfo.getCity());
                condition.put("district", userInfo.getArea());
                condition.put("street", userInfo.getTown());
                condition.put("committee", userInfo.getCommunity());
            }
        }
        pageInfo.setCondition(condition);
        condition.put("index",(pageIndex-1)*pageSize);
        condition.put("size",pageSize);
        List<StaticStock>stocks = staticStockService.selectStaticStocks(condition);
        int index = (pageIndex-1)*pageSize;
        int count = stocks.size();
        int size = index+pageSize;
        if (size > count){
            size = count;
        }
        //总计
        BigDecimal stockNum = new BigDecimal("0");
        BigDecimal firecracker = new BigDecimal("0");
        BigDecimal spray = new BigDecimal("0");
        BigDecimal rotation = new BigDecimal("0");
        BigDecimal bead = new BigDecimal("0");
        BigDecimal toy = new BigDecimal("0");
        BigDecimal combined = new BigDecimal("0");
        if (stocks.size() > 0) {
            for (StaticStock stock : stocks) {
                stockNum = stockNum.add(stock.getStockNum());
                firecracker = firecracker.add(stock.getFirecracker());
                spray = spray.add(stock.getSpray());
                rotation = rotation.add(stock.getRotation());
                bead = bead.add(stock.getBead());
                toy = toy.add(stock.getToy());
                combined = combined.add(stock.getCombined());
            }
        }
        Map<String, Object> totalRow = new HashMap<>();
        totalRow.put("name", "总计");
        totalRow.put("stockNum", stockNum);
        totalRow.put("firecracker", firecracker);
        totalRow.put("spray", spray);
        totalRow.put("rotation", rotation);
        totalRow.put("bead", bead);
        totalRow.put("toy", toy);
        totalRow.put("combined", combined);
        pageInfo.setResult(stocks.subList(index,size));
        pageInfo.setTotalCount((long) count);
        PageInfoExtension<Map> extension = new PageInfoExtension<>(pageInfo);
        extension.setExtension(totalRow);
        msg.setResult(extension);
        return msg;
    }
    @GetMapping("/detail")
    public Msg getStockDetailByItemCode(
                                      @RequestParam(value = "itemCode") String itemCode,
                                      @RequestParam(value = "enterpriseNumber") String enterpriseNumber,
                                      @RequestParam(value = "directionCode",required = false) String directionCode,
                                      @RequestParam(defaultValue = "0") Integer pageIndex,
                                      @RequestParam(defaultValue = "10") Integer pageSize,
                                      String sort, String order){
        Msg msg = new Msg(true);
        PageInfo pageInfo = new PageInfo(pageIndex, pageSize,sort,order);
        Map<String, Object> condition = new HashMap<>(16);
        condition.put("itemCode", itemCode);
        Enterprise enterprise = enterpriseService.selectEnterpriseByNumber(enterpriseNumber);
        if (enterprise == null){
            return new Msg(ERROR_50001);
        }
        condition.put("owner", enterprise.getId());
        if (StringUtils.isNotBlank(directionCode)) {
            condition.put("directionCode", directionCode);
        }
        pageInfo.setCondition(condition);
        stockService.selectStockDetailByItemCode(pageInfo);
        msg.setResult(pageInfo);
        return msg;
    }
    @GetMapping("/enterpriseSale")
    public Msg getEnterpriseSaleList(@RequestParam(value = "name", required = false) String name,
                                      @RequestParam(value = "beginDate") String beginDate,
                                      @RequestParam(value = "endDate") String endDate,
                                      @RequestParam(value = "province", required = false) String province,
                                      @RequestParam(value = "city", required = false) String city,
                                      @RequestParam(value = "area", required = false) String area,
                                      @RequestParam(value = "town", required = false) String town,
                                      @RequestParam(value = "community", required = false) String community,
                                      @RequestParam(value = "enterpriseType", required = false) String type,
                                      @RequestParam(defaultValue = "0") Integer pageIndex,
                                      @RequestParam(defaultValue = "10") Integer pageSize,
                                      String sort, String order){
        Msg msg = new Msg(true);
        PageInfo pageInfo = new PageInfo(pageIndex, pageSize,sort,order);
        Map<String, Object> condition = new HashMap<>(16);
        if (StringUtils.isNotBlank(name)) {
            condition.put("name", name);
        }
        if (StringUtils.isNotBlank(beginDate)) {
            condition.put("beginDate", beginDate);
        }
        if (StringUtils.isNotBlank(endDate)) {
            condition.put("endDate", endDate);
        }
        if (StringUtils.isNotBlank(type)) {
            condition.put("type", type);
        }
        if (StringUtils.isNotBlank(province)) {
            condition.put("province", province);
        }
        if (StringUtils.isNotBlank(city)) {
            condition.put("city", city);
        }
        if (StringUtils.isNotBlank(area)) {
            condition.put("district", area);
        }
        if (StringUtils.isNotBlank(town)) {
            condition.put("town", town);
        }
        if (StringUtils.isNotBlank(community)) {
            condition.put("community", community);
        }
        UserInfo userInfo = userService.getById(getUser().getId());
        assert userInfo != null;
        if (userInfo.getCompanynumber() != null){
            condition.put("operator",userInfo.getCompanynumber());
            List<Enterprise> subs = enterpriseService.selectSubEnterprise(userInfo.getCompanyid());
            List<String> subList = subs.stream().map(Enterprise::getEnterprisenumber).collect(Collectors.toList());
            if (subList.size() > 0)
                condition.put("subList", subList);
        }
        //根据用户省市区权限添加/修改查询条件
        if (userInfo.getCompanyid() == null && userInfo.getType() == 3){
            boolean provinceNull = StringUtils.isBlank(userInfo.getProvince());
            boolean cityNull = !provinceNull && StringUtils.isBlank(userInfo.getCity()) ;
            boolean districtNull = !provinceNull && StringUtils.isNotBlank(userInfo.getCity())
                    && StringUtils.isBlank(userInfo.getArea());
            boolean streetNull = !provinceNull && StringUtils.isNotBlank(userInfo.getCity())
                    && StringUtils.isNotBlank(userInfo.getArea()) && StringUtils.isBlank(userInfo.getTown());
            boolean committeeNull = !provinceNull && StringUtils.isNotBlank(userInfo.getCity())
                    && StringUtils.isNotBlank(userInfo.getArea()) && StringUtils.isNotBlank(userInfo.getTown())
                    && StringUtils.isBlank(userInfo.getCommunity());
            if (cityNull){
                condition.put("province", userInfo.getProvince());
            }else if (districtNull){
                condition.put("province", userInfo.getProvince());
                condition.put("city", userInfo.getCity());
            }else if (streetNull){
                condition.put("province", userInfo.getProvince());
                condition.put("city", userInfo.getCity());
                condition.put("district", userInfo.getArea());
            }else if (committeeNull){
                condition.put("province", userInfo.getProvince());
                condition.put("city", userInfo.getCity());
                condition.put("district", userInfo.getArea());
                condition.put("street", userInfo.getTown());
            }else {
                condition.put("province", userInfo.getProvince());
                condition.put("city", userInfo.getCity());
                condition.put("district", userInfo.getArea());
                condition.put("street", userInfo.getTown());
                condition.put("committee", userInfo.getCommunity());
            }
        }
        pageInfo.setCondition(condition);
        PageInfoExtension<Map> extension = stockService.selectEnterpriseSaleDataGrid(pageInfo);
        msg.setResult(extension);
        return msg;
    }
    @GetMapping("/saleInfo")
    public Msg getSaleInfo(@RequestParam(value = "name", required = false) String name,
                           @RequestParam(value = "directionCode", required = false) String directionCode,
                           @RequestParam(value = "manufacturer", required = false) String manufacturer,
                           @RequestParam(value = "type", required = false) String type,
                           @RequestParam(value = "enterpriseNumber", required = false) String companyNumber,
                           @RequestParam(value = "beginDate") String beginDate,
                           @RequestParam(value = "endDate") String endDate,
                           @RequestParam(defaultValue = "0") Integer pageIndex,
                           @RequestParam(defaultValue = "10") Integer pageSize,
                           String sort, String order){
        Msg msg = new Msg(true);
        PageInfo pageInfo = new PageInfo(pageIndex, pageSize,sort,order);
        Map<String, Object> condition = new HashMap<>(8);
        if (StringUtils.isNotBlank(name)) {
            condition.put("name", name);
        }
        if (StringUtils.isNotBlank(directionCode)) {
            condition.put("directionCode", directionCode);
        }
        if (StringUtils.isNotBlank(manufacturer)) {
            condition.put("manufacturer", manufacturer);
        }
        if (StringUtils.isNotBlank(type)) {
            condition.put("type", type);
        }
        if (StringUtils.isNotBlank(companyNumber)) {
            condition.put("companyNumber", companyNumber);
        }
        condition.put("beginDate",beginDate);
        condition.put("endDate",endDate);
        pageInfo.setCondition(condition);
        stockService.selectSaleDetailDataGrid(pageInfo);
        msg.setResult(pageInfo);
        return msg;
    }
    @PostMapping("/refreshStock")
    public Msg refreshStock(){
        Msg msg = new Msg(true);
        stockService.saveOrUpdateCurrentStock(getUser().getUsername());
        return msg;
    }
    @PostMapping("/clearStock")
    public Msg clearStock(@RequestBody JSONObject object){
        String owners = object.getString("owners");
        UserInfo userInfo = userService.getById(getUser().getId());
        if (userInfo.getType() != 1){
            return new Msg(ERROR_70001);
        }
        if (StringUtils.isBlank(owners)){
            return new Msg(ERROR_10001);
        }
        List<String> list = StringUtils.toList(owners);
        for (String owner : list){
            Enterprise enterprise = enterpriseService.getById(owner);
            if (enterprise == null){
                return new Msg(ERROR_50001);
            }
            boolean flag = stockService.clearStock(enterprise);
        }
        return success();
    }
    @PostMapping("/clearStockByItem")
    public Msg clearStockByItem(@RequestBody JSONObject object){
        String owner = object.getString("owner");
        String directionCodes = object.getString("directionCodes");
        UserInfo userInfo = userService.getById(getUser().getId());
        if (userInfo.getType() != 1){
            return new Msg(ERROR_70001);
        }
        if (StringUtils.isBlank(owner) || StringUtils.isBlank(directionCodes)){
            return new Msg(ERROR_10001);
        }
        List<String> list = StringUtils.toList(directionCodes);
        Enterprise enterprise = enterpriseService.getById(owner);
        if (enterprise == null){
            return new Msg(ERROR_50001);
        }
        boolean flag = stockService.clearStockByItems(enterprise,list);
        return success();
    }
}