package com.bootdo.datas.controller;

import com.alibaba.fastjson.JSONArray;
import com.bootdo.common.annotation.Log;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.datas.domain.ExpertOpinionDO;
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.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.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/expertVerify")
public class DataExpertController {

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

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

    @GetMapping()
    @Log("访问专家审核")
    @RequiresPermissions("datas:expertVerify:data")
    String Data() {

        return "datas/expertVerify/data";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("datas:expertVerify: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("sendVerify", "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("/edit/{id}")
    @RequiresPermissions("datas:expertVerify: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/expertVerify/edit";
    }

    @GetMapping("/expertOpinion/{id}")
    @RequiresPermissions("datas:expertVerify:addExpertOpinion")
    String expertOpinion(@PathVariable("id") Long id, Model model) {
        model.addAttribute("id", id);
        return "datas/expertVerify/expertOpinion";
    }

    /**
     * @Description: 专家意见
     * @Author: stw
     * @Date: 2024/7/13 14:10
     * @param expertOpinionDO
     * @Return: R
     */
    @PostMapping("/addExpertOpinion")
    @ResponseBody
    @RequiresPermissions("datas:expertVerify:addExpertOpinion")
    public R addExpertOpinion(ExpertOpinionDO expertOpinionDO) {
        log.info("专家意见 备案主键 id:" + expertOpinionDO.getId());
        gyDataService.addExpertOpinion(expertOpinionDO);
        return R.ok();
    }

    /**
     * @Description: 列表页面 审核通过
     * @Author: wangp
     * @Date: 2022/3/6 16:35
     * @param id
     * @Return: R
     */
    @PostMapping("/verify")
    @ResponseBody
    @RequiresPermissions("datas:expertVerify: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:expertVerify: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:expertVerify: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:expertVerify: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")
    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: 联合审批
     * @Author: wangp
     * @Date: 2022/3/6 16:35
     * @param ids
     * @Return: R
     */
    @PostMapping("/nextVerify/{deptId}")
    @ResponseBody
    @RequiresPermissions("datas:expertVerify: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.setDataStatus("2");
                data.setSendVerify("3");
                data.setNextVerifyDept(deptId);
                gyDataService.updateStatus(data,"");
            }
        }
        return R.ok();
    }

}
