郑永安
2023-06-19 59e91a4e9ddaf23cebb12993c774aa899ab22d16
src/main/java/com/gk/firework/Controller/SaleOrderController.java
对比新文件
@@ -0,0 +1,1016 @@
package com.gk.firework.Controller;
import com.alibaba.fastjson.JSON;
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.BO.DirectionProductBO;
import com.gk.firework.Domain.BO.SaleOrderDetailInfoBO;
import com.gk.firework.Domain.DO.ProductDO;
import com.gk.firework.Domain.Exception.BusinessException;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gk.firework.Domain.Log.JsonParams;
import com.gk.firework.Domain.SaleOrderDetailInfo;
import com.gk.firework.Domain.Utils.*;
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.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
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/31 8:53
 */
@Api(tags = "订单信息")
@RequestMapping("/order")
@RestController
public class SaleOrderController extends BaseController {
    @Value("${productPath}")
    private String productPath; //配置文件配置的物理保存地址
    @Autowired
    private CustomerService customerService;
    @Autowired
    private UserService userService;
    @Autowired
    private SaleOrderService saleOrderService;
    @Autowired
    private SaleOrderDetailService saleOrderDetailService;
    @Autowired
    private ProductService productService;
    @Autowired
    private ProductPriceService productPriceService;
    @Autowired
    private StockService stockService;
    @Autowired
    private EntryService entryService;
    @Autowired
    private EntryDetailService entryDetailService;
    @Autowired
    private SoldNoStockService soldNoStockService;
    @Autowired
    private ExcelExportService excelExportService;
    @PostMapping("/create")
    @JsonParams
    public Msg createOrder(@RequestParam String encryptStr) {
        String jsonStr = new String(Base64.getDecoder().decode(encryptStr.replaceAll(" +","+")),
                StandardCharsets.UTF_8);
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        Msg msg = new Msg(true);
        JSONObject customer = jsonObject.getJSONObject("customer");
        JSONObject order = jsonObject.getJSONObject("order");
        JSONArray detailObject = jsonObject.getJSONArray("detailInfos");
        String userId = jsonObject.getString("operator");
        Integer num = order.getInteger("boxNum");
        String total = order.getString("total");
        String pay = order.getString("pay");
        String change = order.getString("change");
        String type = jsonObject.getString("type");
        Date salesTime = new Date();
        if (customer == null || detailObject == null || detailObject.isEmpty()) {
            msg.setCode(ERROR_10001.getCode());
            msg.setMessage(ERROR_10001.getMsg());
            return msg;
        }
        if (userId == null) {
            msg.setCode(ERROR_10004.getCode());
            msg.setMessage(ERROR_10004.getMsg()+":用户信息错误");
            return msg;
        }
        UserInfo userInfo = userService.getById(userId);
        if (userInfo == null) {
            msg.setCode(ERROR_10004.getCode());
            msg.setMessage(ERROR_10004.getMsg()+":用户信息错误");
            return msg;
        }
        // 优化1 单独校验数据
//        List<String> directionCodes = new ArrayList<>(detailObject.size());
        Set<String> direction10Codes = new HashSet<>();
        for (int i = 0; i < detailObject.size(); i++) {
            JSONObject object = detailObject.getJSONObject(i);
            String directionCodeStr = object.getString("directionCode");
            if (FireworkDeal.isNotDirectionCode(directionCodeStr)) {
                msg.setCode(ERROR_10004.getCode());
                msg.setMessage(ERROR_10004.getMsg()+":流向码:" + directionCodeStr + "错误");
                return msg;
            }
//            directionCodes.add(directionCodeStr);
            // 10位码
            direction10Codes.add(directionCodeStr.substring(0, 10));
        }
        List<String> direction10CodesList = new ArrayList<>(direction10Codes);
        // 获取所有流向码的
        List<ProductDO> productDos = productService.selectDoByDirections(direction10CodesList);
        // 10位 -> 产品 映射
        Map<String, ProductDO> productDOMap = new HashMap<>(productDos.size());
        for (ProductDO p : productDos) {
            productDOMap.put(p.getDirectionCode(), p);
        }
        // 校验哪个产品不存在
        for (String directionCode : direction10CodesList) {
            if (!productDOMap.containsKey(directionCode)) {
                msg.setCode(ERROR_10004.getCode());
                msg.setMessage(ERROR_10004.getMsg()+":流向码:" + directionCode + "不存在");
                return msg;
            }
        }
        // 产品对应价格
        List<ProductPriceInfo> productPriceInfos = productPriceService.selectByCodes(userInfo.getCompanynumber(), direction10CodesList);
        // 10位 -> 产品价格 映射
        Map<String, BigDecimal> productPriceMap = new HashMap<>(productPriceInfos.size());
        for (ProductPriceInfo productPriceInfo : productPriceInfos) {
            BigDecimal price = BigDecimal.ZERO;
            if (productPriceInfo.getPrice() != null) {
                price = productPriceInfo.getPrice();
            }
            productPriceMap.put(productPriceInfo.getItemcode(), price);
        }
//        for (String directionCode : direction10CodesList) {
//            if (!productPriceMap.containsKey(directionCode)) {
//                msg.setCode(ERROR_10004.getCode());
//                msg.setMessage(ERROR_10004.getMsg()+":流向码:" + directionCode + "价格不存在");
//                return msg;
//            }
//        }
//        List<DirectionProductBO> directionProductBOS = new ArrayList<>(detailObject.size());
//        DirectionProductBO directionProductBO;
//        for (int i = 0; i < detailObject.size(); i++) {
//            directionProductBO = new DirectionProductBO();
//            JSONObject object = detailObject.getJSONObject(i);
//            String directionCodeStr = object.getString("directionCode");
//            directionProductBO.setDirectionCode(directionCodeStr);
//            directionProductBO.setItemCode(directionCodeStr.substring(0,10));
//            directionProductBO.setSlice(productDOMap.get(directionProductBO.getItemCode()).getSlice());
//            directionProductBOS.add(directionProductBO);
//        }
//        List<StockInfo> stockInfos = stockService.selectStockByDirectionsAndSlices(directionProductBOS);
//        Map<String, StockInfo> stockInfoMap = new HashMap<>();
        List<SaleOrderDetailInfoBO> detailInfoList = new ArrayList<>();
        for (int i = 0; i < detailObject.size(); i++) {
            // 遍历 jsonArray 数组,把每一个对象转成 json 对象
            JSONObject object = detailObject.getJSONObject(i);
            String directionCodeStr = object.getString("directionCode");
            ProductDO productDO = productDOMap.get(directionCodeStr.substring(0, 10));
            if (productDO == null || productDO.getSlice() == null) {
                msg.setCode(ERROR_10004.getCode());
                msg.setMessage(ERROR_10004.getMsg()+":流向码:" + directionCodeStr + "错误");
                return msg;
            }
            String slice = productDO.getSlice();
            ProductInfo productInfo = BeanUtils.copy(productDO, ProductInfo.class);
            // 需要分表查询暂不优化
            StockInfo stockInfo = stockService.selectStockByDirectionAndSlice(directionCodeStr, slice);
//            StockInfo stockInfo = stockService.selectStockByDirection(directionCodeStr);
            if (stockInfo == null) {
                msg.setCode(ERROR_50001.getCode());
                msg.setMessage(ERROR_50001.getMsg()+":流向码为:" + directionCodeStr + " 未入库,销售失败");
                return msg;
            }
            if (stockInfo.getStatus() != null && stockInfo.getStatus().equals(StockInfo.STOCK_SOLD)) {
                msg.setCode(ERROR_50002.getCode());
                msg.setMessage(ERROR_50002.getMsg()+":流向码为:" + directionCodeStr + " 已售出,销售失败");
                return msg;
            }
            if (FireworkDeal.is22Characters(directionCodeStr)){
                List<ProductVo>productVoList = new ArrayList<>();
                DirectionDetail directionDetail = FireworkDeal.dealDirectionCode(directionCodeStr);
                ProductVo productVo = BeanUtils.copy(productInfo, ProductVo.class);
                productVo.setDirectionCode(directionCodeStr);
                productVo.setItemCode(directionDetail.getItemCode());
                productVo.setDateCode(directionDetail.getDateCode());
                productVo.setSerialNo(directionDetail.getSerialNo());
                FireworkDeal.getProductVos(directionCodeStr,directionDetail,directionDetail,productVoList,productVo);
                for (ProductVo productVo1 : productVoList){
                    SaleOrderDetailInfoBO detailInfo = new SaleOrderDetailInfoBO();
                    detailInfo.setItemcode(productInfo.getDirectionCode());
                    detailInfo.setDirectioncode(productVo1.getDirectionCode());
                    detailInfo.setItemname(productVo1.getName());
                    detailInfo.setPrice(productPriceMap.get(detailInfo.getDirectioncode()));
                    if (detailInfo.getPrice() == null) {
                        detailInfo.setPrice(BigDecimal.ZERO);
                    }
                    detailInfo.setSpecification(productVo1.getSpecification());
                    detailInfo.setProductDO(productDOMap.get(detailInfo.getItemcode()));
                    detailInfoList.add(detailInfo);
                }
                num = productVoList.size();
            }else {
                SaleOrderDetailInfoBO detailInfo = new SaleOrderDetailInfoBO();
                detailInfo.setItemcode(productInfo.getDirectionCode());
                detailInfo.setDirectioncode(directionCodeStr);
                detailInfo.setItemname(productInfo.getName());
                detailInfo.setPrice(productPriceMap.get(detailInfo.getDirectioncode()));
                if (detailInfo.getPrice() == null) {
                    detailInfo.setPrice(BigDecimal.ZERO);
                }
                detailInfo.setProductDO(productDOMap.get(detailInfo.getItemcode()));
                detailInfo.setSpecification(productInfo.getSpecification());
                detailInfoList.add(detailInfo);
                num = 1;
            }
        }
        String idCardNum = customer.getString("idCardNumber");
        String workerName = customer.getString("workerName");
        if (StringUtils.isBlank(idCardNum) || StringUtils.isBlank(workerName)) {
            msg.setCode(ERROR_50001.getCode());
            msg.setMessage(ERROR_50001.getMsg()+":身份信息有误");
            return msg;
        }
        String auth = getAuth();
        auth = StringUtils.isBlank(auth) ? "NOAUTH" : auth;
        msg = saleOrderService.doSalesProcess(customer, num, idCardNum, userInfo, detailInfoList, type, salesTime, pay, total, change, auth);
        return msg;
    }
    @GetMapping(value = {"/get/idCardNum/{idCardNum}/pageIndex/{pageIndex}/pageSize/{pageSize}/directionCode/{directionCode}",
            "/get/idCardNum/{idCardNum}/pageIndex/{pageIndex}/pageSize/{pageSize}"})
    public Msg getOrderListByIdCardNum(@PathVariable String idCardNum,
                                       @PathVariable Integer pageIndex,
                                       @PathVariable Integer pageSize,
                                       String sort, String order,
                                       @PathVariable(required = false) String directionCode) {
        Msg msg = new Msg(true);
        if (StringUtils.isBlank(idCardNum)) {
            msg.setCode(ERROR_10001.getCode());
            msg.setMessage(ERROR_10001.getMsg()+":身份证号为空,查询失败!");
            return msg;
        }
        if (pageIndex == null){
            pageIndex = 0;
        }
        if (pageSize == null || pageSize == 0){
            pageSize = 10;
        }
        PageInfo pageInfo = new PageInfo(pageIndex, pageSize,sort,order);
        Map<String, Object> condition = new HashMap<>(4);
        condition.put("idCardNum",idCardNum);
        if (StringUtils.isNotBlank(directionCode)) {
            condition.put("directionCode", directionCode);
        }
        pageInfo.setCondition(condition);
        saleOrderService.selectReturnDataGrid(pageInfo);
        msg.setResult(pageInfo);
        return msg;
    }
    @PostMapping("/saleDetailList")
    public Msg getSaleOneDetail(@RequestBody JSONObject jsonObject) {
        String directionCode = jsonObject.getString("directionCode");
        String userId = jsonObject.getString("userId");
        if (StringUtils.isBlank(userId)) {
            throw new BusinessException("操作员信息为空");
        }
        List<SaleDetailVo> details = saleOrderDetailService.getDetailList(directionCode);
        return success(details);
    }
    @PostMapping("/return2storage")
    @JsonParams
    public Msg returnProduct2(@RequestBody JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        String directionCode = jsonObject.getString("directionCode");
        String auth = getAuth();
        auth = StringUtils.isBlank(auth) ? "NOAUTH" : auth;
        saleOrderDetailService.returnAndStorage(directionCode,userId,auth);
        return success();
    }
    @PostMapping("/return")
    @JsonParams
    public Msg returnProduct(@RequestBody JSONObject object) {
        Msg msg = new Msg(true);
        JSONArray directionCodes = object.getJSONArray("directionCodes");
        StringBuilder message = new StringBuilder();
        for (Object dire : directionCodes){
            if (dire == null){
                message.append("流向码:").append("为空退货失败!");
                continue;
            }
            String directionCode = dire.toString();
            if (StringUtils.isBlank(directionCode) || FireworkDeal.isNotDirectionCode(directionCode)) {
                message.append("流向码:").append(directionCode).append("不符合规则,退货失败!");
                continue;
            }
            UserInfo userInfo = userService.getById(getUser().getId());
            String auth = getAuth();
            auth = StringUtils.isBlank(auth) ? "NOAUTH" : auth;
            StockInfo stockInfo = stockService.selectStockByDirection(directionCode);
            if (stockInfo == null) {
                message.append("流向码:+").append(directionCode).append("库存状态异常,退货失败!");
                continue;
            }
            ProductInfo productInfo = productService.selectByDirection(directionCode.substring(0, 10));
            // 创建入库单,type为2,创建入库明细,修改stock
            EntryOrderInfo entryOrderInfo = entryService.generateEntryOrderInfo(EntryUtils.TH_ENTRY, userInfo, new Date(), "", auth);
            EntryDetailInfo entryDetailInfo = new EntryDetailInfo(entryOrderInfo.getCode(), directionCode, productInfo.getDirectionCode(),
                    productInfo.getName(), productInfo.getManufacturer(), new Date(),userInfo.getCompanynumber());
            entryOrderInfo.setNum(1);
            entryDetailInfo.setNum(1);
            SaleOrderDetailInfo detailInfo = saleOrderService.selectOrderByDirectionReturnflag(directionCode,(byte) 0, null);
            if (detailInfo == null){
                msg = new Msg(ERROR_50001,"没有找到销售订单详情或该商品已退货");
                break;
            }
            CustomerInfo customerInfo = customerService.getCustomerBySaleOrder(detailInfo.getOrdercode());
            Byte flag = 1;
            detailInfo.setReturnflag(flag);
            saleOrderDetailService.updateById(detailInfo);
            int i = stockService.doReturn(stockInfo,userInfo,customerInfo, new Date());
            if (i != 1){
                message.append("流向码:+").append(directionCode).append("库存更新失败!");
            }else {
                entryService.save(entryOrderInfo);
                entryDetailService.save(entryDetailInfo);
            }
        }
        if (StringUtils.isNotBlank(message)){
            msg.setCode(ERROR_999.getCode());
            msg.setMessage(message.toString());
        }
        return msg;
    }
    @PostMapping("/returnBatch")
    @JsonParams
    public List<Msg> returnBatch(@RequestBody JSONArray jsonArray){
        if (jsonArray.size() < 1){
            return null;
        }
        List<Msg>msgList = new ArrayList<>();
        for (int i =0 ; i<jsonArray.size(); i++){
            Msg msg = new Msg(true);
            JSONObject object = jsonArray.getJSONObject(i);
            String userId = object.getString("userId");
            String datetime = object.getString("datetime");
            String directionCode = object.getString("directionCode");
            Date date;
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                date = dateFormat.parse(datetime);
            } catch (ParseException e) {
                msg = new Msg(ERROR_10003, "日期类型错误!");
                msgList.add(msg);
                continue;
            }
            UserInfo userInfo = userService.getById(userId);
            String auth = getAuth();
            auth = StringUtils.isBlank(auth) ? "NOAUTH" : auth;
            EntryOrderInfo entryOrderInfo = entryService.generateEntryOrderInfo(EntryUtils.TH_ENTRY, userInfo, new Date(), "", auth);
            List<ProductVo>productVos = new ArrayList<>();
            if (StringUtils.isBlank(directionCode) || FireworkDeal.isNotDirectionCode(directionCode)) {
                msg = new Msg(ERROR_10004,"流向码无效");
                msgList.add(msg);
                continue;
            }
            ProductVo productVo = productService.selectVoByDirection(directionCode);
            if (FireworkDeal.is22Characters(directionCode)) {
                DirectionDetail directionDetail = FireworkDeal.dealDirectionCode(directionCode);
                FireworkDeal.getProductVos(directionCode,directionDetail,directionDetail,productVos,productVo);
            }else {
                productVos.add(productVo);
            }
            // 创建入库单,type为2,创建入库明细,修改stock
            EntryDetailInfo entryDetailInfo = new EntryDetailInfo(entryOrderInfo.getCode(), directionCode, productVo.getDirectionCode(),
                    productVo.getName(), productVo.getManufacturer(), new Date(),userInfo.getCompanynumber());
            entryOrderInfo.setNum(1);
            entryDetailInfo.setNum(1);
            //先行校验是否存在不能退货的商品
            boolean doReturnFlag = true;
            for (ProductVo productVo1 : productVos){
                StockInfo stockInfo = stockService.selectStockByDirection(productVo1.getDirectionCode());
                SaleOrderDetailInfo detailInfo = saleOrderService.selectOrderByDirectionReturnflag(productVo1.getDirectionCode(),(byte) 0,datetime);
                if (detailInfo == null || stockInfo == null){
                    doReturnFlag = false;
                    msg = new Msg(ERROR_50001,"没有找到销售订单详情或该商品已退货");
                    break;
                }
            }
            //如果不存在,进行退货操作
            if (doReturnFlag){
                for (ProductVo productVo1 : productVos){
                    StockInfo stockInfo = stockService.selectStockByDirection(productVo1.getDirectionCode());
                    SaleOrderDetailInfo detailInfo = saleOrderService.selectOrderByDirectionReturnflag(productVo1.getDirectionCode(),(byte) 0,datetime);
                    CustomerInfo customerInfo = customerService.getCustomerBySaleOrder(detailInfo.getOrdercode());
                    Byte flag = 1;
                    detailInfo.setReturnflag(flag);
                    saleOrderDetailService.updateById(detailInfo);
                    int j = stockService.doReturn(stockInfo,userInfo,customerInfo, date);
                    if (j == 0){
                        msg = new Msg(ERROR_40001,"退货失败");
                        break;
                    }
                }
                entryService.save(entryOrderInfo);
                entryDetailService.save(entryDetailInfo);
            }
            msgList.add(msg);
        }
        return msgList;
    }
    @PostMapping("/saleRecord1")
    @ApiOperation(value = "实名购买查询(按流向码查询)", httpMethod = "POST")
    @ApiImplicitParams({})
    Object saleInquiry1(@RequestBody FilterObject jsonFilter) {
        Integer pageIndex = jsonFilter.getPageIndex();
        Integer pageSize = jsonFilter.getPageSize();
        IPage page = saleOrderService.selectSaleRecord1(new Page<>(pageIndex, pageSize), jsonFilter.getFilter(),getUser());
        return success(page);
    }
    @PostMapping("/saleRecord2")
    @ApiOperation(value = "实名购买查询(按零售单位查询)", httpMethod = "POST")
    @ApiImplicitParams({})
    Object saleInquiry2(@RequestBody FilterObject jsonFilter) {
        Integer pageIndex = jsonFilter.getPageIndex();
        Integer pageSize = jsonFilter.getPageSize();
        IPage page = saleOrderService.selectSaleRecord2(new Page<>(pageIndex, pageSize), jsonFilter.getFilter(),getUser());
        return success(page);
    }
    @PostMapping("/saleRecord3")
    @ApiOperation(value = "销售汇总统计", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageIndex",value = "当前页码",required = true),
            @ApiImplicitParam(name = "pageSize",value = "页大小",required = true),
            @ApiImplicitParam(name = "filter.itemcode",value = "流向码",required = true),
            @ApiImplicitParam(name = "filter.itemname",value = "产品名称",required = true),
            @ApiImplicitParam(name = "filter.province",value = "省",required = true),
            @ApiImplicitParam(name = "filter.city",value = "市",required = true),
            @ApiImplicitParam(name = "filter.district",value = "区",required = true),
            @ApiImplicitParam(name = "filter.street",value = "街道",required = true),
            @ApiImplicitParam(name = "filter.committee",value = "委员会",required = true),
            @ApiImplicitParam(name = "filter.starttime",value = "开始时间",required = true),
            @ApiImplicitParam(name = "filter.endtime",value = "结束时间",required = true),
            @ApiImplicitParam(name = "filter.safetysupervision",value = "监管分类",required = true),
            @ApiImplicitParam(name = "filter.enterprisename",value = "企业名称",required = true),
            @ApiImplicitParam(name = "filter.parententerprisename",value = "上级企业名称",required = true),
    })
    Object saleInquiry3(@RequestBody FilterObject jsonFilter) {
        Integer pageIndex = jsonFilter.getPageIndex();
        Integer pageSize = jsonFilter.getPageSize();
        PageInfoExtension<Map> page = saleOrderService.selectSaleRecord3(new Page<>(pageIndex, pageSize), jsonFilter.getFilter(),getUser());
        return success(page);
    }
    @PostMapping("/export/saleRecord3")
    @ApiOperation(value = "销售汇总统计导出", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageIndex",value = "当前页码",required = true),
            @ApiImplicitParam(name = "pageSize",value = "页大小",required = true),
            @ApiImplicitParam(name = "filter.itemcode",value = "流向码",required = true),
            @ApiImplicitParam(name = "filter.itemname",value = "产品名称",required = true),
            @ApiImplicitParam(name = "filter.province",value = "省",required = true),
            @ApiImplicitParam(name = "filter.city",value = "市",required = true),
            @ApiImplicitParam(name = "filter.district",value = "区",required = true),
            @ApiImplicitParam(name = "filter.street",value = "街道",required = true),
            @ApiImplicitParam(name = "filter.committee",value = "委员会",required = true),
            @ApiImplicitParam(name = "filter.starttime",value = "开始时间",required = true),
            @ApiImplicitParam(name = "filter.endtime",value = "结束时间",required = true),
            @ApiImplicitParam(name = "filter.safetysupervision",value = "监管分类",required = true),
            @ApiImplicitParam(name = "filter.enterprisename",value = "企业名称",required = true),
            @ApiImplicitParam(name = "filter.parententerprisename",value = "上级企业名称",required = true),
    })
    Object exportSaleInquiry3(@RequestBody FilterObject jsonFilter) {
        List<Map> list = saleOrderService.selectExportSaleRecord3( jsonFilter.getFilter(),getUser());
        return success(list);
    }
    @PostMapping("/saleRecord4")
    @ApiOperation(value = "实名销售分析导出", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageIndex",value = "当前页码",required = true),
            @ApiImplicitParam(name = "pageSize",value = "页大小",required = true),
            @ApiImplicitParam(name = "filter.starttime",value = "开始时间",required = true),
            @ApiImplicitParam(name = "filter.endtime",value = "结束时间",required = true),
            @ApiImplicitParam(name = "filter.enterprisename",value = "上级企业名称",required = true),
            @ApiImplicitParam(name = "filter.parententerprisename",value = "上级企业名称",required = true),
            @ApiImplicitParam(name = "filter.identify",value = "购买人身份证",required = true),
            @ApiImplicitParam(name = "filter.itemcode",value = "产品流向码",required = true),
    })
    Object saleInquiry4(@RequestBody FilterObject jsonFilter) {
        Integer pageIndex = jsonFilter.getPageIndex();
        Integer pageSize = jsonFilter.getPageSize();
        IPage page = saleOrderService.selectSaleRecord4(new Page<>(pageIndex, pageSize), jsonFilter.getFilter(),getUser());
        Msg result = success(page);
        String jsonStr = JSON.toJSONString(result);
        String base64Str = Base64.getEncoder().encodeToString(jsonStr.getBytes(StandardCharsets.UTF_8));
        return base64Str;
    }
    @PostMapping("/customer/upload/{idCard}")
    @ApiOperation(value = "补全customer照片信息", httpMethod = "POST")
    Msg customerUpload(@PathVariable String idCard, MultipartFile file) {
        customerService.uploadPhoto(idCard, file);
        return success();
    }
    @PostMapping("/export/saleRecord4")
    @ApiOperation(value = "实名销售分析", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "filter.starttime",value = "开始时间",required = true),
            @ApiImplicitParam(name = "filter.endtime",value = "结束时间",required = true),
            @ApiImplicitParam(name = "filter.enterprisename",value = "上级企业名称",required = true),
            @ApiImplicitParam(name = "filter.parententerprisename",value = "上级企业名称",required = true),
            @ApiImplicitParam(name = "filter.identify",value = "购买人身份证",required = true),
            @ApiImplicitParam(name = "filter.itemcode",value = "产品流向码",required = true),
    })
    Object exportSaleInquiry4(@RequestBody FilterObject jsonFilter) {
        List<Map> list = saleOrderService.selectExportSaleRecord4(jsonFilter.getFilter(), getUser());
        return success(list);
    }
    /**
    * @Description: 根据销售企业的单位编号和人员的身份证获取购买明细
    * @date 2021/4/14 12:38
    */
    @PostMapping("/getPurchaseDetailInUnit")
    @ApiOperation(value = "实名购买查询(按购买人查询)", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageIndex",value = "当前页码",required = true),
            @ApiImplicitParam(name = "pageSize",value = "页大小",required = true),
            @ApiImplicitParam(name = "filter.starttime",value = "开始时间",required = true),
            @ApiImplicitParam(name = "filter.endtime",value = "结束时间",required = true),
            @ApiImplicitParam(name = "filter.identify",value = "省份证",required = true),
            @ApiImplicitParam(name = "filter.enterprisenumber",value = "企业单位编号",required = true),
    })
    Object getPurchaseDetailInUnit(@RequestBody FilterObject jsonFilter) {
        Integer pageIndex = jsonFilter.getPageIndex();
        Integer pageSize = jsonFilter.getPageSize();
        IPage page = saleOrderService.getPurchaseDetailInUnit(new Page<>(pageIndex, pageSize), jsonFilter.getFilter(),getUser());
        return success(page);
    }
    @GetMapping(value = {"/soldNoStock/directionCode/{directionCode}/pageIndex/{pageIndex}/pageSize/{pageSize}",
            "/soldNoStock/pageIndex/{pageIndex}/pageSize/{pageSize}"})
    public Msg getSoldNoStockInfo(@PathVariable Integer pageIndex,
                                  @PathVariable Integer pageSize,
                                  String sort, String order,
                                  @PathVariable(required = false) String directionCode) {
        Msg msg = new Msg(true);
        pageIndex = pageIndex == null? 10:pageIndex;
        pageSize = pageSize == null? 10:pageSize;
        PageInfo pageInfo = new PageInfo(pageIndex, pageSize, sort, order);
        Map<String, Object> condition = new HashMap<>(4);
        if (StringUtils.isNotBlank(directionCode)) {
            condition.put("directionCode", directionCode);
        }
        UserInfo userInfo = userService.getById(getUser().getId());
        if (userInfo.getCompanynumber() != null){
            condition.put("companyNumber",userInfo.getCompanynumber());
        }
        pageInfo.setCondition(condition);
        soldNoStockService.selectSoldNoStockDataGrid(pageInfo);
        msg.setResult(pageInfo);
        return msg;
    }
    @GetMapping(value = "/dailySaleReport")
    public Msg dailySaleReport(@RequestParam (value = "startDate")String startDate,
                               @RequestParam (value = "endDate")String endDate,
                               @RequestParam (value = "pageIndex")Integer pageIndex,
                               @RequestParam (value = "pageSize")Integer pageSize,
                               String sort, String order) {
        Msg msg = new Msg(true);
        if (StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)) {
            msg.setCode(ERROR_10001.getCode());
            msg.setMessage(ERROR_10001.getMsg()+":日期为空,查询失败!");
            return msg;
        }
        pageIndex = pageIndex == null ? 0 : pageIndex ;
        pageSize = pageSize == null ? 10 : pageSize ;
        PageInfo pageInfo = new PageInfo(pageIndex, pageSize,sort,order);
        Map<String, Object> condition = new HashMap<>(4);
        UserInfo userInfo = userService.getById(getUser().getId());
        if (StringUtils.isNotBlank(userInfo.getCompanynumber())){
            condition.put("companynumber",userInfo.getCompanynumber());
        }
        condition.put("startDate",startDate);
        condition.put("endDate",endDate);
        pageInfo.setCondition(condition);
        PageInfoExtension pageInfoExtension = saleOrderService.selectDailySaleReport(pageInfo);
        msg.setResult(pageInfoExtension);
        return msg;
    }
    @GetMapping(value = "/info")
    public Msg getOrderInfo(@RequestParam (value = "startDate")String startDate,
                               @RequestParam (value = "endDate")String endDate,
                               @RequestParam (value = "code",required = false)String code,
                               @RequestParam (value = "pageIndex")Integer pageIndex,
                               @RequestParam (value = "pageSize")Integer pageSize,
                               String sort, String order) {
        Msg msg = new Msg(true);
        if (StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)) {
            msg.setCode(ERROR_10001.getCode());
            msg.setMessage(ERROR_10001.getMsg()+":日期为空,查询失败!");
            return msg;
        }
        pageIndex = pageIndex == null ? 0 : pageIndex ;
        pageSize = pageSize == null ? 10 : pageSize ;
        PageInfo pageInfo = new PageInfo(pageIndex, pageSize,sort,order);
        Map<String, Object> condition = new HashMap<>(4);
        UserInfo userInfo = userService.getById(getUser().getId());
        if (StringUtils.isNotBlank(userInfo.getCompanynumber())){
            condition.put("companynumber",userInfo.getCompanynumber());
        }
        if (StringUtils.isNotBlank(code)){
            condition.put("code",code);
        }
        condition.put("startDate",startDate);
        condition.put("endDate",endDate);
        pageInfo.setCondition(condition);
        saleOrderService.selectOrderDataGrid(pageInfo);
        msg.setResult(pageInfo);
        return msg;
    }
    @GetMapping("/detail")
    public Msg getSaleDetailByCode(@RequestParam("code")String code){
        Msg msg = new Msg(true);
        List<SaleOrderDetailInfo>detailInfos = saleOrderDetailService.selectByOrderCode(code);
        msg.setResult(detailInfos);
        return msg;
    }
    @GetMapping("/serialNo")
    public Msg getSerialNo(){
        Msg msg = new Msg(true);
        UserInfo userInfo = userService.getById(getUser().getId());
        int countNum = saleOrderService.getDailySaleCount(userInfo);
        msg.setResult(countNum);
        return msg;
    }
    @ApiOperation(value = "销售汇总统计", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageIndex",value = "当前页码",required = true),
            @ApiImplicitParam(name = "pageSize",value = "页大小",required = true),
            @ApiImplicitParam(name = "filter.province",value = "省",required = true),
            @ApiImplicitParam(name = "filter.city",value = "市",required = true),
            @ApiImplicitParam(name = "filter.district",value = "区",required = true),
            @ApiImplicitParam(name = "filter.street",value = "街道",required = true),
            @ApiImplicitParam(name = "filter.committee",value = "委员会",required = true),
            @ApiImplicitParam(name = "filter.starttime",value = "开始时间",required = true),
            @ApiImplicitParam(name = "filter.endtime",value = "结束时间",required = true),
            @ApiImplicitParam(name = "filter.safetysupervision",value = "监管分类",required = true),
            @ApiImplicitParam(name = "filter.enterprisename",value = "企业名称",required = true),
            @ApiImplicitParam(name = "filter.parententerprisename",value = "上级企业名称",required = true),
    })
    @PostMapping("/enterpriseESS")
    public Msg enterpriseEnterSellStore(@RequestBody FilterObject jsonFilter){
        Integer pageIndex = jsonFilter.getPageIndex();
        Integer pageSize = jsonFilter.getPageSize();
        PageInfo pageInfo = new PageInfo(pageIndex, pageSize);
        UserInfo userInfo = userService.getById(getUser().getId());
        saleOrderService.selectEnterpriseEnterSellStoreDataGrid(pageInfo,jsonFilter.getFilter(),userInfo);
        return success(pageInfo);
    }
    @PostMapping("/enterpriseESSExport")
        public Msg enterpriseEnterSellStoreExport(@RequestBody FilterObject jsonFilter){
        UserInfo userInfo = userService.getById(getUser().getId());
        List<EnterpriseDataVo> enterpriseDataVos =saleOrderService.selectEnterpriseEnterSellStoreData(jsonFilter.getFilter(),userInfo);
        return success(enterpriseDataVos);
    }
    @PostMapping("/cityESS")
    public Msg cityEnterSellStore(@RequestBody FilterObject jsonFilter){
        Integer pageIndex = jsonFilter.getPageIndex();
        Integer pageSize = jsonFilter.getPageSize();
        PageInfo pageInfo = new PageInfo(pageIndex, pageSize);
        saleOrderService.selectCityEnterSellStoreDataGrid(pageInfo,jsonFilter.getFilter());
        return success(pageInfo);
    }
    @PostMapping("/createBatch")
    @JsonParams
    public List<Msg> createOrderBatch(@RequestParam String encryptStr){
        String jsonStr = new String(Base64.getDecoder().decode(encryptStr), StandardCharsets.UTF_8);
        JSONArray jsonArray = JSON.parseArray(jsonStr);
        if (jsonArray.size() < 1){
            return null;
        }
        List<Msg>msgList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
//            Msg msg = dealOrderCreated(jsonObject);
            Msg msg = createOrder(Base64.getEncoder().encodeToString(jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8)));
            msgList.add(msg);
        }
        return msgList;
    }
    private Msg dealOrderCreated(JSONObject jsonObject) {
        JSONObject customer = jsonObject.getJSONObject("customer");
        JSONObject order = jsonObject.getJSONObject("order");
        JSONArray detailObject = jsonObject.getJSONArray("detailInfos");
        String userId = jsonObject.getString("operator");
        Integer num = order.getInteger("boxNum");
        String total = order.getString("total");
        String pay = order.getString("pay");
        String change = order.getString("change");
        String type = jsonObject.getString("type");
        String time = jsonObject.getString("datetime");
        Date salesTime;
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            salesTime = dateFormat.parse(time);
        } catch (ParseException e) {
            return new Msg(ERROR_10003,"出库日期类型错误");
        }
        if (customer == null || detailObject == null || detailObject.isEmpty()) {
            return new Msg(ERROR_10001);
        }
        boolean isUser = userService.checkUserById(userId);
        if (!isUser) {
            return new Msg(ERROR_20001);
        }
        UserInfo userInfo = userService.getById(userId);
        List<SaleOrderDetailInfo> detailInfoList = new ArrayList<>();
        for (int j = 0; j < detailObject.size(); j++) {
            // 遍历 jsonArray 数组,把每一个对象转成 json 对象
            JSONObject object = detailObject.getJSONObject(j);
            String directionCodeStr = object.getString("directionCode");
            if (FireworkDeal.isNotDirectionCode(directionCodeStr)) {
                return new Msg(ERROR_10004,"流向码:"+directionCodeStr+"错误");
            }
            if (!productService.hasProductByDire(directionCodeStr.substring(0, 10))) {
                return new Msg(ERROR_10004,"流向码:"+directionCodeStr+"错误");
            }
            ProductInfo productInfo = productService.selectByDirection(directionCodeStr.substring(0, 10));
            if (FireworkDeal.is22Characters(directionCodeStr)){
                List<ProductVo>productVoList = new ArrayList<>();
                DirectionDetail directionDetail = FireworkDeal.dealDirectionCode(directionCodeStr);
                ProductVo productVo = productService.selectVoByDirection(directionCodeStr);
                FireworkDeal.getProductVos(directionCodeStr,directionDetail,directionDetail,productVoList,productVo);
                for (ProductVo productVo1 : productVoList){
                    SaleOrderDetailInfo detailInfo = new SaleOrderDetailInfo(productInfo.getDirectionCode(), productVo1.getDirectionCode());
                    ProductPriceInfo productPriceInfo = productPriceService.selectByCode(userInfo.getCompanynumber(), productVo1.getName());
                    BigDecimal price = productPriceInfo == null ? new BigDecimal("0") : productPriceInfo.getPrice() == null ? BigDecimal.valueOf(0) : productPriceInfo.getPrice();
                    detailInfo.setPrice(price);
                    detailInfo.setItemname(productVo1.getName());
                    detailInfo.setSpecification(productVo1.getSpecification());
                    detailInfoList.add(detailInfo);
                }
                num = productVoList.size();
            }else {
                SaleOrderDetailInfo detailInfo = new SaleOrderDetailInfo(productInfo.getDirectionCode(), directionCodeStr);
                ProductPriceInfo productPriceInfo = productPriceService.selectByCode(userInfo.getCompanynumber(), productInfo.getName());
                BigDecimal price = productPriceInfo == null ? new BigDecimal("0") : productPriceInfo.getPrice() == null ? BigDecimal.valueOf(0) : productPriceInfo.getPrice();
                detailInfo.setPrice(price);
                detailInfo.setItemname(productInfo.getName());
                detailInfo.setSpecification(productInfo.getSpecification());
                detailInfoList.add(detailInfo);
                num = 1;
            }
        }
        String idCardNum = customer.getString("idCardNumber");
        String workerName = customer.getString("workerName");
        if (StringUtils.isBlank(idCardNum) || StringUtils.isBlank(workerName)) {
            return new Msg(ERROR_50001,"身份信息有误");
        }
        String auth = getAuth();
        auth = StringUtils.isBlank(auth) ? "NOAUTH" : auth;
        idCardNum = idCardNum.replaceAll("[\r\n]","").trim();
        //校验数据是否已上传
        CustomerInfo customerExist = customerService.getCustomerByIdCardNum(idCardNum);
        if (customerExist != null){
            SaleOrderInfo orderInfo = saleOrderService.isExist(customerExist.getId(),userInfo.getCompanynumber(),salesTime);
            if (orderInfo != null){
                return new Msg(SUCCESS,"数据已上传");
            }
        }
