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.domain.UnionOpinionDO;
import com.bootdo.datas.dto.ExamineLogDTO;
import com.bootdo.datas.dto.GyDataImportDTO;
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.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;


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

@Controller
@RequestMapping("/datas/unionVerify")
public class DataUnionController {

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

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

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

    @GetMapping()
    @Log("访问联合审查")
    @RequiresPermissions("datas:unionVerify:data")
    String Data() {

        return "datas/unionVerify/data";
    }

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

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("datas:unionVerify:data")
    public PageUtils list(@RequestParam Map<String, Object> params) {
        UserDO currUser = ShiroUtils.getUser();
        // 查询列表数据
        Query query = new Query(params);
        if (!managerValue.contains(currUser.getDeptId().toString())) {
            query.put("nextVerifyDept", String.valueOf(currUser.getDeptId()));
        }
        String dataStatus = (String) params.get("dataStatus");
        if (StringUtils.isNotEmpty(dataStatus)) {
            query.put("dataStatusArrs", Lists.newArrayList((dataStatus)));
        }
        query.put("sendVerify", "3");
        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:unionVerify: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/unionVerify/edit";
    }


    @GetMapping("/unionOpinion/{id}")
    @RequiresPermissions("datas:unionVerify:addUnionOpinion")
    String unionOpinion(@PathVariable("id") Long id, Model model) {
        model.addAttribute("id", id);
        return "datas/unionVerify/unionOpinion";
    }

    /**
     * @Description: 联合审核意见
     * @Author: stw
     * @Date: 2024/10/13 14:10
     * @param unionOpinionDO
     * @Return: R
     */
    @PostMapping("/addUnionOpinion")
    @ResponseBody
    @RequiresPermissions("datas:unionVerify:addUnionOpinion")
    public R addUnionOpinion(UnionOpinionDO unionOpinionDO) {
        log.info("联合审核意见 备案主键 id:" + unionOpinionDO.getId());
        gyDataService.addUnionOpinion(unionOpinionDO);
        return R.ok();
    }

    /**
     * @param id
     * @Description: 列表页面 审核通过
     * @Author: wangp
     * @Date: 2022/3/6 16:35
     * @Return: R
     */
    @PostMapping("/verify")
    @ResponseBody
    @RequiresPermissions("datas:unionVerify: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();
    }

    /**
     * @param ids
     * @Description: 批量审核
     * @Author: wangp
     * @Date: 2022/3/6 16:35
     * @Return: R
     */
    @PostMapping("/batchVerify")
    @ResponseBody
    @RequiresPermissions("datas:unionVerify: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:驳回
                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:unionVerify: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:unionVerify: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:驳回
                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);
        }
    }

}
