package com.ruoyi.web.controller.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.zqt.ZQTHttpHelper;
import com.ruoyi.common.zqt.ZQTPageModel;
import com.ruoyi.system.domain.task.TkCommonDiaodu;
import com.ruoyi.system.domain.task.TkCommonDiaoduExample;
import com.ruoyi.system.service.task.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags = "工单 调度任务")
@RestController
@RequestMapping("/api/task/diaodu")
public class CommonDiaoDuController {
    @Resource
    private TkCommonDiaoduService tkCommonDiaoduService;

    @Value("${app.mgrdata.url}")
    private  String managedataUrl;

    @ApiOperation("新增联级调度")
    @RequestMapping(value = "add", method = RequestMethod.POST)
    @ResponseBody
    public String add(@RequestBody TkCommonDiaodu tkCommonDiaodu) {
        try{
            tkCommonDiaodu.setDdStatus("0");
            tkCommonDiaodu.setDdTkstatus("0");
            tkCommonDiaodu.setDdCreatetime(new Date());
            tkCommonDiaodu.setId(UUID.randomUUID().toString());
            int insert = tkCommonDiaoduService.insert(tkCommonDiaodu);
            if(insert==0){
                return JSON.toJSONString(AjaxResult.build(400, "fail", "保存出错"));
            }

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", "保存出错"));
        }


        return JSON.toJSONString(AjaxResult.build(200, "success", "保存成功"));
    }

    /**
     *
     * @param pageNum
     * @param pageSize
     * @param ddName    工单标题
     * @param ddYouxianji   优先级 0普通  1重要 2紧急
     * @param ddStatus      签批状态  0未签批 1已签批
     * @param ddTkstatus    工单状态  0处理中  1已办结（未签批的时候也是处理中）
     * @param starttime     开始时间
     * @param endtime       结束时间
     * @return
     */
    @ApiOperation("列表")
    @RequestMapping(value = "list", method = RequestMethod.GET)
    @ResponseBody
    public String commonTasklist(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                 @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                 @RequestParam(required = false) String ddName,
                                 @RequestParam(required = false) String ddYouxianji, @RequestParam(required = false) String ddStatus,
                                 @RequestParam(required = false) String ddTkstatus,
                                 @RequestParam(required = false) String starttime,@RequestParam(required = false) String endtime) {




        TkCommonDiaoduExample tkCommonDiaoduExample=new TkCommonDiaoduExample();
        TkCommonDiaoduExample.Criteria criteria = tkCommonDiaoduExample.createCriteria();
        if (StringUtils.isNotBlank(ddName)) {
            criteria.andDdNameLike("%"+ddName+"%");
        }
        if (StringUtils.isNotBlank(ddYouxianji)) {
            criteria.andDdYouxianjiEqualTo(ddYouxianji);
        }
        if (StringUtils.isNotBlank(ddStatus)) {
            criteria.andDdStatusEqualTo(ddStatus);
        }
        if (StringUtils.isNotBlank(ddTkstatus)) {
            criteria.andDdTkstatusEqualTo(ddTkstatus);
        }
        try {
            if (StringUtils.isNotBlank(starttime) && StringUtils.isNotBlank(endtime)) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                criteria.andDdCreatetimeBetween(sdf.parse(starttime),sdf.parse(endtime));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        PageHelper.startPage(pageNum,pageSize);
        tkCommonDiaoduExample.setOrderByClause("dd_createtime desc");
        List<TkCommonDiaodu> tkCommonDiaodus = tkCommonDiaoduService.selectByExampleWithBLOBs(tkCommonDiaoduExample);
        int recordCount = tkCommonDiaoduService.countByExample(tkCommonDiaoduExample);//总记录数
        
        ZQTPageModel result = new ZQTPageModel();
        //分页
        result.setItemList(tkCommonDiaodus);
        //总记录数
        result.setRecordCount(recordCount);
        //总页数
        result.setPageCount((recordCount + pageSize - 1) / pageSize);
        //当前页
        result.setCurPage(recordCount == 0 ? 0 : pageNum);


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


    /**
     * 指挥调度当前应急响应、累计应急响应数据
     * 未完成和已完成的数量
     * @return
     */
    @ApiOperation("指挥调度当前应急响应、累计应急响应数据" +
            "\r\n未完成和已完成的数量")
    @RequestMapping(value = "diaoduTaskNum", method = RequestMethod.GET)
    @ResponseBody
    public String diaoduTaskNum() {
        Map<String,Object> map=new HashedMap();
        try{
            TkCommonDiaoduExample tkCommonDiaoduExample=new TkCommonDiaoduExample();
            TkCommonDiaoduExample.Criteria criteria = tkCommonDiaoduExample.createCriteria();
            criteria.andDdTkstatusEqualTo("0");//0处理中
            int doingCount = tkCommonDiaoduService.countByExample(tkCommonDiaoduExample);
            map.put("doingCount",doingCount);

            TkCommonDiaoduExample tkCommonDiaoduExample2=new TkCommonDiaoduExample();
            TkCommonDiaoduExample.Criteria criteria2 = tkCommonDiaoduExample2.createCriteria();
            criteria2.andDdTkstatusEqualTo("1");//1已完成
            int endCount = tkCommonDiaoduService.countByExample(tkCommonDiaoduExample2);
            map.put("endCount",endCount);
            map.put("allCount",doingCount+endCount);

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.build(400, "fail", map));
        }


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



    private void XZData(List<Map<String, Object>> idAndName) {
        try {

            String url=managedataUrl+"/manageData/getXZData";
//            //获取区下所有乡镇
            Map<String,String> map = new HashedMap();
            Map<String, String> headParams = new HashMap<String, String>();
            headParams.put("Content-Type", "application/json");
            String ret = ZQTHttpHelper.doPostJson(url, JSON.toJSONString(map), headParams);


            JSONObject jsonObject = JSONObject.parseObject(ret);
            if(jsonObject != null &&  jsonObject.get("msg").equals("success")){
                JSONArray data=(JSONArray)jsonObject.get("data");
                for(int i=0;i<data.size();i++){
                    JSONObject jo=(JSONObject)data.get(i);
                    Map<String,Object> idName=new HashedMap();
                    idName.put("id",jo.get("id")==null?"":jo.get("id").toString());
                    idName.put("name",jo.get("xzmc")==null?"":jo.get("xzmc").toString());
                    idName.put("longitude",jo.get("longitude")==null?"":jo.get("longitude").toString());
                    idName.put("latitude",jo.get("latitude")==null?"":jo.get("latitude").toString());
                    idAndName.add(idName);
                }

            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

}



