package cn.iocoder.yudao.module.configure.controller.admin.tracetemplate;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.io.JsonFileUtils;
import cn.iocoder.yudao.framework.common.util.string.StrUtils;
import cn.iocoder.yudao.module.configure.controller.admin.tracelink.vo.TraceLinkRespVO;
import cn.iocoder.yudao.module.configure.controller.admin.tracetemplate.vo.*;
import cn.iocoder.yudao.module.configure.convert.tracetemplate.TraceTemplateConvert;
import cn.iocoder.yudao.module.configure.dal.dataobject.tracetemplate.TraceTemplateDO;
import cn.iocoder.yudao.module.configure.service.tracetemplate.TraceTemplateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Api(tags = "管理后台 - 溯源模板")
@RestController
@RequestMapping("/configure/trace-template")
@Validated
public class TraceTemplateController {

    @Resource
    private TraceTemplateService traceTemplateService;

    @PostMapping("/create")
    @ApiOperation("创建溯源模板")
    @PreAuthorize("@ss.hasPermission('configure:trace-template:create')")
    public CommonResult<Long> createTraceTemplate(@Valid @RequestBody TraceTemplateCreateReqVO createReqVO) {
        return success(traceTemplateService.createTraceTemplate(createReqVO));
    }

    @PutMapping("/update")
    @ApiOperation("更新溯源模板")
    @PreAuthorize("@ss.hasPermission('configure:trace-template:update')")
    public CommonResult<Boolean> updateTraceTemplate(@Valid @RequestBody TraceTemplateUpdateReqVO updateReqVO) {
        traceTemplateService.updateTraceTemplate(updateReqVO);
        return success(true);
    }

    @PutMapping("/updateLinkConfig")
    @ApiOperation("更新溯源模板环节配置")
    @PreAuthorize("@ss.hasPermission('configure:trace-template:update')")
    public CommonResult<Boolean> updateLinkConfig(@Valid @RequestBody LinkConfigUpdateReqVO updateReqVO) {
        traceTemplateService.updateLinkConfig(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除溯源模板")
    @ApiImplicitParam(name = "id", value = "编号", required = true, dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermission('configure:trace-template:delete')")
    public CommonResult<Boolean> deleteTraceTemplate(@RequestParam("id") Long id) {
        traceTemplateService.deleteTraceTemplate(id);
        return success(true);
    }

    @GetMapping("/get")
    @ApiOperation("获得溯源模板")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermission('configure:trace-template:query')")
    public CommonResult<TraceTemplateRespVO> getTraceTemplate(@RequestParam("id") Long id) {
        TraceTemplateDO traceTemplate = traceTemplateService.getTraceTemplate(id);
        return success(TraceTemplateConvert.INSTANCE.convert(traceTemplate));
    }

    @GetMapping("/page")
    @ApiOperation("获得溯源模板分页")
    @PreAuthorize("@ss.hasPermission('configure:trace-template:query')")
    public CommonResult<PageResult<TraceTemplateRespVO>> getTraceTemplatePage(@Valid TraceTemplatePageReqVO pageVO) {
        return success(traceTemplateService.getTraceTemplatePage(pageVO));
    }

    @GetMapping("/getTraceTemplateListByGoodsId")
    @ApiOperation("通过商品编码获得溯源模板")
    @ApiImplicitParam(name = "goodsId", value = "商品编码", required = true, example = "GOCD202304131028TSOC", dataTypeClass = String.class)
    @PreAuthorize("@ss.hasPermission('configure:trace-template:query')")
    public CommonResult<List<TraceTemplateRespVO>> getTraceTemplateListByGoodsId(@RequestParam("goodsId") String goodsId) {
        return success(traceTemplateService.getTraceTemplateListByGoodsId(goodsId));
    }

    @GetMapping("/getLinkListByTemplateId")
    @ApiOperation("通过模板编码获得环节列表信息")
    @ApiImplicitParam(name = "templateId", value = "模板编码", required = true, example = "TATE202305081550KWXM", dataTypeClass = String.class)
    @PreAuthorize("@ss.hasPermission('configure:trace-template:query')")
    public CommonResult<List<TraceLinkRespVO>> getLinkListByTemplateId(@RequestParam("templateId") String templateId) {
        return success(traceTemplateService.getLinkListByTemplateId(templateId));
    }

    @PostMapping("/copyLinkConfigToTemplate")
    @ApiOperation("复制环节信息配置到溯源模板")
    @PreAuthorize("@ss.hasPermission('configure:trace-template:create')")
    public CommonResult<Integer> copyLinkConfigToTemplate(@Valid @RequestBody TraceTemplateCopyReqVO copyReqVO) {
        return success(traceTemplateService.copyLinkConfigToTemplate(copyReqVO));
    }

    @PostMapping("/importLinkConfig")
    @ApiOperation("导入溯源环节配置")
    @ApiImplicitParam(name = "file", value = "文件", required = true, dataTypeClass = MultipartFile.class)
    @PreAuthorize("@ss.hasPermission('product:harvest-batch:update')")
    public CommonResult<List<LinkFileVO>> importLinkConfig(@RequestParam("file") MultipartFile file) {
        List<LinkFileVO> linkFiles = JsonFileUtils.readJsonAndConvertToList(file, LinkFileVO.class);
        return CommonResult.success(linkFiles);
    }

    @GetMapping("/exportLinkConfig")
    @ApiOperation("导出溯源环节配置")
    @ApiImplicitParam(name = "templateId", value = "模板编码", required = true, example = "TATE202305081550KWXM", dataTypeClass = String.class)
    @PreAuthorize("@ss.hasPermission('product:harvest-batch:query')")
    public void exportLinkConfig(@RequestParam("templateId") @NotNull String templateId, HttpServletResponse response) {
        // 根据批次id获得环节配置信息
        List<TraceLinkRespVO> traceLinks = traceTemplateService.getLinkListByTemplateId(templateId);
        List<LinkFileVO> linkFiles = traceLinks.stream().map(link -> {
            LinkFileVO linkFile = new LinkFileVO();
            BeanUtil.copyProperties(link, linkFile);
            List<LinkItemFileVO> linkFileItems = link.getTraceLinkItems().stream().map(detail -> {
                LinkItemFileVO LinkItemFile = new LinkItemFileVO();
                BeanUtil.copyProperties(detail, LinkItemFile);
                return LinkItemFile;
            }).collect(Collectors.toList());
            linkFile.setTraceLinkItems(linkFileItems);
            return linkFile;
        }).collect(Collectors.toList());
        // 导出到前端
        JsonFileUtils.writeJsonFile(response, linkFiles, StrUtils.getRandomUpperString(10));
    }

}
