package jnpf.cultivate.v2.controller.web.identify;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import io.swagger.v3.oas.annotations.Operation;
import jnpf.base.ActionResult;
import jnpf.base.vo.PageListVO;
import jnpf.constant.MsgCode;
import jnpf.cultivate.v2.service.FtbCultivateIdentifyCategoriesService;
import jnpf.cultivate.v2.service.FtbCultivateIdentifyItemsPoolService;
import jnpf.cultivate.v2.service.FtbCultivateLabelService;
import jnpf.cultivate.v2.service.V2CultivateIdentifyTableService;
import jnpf.cultivate.v2.util.CultivateIdentityUtil;
import jnpf.model.cultivate.CultivatePage;
import jnpf.model.cultivate.po.FtbCultivateIdentifyCategories;
import jnpf.model.cultivate.po.FtbCultivateIdentifyItemsPool;
import jnpf.model.cultivate.v2.identify.req.V2IdentifyTableImportSaveReq;
import jnpf.model.cultivate.v2.identify.req.V2IdentifyTableListReq;
import jnpf.model.cultivate.v2.identify.req.V2IdentifyTableSaveReq;
import jnpf.model.cultivate.v2.identify.vo.*;
import jnpf.model.cultivate.v2.label.vo.FtbCultivateLabelVo;
import jnpf.util.RedisUtil;
import jnpf.util.excel.EasyExcelUtils;
import jnpf.util.excelv2.util.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * web实操鉴定表模块
 *
 * @author xgl
 */
@Slf4j
@RestController
@RequestMapping(value = "/v2/web/identify/")
public class V2CultivateIdentifyController {


    @Autowired
    private V2CultivateIdentifyTableService v2CultivateIdentifyTableService;

    @Autowired
    private FtbCultivateIdentifyCategoriesService ftbCultivateIdentifyCategoriesService;

    @Autowired
    private FtbCultivateLabelService ftbCultivateLabelService;

    @Autowired
    private FtbCultivateIdentifyItemsPoolService ftbCultivateIdentifyItemsPoolService;

    @Autowired
    private RedisUtil redisUtil;


    /**
     * 鉴定表/列表
     *
     * @param req 帅选条件
     * @return
     * @
     */
    @Operation(summary = "列表")
    @GetMapping(value = "/page-list")
    public ActionResult<PageListVO<V2IdentifyTableListVo>> getPageList(@Valid V2IdentifyTableListReq req) {
        return ActionResult.success(CultivatePage.coverPageList(v2CultivateIdentifyTableService.getPageList(req)));
    }

    /**
     * 鉴定表/详情
     *
     * @return
     * @
     */
    @Operation(summary = "详情")
    @GetMapping(value = "/get/{tableId}")
    public ActionResult<V2IdentifyTableInfoVo> getInfo(@PathVariable("tableId") String tableId) {
        return ActionResult.success(v2CultivateIdentifyTableService.getInfo(tableId));
    }


    /**
     * 按分类获取鉴定表
     *
     * @return
     */
    @Operation(summary = "详情")
    @GetMapping(value = "/getTableForCate")
    public ActionResult<List<V2CateIdentifyTableVo>> getTableForCate() {
        return ActionResult.success("成功", v2CultivateIdentifyTableService.getTableForCate());

    }

    /**
     * 鉴定表/新增
     *
     * @return
     * @
     */
    @Operation(summary = "新增")
    @PostMapping(value = "/add")
    public ActionResult<Boolean> save(@Valid @RequestBody V2IdentifyTableSaveReq req) {
        v2CultivateIdentifyTableService.saveData(req);
        return ActionResult.success("操作成功", true);
    }

    /**
     * 鉴定表/修改
     *
     * @return
     */
    @Operation(summary = "修改")
    @PutMapping(value = "/update/{tableId}")
    public ActionResult<Boolean> update(@PathVariable("tableId") String tableId, @Valid @RequestBody V2IdentifyTableSaveReq req) {
        v2CultivateIdentifyTableService.updateData(tableId, req);
        return ActionResult.success(MsgCode.SU004.get());
    }


    /**
     * 鉴定表/删除
     *
     * @return
     * @
     */
    @Operation(summary = "删除")
    @DeleteMapping(value = "/delete/{tableId}")
    public ActionResult<Boolean> delete(@PathVariable("tableId") String tableId) {
        v2CultivateIdentifyTableService.deleteData(tableId);
        return ActionResult.success("删除成功", true);
    }


