package com.ruoyi.web.controller.task;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtil;
import com.ruoyi.common.zqt.ZQTPageModel;
import com.ruoyi.system.domain.grid.GridRegionUser;
import com.ruoyi.system.domain.task.TkRoundPlan;
import com.ruoyi.system.domain.task.TkRoundPlanExample;
import com.ruoyi.system.domain.task.vo.BsGridRegionUser;
import com.ruoyi.system.domain.task.vo.RoundPlanVO;
import com.ruoyi.system.service.task.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Api(tags = "工单 巡查 计划")
@RestController
@RequestMapping("/api/task/roundPlan")
public class RoundPlanController {
    @Autowired
    TkRoundPlanService tkRoundPlanService;
    @Autowired
    DiyService diyService;

    @ApiOperation("新增")
    @RequestMapping(value = "save", method = RequestMethod.POST)
    @ResponseBody
    public String saveSubTask(@RequestBody RoundPlanVO roundPlanVO) {
        Integer result = null;
        if (roundPlanVO == null || StringUtils.isBlank(roundPlanVO.getName())) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", "参数不完整！"));
        }

        String[] chooseObjIds = roundPlanVO.getChooseObjIds();
        String[] chooseUserIds = roundPlanVO.getChooseUserIds();

        TkRoundPlan tkRoundPlan = new TkRoundPlan();
        tkRoundPlan.setId(roundPlanVO.getId());
        tkRoundPlan.setName(roundPlanVO.getName());
        tkRoundPlan.setDescription(roundPlanVO.getDescription());
//        4:日常巡查
        tkRoundPlan.setPeriodType("4");
        tkRoundPlan.setPeriodHz(roundPlanVO.getPeriodHz());
        tkRoundPlan.setPeriodInterval(roundPlanVO.getPeriodInterval());
        tkRoundPlan.setStartDate(roundPlanVO.getStartDate());
        tkRoundPlan.setEndDate(roundPlanVO.getEndDate());
        tkRoundPlan.setObjType(roundPlanVO.getObjType());
        tkRoundPlan.setMatterId(roundPlanVO.getMatterId());
        tkRoundPlan.setMatterName(roundPlanVO.getMatterName());
        tkRoundPlan.setStatus(roundPlanVO.getStatus());
        tkRoundPlan.setCreateBy(roundPlanVO.getCreateBy());
        tkRoundPlan.setCreateName(roundPlanVO.getCreateName());
        tkRoundPlan.setUpdateBy(roundPlanVO.getUpdateBy());
        tkRoundPlan.setStartDate(new Date());


        tkRoundPlan.setUserIds(StringUtils.join(chooseUserIds, ","));
        tkRoundPlan.setObjIds(StringUtils.join(chooseObjIds, ","));

        tkRoundPlan.setUserNames(roundPlanVO.getCreateName());
        tkRoundPlan.setUserIds(roundPlanVO.getCreateBy());


        tkRoundPlan.setId(UUID.randomUUID().toString());
        tkRoundPlan.setCreateTime(new Date());
        tkRoundPlan.setStatus("1");
        List<BsGridRegionUser> chooseObjJson = new ArrayList<>();
        BsGridRegionUser bsWgdxb = new BsGridRegionUser();
        bsWgdxb.setName(roundPlanVO.getObjNames());
        bsWgdxb.setWgId(roundPlanVO.getGridId());
        chooseObjJson.add(bsWgdxb);
        result = diyService.insert(tkRoundPlan, chooseObjIds, chooseUserIds, null, chooseObjJson, roundPlanVO.getOrigin(), roundPlanVO.getStandby3());

