package com.ruoyi.web.controller.screen;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.bean.BeanCopyUtil;
import com.ruoyi.system.domain.grid.GridRegion;
import com.ruoyi.system.domain.grid.GridRegionExample;
import com.ruoyi.system.domain.other.BsCommon;
import com.ruoyi.system.domain.other.BsCommonExample;
import com.ruoyi.system.domain.task.*;
import com.ruoyi.system.domain.task.vo.SimpleTaskVo;
import com.ruoyi.system.domain.visit.VisitPlanTaskExample;
import com.ruoyi.system.mapper.grid.GridRegionMapper;
import com.ruoyi.system.mapper.task.ext.TkCommonTaskExtMapper;
import com.ruoyi.system.mapper.visit.VisitPlanTaskMapper;
import com.ruoyi.system.service.grid.*;
import com.ruoyi.system.service.task.TkCommonAssignedService;
import com.ruoyi.system.service.task.TkCommonTaskDynamicService;
import com.ruoyi.system.service.task.TkCommonTaskService;
import com.ruoyi.system.service.visit.VisitFreeInterviewService;
import com.ruoyi.system.service.visit.VisitPlanService;
import com.ruoyi.web.controller.screen.res.GridRegionExtInfo;
import io.swagger.annotations.Api;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * * Author: brenda
 * * 2024/12/18
 **/
@Api(tags = "大屏接口-网格建设")
@RestController
@RequestMapping("/api/grid/screen/build")
public class ScreenBuildController extends BaseController {

    @Autowired
    private GridPeopleService gridPeopleService;
    @Autowired
    private GridHouseService gridHouseService;
    @Autowired
    private VisitPlanService visitPlanService;
    @Autowired
    private GridRegionFacadeService gridRegionFacadeService;
    @Autowired
    private TkCommonTaskService tkCommonTaskService;
    @Autowired
    private GridRegionMapper gridRegionMapper;
    @Autowired
    private VisitPlanTaskMapper visitPlanTaskMapper;
    @Autowired
    private VisitFreeInterviewService visitFreeInterviewService;
    @Autowired
    TkCommonTaskExtMapper tkCommonTaskExtMapper;
    @Autowired
    TkCommonTaskDynamicService tkCommonTaskDynamicService;
    @Autowired
    TkCommonAssignedService tkCommonAssignedService;

    /**
     * 走访管理：（序号，对象，走访时间，走访反馈）
     * @param visitType 自由走访F，更新走访U
     * @param wgCode
     * @return
     */
    @RequestMapping(value = "/planTaskList", method = RequestMethod.GET)
    public AjaxResult planTaskForPage(@RequestParam(value = "visitType") String visitType,
                                      @RequestParam(value = "wgCode", required = false) String wgCode) {
        LocalDate nowDate = LocalDate.now();
        String dateStr = nowDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate threeDateBefore = nowDate.minusMonths(10);
        String threeDateStr = threeDateBefore.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        return AjaxResult.success(visitFreeInterviewService.interviewList(visitType, wgCode,threeDateStr, dateStr));
    }


    /**
     * 根据wgCode获取上级网格信息和统计网格数和网格员数
     *
     * @param wgCode
     * @return
     */
    @RequestMapping(value = "/getWsParentRegionAndCount", method = RequestMethod.GET)
    @ResponseBody
    public String getWsParentRegionAndCount(@RequestParam(value = "wgCode", required = false) String wgCode) {
        AjaxResult result = new AjaxResult();
        gridRegionFacadeService.getWsParentRegionAndCount(wgCode, result);
        return JSON.toJSONString(result);
    }