    /**
     * 鉴定表导入
     *
     * @param file
     * @return
     */
    @PostMapping("/table/import")
    public ActionResult<V2PreIdentifyImportVo> importData(@RequestPart("file") MultipartFile file) throws IOException {

        List<FtbCultivateIdentifyCategories> itemCateList = ftbCultivateIdentifyCategoriesService.getAllList();
        List<FtbCultivateLabelVo> labelVoList = ftbCultivateLabelService.getList(2, 0);
        if (CollUtil.isEmpty(itemCateList)) {
            throw new RuntimeException("请先添加鉴定项分类");
        }
        if (CollUtil.isEmpty(labelVoList)) {
            throw new RuntimeException("请先添加鉴定表标签");
        }
        InputStream inputStream = file.getInputStream();
        List<List<String>> lists = CultivateIdentityUtil.readIrregularExcelRowByRow(inputStream);
        long oldTableNum = 0L;
        if (CollUtil.isNotEmpty(lists)) {
            String tableName = lists.get(0).get(1);
            if (StringUtils.isNotEmpty(tableName)) {
                oldTableNum = v2CultivateIdentifyTableService.queryByTableName(tableName);
            }
        }
        List<FtbCultivateIdentifyItemsPool> poolList = ftbCultivateIdentifyItemsPoolService.listAll();
        V2IdentifyTableImportSaveReq v2IdentifyTableSaveReq = CultivateIdentityUtil.convertExcelData(lists, itemCateList, labelVoList, oldTableNum, poolList);
        if (CollUtil.isNotEmpty(v2IdentifyTableSaveReq.getPreIdentifyImportVo().getItemList())) {
            v2IdentifyTableSaveReq.getPreIdentifyImportVo().setIsSuccess(false);
            redisUtil.insert(v2IdentifyTableSaveReq.getPreIdentifyImportVo().getUniqueId(), v2IdentifyTableSaveReq.getPreIdentifyImportVo(), 60 * 60);
        } else {
            v2CultivateIdentifyTableService.importData(v2IdentifyTableSaveReq);
        }

        return ActionResult.success("成功", v2IdentifyTableSaveReq.getPreIdentifyImportVo());

    }

    /**
     * 鉴定表错误导出
     *
     * @param key key
     */
    @PostMapping("/table/down-error/{key}")
    public void downError(@PathVariable(name = "key") String key, HttpServletResponse response) throws IOException {
        if (!redisUtil.exists(key)) {
            throw new RuntimeException("导入数据已过期，请重新导入!");
        }
        V2PreIdentifyImportVo data = JSON.parseObject(redisUtil.getString(key).toString(), V2PreIdentifyImportVo.class);
        if (data == null || CollUtil.isEmpty(data.getItemList())) {
            throw new RuntimeException("无异常数据可以导出");
        }
        ExcelUtils<V2PreIdentifyErrorVo> util = new ExcelUtils<>(V2PreIdentifyErrorVo.class);
        util.exportExcel(response, "鉴定表导入异常数据.xlsx", "鉴定表导入异常数据", data.getItemList());
    }

    /**
     * 下载导入模版
     *
     * @param response 响应
     * @throws IOException 抛出异常
     */
    @GetMapping("/table/down-template")
    public void importTemplate(HttpServletResponse response) throws IOException {
        List<String> allNameList = ftbCultivateIdentifyCategoriesService.getAllNameList();
        List<FtbCultivateLabelVo> labelVoList = ftbCultivateLabelService.getList(2, 0);
        ExcelUtils.setResponseHeader(response, "鉴定表下载模版.xlsx");
        InputStream inputStream = EasyExcelUtils.checkExcelFile("https://jnpf-resource-1304460613.cos.ap-chengdu.myqcloud.com/jnpf-resources/v2/face/xlsx/%E9%89%B4%E5%AE%9A%E8%A1%A8%E5%AF%BC%E5%85%A5%E6%A8%A1%E7%89%88.xlsx");
//        InputStream inputStream = EasyExcelUtils.checkExcelFile("http://127.0.0.1/1.xlsx");

        Workbook workbook = WorkbookFactory.create(inputStream);
        Sheet sheetAt = workbook.getSheetAt(0);
        String[] itemCategoryNameList = new String[]{};
        if (CollUtil.isNotEmpty(allNameList)) {
            itemCategoryNameList = allNameList.toArray(new String[0]);
        }
        ExcelUtils.setPromptOrValidation(sheetAt, itemCategoryNameList, "", 6, 1000, 2, 2);
        String[] lableNameList = new String[]{};
        if (CollUtil.isNotEmpty(labelVoList)) {
            ExcelUtils.setCellValue(sheetAt, 1, 1, labelVoList.get(0).getName());
            lableNameList = labelVoList.stream().map(FtbCultivateLabelVo::getName).toArray(String[]::new);
        }
        ExcelUtils.setPromptOrValidation(sheetAt, lableNameList, "", 1, 1, 1, 1);

        workbook.write(response.getOutputStream());


    }
}