        if (result == 0) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", "巡查计划保存失败！"));
        }


        return JSON.toJSONString(AjaxResult.build(200, "success", roundPlanVO));
    }


    @ApiOperation("查询列表")
    @GetMapping
    @ResponseBody
    public String getList(@RequestParam(required = false, value = "pageNum", defaultValue = "1") int pageNum,
                          @RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize,
                          @RequestParam(required = false, value = "periodType") String periodType,
                          @RequestParam(required = false, value = "startDate") String startDate,
                          @RequestParam(required = false, value = "status") String status,
                          @RequestParam(required = false, value = "name") String name
    ) {
        TkRoundPlanExample tkRoundPlanExample = new TkRoundPlanExample();
        TkRoundPlanExample.Criteria criteria = tkRoundPlanExample.createCriteria();

        tkRoundPlanExample.setOrderByClause("create_time desc");
        if (StringUtils.isNotBlank(periodType)) {
            // 0:从不重复,1:月巡查,2:周巡查,3:日巡查
            criteria.andPeriodTypeEqualTo(periodType);
        }else{
            criteria.andPeriodTypeNotEqualTo("4");
        }

        if (StringUtils.isNotBlank(startDate)) {
            Date startDate2 = DateUtil.getDate(startDate, DateUtil.DATAFORMAT_STR);
            criteria.andStartDateEqualTo(startDate2);
        }
        if (StringUtils.isNotBlank(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        if (StringUtils.isNotBlank(status)) {
            // 0:无效,1:有效
            criteria.andStatusEqualTo(status);
        }

        PageHelper.startPage(pageNum, pageSize);

        List<TkRoundPlan> tkRoundPlanList = tkRoundPlanService.selectByExampleWithBLOBs(tkRoundPlanExample);
        int recordCount = tkRoundPlanService.countByExample(tkRoundPlanExample);

        // 分页
        ZQTPageModel zqtongPageListResult = new ZQTPageModel();
        //当前页
        zqtongPageListResult.setCurPage(recordCount == 0 ? 0 : pageNum);
        zqtongPageListResult.setItemList(tkRoundPlanList);
        //总页数
        int totalPageNum = (recordCount + pageSize - 1) / pageSize;
        zqtongPageListResult.setPageCount(totalPageNum);
        zqtongPageListResult.setRecordCount(recordCount);

        return JSON.toJSONString(AjaxResult.build(200, "success", zqtongPageListResult));
    }

    @ApiOperation("新增记录")
    @PostMapping
    @ResponseBody
    public String save(@RequestBody RoundPlanVO roundPlanVO) {
        Integer result = null;
        if (roundPlanVO == null || StringUtils.isBlank(roundPlanVO.getName())) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", "参数不完整！"));
        }

        String[] chooseObjIds = roundPlanVO.getChooseObjIds();
        String[] chooseUserIds = roundPlanVO.getChooseUserIds();
        List<GridRegionUser> chooseUserJson = roundPlanVO.getChooseUserJson();
        List<BsGridRegionUser> chooseObjJson = roundPlanVO.getChooseObjJson();

        TkRoundPlan tkRoundPlan = new TkRoundPlan();
        tkRoundPlan.setId(roundPlanVO.getId());
        tkRoundPlan.setName(roundPlanVO.getName());
        tkRoundPlan.setDescription(roundPlanVO.getDescription());
        tkRoundPlan.setPeriodType(roundPlanVO.getPeriodType());
        tkRoundPlan.setPeriodHz(roundPlanVO.getPeriodHz());
        tkRoundPlan.setPeriodInterval(roundPlanVO.getPeriodInterval());
        tkRoundPlan.setStartDate(roundPlanVO.getStartDate());
        tkRoundPlan.setEndDate(roundPlanVO.getEndDate());
        tkRoundPlan.setObjType(roundPlanVO.getObjType());
//        tkRoundPlan.setObjNames(roundPlanVO.getObjNames());
        tkRoundPlan.setMatterId(roundPlanVO.getMatterId());
        tkRoundPlan.setMatterName(roundPlanVO.getMatterName());
        tkRoundPlan.setStatus(roundPlanVO.getStatus());
        tkRoundPlan.setCreateBy(roundPlanVO.getCreateBy());
        tkRoundPlan.setCreateName(roundPlanVO.getCreateName());
        tkRoundPlan.setUpdateBy(roundPlanVO.getUpdateBy());


        tkRoundPlan.setUserIds(StringUtils.join(chooseUserIds, ","));
        tkRoundPlan.setObjIds(StringUtils.join(chooseObjIds, ","));
        StringBuffer userNames = new StringBuffer();
        for (GridRegionUser user : chooseUserJson) {
            userNames.append(user.getYlzd1());
            userNames.append(",");
        }
        tkRoundPlan.setUserNames(userNames.toString());


        tkRoundPlan.setId(UUID.randomUUID().toString());
        tkRoundPlan.setCreateTime(new Date());
        tkRoundPlan.setStatus("1");
        result = diyService.insert(tkRoundPlan, chooseObjIds, chooseUserIds, chooseUserJson, chooseObjJson, roundPlanVO.getOrigin(), null);

        if (result == 0) {
            return JSON.toJSONString(AjaxResult.build(400, "fail", "巡查计划保存失败！"));
        }


        return JSON.toJSONString(AjaxResult.build(200, "success", roundPlanVO));
    }


    @ApiOperation("更新所有")
    @PutMapping
    @ResponseBody
    public String put(@RequestBody TkRoundPlan tkRoundPlan) {
        Integer result = null;

        tkRoundPlan.setUpdateTime(new Date());
        result = tkRoundPlanService.updateByPrimaryKey(tkRoundPlan);

        if (result == 1) {
            return JSON.toJSONString(AjaxResult.build(200, "success", tkRoundPlan));
        } else {
            return JSON.toJSONString(AjaxResult.build(400, "fail", null));
        }
    }

    @ApiOperation("修改信息")
    @PatchMapping
    @ResponseBody
    public String patch(@RequestBody TkRoundPlan tkRoundPlan) {
        Integer result = null;

        tkRoundPlan.setUpdateTime(new Date());
        result = tkRoundPlanService.updateByPrimaryKeySelective(tkRoundPlan);

        if (result == 1) {
            return JSON.toJSONString(AjaxResult.build(200, "success", tkRoundPlan));
        } else {
            return JSON.toJSONString(AjaxResult.build(400, "fail", null));
        }
    }

    @ApiOperation("删除记录")
    @RequestMapping(value = "{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public String deleteById(@PathVariable String id) {
        System.out.println("/test/roundPlan/del----->" + id);

        int result = diyService.deletePlanById(id);

        if (result == 1) {
            return JSON.toJSONString(AjaxResult.build(200, "success", id));
        } else {
            return JSON.toJSONString(AjaxResult.build(400, "fail", null));
        }
    }

    @ApiOperation("详情")
    @RequestMapping(value = "{id}", method = RequestMethod.GET)
    @ResponseBody
    public String getById(@PathVariable String id) {

        TkRoundPlan result = tkRoundPlanService.selectByPrimaryKey(id);

        if (result != null) {
            return JSON.toJSONString(AjaxResult.build(200, "success", result));
        } else {
            return JSON.toJSONString(AjaxResult.build(400, "fail", "查询失败！"));
        }
    }

    @ApiOperation("状态开关")
    @RequestMapping(value = "{id}", method = RequestMethod.PATCH)
    @ResponseBody
    public String statusUpdate(@PathVariable String id) {
        Integer result = null;
        TkRoundPlan tkRoundPlan = tkRoundPlanService.selectByPrimaryKey(id);

        result = diyService.onOff(tkRoundPlan);

        if (result == 1) {
            return JSON.toJSONString(AjaxResult.build(200, "success", tkRoundPlan));
        } else {
            return JSON.toJSONString(AjaxResult.build(400, "fail", null));
        }
    }

    @ApiOperation("查第一个详情")
    @RequestMapping(value = "first", method = RequestMethod.GET)
    @ResponseBody
    public String getFirst(@RequestParam(required = false, value = "pageNum", defaultValue = "1") int pageNum,
                           @RequestParam(required = false, value = "pageSize", defaultValue = "1") int pageSize,
                           @RequestParam(required = false, value = "periodType") String periodType,
                           @RequestParam(required = false, value = "startDate") String startDate,
                           @RequestParam(required = false, value = "status") String status,
                           @RequestParam(required = false, value = "name") String name
    ) {
        TkRoundPlanExample tkRoundPlanExample = new TkRoundPlanExample();
        TkRoundPlanExample.Criteria criteria = tkRoundPlanExample.createCriteria();

        tkRoundPlanExample.setOrderByClause("start_date desc");
        if (StringUtils.isNotBlank(periodType)) {
            // 0:从不重复,1:月巡查,2:周巡查,3:日巡查
            criteria.andPeriodTypeEqualTo(periodType);
        }

        if (StringUtils.isNotBlank(startDate)) {
            Date startDate2 = DateUtil.getDate(startDate, DateUtil.DATAFORMAT_STR);
            criteria.andStartDateEqualTo(startDate2);
        }
        if (StringUtils.isNotBlank(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        if (StringUtils.isNotBlank(status)) {
            // 0:无效,1:有效
            criteria.andStatusEqualTo(status);
        }
        PageHelper.startPage(pageNum, pageSize);

        List<TkRoundPlan> tkRoundPlanList = tkRoundPlanService.selectByExampleWithBLOBs(tkRoundPlanExample);

        if (tkRoundPlanList == null || tkRoundPlanList.size() == 0) {
            return JSON.toJSONString(AjaxResult.build(200, "success", "没数据！"));
        }

        return JSON.toJSONString(AjaxResult.build(200, "success", tkRoundPlanList.get(0)));
    }

    @ApiOperation("计划数量和企业巡查次数")
    @RequestMapping(value = "num", method = RequestMethod.GET)
    @ResponseBody
    public String roundPlanNum() {
        Map<String, Object> map = new HashMap<>();
        TkRoundPlanExample tkRoundPlanExample = new TkRoundPlanExample();
        Integer totalPlanNum = tkRoundPlanService.countByExample(tkRoundPlanExample);

        Integer totalQYRecordNum = diyService.countByDxlx("qy");

        map.put("planNum", totalPlanNum);
        map.put("recordNum", totalQYRecordNum);

        return JSON.toJSONString(AjaxResult.build(200, "success", map));
    }

}
