package cn.ezhizao.project.business.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.ezhizao.common.utils.poi.ExcelUtil;
import cn.ezhizao.framework.aspectj.lang.annotation.Log;
import cn.ezhizao.framework.aspectj.lang.enums.BusinessType;
import cn.ezhizao.framework.task.RyTask;
import cn.ezhizao.framework.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.framework.web.page.TableDataInfo;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.ezhizao.project.business.domain.BizStorageCode;
import cn.ezhizao.project.business.service.IBizStorageCodeService;

/**
 * 存储码Controller
 *
 * @author ezhizao
 * @date 2025-05-15
 */
@RestController
@RequestMapping("/business/storageCode")
public class BizStorageCodeController extends BaseController
{
    @Resource
    private IBizStorageCodeService bizStorageCodeService;
    @Resource
    HttpServletRequest request;
    @Resource
    private RyTask task;

    /**
     * 查询存储码列表
     */
    @GetMapping("/list")
    public TableDataInfo list(BizStorageCode bizStorageCode) throws NoSuchFieldException, IllegalAccessException, JsonProcessingException {
        startPage();
        String tenantId = request.getHeader("tenantId");
        if(!tenantId.equals("0")){
            bizStorageCode.setTenantId(Long.valueOf(tenantId));
        }

        List<BizStorageCode> list = bizStorageCodeService.getList(bizStorageCode);
        for (BizStorageCode item : list
        ) {
            if (item.getQcCode().equals("")) {
                task.GenerateQcCode(item);
            }
        }
        return getDataTable(list);
    }
    @Log(title="存储码pdf", businessType = BusinessType.UPDATE)
    @GetMapping("/printUpdate/{ids}")
    public AjaxResult printUpdate(@PathVariable List<Long> ids) {
        List<BizStorageCode> storageCodes = bizStorageCodeService.query().in("id", ids.isEmpty() ? Collections.singletonList(-1) : ids).list();
        storageCodes.forEach(l -> {
            l.setIsPrint(1);
        });
        return toAjax(storageCodes.isEmpty() || bizStorageCodeService.updateBatchById(storageCodes));
    }

    /**
     * 导出存储码列表
     */
    @Log(title = "存储码", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizStorageCode bizStorageCode) throws NoSuchFieldException, IllegalAccessException
    {
        bizStorageCode.setTenantId(Long.valueOf(request.getHeader("tenantId")));
        List<BizStorageCode> list = bizStorageCodeService.getList(bizStorageCode);
        ExcelUtil<BizStorageCode> util = new ExcelUtil<BizStorageCode>(BizStorageCode.class);
        util.exportExcel(response, list, "存储码数据");
    }

    /**
     * 获取存储码详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(bizStorageCodeService.getById(id));
    }

    /**
     * 新增存储码
     */
    @Log(title = "存储码", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizStorageCode bizStorageCode) throws NoSuchFieldException, IllegalAccessException
    {
        //厂别
        String tenantId = request.getHeader("tenantId");
        if(tenantId.equals("0")){
            tenantId = "1";
        }
        //判断年份下的流水号
        List<BizStorageCode> list = bizStorageCodeService.query().eq("year", bizStorageCode.getYear()).orderByDesc("serial_number").list();
        List<BizStorageCode> storageCodeList = new ArrayList<>();
        if(list.size() > 0){
            //当前年份存过值
            Long serialNumber = list.get(0).getSerialNumber();
            //超过四位
            if(serialNumber + bizStorageCode.getNum() > 99999){
                return error("超过五位流水号，请重新生成");
            }
            for(int i = 0; i <  bizStorageCode.getNum(); i++){
                BizStorageCode code = new BizStorageCode();
                code.setTenantId(Long.valueOf(tenantId));
                code.setYear(bizStorageCode.getYear());
                ++serialNumber;
                code.setSerialNumber(serialNumber);
                String serialStr = String.format("%05d", serialNumber);
                // 拼接生成QcCode
                String codeStr = bizStorageCode.getYear() + serialStr;
                code.setCode(codeStr);
                storageCodeList.add(code);
            }
        }else{
            Long serialNumber = 0L;
            //当前年份没有存过值
            for(int i = 0; i <  bizStorageCode.getNum(); i++){
                BizStorageCode code = new BizStorageCode();
                code.setTenantId(Long.valueOf(tenantId));
                code.setYear(bizStorageCode.getYear());
                ++serialNumber;
                code.setSerialNumber(serialNumber);
                String serialStr = String.format("%05d", serialNumber);
                // 拼接生成QcCode
                String codeStr = bizStorageCode.getYear() + serialStr;
                code.setCode(codeStr);
                storageCodeList.add(code);
            }
        }
        return toAjax(bizStorageCodeService.saveBatch(storageCodeList));
    }

    /**
     * 修改存储码
     */
    @PreAuthorize("@ss.hasPermi('business:storageCode:edit')")
    @Log(title = "存储码", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizStorageCode bizStorageCode) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizStorageCode);
        return toAjax(bizStorageCodeService.updateById(bizStorageCode));
    }

    /**
     * 删除存储码
     */
    @PreAuthorize("@ss.hasPermi('business:storageCode:remove')")
    @Log(title = "存储码", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids)
    {
        return toAjax(bizStorageCodeService.removeBatchByIds(ids));
    }
}
