package com.bootdo.datas.controller;

import com.alibaba.fastjson.JSONArray;
import com.bootdo.common.annotation.Log;
import com.bootdo.common.utils.*;
import com.bootdo.datas.domain.GyDataExcelDO;
import com.bootdo.datas.dto.GyDataImportDTO;
import com.bootdo.datas.service.GyDataService;
import com.bootdo.datas.tools.ExcelUtils;
import com.bootdo.datas.tools.gm.FileCryptTool;
import com.google.common.collect.Lists;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/datas/gyDataImport")
public class GyDataImportController {

    private static Logger log = LoggerFactory.getLogger(GyDataImportController.class);

    @Autowired
    private GyDataService gyDataService;

    @GetMapping()
    @Log("访问数据导入")
    @RequiresPermissions("datas:gyDataImport:data")
    String Data() {

        return "datas/gyDataImport/data";
    }

    @GetMapping("dataInfo")
    @RequiresPermissions("datas:gyDataImport:data")
    String dataInfo(String type, Model model) {
        log.info("dataLevel:" + type);
        model.addAttribute("dataLevel", type);
        return "datas/gyDataImport/dataInfo";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("datas:gyDataImport:data")
    public PageUtils list(@RequestParam Map<String, Object> params) {
        // 查询列表数据
        Query query = new Query(params);
        String dataStatus = (String) params.get("dataStatus");
        if(StringUtils.isNotEmpty(dataStatus)) {
            query.put("dataStatusArrs", Lists.newArrayList((dataStatus)));
        }
        query.put("neqDataStatus", "4");
        List<GyDataImportDTO> dataList = gyDataService.list(query);
        int total = gyDataService.countTotal(query);
        PageUtils pageUtils = new PageUtils(dataList, total);
        return pageUtils;
    }

    @GetMapping("/add")
    @RequiresPermissions("datas:gyDataImport:add")
    String add() {
        return "datas/gyDataImport/add";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("datas:gyDataImport:edit")
    String edit(@PathVariable("id") Long id, Model model) {
        GyDataImportDTO data = gyDataService.get(id);
        model.addAttribute("data", data);
        return "datas/gyDataImport/edit";
    }

    /**
     * @Description: 跳转批量导入页面
     */
    @GetMapping("/batchAdd")
    @RequiresPermissions("datas:gyDataImport:data")
    String batchAdd() {
        return "datas/gyDataImport/batchAdd";
    }

    /**
     * 密文导入
     */
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("datas:gyDataImport:add")
    public R save(@RequestParam("data_file") MultipartFile file) {
        try {
            String fileName = file.getOriginalFilename();
            log.info("fileName:" + fileName);
            String type = fileName.substring(fileName.lastIndexOf(".") + 1);
            // 根据excel类型取数据
            if ("xlsx".equals(type) || "xlsx".equals(type)) {
                // 文件解密
                String decFlg = gyDataService.dec(file);
                log.info("decFlg:" + decFlg);
                if (StringUtils.isNotBlank(decFlg)) {
                    try {
                        String reault = gyDataService.cipherTextImport(decFlg, 1);
                        if (!ObjectUtils.isEmpty(reault)) {
                            return R.ok(fileName + ":" + reault);
                        }
                    } catch (Exception e) {
                        log.info("Exception:", e);
                        return R.error("文件异常！");
                    }
                } else {
                    return R.error("文件解密异常！");
                }
            } else {
                return R.error("请使用excel导入！");
            }
            return R.ok("0");
        } catch (BDException e){
            return R.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("导入失败");
        }
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("datas:gyDataImport:remove")
    public R remove(Long id) {

        Long[] longArray = new Long[]{id};
        gyDataService.batchRemove(longArray);
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("datas:gyDataImport:batchRemove")
    public R remove(@RequestParam("ids[]") Long[] ids) {
        gyDataService.batchRemove(ids);
        return R.ok();
    }

    /**
     * @Description: 批量导出
     */
    @GetMapping("/batchExports")
    @RequiresPermissions("datas:gyDataImport:export")
    public void batchExports(HttpServletResponse responses, String idValue) {
        log.info("批量导出 备案主键 idvalue:" + idValue);
        List<GyDataExcelDO> list = new ArrayList<>();
        JSONArray json = (JSONArray)JSONArray.parse(idValue);
        for (int i = 0; i < json.size(); i++) {
            String id = String.valueOf(json.get(i));
            log.info("批量导出 id:" + json.get(i));
            GyDataExcelDO data = new GyDataExcelDO();
            data = gyDataService.getDataExcel(Long.parseLong(id));
            data.setNo(i + 1); //序号
            list.add(data);
        }
        log.info("list size:" + list.size());
        // 导出xlsx操作
        try {
            ExcelUtils.export(responses, GyDataExcelDO.class, list, "数据备案导出信息");
        } catch (Exception e) {
            log.error("export error", e);
        }
    }

    /**
     * @Description: 加密导出
     */
    @GetMapping("/encryptExports")
    @RequiresPermissions("datas:gyDataImport:encryptExports")
    public void encryptExports(HttpServletResponse responses, String idValue) throws Exception {
        log.info("批量导出 备案主键 idvalue:" + idValue);
        // 导出xlsx操作
        try {
            gyDataService.encryptExports(responses,idValue);
        } catch (Exception e) {
            log.error("export error", e);
        }
    }

    /**
     * @Description: 送审
     */
    @PostMapping("/sendVerify")
    @ResponseBody
    @RequiresPermissions("datas:gyDataImport:sendVerify")
    public R sendVerify(@RequestParam("ids[]") Long[] ids, @RequestParam("roleId") Long roleId) {
        log.info("送审 ids:" + ids.toString());
        for (Long id : ids) {
            log.info("送审 id:" + id);
            GyDataImportDTO data = new GyDataImportDTO();
            // 判断是否已审核过
            data = gyDataService.get(id);
            // 送审状态 0 未送审 1 送审 2 专家审核
            log.info("status:" + data.getSendVerify());
            if ("0".equals(data.getSendVerify())) {
                data.setId(id);
                data.setSendVerify("1");// 0 未送审 1 送审 2 专家审核
                // 0:待审核 1:删除 2:审核中 3:通过审核 4:驳回 5:联合审批 6:终审
                data.setDataStatus("2");
                data.setRoleId(roleId);
                gyDataService.updateStatus(data,"");
            }
        }
        return R.ok();
    }

    /**
     * @Description: 跳转明文导入页面
     */
    @GetMapping("/dataImport")
    @RequiresPermissions("datas:gyDataImport:plainTextImport")
    String dataImport() {
        return "datas/gyDataImport/dataImport";
    }

    /**
     * @Description: 明文导入
     */
    @ResponseBody
    @PostMapping("/plainTextImport")
    @RequiresPermissions("datas:gyDataImport:plainTextImport")
    public R plainTextImport(@RequestParam("data_file") MultipartFile file) {
        try {
            String fileName = file.getOriginalFilename();
            log.info("fileName:" + fileName);
            String type = fileName.substring(fileName.lastIndexOf(".") + 1);
            // 根据excel类型取数据
            if ("xlsx".equals(type) || "xlsx".equals(type)) {
                String reault = gyDataService.plainTextImport(file, 1);
                if (!ObjectUtils.isEmpty(reault)) {
                    return R.ok(fileName + ":" + reault);
                }

            } else {
                return R.error("请使用excel导入！");
            }
            return R.ok("0");
        } catch (BDException e){
            return R.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("导入失败");
        }
    }

    public static void main(String[] args) {
        FileCryptTool.encryptFile("F:/dev-dys/sm2/sm2_client_enc_cert.crt", "F:/dev-dys/res/测试导入.xlsx", "F:/dev-dys/res/enc-测试导入.xlsx");
    }


}
