package com.artfess.yhxt.specialcheck.controller;


import com.artfess.base.annotation.ApiGroup;
import com.artfess.base.constants.ApiGroupConsts;
import com.artfess.base.context.BaseContext;
import com.artfess.base.model.CommonResult;
import com.artfess.base.query.*;
import com.artfess.uc.model.User;
import com.artfess.uc.util.ContextUtil;
import com.artfess.yhxt.basedata.manager.RoadManager;
import com.artfess.yhxt.basedata.model.Road;
import com.artfess.yhxt.disease.model.Disease;
import com.artfess.yhxt.specialcheck.vo.*;
import com.artfess.yhxt.util.PermissionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.artfess.base.controller.BaseController;
import com.artfess.yhxt.specialcheck.model.SiteInspection;
import com.artfess.yhxt.specialcheck.manager.SiteInspectionManager;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 巡检表 前端控制器
 *
 * @author xzh
 * @company 阿特菲斯信息技术有限公司
 * @since 2021-08-12
 */
@RestController
@RequestMapping("/siteInspection/v1/")
@Api(tags = "巡检管理接口")
@ApiGroup(group = {ApiGroupConsts.GROUP_BIZ})
public class SiteInspectionController extends BaseController<SiteInspectionManager, SiteInspection> {


    @Resource
    private RoadManager roadManager;

    @RequestMapping(value = "/getReport", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "获取报表信息", httpMethod = "POST")
    public List<SiteInspecionReportVO> getReport(String year,String orgId) {
        LocalDateTime now = LocalDateTime.now();
        List<SiteInspecionReportVO> vos =  new ArrayList<>();
        QueryWrapper<Road> roadWrapper = new QueryWrapper<>();
        roadWrapper.eq("IS_DELE_","0");
        roadWrapper.like("COMPANY_IDS_",orgId);
        List<Road> roads = roadManager.list(roadWrapper);
        int day = 0;
        int month = 0;
        if (now.getYear()==Integer.valueOf(year)){
            day+=now.getDayOfYear();
            month+=now.getMonthValue();
        }else {
            day+=365;
            month+=12;
        }
        for (Road road : roads){
            SiteInspecionReportVO vo = new SiteInspecionReportVO();
            int dayCount = 0;
            int nightCount = 0;
            QueryWrapper<SiteInspection> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("ROAD_SEGMENT_ID_",road.getId());
            queryWrapper.eq("IS_DELE_","0");
            queryWrapper.apply("date_format(CREATE_TIME_,'%Y') = {0}",year);
            List<SiteInspection> list = baseService.list(queryWrapper);
            dayCount = list.stream().filter(s->s.getType()==1).collect(Collectors.toList()).size();
            nightCount = list.stream().filter(s->s.getType()==2).collect(Collectors.toList()).size();
            vo.setRoadName(road.getName());
            vo.setDayCount(dayCount);
            vo.setNightCount(nightCount);

            vo.setDayRate(new BigDecimal(dayCount).divide(new BigDecimal(day),2,BigDecimal.ROUND_HALF_UP));
            vo.setNightRate(new BigDecimal(nightCount).divide(new BigDecimal(month),2,BigDecimal.ROUND_HALF_UP));
            vos.add(vo);
        }
        return vos;
    }

    @RequestMapping(value = "/getJson", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "分页查询巡检管理", httpMethod = "POST")
    public PageList<SiteInspectionVo> getJson(@ApiParam(name = "queryFilter", value = "分页查询信息") @RequestBody QueryFilter<SiteInspection> queryFilter) {
        queryFilter.addFilter("a.is_dele_", "0", QueryOP.EQUAL);
        List<FieldSort> sorter = queryFilter.getSorter();


        //设置默认排序 安装巡检日期倒序排序
        if(null == sorter || sorter.isEmpty()){
            sorter.add(new FieldSort("ID_", Direction.DESC));
            queryFilter.setSorter(sorter);
        }


        PageList<SiteInspectionVo> pageList = baseService.querySiteInspection(queryFilter);
        return pageList;
    }

    @RequestMapping(value = "/saveSiteInspectionSpecial", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "保存,修改巡检管理信息", httpMethod = "POST")
    public CommonResult<SiteInspection> saveSiteInspection(@ApiParam(name = "siteInspection", value = "巡检管理信息对象") @RequestBody SiteInspection siteInspection) throws Exception {
        String msg = "添加成功";
        if (StringUtils.isEmpty(siteInspection.getId())) {
            siteInspection.setIsDele("0");
            //User user = ContextUtil.getCurrentUser();
            baseService.create(siteInspection);
        } else {
            baseService.update(siteInspection);
            msg = "修改成功";
        }
        return new CommonResult<SiteInspection>(true, msg, siteInspection);
    }


