package com.steerinfo.ems.tcmtimelist.controller;

import com.steerinfo.ems.Utils.DateUtils;
import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.ems.tcmtimelist.model.TCmTimelist;
import com.steerinfo.ems.tcmtimedefinition.model.TCmTimeDefinition;
import com.steerinfo.ems.tcmtimelist.service.ITCmTimelistService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * TCmTimelist RESTful接口：
 * @author 王金涛
 * @version 1.0-SNAPSHORT 2019-10-14
 * 类描述
 * 修订历史：
 * 日期：2019-10-12
 * 作者：王金涛
 * 参考：
 * 描述：TCmTimelist RESTful接口
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@RestController
@RequestMapping("/${api.version}/tcmtimelists")
public class TCmTimelistController extends BaseRESTfulController {

    @Autowired
    ITCmTimelistService tCmTimelistService;

    @ApiOperation(value="获取列表", notes="根据起始时间，截止时间和TCmTimeDefinition对象中的TIMEGRANID分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize) {
        if(parmas.containsKey("starttime") && parmas.get("starttime") != null && !"".equals(parmas.get("starttime"))) {
            parmas.put("starttime", DateUtils.dateToString(parmas.get("starttime").toString(), "yyyyMMddHHmmss"));
        }
        if (parmas.containsKey("endtime")&& parmas.get("endtime") != null && !"".equals(parmas.get("endtime"))) {
            parmas.put("endtime", DateUtils.dateToString(parmas.get("endtime").toString(), "yyyyMMddHHmmss"));
        }
        if(parmas.containsKey("starttime") && parmas.containsKey("endtime") && !"".equals(parmas.get("starttime")) && !"".equals(parmas.get("endtime")) && parmas.get("starttime").toString().compareTo(parmas.get("endtime").toString()) >= 0) {
            return failed(null, "起始时间大于或等于截止时间");
        }
        PageList<TCmTimelist> list = tCmTimelistService.queryForPage(parmas, pageNum, pageSize);
        return success(list);
    }

