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.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/dataSendProvince")
public class DataSendProvinceController {

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

    @Autowired
    private GyDataService gyDataService;

    @GetMapping()
    @Log("访问上报到省级")
    @RequiresPermissions("datas:dataSendProvince:data")
    String Data() {
        return "datas/dataSendProvince/data";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("datas:dataSendProvince:data")
    public PageUtils list(@RequestParam Map<String, Object> params) {
        // 查询列表数据
        Query query = new Query(params);
        query.put("dataStatusArrs", Lists.newArrayList(3));
        query.put("auditStageMenu", "1");
        query.put("neqDataStatus", "4");

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


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


    /**
     * @Description: 上报到省级
     */
    @PostMapping("/sendProvince")
    @ResponseBody
    @RequiresPermissions("datas:dataSendProvince:sendProvince")
    public R sendProvince(@RequestParam("ids[]") Long[] ids) {
        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())
                    && "1".equals(data.getAuditStage())
                    && "3".equals(data.getDataStatus())) {
                data.setId(id);
                data.setSendVerify("0");// 0 未送审 1 送审 2 专家审核
                // 0:待审核 1:删除 2:审核中 3:通过审核 4:驳回
                data.setDataStatus("0");
                data.setAuditStage("2");
                gyDataService.updateStatus(data,"");
            }
        }
        return R.ok();
    }

    /**
     * @Description: 加密导出
     */
    @GetMapping("/encryptExports")
    @RequiresPermissions("datas:dataSendProvince: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/16 10:46
     * @param idValue
     * @Return: R
     */
    @GetMapping("/batchExports")
    @RequiresPermissions("datas:dataSendProvince: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);
        }
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("datas:dataSendProvince:remove")
    public R remove(Long id) {
        Long[] longArray = new Long[]{id};
        gyDataService.batchRemove(longArray);
        return R.ok();
    }

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

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

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

    /**
     * 密文导入
     */
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("datas:dataSendProvince: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, 3);
                    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("导入失败");
        }
    }

}
