package com.sckw.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.sckw.core.model.constant.NumberConstant;
import com.sckw.core.model.file.FileInfo;
import com.sckw.core.utils.IdWorker;
import com.sckw.core.utils.StringUtils;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.response.HttpResult;
import com.sckw.example.dao.KwsDeptDao;
import com.sckw.example.model.KwsDept;
import com.sckw.example.model.vo.ProjectPageVo;
import com.sckw.example.model.vo.SysUserVo;
import com.sckw.example.service.ExcelExportService;
import com.sckw.excel.easyexcel.ExcelImportListener;
import com.sckw.excel.easyexcel.RequestHolder;
import com.sckw.excel.utils.DateUtil;
import com.sckw.excel.utils.ExcelUtil;
import com.sckw.file.api.dubbo.FileApiDubboService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/export")
public class ExcelExportController {

    @Autowired
    ExcelExportService excelExportService;

    @DubboReference(version = "1.0.0", group = "design", check = false)
    FileApiDubboService fileApiDubboService;

    @Autowired
    KwsDeptDao kwsDeptDao;

    /**
     * 模板下载
     *
     * @param request  请求流
     * @param response 响应流
     * @param type     模板类型
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/downloadTemplates")
    public void download(HttpServletRequest request, HttpServletResponse response, @RequestParam("type") Integer type) {
        try {
            excelExportService.downloadTemplates(request, response, type);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 单个sheet导出
     *
     * @return
     */
    @GetMapping("/export")
    public HttpResult export() {
        HttpServletResponse response = RequestHolder.getResponse();
        List<SysUserVo> list = excelExportService.export();
        if (!CollectionUtils.isEmpty(list)) {
            ExcelUtil.download(response, SysUserVo.class, list);
            return null;
        }
        return HttpResult.error("没有可导出的数据");
    }

    /**
     * 多个sheet导出
     *
     * @return
     */
    @GetMapping("/exportList")
    public HttpResult exportList() {
        HttpServletResponse response = RequestHolder.getResponse();
        List<List> list = excelExportService.exportList();
        if (!CollectionUtils.isEmpty(list)) {
            ExcelUtil.download(response, list);
            return null;
        }
        return HttpResult.error("没有可导出的数据");
    }

    /**
     * 导入
     *
     * @param file 文件
     * @param type 文件类型-指的是什么模板 用于公共导入处理
     *
     * @return
     */
    @SneakyThrows
    @RequestMapping("/importExcel")
    public HttpResult importExcel(@RequestParam("file") MultipartFile file, @RequestParam("type") @Range(min = 1, max = 10, message = "类型错误") Integer type) {
        if (ExcelUtil.checkExcel(file)) {
            throw new UnsupportedOperationException("请上传Excel格式的文件!");
        }
        String fileName = file.getOriginalFilename();
        if (StringUtils.isNotBlank(fileName) && fileName.contains("?")) {
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            fileName = "自定义" + suffix;
        }
//        String filePath = path + DateUtil.date() + File.separator +
//               DateUtil.getDateTime("yyyyMMddHHmmssSSS") + "_" + fileName;
        //String path=""; 系统定义存储文件地址，便于查看上传文件内容
        String filePath = DateUtil.date() + File.separator +
                DateUtil.getDateTime("yyyyMMddHHmmssSSS") + "_" + fileName;
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(filePath));
        ExcelImportListener importListener = new ExcelImportListener();
        return excelExportService.importExcel(file, importListener);
    }

    /**
     * 分布式事务验证
     *
     * @return
     */
    @GlobalTransactional(rollbackFor = Exception.class, name = "example-seata-service-group")
    @RequestMapping(value = "globalTransactionalDemo", method = RequestMethod.GET)
    public HttpResult globalTransactionalDemo() {
        KwsDept dos = new KwsDept();
        HttpResult result = new HttpResult();
        result.setMsg(HttpStatus.SUCCESS_MESSAGE);
        try {
            long l = new IdWorker(1).nextId();
            dos.setId(l);
            dos.setSystemType("1");
            dos.setAccount("张三");
            dos.setPassword("password");
            dos.setName("张三");
            dos.setPhone("4564789113");
            dos.setPhoto("44546545");
            dos.setEmail("45456454");
            dos.setClientId("7879814");
            dos.setIsMain(0);
            dos.setCreateBy(123L);
            dos.setUpdateBy(123L);
            dos.setCreateTime(new Date());
            dos.setUpdateTime(new Date());
//            kwsDeptDao.insert(dos);
//            KwsDept kwsDept = new KwsDept();
            int insert = kwsDeptDao.insert(dos);
            String xid = RootContext.getXID();
            System.out.println(xid);
            System.out.println(l);
            result = fileApiDubboService.selectAll();
            long nextId = new IdWorker(NumberConstant.ONE).nextId();
            dos.setId(nextId);
            int insert1 = kwsDeptDao.insert(dos);
            log.info(JSONObject.toJSONString(result));
        } catch (Exception e) {
            result.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
            result.setMsg(e.getMessage());
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * dubboFile文件调用
     *
     * @return
     */
    @RequestMapping(value = "/fileInfoInsert", method = RequestMethod.POST)
    public HttpResult fileDubboUpload(@Validated @RequestBody FileInfo fileInfo) {
        try {
            return fileApiDubboService.fileInfoInsert(fileInfo);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 导出注解翻译示例
     */
    @RequestMapping(value = "/easyExcelDemo", method = RequestMethod.GET)
    public HttpResult easyExcelDemo() {
        HttpServletResponse response = RequestHolder.getResponse();
        List<ProjectPageVo> list = excelExportService.easyExcelDemo();
        if (!CollectionUtils.isEmpty(list)) {
            ExcelUtil.download(response, ProjectPageVo.class, list);
            return null;
        }
        return HttpResult.error("没有可导出的数据");
    }
}
