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.GbDataExcelDO;
import com.bootdo.datas.domain.GbDataExcelExpDO;
import com.bootdo.datas.domain.GyDataExcelDO;
import com.bootdo.datas.dto.GyDataImportDTO;
import com.bootdo.datas.service.DataService;
import com.bootdo.datas.service.GyDataService;
import com.bootdo.datas.tools.ExcelUtils;
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.BeanUtils;
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;


/**
 * 重要数据表
 *
 * @author admin
 * @email admin@163.com
 * @date 2022-03-06 10:37:54
 */

@Controller
@RequestMapping("/datas/data")
public class DataController {

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


    @Autowired
    private GyDataService gyDataService;

    @GetMapping()
    @Log("访问数据目录")
    @RequiresPermissions("datas:data:data")
    String Data() {

        return "datas/data/data";
    }

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

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

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("datas:data:data")
    public PageUtils list(@RequestParam Map<String, Object> params) {
        // 查询列表数据

        Query query = new Query(params);
        query.put("dataStatusArrs", Lists.newArrayList(3));
        query.put("auditStageMenu", "2");
        query.put("neqDataStatus", "4");

        List<GyDataImportDTO> dataList = gyDataService.list(query);
        int total = gyDataService.countTotal(query);
        PageUtils pageUtils = new PageUtils(dataList, total);
        return pageUtils;
    }

