package com.fs.hisStore.controller;

import java.util.List;

import com.fs.common.core.domain.R;
import com.fs.common.core.domain.model.LoginUser;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.poi.ExcelUtil;

import com.fs.course.dto.FsStoreVerifyCodeDTO;
import com.fs.course.dto.WriteOffDTO;
import com.fs.framework.web.service.TokenService;
import com.fs.hisStore.domain.FsStoreVerifyCodeScrm;
import com.fs.hisStore.service.IFsStoreVerifyCodeScrmService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.enums.BusinessType;
import com.fs.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 核销码Controller
 * 
 * @author fs
 * @date 2025-11-27
 */
@RestController
@RequestMapping("/shop/scrm")
public class FsStoreVerifyCodeScrmController extends BaseController
{
    @Autowired
    private IFsStoreVerifyCodeScrmService fsStoreVerifyCodeScrmService;

    @Autowired
    private TokenService tokenService;


    // 允许的文件扩展名
    private static final String[] ALLOWED_EXCEL_EXTENSIONS = {".xlsx", ".xls"};

    // 最大文件大小（5MB）
    private static final long MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB


    /**
     * 查询核销码列表
     */
    @PreAuthorize("@ss.hasPermi('shop:scrm:list')")
    @GetMapping("/list")
    public TableDataInfo list(FsStoreVerifyCodeScrm fsStoreVerifyCodeScrm)
    {
        startPage();
        List<FsStoreVerifyCodeScrm> list = fsStoreVerifyCodeScrmService.selectFsStoreVerifyCodeScrmList(fsStoreVerifyCodeScrm);
        return getDataTable(list);
    }

    /**
     * 导出核销码列表
     */
    @PreAuthorize("@ss.hasPermi('shop:scrm:export')")
    @Log(title = "核销码", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(FsStoreVerifyCodeScrm fsStoreVerifyCodeScrm)
    {
        List<FsStoreVerifyCodeScrm> list = fsStoreVerifyCodeScrmService.selectFsStoreVerifyCodeScrmList(fsStoreVerifyCodeScrm);
        ExcelUtil<FsStoreVerifyCodeScrm> util = new ExcelUtil<FsStoreVerifyCodeScrm>(FsStoreVerifyCodeScrm.class);
        return util.exportExcel(list, "核销码数据");
    }

    /**
     * 获取核销码详细信息
     */
    @PreAuthorize("@ss.hasPermi('shop:scrm:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return AjaxResult.success(fsStoreVerifyCodeScrmService.selectFsStoreVerifyCodeScrmById(id));
    }

    /**
     * 新增核销码
     */
    @PreAuthorize("@ss.hasPermi('shop:scrm:add')")
    @Log(title = "核销码", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FsStoreVerifyCodeScrm fsStoreVerifyCodeScrm)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        fsStoreVerifyCodeScrm.setCreateBy(loginUser.getUserId().toString());
        return toAjax(fsStoreVerifyCodeScrmService.insertFsStoreVerifyCodeScrm(fsStoreVerifyCodeScrm));
    }

    /**
     * 修改核销码
     */
    @PreAuthorize("@ss.hasPermi('shop:scrm:edit')")
    @Log(title = "核销码", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FsStoreVerifyCodeScrm fsStoreVerifyCodeScrm)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        fsStoreVerifyCodeScrm.setUpdateBy(loginUser.getUserId().toString());
        return toAjax(fsStoreVerifyCodeScrmService.updateFsStoreVerifyCodeScrm(fsStoreVerifyCodeScrm));
    }

    /**
     * 删除核销码
     */
    @PreAuthorize("@ss.hasPermi('shop:scrm:remove')")
    @Log(title = "核销码", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        return toAjax(fsStoreVerifyCodeScrmService.deleteFsStoreVerifyCodeScrmByIds(ids,loginUser.getUserId()));
    }

    @GetMapping("/downloadTemplate")
    public AjaxResult downloadTemplate() {
        ExcelUtil<FsStoreVerifyCodeDTO> util = new ExcelUtil<>(FsStoreVerifyCodeDTO.class);
        return util.importTemplateExcel("溯源码那导入模板");
    }

    /**
     * 溯源码导入
     * @param file 导入文件
     * @return R
     * **/
    @Log(title = "核销码批量导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('shop:scrm:importExpress')")
    @PostMapping("/importExpress")
    public R importExpress(@RequestParam("file") MultipartFile file,@RequestParam("productId") Long productId) {
        // 1. 检查文件是否为空
        if (file.isEmpty()) {
            return R.error("上传的文件不能为空");
        }
        // 2. 检查文件大小
        if (file.getSize() > MAX_FILE_SIZE) {
            return R.error("文件大小不能超过5MB");
        }
        // 3. 检查文件扩展名
        String fileName = file.getOriginalFilename();
        if (fileName == null || !isValidExcelFile(fileName)) {
            return R.error("请上传Excel文件（.xlsx或.xls格式）");
        }

        ExcelUtil<FsStoreVerifyCodeDTO> util=new ExcelUtil<>(FsStoreVerifyCodeDTO.class);
        try {
            List<FsStoreVerifyCodeDTO> dtoList = util.importExcel(file.getInputStream());
            if(!dtoList.isEmpty()){
                if(dtoList.size() > 200){
                    R.error("操作失败，导入数据不能大于200条！");
                }
                LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
                return fsStoreVerifyCodeScrmService.importExpress(dtoList,String.valueOf(loginUser.getUserId()),productId);
            }else {
                R.error("操作失败，导入数据不能小于1条！");
            }
        }catch (Exception e){
            e.getStackTrace();
        }
        return R.ok();
    }

    /**
     * 核销码核销
     * @return R
     * **/
    @PreAuthorize("@ss.hasPermi('shop:scrm:writeOff')")
    @Log(title = "核销码核销", businessType = BusinessType.IMPORT)
    @PostMapping("/writeOff")
    public R writeOff(@RequestBody WriteOffDTO writeOffDTO){
        if (writeOffDTO.getIds() == null || writeOffDTO.getIds().length == 0) {
            return R.error("操作失败，核销ID列表不能为空！");
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        return fsStoreVerifyCodeScrmService.writeOff(writeOffDTO.getIds(),String.valueOf(loginUser.getUserId()));
    }


    // 检查文件是否为有效的Excel文件
    private boolean isValidExcelFile(String fileName) {
        for (String ext : ALLOWED_EXCEL_EXTENSIONS) {
            if (fileName.toLowerCase().endsWith(ext)) {
                return true;
            }
        }
        return false;
    }
}
