package com.ruoyi.web.controller.task;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.file.WordUtils;
import com.ruoyi.system.domain.task.TkChengyunTask;
import com.ruoyi.system.domain.task.TkChengyunTaskExample;
import com.ruoyi.system.service.task.TkChengyunTaskService;
import freemarker.core.XMLOutputFormat;
import freemarker.template.Configuration;
import freemarker.template.Template;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @Auther: jyx
 * @Date: 2022/7/26
 * @Description: 万石城运同步工单
 */
@Api(tags = "工单 城运任务")
@RestController
@RequestMapping("/api/task/chengyun")
public class ChengyunTaskController {

    @Autowired
    private TkChengyunTaskService tkChengyunTaskService;

    @ApiOperation("列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public String list(@RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize, String isPush, String name, String cedeventcode) {

        AjaxResult result = new AjaxResult();
        tkChengyunTaskService.getRoles(cedeventcode, name, isPush, pageNum, pageSize, result);
        return JSON.toJSONString(result);
    }

    @ApiOperation("编辑")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public String update(@RequestBody TkChengyunTask chengyunTask) {
        int result = tkChengyunTaskService.updateByPrimaryKeySelective(chengyunTask);
        if (result == 1) {
            return JSON.toJSONString(AjaxResult.success("success", chengyunTask.getCedeventcode()));
        } else {
            return JSON.toJSONString(AjaxResult.error(400, "fail"));
        }
    }

    @ApiOperation("下载")
    @GetMapping(value = "/download")
    public void download(@RequestParam(value = "cedeventcode") String cedeventcode, HttpServletRequest request, HttpServletResponse response) {
        try {
            TkChengyunTask bsWgchengyunTask = tkChengyunTaskService.selectByPrimaryKey(cedeventcode);

            // Configuration用于读取ftl文件
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("utf-8");
            configuration.setOutputFormat(XMLOutputFormat.INSTANCE);

            configuration.setClassForTemplateLoading(this.getClass(), "/template");
            Template template = configuration.getTemplate("serviceOrder.ftl");
            Map<String, Object> map = new HashMap<>();
            map.put("cedeventcode", bsWgchengyunTask.getCedeventcode());
            map.put("complaintsPhone", bsWgchengyunTask.getComplaintsPhone());
            map.put("complaintsPerson", bsWgchengyunTask.getComplaintsPerson());
            map.put("address", bsWgchengyunTask.getFsdz());
            map.put("sfsj", bsWgchengyunTask.getSfsj());
            map.put("name", bsWgchengyunTask.getName());
            map.put("nameDetail", bsWgchengyunTask.getNameDetail());
            map.put("distributeDate", bsWgchengyunTask.getCreateTime());
            map.put("deadline", bsWgchengyunTask.getEndTime());
            // word中默认的数据
            map.put("appealType", "举报");
            map.put("originType", "电话");
            map.put("townStreet", "万石镇");
            map.put("opinion", "请处理部门查看工单后，尽快核实情况并处理该问题。");

            // 浏览器端下载
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            String fileName = bsWgchengyunTask.getName() + "_" + bsWgchengyunTask.getEndTime() + ".doc";
            response.setHeader("Content-Disposition", "attachment;filename=\"" + UriUtils.encode(fileName, "utf-8") + "\"");
            Writer writer = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8));
            template.process(map, writer);
            writer.flush();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping(value = "/downloadBatch")
    public void downloadBatch(@RequestBody String[] cedeventcodeArr, HttpServletRequest request, HttpServletResponse response) {
        try {
            TkChengyunTaskExample example = new TkChengyunTaskExample();
            TkChengyunTaskExample.Criteria criteria = example.createCriteria();
            criteria.andCedeventcodeIn(Arrays.asList(cedeventcodeArr));
            List<TkChengyunTask> TkChengyunTaskList = tkChengyunTaskService.selectByExample(example);

            // 数据集
            List<Map<String, Object>> list = new ArrayList<>();
            // 文件名
            List<String> fileList = new ArrayList<>();
            for (TkChengyunTask bsWgchengyunTask : TkChengyunTaskList) {
                Map<String, Object> map = new HashMap<>();
                map.put("cedeventcode", bsWgchengyunTask.getCedeventcode());
                map.put("complaintsPhone", bsWgchengyunTask.getComplaintsPhone());
                map.put("complaintsPerson", bsWgchengyunTask.getComplaintsPerson());
                map.put("address", bsWgchengyunTask.getFsdz());
                map.put("sfsj", bsWgchengyunTask.getSfsj());
                map.put("name", bsWgchengyunTask.getName());
                map.put("nameDetail", bsWgchengyunTask.getNameDetail());
                map.put("distributeDate", bsWgchengyunTask.getCreateTime());
                map.put("deadline", bsWgchengyunTask.getEndTime());
                // word中默认的数据
                map.put("appealType", "举报");
                map.put("originType", "电话");
                map.put("townStreet", "万石镇");
                map.put("opinion", "请处理部门查看工单后，尽快核实情况并处理该问题。");
                list.add(map);
                String fileName = bsWgchengyunTask.getName() + "_" + bsWgchengyunTask.getEndTime();
                fileList.add(fileName);
            }
            //设置模板路径
            String ftlName = "/template/serviceOrder.ftl";
            WordUtils.exportWordBatch(list, fileList, ftlName, response, request);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
