package cn.cecep.talroad.controller.analysis;

import cn.cecep.talroad.common.core.domain.R;
import cn.cecep.talroad.common.core.utils.poi.ExcelUtil;
import cn.cecep.talroad.common.core.web.domain.AjaxResults;
import cn.cecep.talroad.common.log.annotation.Log;
import cn.cecep.talroad.common.log.enums.BusinessType;
import cn.cecep.talroad.common.security.utils.SecurityUtils;
import cn.cecep.talroad.domain.analysis.BCoDischargePlan;
import cn.cecep.talroad.domain.analysis.BCoDischargePlanInfo;
import cn.cecep.talroad.feign.BaseRegionService;
import cn.cecep.talroad.service.analysis.BCoDischargePlanInfoService;
import cn.cecep.talroad.service.analysis.BCoDischargePlanService;
import cn.cecep.talroad.vo.analysis.CoPlanAllInfo;
import cn.cecep.talroad.vo.query.analysis.BCoDischargePlanQuery;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.seata.common.util.CollectionUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("coDischargePlan")
@Api(tags = "CO放散计划")
public class BCoDischargePlanController {
    @Autowired
    private BCoDischargePlanService planService;
    @Autowired
    private BCoDischargePlanInfoService planInfoService;
    @Autowired
    @Qualifier("baseRegionService")
    private BaseRegionService baseRegionService;

    @ApiOperation(value = "查询CO放散计划列表")
    @GetMapping("/list")
    public AjaxResults<IPage<BCoDischargePlan>> getPlanList(BCoDischargePlanQuery query){
        Page<BCoDischargePlan> page=new Page<>(query.getPageNum(),query.getPageSize());
        query.setDeleteStatus(0);
        try {
            query.setFactoryId(SecurityUtils.getLoginUser().getSysUser().getFactoryId());
        }catch (Exception e){
            return AjaxResults.error("请使用企业账号，并确保账号未失效");
        }
        IPage<BCoDischargePlan> list = planService.page(page, BCoDischargePlanQuery.createLambdaQueryWrapper(query).orderByDesc(BCoDischargePlan.COL_PLAN_ID));
        return AjaxResults.success(list);
    }
    @ApiOperation(value = "查询CO放散计划详情")
    @GetMapping("/info/{planId}")
    public AjaxResults<List<BCoDischargePlanInfo>> getPlanInfo(@PathVariable(name = "planId") Integer  planId){
        HashMap<String, Object> columnMap = new HashMap<>();
        columnMap.put("plan_id", planId);
        List<BCoDischargePlanInfo> list = planInfoService.listByMap(columnMap);
        return AjaxResults.success(list);
    }

    @ApiOperation(value = "编辑CO放散计划详情")
    @PostMapping("/updateInfo/{planId}/{type}")
    @Log(title = "编辑CO放散计划详情",businessType = BusinessType.UPDATE)
    @Transactional(rollbackFor = Exception.class)
    public AjaxResults<Boolean> updatePlanInfo(@RequestBody List<BCoDischargePlanInfo>  infos,
                                               @PathVariable(name = "type") Integer type,
                                               @PathVariable(name = "planId") Integer planId){
        BCoDischargePlan plan =new BCoDischargePlan();
        plan.setPlanId(planId);
        planInfoService.updatePlanInfo(infos,planId);
        plan.setReportStatus(type);
        planService.updateById(plan);
        return  AjaxResults.success();
    }
    @ApiOperation(value = "更新CO放散计划--删除 传递deleteStatus=1")
    @PostMapping("/update")
    @Log(title = "更新CO放散计划",businessType = BusinessType.UPDATE)
    @Transactional(rollbackFor = Exception.class)
    public AjaxResults<Boolean> updatePlan(@RequestBody BCoDischargePlan  plan){
        planService.updateById(plan);
        return AjaxResults.success(true);
    }
    @ApiOperation(value = "查询CO放散计划详情列表")
    @GetMapping({"/infoList/{planId}","/infoList"})
    public AjaxResults<List<BCoDischargePlanInfo>> getInfoList(@PathVariable(name = "planId" ,required = false) Integer planId){
        return AjaxResults.success(planInfoService.selectAllDeviceService(SecurityUtils.getLoginUser().getSysUser().getFactoryId(),planId));
    }
    @ApiOperation(value = "保存CO放散计划-type传递0：暂存，1：提交")
    @PostMapping("/add/{type}")
    @Log(title = "添加CO放散计划",businessType = BusinessType.INSERT)
    @Transactional(rollbackFor = Exception.class)
    public AjaxResults<Boolean> addPlanInfos(@RequestBody List<BCoDischargePlanInfo>  planInfos,@PathVariable(name = "type") Integer type){
        List<BCoDischargePlanInfo> collect = planInfos.stream().filter(p -> p.getPlanStartTime() != null && p.getPlanEndTime() != null).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(collect)){
            return AjaxResults.success();
        }
        BCoDischargePlan plan = planService.newPlan(SecurityUtils.getLoginUser().getSysUser().getFactoryId());
        plan.setPlanNumber(collect.size());
        plan.setReportStatus(type);
        plan.setCreateTime(new Date());
        plan.setCreateUser(SecurityUtils.getLoginUser().getSysUser().getNickName());
        plan.setDeleteStatus(0);
        planService.save(plan);
        for (BCoDischargePlanInfo bCoDischargePlanInfo : collect) {
            bCoDischargePlanInfo.setPlanId(plan.getPlanId());
        }
        planInfoService.saveOrUpdateBatch(collect);
        return AjaxResults.success(true);
    }

    @ApiOperation(value = "查询CO放散计划全信息列表---产治排接口")
    @GetMapping("/AllList")
    public AjaxResults<IPage<CoPlanAllInfo>> getList(CoPlanAllInfo info){
        try {
            String regionCode = SecurityUtils.getLoginUser().getSysUser().getRegionCode();
            R<List<String>> r = baseRegionService.getRegionCodeListChild(regionCode);
            if(r.getCode()==200){
                info.setRegionCodes(r.getData());
            }
        }catch (Exception e){
            System.err.println("获取区域列表失败");
        }
        return     AjaxResults.success(planService.selectCoAllInfoService(info));
    }
    @ApiOperation(value = "导出CO放散计划全信息列表---产治排接口")
    @Log(title = "导出CO放散计划", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestBody CoPlanAllInfo info) {
        try {
            String regionCode = SecurityUtils.getLoginUser().getSysUser().getRegionCode();
            R<List<String>> r = baseRegionService.getRegionCodeListChild(regionCode);
            if(r.getCode()==200){
                info.setRegionCodes(r.getData());
            }
        }catch (Exception e){
            System.err.println("获取区域列表失败");
        }
        List<CoPlanAllInfo> list = planService.selectCoAllInfoServiceList(info);
        ExcelUtil<CoPlanAllInfo> util = new ExcelUtil<>(CoPlanAllInfo.class);
        util.hideColumnNative(0);
        util.exportExcel(response, list, "CO放散计划列表");
    }
}