    @ResponseBody
    @GetMapping("/listNoPerms")
    public PageUtils listNoPerms(@RequestParam Map<String, Object> params) {
        // 查询列表数据

        Query query = new Query(params);
        query.put("dataStatusArrs", Lists.newArrayList(3));
        query.put("auditStageMenu", "2");
        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:data:add")
    String add() {
        return "datas/data/add";
    }

    /**
     * @Description: 跳转批量导入页面
     * @Author: wangp
     * @Date: 2022/3/21 10:06
     * @param
     * @Return: String
     */
    @GetMapping("/batchAdd")
    @RequiresPermissions("datas:data:data")
    String batchAdd() {
        return "datas/data/batchAdd";
    }

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

    /**
     * 密文导入
     */
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("datas:data: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)) {
                // dataService.save(file);
                // 文件解密
                String decFlg = gyDataService.dec(file);
                log.info("decFlg:" + decFlg);
                if (StringUtils.isNotBlank(decFlg)) {
                    String reault = gyDataService.cipherTextImport(decFlg, 2);
                    if (!ObjectUtils.isEmpty(reault)) {
                        return R.ok(fileName + ":" + reault);
                    }
                } 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:data:remove")
    public R remove(Long id) {
        //判断一下该条数据是否被风评系统使用
        int cnt = gyDataService.countAaAssData(id);
        if(cnt > 0){
            return R.error("该条数据已经被风评系统使用，不能删除！");
        }
        Long[] longArray = new Long[]{id};
        gyDataService.batchRemove(longArray);
        return R.ok();
    }

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

    /**
     * @Description: 列表页面 审核通过
     * @Author: wangp
     * @Date: 2022/3/6 16:35
     * @param id
     * @Return: R
     */
    @PostMapping("/verify")
    @ResponseBody
    @RequiresPermissions("datas:data:verify")
    public R verify(Long id) {
        log.info("审核通过 id:" + id);
        GyDataImportDTO data = new GyDataImportDTO();
        // 0:待审核 1:删除 2:已上报 3:通过审核 4:驳回
        data.setId(id);
        data.setDataStatus("3");
        gyDataService.updateStatus(data,"");
        return R.ok();
    }

    /**
     * @Description: 批量审核
     * @Author: wangp
     * @Date: 2022/3/6 16:35
     * @param ids
     * @Return: R
     */
    @PostMapping("/batchVerify")
    @ResponseBody
    @RequiresPermissions("datas:data:verify")
    public R batchVerify(@RequestParam("ids[]") Long[] ids) {
        log.info("批量审核通过 ids:" + ids.toString());
        List<String> failedDataNames = new ArrayList<>();
        List<GyDataImportDTO> dataImportDTOList = new ArrayList<>();
        for (Long id : ids) {
            log.info("审核通过 id:" + id);
            GyDataImportDTO data = new GyDataImportDTO();
            // 判断是否已审核过
            data = gyDataService.get(id);
            log.info("status:" + data.getDataStatus());
            if ("2".equals(data.getDataStatus()) || "5".equals(data.getDataStatus())
                || "6".equals(data.getDataStatus())) {
                // 0:待审核 1:删除 2:已上报 3:通过审核 4:驳回 5:联合审批 6:终审
                data.setId(id);
                data.setDataStatus("3");
                dataImportDTOList.add(data);
            } else {
                failedDataNames.add(data.getDataName());
            }
        }
        if (failedDataNames.size() > 0) {
            return R.error(String.join(",", failedDataNames) + ",审核失败");
        } else {
            if(dataImportDTOList.size() > 0){
                for(GyDataImportDTO importDTO : dataImportDTOList){
                    gyDataService.updateStatus(importDTO,"");
                }
            }
        }
        return R.ok();
    }

    /**
     * @Description: 列表页面 驳回
     * @Author: wangp
     * @Date: 2022/3/6 16:35
     * @param id
     * @Return: R
     */
    @PostMapping("/rebut")
    @ResponseBody
    @RequiresPermissions("datas:data:rebut")
    public R rebut(Long id,String opinion) {
        log.info("驳回  id:" + id);
        GyDataImportDTO data = new GyDataImportDTO();
        // 0:正常 1:删除 2:已上报 3:通过审核 4:驳回
        data.setId(id);
        data.setDataStatus("4");
        gyDataService.updateStatus(data,opinion);
        return R.ok();
    }

    /**
     * @Description: 批量审核
     * @Author: wangp
     * @Date: 2022/3/3 14:10
     * @param ids
     * @Return: R
     */
    @PostMapping("/batchRebut")
    @ResponseBody
    @RequiresPermissions("datas:data:rebut")
    public R batchRebut(@RequestParam("ids[]") Long[] ids,@RequestParam("opinion")String opinion) {
        log.info("审核通过 备案主键 ids:" + ids);
        List<String> failedDataNames = new ArrayList<>();
        List<GyDataImportDTO> dataImportDTOList = new ArrayList<>();
        for (Long id : ids) {
            log.info("审核通过 id:" + id);
            GyDataImportDTO data = new GyDataImportDTO();
            // 判断是否已审核过
            data = gyDataService.get(id);
            log.info("status:" + data.getDataStatus());
            if ("2".equals(data.getDataStatus()) || "5".equals(data.getDataStatus())
                || "6".equals(data.getDataStatus())) {
                // 0:待审核 1:删除 2:已上报 3:通过审核 4:驳回 5:联合审批 6:终审
                data.setId(id);
                data.setDataStatus("4");
                dataImportDTOList.add(data);
            } else {
                failedDataNames.add(data.getDataName());
            }
        }
        if (failedDataNames.size() > 0) {
            return R.error(String.join(",", failedDataNames) + ",驳回失败");
        } else {
            if(dataImportDTOList.size() > 0){
                for(GyDataImportDTO importDTO : dataImportDTOList){
                    gyDataService.updateStatus(importDTO,opinion);
                }
            }
        }
        return R.ok();
    }

    /**
     * @Description: 批量导出
     * @Author: wangp
     * @Date: 2022/3/16 10:46
     * @param idValue
     * @Return: R
     */
    @GetMapping("/batchExports")
    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("/gbExports")
    @RequiresPermissions("datas:data:gbExport")
    public void gbExports(HttpServletResponse responses, String idValue) {
        log.info("批量导出 备案主键 idvalue:" + idValue);
        List<GbDataExcelExpDO> 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));
            GbDataExcelDO dataDb = gyDataService.getGbDataExcel(Long.parseLong(id));
            GbDataExcelExpDO data = new GbDataExcelExpDO();
            BeanUtils.copyProperties(dataDb,data);
            data.setNo(i + 1); //序号
            list.add(data);
        }
        log.info("list size:" + list.size());
        // 导出xlsx操作
        try {
            ExcelUtils.export(responses, GbDataExcelExpDO.class, list, "国办导出信息");
        } catch (Exception e) {
            log.error("export error", e);
        }
    }

    /**
     * @Description: 加密导出
     */
    @GetMapping("/encryptExports")
    @RequiresPermissions("datas:data: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: 联合审批
     * @Author: wangp
     * @Date: 2022/3/6 16:35
     * @param ids
     * @Return: R
     */
    @PostMapping("/nextVerify/{deptId}")
    @ResponseBody
    @RequiresPermissions("datas:data:nextVerify")
    public R nextVerify(@RequestParam("ids[]") Long[] ids, @PathVariable("deptId") Long deptId) {
        log.info("联合审批通过 ids:" + ids.toString());
        log.info("联合审批通过 deptId:" + deptId);
        for (Long id : ids) {
            log.info("联合审批通过 id:" + id);
            GyDataImportDTO data = new GyDataImportDTO();
            // 判断是否已审核过
            data = gyDataService.get(id);
            log.info("status:" + data.getDataStatus());
            if ("2".equals(data.getDataStatus())) {
                // 0:待审核 1:删除 2:已上报 3:通过审核 4:驳回
                data.setId(id);
                data.setSendVerify("3");
                data.setNextVerifyDept(deptId);
                gyDataService.updateStatus(data,"");
            }
        }
        return R.ok();
    }


    /**
     * @Description: 跳转批量导入页面
     * @Author: wangp
     * @Date: 2022/3/21 10:06
     * @param
     * @Return: String
     */
    @GetMapping("/dataImport")
    @RequiresPermissions("datas:data:plainTextImport")
    String dataImport() {
        return "datas/data/dataImport";
    }

    /**
     * @Description: 明文导入
     * @Author: wangp
     * @Date: 2022/6/10 15:01
     * @param file
     * @Return: R
     */
    @ResponseBody
    @PostMapping("/plainTextImport")
    @RequiresPermissions("datas:data: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, 2);
                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("导入失败");
        }
    }

}