//        return saleOrderService.doSalesProcess(customer, num, idCardNum, userInfo, detailInfoList, type, salesTime, pay, total, change, auth);
        return null;
    }
    /**
     * @Description: 销售查询
     * @date 2021/11/10 9:32
     */
    @PostMapping("/salenum-query")
    @ApiOperation(value = "销售查询")
    Object getSaleNumInfo(@RequestBody FilterObject filter) {
        Integer pageIndex = filter.getPageIndex();
        Integer pageSize = filter.getPageSize();
        IPage page = saleOrderDetailService.selectSaleNumInfo(new Page<>(pageIndex, pageSize), filter.getFilter(), getUser());
        return success(page);
    }
    @PostMapping("/salenum-detail")
    @ApiOperation(value = "销售详情")
    Object getSaleNumInfoDetail(@RequestBody FilterObject filter) {
        Integer pageIndex = filter.getPageIndex();
        Integer pageSize = filter.getPageSize();
        IPage page = saleOrderDetailService.selectSaleNumInfoDetail(new Page<>(pageIndex, pageSize), filter.getFilter(), getUser());
        return success(page);
    }
    @GetMapping("/idcard-check")
    @ApiOperation(value = "身份证校验")
    Msg idcardCheck(@RequestParam String idcard) {
        boolean flag = IdCardUtil.strongVerifyIdNumber(idcard);
        return success(flag);
    }
    @PostMapping("/importSaleProduct")
    @ApiOperation(value = "导入销售流向码",response = Msg.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file",value = "文件",required = true),
    })
    public Msg importSaleProduct(MultipartFile file){
        Msg msg = new Msg();
        msg.setCode("200");
        msg.setMessage("success");
        String filesave ="";
        try {
            SimpleDateFormat sdf = new SimpleDateFormat( "yyyyMMddHHmmssSSS" );
            if (file == null)
            {
                msg.setCode("404");
                msg.setMessage("未找到上传文件");
                return msg;
            }
            long size = file.getSize();
            if(0 == size)
            {
                msg.setCode("404");
                msg.setMessage("上传文件大小为空");
                return msg;
            }
            if(!FileOptUtils.isDirExists(productPath)){
                msg.setCode("500");
                msg.setMessage("发生错误或不为目录");
                return msg;
            }
            filesave = productPath + getUser().getUsername() + "_" + sdf.format(new Date()) +".xlsx";
            file.transferTo(new File(filesave));
            InputStream in = new FileInputStream(filesave);
            String name = file.getOriginalFilename();
            Boolean isExcel2007 = name.substring(name.lastIndexOf(".") + 1).endsWith("xlsx")? true:false;
            BooleanReason blret = excelExportService.imporSaleProductExcel(in,getUser().getUsername(),isExcel2007);
            if(blret.getValue().equals(false))
            {
                msg.setCode("500");
                msg.setMessage(blret.getResultmsg());
                return msg;
            }else {
                msg.setMessage(blret.getResultmsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg.setCode("500");
            msg.setMessage("导入发生错误");
            return msg;
        }
        return msg;
    }
    @PostMapping("/importSaleOrder")
    @ApiOperation(value = "导入实名销售",response = Msg.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file",value = "文件",required = true),
    })
    public Msg importSaleOrder(MultipartFile file){
        Msg msg = new Msg();
        msg.setCode("200");
        msg.setMessage("success");
        String filesave ="";
        try {
            SimpleDateFormat sdf = new SimpleDateFormat( "yyyyMMddHHmmssSSS" );
            if (file == null)
            {
                msg.setCode("404");
                msg.setMessage("未找到上传文件");
                return msg;
            }
            long size = file.getSize();
            if(0 == size)
            {
                msg.setCode("404");
                msg.setMessage("上传文件大小为空");
                return msg;
            }
            if(!FileOptUtils.isDirExists(productPath)){
                msg.setCode("500");
                msg.setMessage("发生错误或不为目录");
                return msg;
            }
            filesave = productPath + getUser().getUsername() + "_" + sdf.format(new Date()) +".xlsx";
            file.transferTo(new File(filesave));
            InputStream in = new FileInputStream(filesave);
            String name = file.getOriginalFilename();
            Boolean isExcel2007 = name.substring(name.lastIndexOf(".") + 1).endsWith("xlsx")? true:false;
            BooleanReason blret = excelExportService.imporSaleOrderExcel(in,getUser().getUsername(),isExcel2007);
            if(blret.getValue().equals(false))
            {
                msg.setCode("500");
                msg.setMessage(blret.getResultmsg());
                return msg;
            }else {
                msg.setMessage(blret.getResultmsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg.setCode("500");
            msg.setMessage("导入发生错误");
            return msg;
        }
        return msg;
    }
}