package com.hzs.system.config.controller.manage;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.msg.ConfigMsgConstants;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.exception.ServiceException;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.utils.poi.ExcelUtil;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.system.config.BdBarCode;
import com.hzs.common.domain.system.config.BdBarCodeItems;
import com.hzs.common.domain.system.config.ext.BdBarCodeItemsExt;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.core.utils.TransactionUtils;
import com.hzs.system.config.param.BdBarCodeItemsParam;
import com.hzs.system.config.service.IBdBarCodeItemsService;
import com.hzs.system.config.service.IBdBarCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 条形码明细 前端控制器
 * </p>
 *
 * @author zhangjing
 * @since 2022-10-18
 */
@Slf4j
@RestController
@RequestMapping("/manage/bar-code-items")
public class BdBarCodeItemsController extends BaseController {

    @Autowired
    private IBdBarCodeItemsService barCodeItemsService;
    @Autowired
    private IBdBarCodeService barCodeService;

    /**
     * @description: 查询条形码列表
     * @author: zhang jing
     * @date: 2022/8/30 10:20
     * @param: [barCodeItems]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.BAR_CODE_ITEMS, method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(BdBarCodeItemsExt barCodeItems) {
        startPage();
        List<BdBarCodeItems> list = barCodeItemsService.queryBarCodeItemsList(barCodeItems);
        return getDataTable(list);
    }

    /**
     * @description: 查询条形码列表
     * @author: zhang jing
     * @date: 2022/8/30 10:20
     * @param: [barCodeItems]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.BAR_CODE_ITEMS, method = EOperationMethod.SELECT)
    @PostMapping("/export")
    public void export(HttpServletResponse response,BdBarCodeItemsExt barCodeItems) {
        List<BdBarCodeItems> list = barCodeItemsService.queryBarCodeItemsList(barCodeItems);
        ExcelUtil<BdBarCodeItems> util = new ExcelUtil<>(BdBarCodeItems.class);
        util.exportExcel(response, list, "条形码");
    }


    /**
     * @description: 生成条形码
     * @author: zhang jing
     * @date: 2022/8/30 10:21
     * @param: [barCodeItems]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.BAR_CODE_ITEMS, method = EOperationMethod.INSERT)
    @PostMapping("/save")
    public AjaxResult save(@RequestBody BdBarCodeItemsParam barCodeItemsParam) {
        List<Long> pkBarCodeList =barCodeItemsParam.getPkBarCode();
        if(CollectionUtil.isNotEmpty(pkBarCodeList)){
            for(Long pkBarCode:pkBarCodeList){
                BdBarCode bdBarCode = barCodeService.getOneBarCode(pkBarCode);
                if(StringUtils.isNull(bdBarCode)){
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PK_BAR_CODE_NOT_NULL));
                }
            }
        }else{
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PK_BAR_CODE_NOT_NULL));
        }
        if(StringUtils.isNull(barCodeItemsParam.getGenerateCount())&&barCodeItemsParam.getGenerateCount()>0){
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.GENERATE_COUNT_NOT_NULL));
        }
        return toAjax(barCodeItemsService.savBarCode(pkBarCodeList,barCodeItemsParam.getGenerateCount()));
    }

    /**
     * @description: 打印条形码
     * @author: zhang jing
     * @date: 2022/10/21 13:49
     * @param: [barCodeItemsParam]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.BAR_CODE_ITEMS, method = EOperationMethod.SUBMIT)
    @PostMapping("/printTxm")
    public void printTxm(HttpServletResponse response,BdBarCodeItemsExt barCodeItems) throws IOException {
        QueryWrapper<BdBarCodeItems> querywrapper=new QueryWrapper();
        if(null!=barCodeItems.getCodeStatus()&&barCodeItems.getCodeStatus()==EBarcodeStatus.BOUND.getValue()){
            throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.ALREADY_BINDING_RANGE));
        }else{
            querywrapper.ne("CODE_STATUS",EBarcodeStatus.BOUND.getValue());
        }
        querywrapper.eq("PK_BAR_CODE",barCodeItems.getPkBarCode());
        if(null!=barCodeItems.getCodeStatus()){
            querywrapper.eq("CODE_STATUS",barCodeItems.getCodeStatus());
        }
        if(StringUtils.isNotEmpty(barCodeItems.getBarCode())){
            querywrapper.eq("BAR_CODE",barCodeItems.getBarCode());
        }
        if(null!=barCodeItems.getBatch()){
            querywrapper.eq("BATCH",barCodeItems.getBatch());
        }
        // 生成时间筛选
        if (barCodeItems.getStartDate() != null && barCodeItems.getEndDate() != null) {
            barCodeItems.setEndDate(DateUtils.afterDate(1, ChronoUnit.DAYS, barCodeItems.getEndDate()));
            querywrapper.between("CREATION_TIME", barCodeItems.getStartDate(), barCodeItems.getEndDate());
        }
        // 打印时间筛选
        if (barCodeItems.getStartDatePrint() != null && barCodeItems.getEndDatePrint() != null) {
            barCodeItems.setEndDatePrint(DateUtils.afterDate(1, ChronoUnit.DAYS, barCodeItems.getEndDatePrint()));
            querywrapper.between("PRINT_TIME", barCodeItems.getStartDatePrint(), barCodeItems.getEndDatePrint());
        }
        querywrapper.orderByDesc("PK_ID");
        List<BdBarCodeItems> list = barCodeItemsService.list(querywrapper);
        if(CollectionUtil.isNotEmpty(list)){
            List<String> barcodes = list.stream().map(BdBarCodeItems::getBarCode).collect(Collectors.toList());
            //打印完成后更改条形码表中status状态
            for(BdBarCodeItems bbc: list){
                bbc.setCodeStatus(EBarcodeStatus.PRINT.getValue());
                bbc.setPrintTime(new Date());
                barCodeItemsService.updateById(bbc);
            }
        }
    }



    /**
     * @description: 查询单条条形码
     * @author: zhang jing
     * @date: 2022/8/30 10:21
     * @param: [pkId]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.BAR_CODE_ITEMS, method = EOperationMethod.SELECT)
    @GetMapping("/getOne/{pkId}")
    public AjaxResult getOne(@PathVariable Long pkId) {
        BdBarCodeItems barCodeItems = barCodeItemsService.getById(pkId);
        return AjaxResult.success(barCodeItems);
    }


    /**
     * @description: 删除条形码
     * @author: zhang jing
     * @date: 2022/8/30 10:21
     * @param: [pkId]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.BAR_CODE_ITEMS, method = EOperationMethod.DELETE)
    @DeleteMapping("/{pkId}")
    public AjaxResult delete(@PathVariable Long pkId) {
        UpdateWrapper<BdBarCodeItems> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("PK_ID", pkId);
        updateWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
        updateWrapper.set("PK_MODIFIED", SecurityUtils.getUserId());
        updateWrapper.set("MODIFIED_TIME", new Date());
        return toAjax(barCodeItemsService.update(updateWrapper));
    }

}