    /**
     * 区级 工单数量（累计工单 办结工单 办结率,走访总数）
     *dateType  1 本周 2 本月 3 年
     * @return
     */
    @RequestMapping(value = "areaTaskNum", method = RequestMethod.GET)
    @ResponseBody
    public String areaTaskNum(String wgCode, String dateType) {
        Map map = new HashedMap();
        DecimalFormat df = new DecimalFormat("0.00");
        Date startDate = DateUtils.getBeginDayOfWeek();
        Date endDate = DateUtils.getEndDayOfWeek();
        if(StringUtils.isBlank(dateType)){
            dateType = "1";
        }
        if("2".equals(dateType)){
            startDate = DateUtils.getBeginDayOfMonth();
            endDate = DateUtils.getEndDayOfMonth();
        }else if("3".equals(dateType)){
            startDate = DateUtils.getCurrYearFirst();
            endDate = DateUtils.getCurrYearLast();
        }
        //工单
        int count = tkCommonTaskExtMapper.countByReleaseTimeAndUserId(startDate,endDate,null,null,null);
        map.put("allCount", count);
        //办结工单
        int endCount = tkCommonTaskExtMapper.countByReleaseTimeAndUserId(startDate, endDate,null,50,null);
        map.put("endCount", endCount);
        //办结率
        map.put("bjl",count==0?"0":df.format(((double) endCount / (double) count) * 100));

        //走访总数
        VisitPlanTaskExample allTaskExample = new VisitPlanTaskExample();
        allTaskExample.createCriteria().andIsValidEqualTo("1").andObjWgCodeLike(wgCode + "%");
        allTaskExample.createCriteria().andCreateTimeBetween(startDate, endDate);
        double allZfCount = visitPlanTaskMapper.countByExample(allTaskExample);

        map.put("zfCount", allZfCount);

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

    /**
     * 任务查询
     *
     * @param
     *
     * @return
     */
    @RequestMapping(value = "/bigWindow/taskList", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult bigWindowTaskList() {
        Map<String, Object> data = new HashedMap();
        data.put("unfinished", 50);//未完成
        data.put("currIndex",0);
        data.put("pageSize", 50);
        List<SimpleTaskVo> sysTestList = tkCommonTaskExtMapper.selectSimpleList(data);
        return AjaxResult.success(sysTestList);
    }

    /**
     * 经济建设工单点位
     * @return
     */
    @RequestMapping(value = "/bigWindow/taskPoint", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult bigWindowTaskPoint() {
        Map<String, Object> data = new HashedMap();
        data.put("unfinished", 50);//未完成
        data.put("currIndex",0);
        data.put("pageSize", 999);
        List<SimpleTaskVo> sysTestList = tkCommonTaskExtMapper.selectSimpleList(data);
        return AjaxResult.success(sysTestList);
    }

    /**
     * 任务详情接口
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/taskDetail", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getTaskDetail(@RequestParam String id) {

        try {
            TkCommonTask tkCommonTask = tkCommonTaskService.selectByPrimaryKey(id);
            //查询最后一条指派人信息
            List<TkCommonAssigned> tkCommonAssigneds = getTkCommonAssigneds(id);
            if (tkCommonAssigneds.size() > 0) {
                //塞入最后一个被指派人id
                tkCommonTask.setAssBeassignedUserId(tkCommonAssigneds.stream().map(TkCommonAssigned::getBeassignedUserId).collect(Collectors.joining(",")));
                //塞入最后一个被指派人角色等级
                tkCommonTask.setAssBeassignedRole(tkCommonAssigneds.stream().map(TkCommonAssigned::getBeassignedRole).map(String::valueOf).collect(Collectors.joining(",")));
                tkCommonTask.setAssBeassignedUserName(tkCommonAssigneds.stream().map(TkCommonAssigned::getBeassignedUserName).map(String::valueOf).collect(Collectors.joining(",")));

                //塞入最后一个指派人id
                tkCommonTask.setAssAssignedUserId(tkCommonAssigneds.get(0).getAssignedUserId());
                //塞入最后一个指派人姓名
                tkCommonTask.setAssAssignedUserName(tkCommonAssigneds.get(0).getAssignedUserName());
                //塞入最后一个被指派说明
                tkCommonTask.setAssAssignedNode(tkCommonAssigneds.get(0).getAssignedNode());
                //塞入最后一个指派的时间
                tkCommonTask.setAssAssignedCreatetime(tkCommonAssigneds.get(0).getCreateTime());
            } else {
                //塞入最后一个指派人id
                tkCommonTask.setAssAssignedUserId(tkCommonTask.getAssignedUserId());
                //塞入最后一个指派人姓名
                tkCommonTask.setAssAssignedUserName(tkCommonTask.getAssignedUserName());
            }
            tkCommonTask.setTkCommonTaskDynamics(null);
            return AjaxResult.success(tkCommonTask);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(400,"查询出错");
        }
    }

    @GetMapping("/task/process/list")
    public AjaxResult getTaskProcessList(@RequestParam String id){
        TkCommonTask tkCommonTask = tkCommonTaskService.selectByPrimaryKey(id);
        //获取任务动态
        TkCommonTaskDynamicExample tkCommonTaskDynamicExample = new TkCommonTaskDynamicExample();
        TkCommonTaskDynamicExample.Criteria criteria = tkCommonTaskDynamicExample.createCriteria();
        criteria.andCommonTkIdEqualTo(tkCommonTask.getId());
        tkCommonTaskDynamicExample.setOrderByClause("create_time desc");
        List<TkCommonTaskDynamic> tkCommonTaskDynamics = tkCommonTaskDynamicService.selectByExample(tkCommonTaskDynamicExample);
        return AjaxResult.success(tkCommonTaskDynamics);
    }

    private List<TkCommonAssigned> getTkCommonAssigneds(@RequestParam String id) {
        TkCommonAssignedExample tkCommonAssignedExample = new TkCommonAssignedExample();
        TkCommonAssignedExample.Criteria criteria1 = tkCommonAssignedExample.createCriteria();
        criteria1.andCommonTkIdEqualTo(id);
        tkCommonAssignedExample.setOrderByClause("assigned_status desc");
        List<TkCommonAssigned> list = tkCommonAssignedService.selectByExample(tkCommonAssignedExample);
        if(CollectionUtils.isEmpty(list)){
            return list;
        }
        Integer maxStatus = list.stream().mapToInt(TkCommonAssigned::getAssignedStatus).max().getAsInt();
        return list.stream().filter(t->maxStatus.equals(t.getAssignedStatus())).collect(Collectors.toList());
    }

    /**
     * 大屏事项来源
     *
     * @return
     */
    @RequestMapping(value = "/bigWindow/taskCountByComeFrom", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult taskCountByComeFrom(String wgCode, String startTime, String endTime) {
        List<Map<String, Object>> tkCommonTasks = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashedMap();
        if (StringUtils.isNotBlank(startTime)) {
            data.put("startTime", startTime);
        }
        if (StringUtils.isNotBlank(endTime)) {
            data.put("endTime", endTime);
        }
        if (StringUtils.isNotEmpty(wgCode)) {
            data.put("wgCode", wgCode);
        }
        tkCommonTasks = tkCommonTaskService.taskCountByComeFrom(data);
        return AjaxResult.success(tkCommonTasks);
    }

    /**
     * 网格点位列表
     * level: 1,2,3,4专属
     */
    @GetMapping("/wgPointList")
    @ResponseBody
    public AjaxResult wgPointList(String level){
        GridRegionExample wgsExample = new GridRegionExample();
        GridRegionExample.Criteria criteria = wgsExample.createCriteria();
        criteria.andIsValidEqualTo("1");
        criteria.andWgTypeEqualTo("1");
        if(StringUtils.isNotBlank(level)){
            if("4".equals(level)){
                criteria.andLevelEqualTo("3");
                criteria.andYlzd2EqualTo("1");
            }else{
                criteria.andLevelEqualTo(level);
                criteria.andYlzd2NotEqualTo("1");
            }
        }else{
            //默认2级
            criteria.andLevelEqualTo("2");
        }
        List<GridRegion> gridRegionList = gridRegionMapper.selectByExample(wgsExample);
        List<GridRegionExtInfo> list = BeanCopyUtil.bathToBean(gridRegionList, GridRegionExtInfo.class);
        if(!CollectionUtils.isEmpty(list)){
            list.forEach(e ->{
                if(StringUtils.isNotBlank(e.getWgCoordinate())){
                    String point = "MULTILINESTRING((" + e.getWgCoordinate().replaceAll("\\|"," ")+"))";
                    e.setWgCoordinate(point);
                }
                if(StringUtils.isNotBlank(e.getWgCentreCoordinate()) && e.getWgCentreCoordinate().contains("|")){
                    if(StringUtils.isNotBlank(e.getWgCentreCoordinate())){
                        String longitude = e.getWgCentreCoordinate().substring(0, e.getWgCentreCoordinate().indexOf("|"));
                        String latitude = e.getWgCentreCoordinate().substring(e.getWgCentreCoordinate().indexOf("|")+1);
                        e.setLongitude(longitude);
                        e.setLatitude(latitude);
                        String point = e.getWgCentreCoordinate().replaceAll("\\|"," ");
                        e.setWgCentreCoordinate(point);
                    }
                }
            });
        }
        return AjaxResult.success(list);
    }


}
