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.ExamineLogDTO;
import com.bootdo.datas.dto.GyDataImportDTO;
import com.bootdo.datas.service.DataService;
import com.bootdo.datas.service.ExamineLogService;
import com.bootdo.datas.service.GyDataService;
import com.bootdo.datas.tools.ExcelUtils;
import com.bootdo.system.domain.UserDO;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang.ObjectUtils;
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.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

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


/**
 * 数据审核
 */

@Controller
@RequestMapping("/datas/dataVerify")
public class DataVerifyController {

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

    @Value("${managerValue}")
    public String managerValue;

    @Autowired
    private GyDataService gyDataService;
    @Autowired
    private ExamineLogService examineLogService;

    @GetMapping()
    @Log("访问数据审核")
    @RequiresPermissions("datas:dataVerify:data")
    String Data() {

        return "datas/dataVerify/data";
    }

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

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("datas:dataVerify:data")
    public PageUtils list(@RequestParam Map<String, Object> params) {
        UserDO currUser = ShiroUtils.getUser();
        // 查询列表数据
        Query query = new Query(params);
        if (!managerValue.contains(currUser.getDeptId().toString())) {
            if (currUser.getExamineRoleId() != null) {
                query.put("roleId", String.valueOf(currUser.getExamineRoleId()));
            } else { //不是管理员部门且也不是审核员类型角色的不允许看
                query.put("roleId", "-1");
            }
        }
        String dataStatus = (String) params.get("dataStatus");
        if(StringUtils.isNotEmpty(dataStatus)) {
            query.put("dataStatusArrs", Lists.newArrayList((dataStatus)));
        } else {
            query.put("dataStatusArrs", Lists.newArrayList(2,3,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:dataVerify:edit")
    String edit(@PathVariable("id") Long id, Model model) {
        GyDataImportDTO data = gyDataService.get(id);
        Map<String, Object> reqParamMap = Maps.newHashMap();
        reqParamMap.put("dataType", "DI_OPER");
        reqParamMap.put("uniqueKey", id);
        List<ExamineLogDTO> examineLogList = examineLogService.list(reqParamMap);
        model.addAttribute("data", data);
        if (!CollectionUtils.isEmpty(examineLogList)) {
            model.addAttribute("examineLog", examineLogList);
        }
        return "datas/dataVerify/edit";
    }

    /**
     * @Description: 列表页面 审核通过
     * @Author: wangp
     * @Date: 2022/3/6 16:35
     * @param id
     * @Return: R
     */
    @PostMapping("/verify")
    @ResponseBody
    @RequiresPermissions("datas:dataVerify: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:dataVerify: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())) {
                // 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:dataVerify: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");
        data.setAuditStage("1");
        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:dataVerify: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())) {
                // 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")
    @RequiresPermissions("datas:dataVerify: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:dataVerify: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:dataVerify:nextVerify")
    public R nextVerify(@RequestParam("ids[]") Long[] ids, @PathVariable("deptId") Long deptId) {
        log.info("联合审批通过 ids:" + ids.toString());
        log.info("联合审批通过 deptId:" + deptId);
        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())) {
                // 0:正常 1:删除 2:已上报 3:通过审核 4:驳回
                data.setId(id);
                data.setDataStatus("2");
                data.setSendVerify("3");
                data.setNextVerifyDept(deptId);
                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/3 14:10
     * @param ids
     * @Return: R
     */
    @PostMapping("/expert")
    @ResponseBody
    @RequiresPermissions("datas:dataVerify:expert")
    public R expert(@RequestParam("ids[]") Long[] ids) {
        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());
            //送审状态  0 未送审 1 送审 2 专家审核
            log.info("status:" + data.getSendVerify());
            if ("1".equals(data.getSendVerify()) && "2".equals(data.getDataStatus())) {
                data.setId(id);
                data.setSendVerify("2");// 0 未送审 1 送审 2 专家审核
                // 0:待审核 1:删除 2:审核中  3:通过审核 4:驳回 5:联合审批 6:终审
//                data.setDataStatus("6");
                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();
    }



}