    @RequestMapping(value = "/updateSiteInspection", method = RequestMethod.DELETE, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "逻辑删除巡检管理信息", httpMethod = "POST", notes = "逻辑删除巡检管理信息")
    public CommonResult<String> updateSiteInspection(@ApiParam(name = "ids", value = "ID集合以，隔开", required = true)
                                                     @RequestParam(value = "ids", required = true) String ids) throws Exception {
        if (StringUtils.isNotBlank(ids)) {
            List<String> idsList = Arrays.asList(ids.split(","));
            UpdateWrapper<SiteInspection> updateWrapper = new UpdateWrapper<>();
            updateWrapper.in("id_", idsList);
            updateWrapper.set("is_dele_", "1");
            baseService.update(null, updateWrapper);
        }
        return new CommonResult<>(true, "删除成功");
    }

    @GetMapping(value = "get/{id}")
    @ApiOperation(value = "根据ID查询巡检管理信息", httpMethod = "GET", notes = "根据ID查询巡检管理信息")
    public SiteDiseaseVo get(@ApiParam(name = "id", value = "业务对象主键", required = true) @PathVariable String id) throws Exception {
        return baseService.getSiteInspectionById(id);
    }


    @RequestMapping(value = "getSiteInspectionStatus", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "获取所有的工单状态TEST", httpMethod = "POST", notes = "获取所有的工单状态TEST")
    public PageList<DefaultBpmCheckOpinionVo> getSiteInspectionStatus(@ApiParam(required = true, name = "queryFilter", value = "查询参数对象") @RequestBody QueryFilter queryFilter) throws Exception {

        return baseService.getSiteInspectionStatus(queryFilter);
    }

    @RequestMapping(value = "getSiteInspectionTask", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "获取所有的工单状态", httpMethod = "POST", notes = "获取所有的工单状态")
    public PageList<SiteInspectionTaskVo> getSiteInspectionTask(@ApiParam(required = true, name = "queryFilter", value = "查询参数对象") @RequestBody QueryFilter queryFilter) throws Exception {

        return baseService.getSiteInspectionTask(queryFilter);
    }

    @RequestMapping(value = "/saveVo", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "保存,修改巡检管理信息Vo", httpMethod = "POST")
    public CommonResult<SiteInspectionDiseaseVo> saveSiteDiseaseVo(@ApiParam(name = "siteInspection", value = "巡检管理信息对象") @RequestBody SiteInspectionDiseaseVo vo) throws Exception {
        SiteInspectionDiseaseVo siteInspectionDiseaseVo = this.baseService.saveSiteDiseaseVo(vo);
        return new CommonResult<>(true,"操作成功",siteInspectionDiseaseVo);
    }


    @RequestMapping(value = "/startSiteInspectionSpecial", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "添加巡检工单信息", httpMethod = "POST")
    public CommonResult<SiteInspection> startSiteInspectionSpecial(@ApiParam(name = "siteInspection", value = "巡检管理信息对象") @RequestBody SiteInspection siteInspection) throws Exception {
        String msg = "添加成功";
        SiteInspection returnVo = baseService.saveSite(siteInspection);
        if (returnVo!=null){
            if ("1".equals(returnVo.getId())){
                return new CommonResult<SiteInspection>(true, "修改成功", siteInspection);
            }else{
                return new CommonResult<SiteInspection>(true, msg, returnVo);
            }

        }

        return new CommonResult<SiteInspection>(false, "任务已接受无法修改", null);
    }

    @RequestMapping(value = "/updateSiteInspectionSpecial", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "修改巡检状态", httpMethod = "POST")
    public CommonResult<SiteInspection> updateSiteInspectionSpecial(@ApiParam(name = "siteTaskVo", value = "待办vo") @RequestBody SiteTaskVo siteTaskVo) throws Exception {

        baseService.updateSitestatus(siteTaskVo);
        return new CommonResult<SiteInspection>(true, "操作成功");
    }

    @RequestMapping(value = "/getJsonTaskHistory", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "分页查询巡检已办", httpMethod = "POST")
    public PageList<SiteInspectionVo> getJsonTaskHistory(@ApiParam(name = "queryFilter", value = "分页查询信息") @RequestBody QueryFilter<SiteInspection> queryFilter) {
        queryFilter.addFilter("a.is_dele_", "0", QueryOP.EQUAL);
        List<FieldSort> sorter = queryFilter.getSorter();
        //设置默认排序 安装巡检日期倒序排序
        if(null == sorter || sorter.isEmpty()){
            sorter.add(new FieldSort("ID_", Direction.DESC));
            queryFilter.setSorter(sorter);
        }
        PageList<SiteInspectionVo> pageList = baseService.queryTaskHistory(queryFilter);
        return pageList;
    }

/*    @RequestMapping(value = "/exportSite", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "巡检导出", httpMethod = "GET")
    public void exportSite(@ApiParam(name = "ids", value = "巡检ID")  @RequestParam String ids) {
      baseService.exportSite(ids);
    }*/

}
