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.BMaintenancePlan;
import cn.cecep.talroad.domain.analysis.BMaintenancePlanInfo;
import cn.cecep.talroad.feign.BaseRegionService;
import cn.cecep.talroad.service.analysis.BCoDischargePlanService;
import cn.cecep.talroad.service.analysis.BMaintenancePlanInfoService;
import cn.cecep.talroad.service.analysis.BMaintenancePlanService;
import cn.cecep.talroad.vo.analysis.MaintenancePlanAllInfo;
import cn.cecep.talroad.vo.query.analysis.BMaintenancePlanQuery;
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("maintenancePlan")
@Api(tags = "检修计划")
public class BMaintenancePlanController {

    @Autowired
    private BMaintenancePlanService planService;

    @Autowired
    private BMaintenancePlanInfoService planInfoService;

    @Autowired
    private BCoDischargePlanService coDischargePlanService;
    @Autowired
    @Qualifier("baseRegionService")
    private BaseRegionService baseRegionService;


    @ApiOperation(value = "查询检修计划列表")
    @GetMapping("/list")
    public AjaxResults<IPage<BMaintenancePlan>> getPlanList(BMaintenancePlanQuery query){
        Page<BMaintenancePlan> page=new Page<>(query.getPageNum(),query.getPageSize());
        query.setDeleteStatus(0);
        query.setFactoryId(SecurityUtils.getLoginUser().getSysUser().getFactoryId());
        IPage<BMaintenancePlan> list = planService.page(page, BMaintenancePlanQuery.createLambdaQueryWrapper(query));
        return AjaxResults.success(list);
    }
    @ApiOperation(value = "查询检修计划详情")
    @GetMapping("/info/{planId}")
    public AjaxResults<List<BMaintenancePlanInfo>> getPlanInfo(@PathVariable(name = "planId") Integer  planId){

        HashMap<String, Object> columnMap = new HashMap<>();
        columnMap.put("plan_id",planId);
        List<BMaintenancePlanInfo> list = planInfoService.listByMap(columnMap);
        return AjaxResults.success(list);
    }
    @ApiOperation(value = "编辑检修计划详情")
    @PostMapping("/updateInfo/{planId}/{type}")
    @Log(title = "编辑检修计划详情",businessType = BusinessType.UPDATE)
    @Transactional(rollbackFor = Exception.class)
    public AjaxResults<Boolean> updatePlanInfo(@RequestBody List<BMaintenancePlanInfo>  infos,
                                               @PathVariable(name = "type") Integer type,
                                               @PathVariable(name = "planId") Integer planId){
        planInfoService.updatePlanInfo(infos,planId);
        BMaintenancePlan plan =new BMaintenancePlan();
        plan.setPlanId(planId);
        plan.setReportStatus(type);
        return  AjaxResults.success(planService.updateById(plan));
    }
    @ApiOperation(value = "更新检修计划--删除 传递deleteStatus=1")
    @PostMapping("/update")
    @Log(title = "更新CO放散计划",businessType = BusinessType.UPDATE)
    @Transactional(rollbackFor = Exception.class)
    public AjaxResults<Boolean> updatePlan(@RequestBody BMaintenancePlan  plan){
        planService.updateById(plan);
        return AjaxResults.success(true);
    }
    @ApiOperation(value = "查询检修计划详情列表--新增和编辑时使用的查询详情")
    @GetMapping({"/infoList/{planId}","/infoList"})
    public AjaxResults<List<BMaintenancePlanInfo>> getInfoList(@PathVariable(name = "planId" ,required = false) Integer planId){
        return AjaxResults.success(planInfoService.selectAllDeviceService(SecurityUtils.getLoginUser().getSysUser().getFactoryId(),planId));
    }

    @ApiOperation(value = "查询检修计划详情列表--app端新增和编辑时使用的查询详情(分页)")
    @GetMapping("/infoPageList")
    public AjaxResults<IPage<BMaintenancePlanInfo>> infoPageList(BMaintenancePlanQuery bMaintenancePlanQuery){
        Page<BMaintenancePlanInfo> page = new Page<>(bMaintenancePlanQuery.getPageNum(), bMaintenancePlanQuery.getPageSize());
        planInfoService.infoPageList(page,SecurityUtils.getLoginUser().getSysUser().getFactoryId(),bMaintenancePlanQuery);
        return AjaxResults.success(page);
    }

    @ApiOperation(value = "保存检修计划-type传递0：暂存，1：提交")
    @PostMapping("/add/{type}")
    @Log(title = "添加检修计划",businessType = BusinessType.INSERT)
    @Transactional(rollbackFor = Exception.class)
    public AjaxResults<Boolean> addPlanInfos(@RequestBody List<BMaintenancePlanInfo>  planInfos,@PathVariable(name = "type") Integer type){
        List<BMaintenancePlanInfo> collect = planInfos.stream().filter(p -> p.getPlanStartTime() != null && p.getPlanEndTime() != null).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(collect)){
            return AjaxResults.success();
        }
        BMaintenancePlan plan=new BMaintenancePlan();
        BCoDischargePlan coDischargePlan = coDischargePlanService.newPlan(SecurityUtils.getLoginUser().getSysUser().getFactoryId());
        plan.setFactoryId(coDischargePlan.getFactoryId());
        plan.setFactoryName(coDischargePlan.getFactoryName());
        plan.setPlanNumber(collect.size());
        plan.setIndustryCategoryName(coDischargePlan.getIndustryCategoryName());
        plan.setReportStatus(type);
        plan.setCreateTime(new Date());
        plan.setCreateUser(SecurityUtils.getLoginUser().getSysUser().getNickName());
        plan.setDeleteStatus(0);
        planService.save(plan);
        for (BMaintenancePlanInfo info : collect) {
            info.setPlanId(plan.getPlanId());
        }
        planInfoService.saveOrUpdateBatch(collect);
        return AjaxResults.success(true);
    }

    @ApiOperation(value = "查询检修计划全信息列表---产治排接口")
    @GetMapping("/AllList")
    public AjaxResults<IPage<MaintenancePlanAllInfo>> getList(MaintenancePlanAllInfo 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 = "导出检修计划全信息列表---产治排接口")
    @Log(title = "导出检修计划全信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestBody MaintenancePlanAllInfo 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<MaintenancePlanAllInfo> list = planService.selectCoAllInfoServiceList(info);
        ExcelUtil<MaintenancePlanAllInfo> util = new ExcelUtil<>(MaintenancePlanAllInfo.class);
        util.hideColumnNative(0);
        util.exportExcel(response, list, "CO放散计划列表");
    }
}