    @ApiOperation(value="生成时间序列", notes="根据起始时间，截止时间和TCmTimeDefinition对象来创建")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "starttime", value = "起始时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "endtime", value = "截止时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "tCmTimeDefinition", value = "详细实体tCmTimeDefinition", required = true, dataType = "TCmTimeDefinition")
    })
    @PostMapping(value = "/")
    public RESTfulResult addtimelist(@ModelAttribute TCmTimeDefinition model,String starttime, String endtime) {
        if("".equals(starttime) || "".equals(endtime)){
            return failed(null, "起始时间和截止时间不能为空");
        }
        else if(starttime.compareTo(endtime) >= 0 ){
            return failed(null, "起始时间大于或等于截止时间");
        }
        else {
            try {
                Date d1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(starttime+" 00:00:00");//定义起始日期
                Date d2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endtime+" 00:00:00");//定义结束日期
                if(model.getOffsetinfo() != null && !"".equals(model.getOffsetinfo())) {
                    d1 = DateUtils.offsetDate(d1, model.getOffsetinfo());
                    d2 = DateUtils.offsetDate(d2, model.getOffsetinfo());
                }
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");//定义开始结束时间格式
                SimpleDateFormat sdf2 = new SimpleDateFormat(model.getTimeformat());//定义目标时间格式
                Map<String, Object> parameters = new HashMap();
                parameters.put("defid",model.getDefid());
                parameters.put("starttime",sdf1.format(d1));
                parameters.put("endtime",sdf1.format(d2));
                if( tCmTimelistService.query(parameters).size() != 0){
                    return failed(null, "该时间段已存在时间序列");
                }
                int infoindex = 0;//附加序列说明数组下标
                String str1,str2;
                List<TCmTimelist> list= new ArrayList<>();
                Calendar dd = Calendar.getInstance();//定义日期实例
                dd.setTime(d1);//设置日期起始时间
                List<String> extrainfolist = Arrays.asList(model.getExtrainfo().split(","));
                System.out.println();
                while(dd.getTime().before(d2)){//判断是否到结束日期
                    TCmTimelist tCmTimelist = new TCmTimelist();
                    int interval =  Integer.parseInt(model.getInterval());
                    str1 = sdf1.format(dd.getTime());
                    switch (model.getTimegranid()){
                        case "HOUR":
                            dd.add(Calendar.HOUR, interval);
                            break;
                        case "SHIFT":
                            dd.add(Calendar.HOUR, interval);
                            break;
                        case "DAY":
                            dd.add(Calendar.DATE, interval);
                            break;
                        case "MONTH":
                            dd.add(Calendar.MONTH, interval);
                            break;
                        case "YEAR":
                            dd.add(Calendar.YEAR, interval);
                            break;
                        default:
                            failed(null, "时间粒度错误");
                    }
                    dd.add(Calendar.SECOND, -1);
                    str2 = sdf1.format(dd.getTime());
                    tCmTimelist.setStarttime(str1);
                    tCmTimelist.setEndtime(str2);
                    tCmTimelist.setDefid(model.getId());
                    tCmTimelist.setDefname(model.getDefname());
                    tCmTimelist.setTimedefault(model.getGrandefault());
                    tCmTimelist.setTimegranid(model.getTimegranid());
                    if (extrainfolist.size() != 0) {
                        tCmTimelist.setDesttime(sdf2.format(dd.getTime()) +" "+ extrainfolist.get(infoindex));
                        tCmTimelist.setTimeformat(model.getTimeformat() +" "+ extrainfolist.get(infoindex));
                        infoindex++;
                        infoindex = infoindex % extrainfolist.size();
                    }
                    else {
                        tCmTimelist.setDesttime(sdf2.format(dd.getTime()));
                        tCmTimelist.setTimeformat(model.getTimeformat());
                    }
                    list.add(tCmTimelist);
                    dd.add(Calendar.SECOND, 1);
                }
                tCmTimelistService.batchAdd(list);
                return success();
            }
            catch (ParseException e){
                e.printStackTrace();
                return failed();
            }
        }
    }

    @ApiOperation(value="清空时间序列", notes="根据时间序列删除对象")
    @ApiImplicitParam(name = "tCmTimelist", value = "详细实体tCmTimelist", required = true, dataType = "TCmTimelist")
    @DeleteMapping(value = "/")
    public RESTfulResult delete(@RequestBody TCmTimelist model) {
        model.setStarttime(DateUtils.dateToString(model.getStarttime(), "yyyyMMddHHmmss"));
        model.setEndtime(DateUtils.dateToString(model.getEndtime(), "yyyyMMddHHmmss"));
        tCmTimelistService.deletebymodel(model);
        return success();
    }

    /**
     @ApiOperation(value="获取列表", notes="分页模糊查询")
     @ApiImplicitParams({
     @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
     @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
     })
     //@RequiresPermissions("tcmtimelist:view")
     @GetMapping(value = "/like/")
     public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
     PageList<TCmTimelist> list = tCmTimelistService.queryLikeForPage(parmas, pageNum, pageSize);
     return success(list);
     }

     @ApiOperation(value="创建", notes="根据TCmTimelist对象创建")
     @ApiImplicitParam(name = "tCmTimelist", value = "详细实体tCmTimelist", required = true, dataType = "TCmTimelist")
     //@RequiresPermissions("tcmtimelist:create")
     @PostMapping(value = "/")
     public RESTfulResult add(@ModelAttribute TCmTimelist model){
     TCmTimelist tCmTimelist = tCmTimelistService.add(model);
     return success(tCmTimelist);
     }

     @ApiOperation(value="获取详细信息", notes="根据url的id来获取详细信息")
     @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
     //@RequiresPermissions("tcmtimelist:view")
     @GetMapping(value = "/{id}")
     public RESTfulResult get(@PathVariable String id){
     TCmTimelist tCmTimelist = tCmTimelistService.getById(id);
     return success(tCmTimelist);
     }

     @ApiOperation(value="更新详细信息", notes="根据url的id来指定更新对象，并根据传过来的tCmTimelist信息来更新详细信息")
     @ApiImplicitParams({
     @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String"),
     @ApiImplicitParam(name = "tCmTimelist", value = "详细实体tCmTimelist", required = true, dataType = "TCmTimelist")
     })
     //@RequiresPermissions("tcmtimelist:update")
     @PutMapping(value = "/{id}", produces  = "application/json;charset=UTF-8")
     public RESTfulResult update(@PathVariable String id, @RequestBody TCmTimelist model){
     model.setId(id);
     TCmTimelist tCmTimelist = tCmTimelistService.modify(model);
     return success(tCmTimelist);
     }
     */

}
