package com.persagy.calendar.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.persagy.calendar.client.model.BaseModel;
import com.persagy.calendar.client.model.RwdObjectModel;
import com.persagy.calendar.constant.WorkCalendarConstant;
import com.persagy.calendar.pojo.dto.WorkCalendar;
import com.persagy.calendar.pojo.dto.WorkCalendarObject;
import com.persagy.calendar.pojo.vo.RwdObjectQueryVO;
import com.persagy.calendar.pojo.vo.WorkCalendarObjectUpdateVO;
import com.persagy.calendar.pojo.vo.WorkCalendarQueryVO;
import com.persagy.calendar.service.IWorkCalendarObjectService;
import com.persagy.calendar.service.IWorkCalendarService;
import com.persagy.calendar.service.RwdObjectService;
import com.persagy.common.enums.ResponseCode;
import com.persagy.common.utils.DateUtil;
import com.persagy.common.utils.ResponseResult;
import com.persagy.common.utils.ResponseUtil;
import com.persagy.common.utils.StringUtil;

import cn.hutool.core.collection.CollectionUtil;

/**
 * 物理世界对象管理
 * 
 * @version 
 * @company persagy
 * @author zhangqiankun
 * @since 2021年3月2日:	下午3:16:15
 */
@RestController
@RequestMapping(value = "/v2.0/rwdObject", method = RequestMethod.POST)
public class RwdObjectController {
	
	@Autowired
	private RwdObjectService rwdObjectService;
	
    @Autowired
    private IWorkCalendarService workCalendarService;
    
	@Autowired
	private IWorkCalendarObjectService workCalendarObjectService;
	
	/**
	 * 物理世界对象列表查询
	 * @param queryVO
	 * @return
	 */
    @RequestMapping(value = "queryRwdObjects")
	public ResponseResult queryRwdObjects(@RequestBody @Validated RwdObjectQueryVO queryVO) {
		BaseModel baseModel = new BaseModel();
		BeanUtils.copyProperties(queryVO, baseModel);
		RwdObjectModel objectModel = new RwdObjectModel();
		BeanUtils.copyProperties(queryVO, objectModel);
		return this.rwdObjectService.queryRwdObjects(baseModel, objectModel);
	}
	
	/**
	 * 查询工作历对象列表
	 * @param queryVO
	 * @return
	 */
    @RequestMapping(value = "queryCalendarObjectList")
    public ResponseResult queryCalendarObjectList(@RequestBody @Validated WorkCalendarQueryVO queryVO) {
		QueryWrapper<WorkCalendarObject> queryWrapper = null;
    	if (StringUtil.isNotBlank(queryVO.getObjId()) && StringUtil.isBlank(queryVO.getId())) {
    		queryWrapper = new WorkCalendarObject.Builder().createQueryWrapper()
    				.groupCodeEq(queryVO.getGroupCode()).projectIdEq(queryVO.getProjectId())
    				.objectIdEq(queryVO.getObjId()).builderQueryWrapper();
			WorkCalendarObject calendarObject = this.workCalendarObjectService.getOne(queryWrapper);
			if (calendarObject == null) {
				return ResponseUtil.successResult(Lists.newArrayList(), 0L);
			}
			queryVO.setId(calendarObject.getCalendarId());
		}
    	// 默认只查正常的
    	QueryWrapper<WorkCalendar> calendarWrapper = new WorkCalendar.Builder().createQueryWrapper()
    			.idEq(queryVO.getId()).groupCodeEq(queryVO.getGroupCode())
    			.projectIdEq(queryVO.getProjectId()).calendarNameLike(queryVO.getCalendarName())
    			.delFlagEq(WorkCalendarConstant.WORK_CALENDAR_DEL_FLAG_NOR).builderQueryWrapper();
    	List<WorkCalendar> list = this.workCalendarService.list(calendarWrapper);
    	if (CollectionUtil.isEmpty(list)) {
    		return ResponseUtil.successResult(Lists.newArrayList(), 0L);
		}
    	// 遍历获取对象名称
		BaseModel baseModel = new BaseModel();
		BeanUtils.copyProperties(queryVO, baseModel);
		RwdObjectModel objectModel = new RwdObjectModel();
		objectModel.setObjType(Sets.newHashSet("space", "floor", "building", "project"));
    	for (WorkCalendar workCalendar : list) {
    		queryWrapper = new WorkCalendarObject.Builder().createQueryWrapper()
    				.groupCodeEq(queryVO.getGroupCode()).projectIdEq(queryVO.getProjectId())
    				.calendarIdEq(workCalendar.getId()).builderQueryWrapper();
			List<WorkCalendarObject> calendarObjects = this.workCalendarObjectService.list(queryWrapper);
			if (CollectionUtil.isNotEmpty(calendarObjects)) {
				List<JSONObject> objects = workCalendar.getObjects();
				objects = CollectionUtil.isEmpty(objects) ? new ArrayList<JSONObject>() : objects;
				for (WorkCalendarObject object : calendarObjects) {
					objectModel.setId(object.getObjectId());
					ResponseResult result = this.rwdObjectService.queryRwdObjects(baseModel, objectModel);
					Object content = result.getContent();
					if (content != null) {
						JSONArray array = JSONArray.parseArray(JSON.toJSONString(content));
						if (array != null && array.size() > 0) {
							JSONObject jsonObject = array.getJSONObject(0);
							String objectName = jsonObject.getString("localName");
							jsonObject = new JSONObject();
							jsonObject.put("objectName", objectName);
							jsonObject.put("objectId", object.getObjectId());
							objects.add(jsonObject);
						}
					}
				}
				workCalendar.setObjects(objects);
			}
		}
    	return ResponseUtil.successResult(list, (long)list.size());
    }
	
	/**
	 * 添加对象工作历
	 */
	@RequestMapping(value = "addCalendarObject")
	public ResponseResult addCalendarObject(@RequestBody @Validated WorkCalendarObjectUpdateVO updateVO) {
		if (StringUtil.isBlank(updateVO.getCalendarId())) {
			return ResponseUtil.errorResult(ResponseCode.A0402.getCode(), "工作历ID不可为空");
		}
		if (StringUtil.isBlank(updateVO.getObjId()) && CollectionUtil.isEmpty(updateVO.getObjIds())) {
			return ResponseUtil.errorResult(ResponseCode.A0402.getCode(), "对象ID或对象ID集合，必须存在其一");
		}
		WorkCalendarObject calendarObject = new WorkCalendarObject();
		BeanUtils.copyProperties(updateVO, calendarObject);
		if (CollectionUtil.isEmpty(updateVO.getObjIds())) {
			updateVO.setObjIds(Sets.newHashSet(updateVO.getObjId()));
		} else {
			updateVO.getObjIds().add(updateVO.getObjId());
		}
		this.workCalendarObjectService.batchInsertObjects(calendarObject, updateVO.getObjIds());
		return ResponseUtil.successResult("添加成功");
	}
	
	/**
	 * 删除加对象工作历
	 */
	@RequestMapping(value = "deleteCalendarObject")
	public ResponseResult deleteCalendarObject(@RequestBody @Validated WorkCalendarObjectUpdateVO updateVO) {
		if (StringUtil.isBlank(updateVO.getObjId()) && CollectionUtil.isEmpty(updateVO.getObjIds())) {
			return ResponseUtil.errorResult(ResponseCode.A0402.getCode(), "对象ID或对象ID集合，必须存在其一");
		}
		WorkCalendarObject calendarObject = new WorkCalendarObject();
		BeanUtils.copyProperties(updateVO, calendarObject);
		if (CollectionUtil.isEmpty(updateVO.getObjIds())) {
			updateVO.setObjIds(Sets.newHashSet(updateVO.getObjId()));
		} else {
			updateVO.getObjIds().add(updateVO.getObjId());
		}
		QueryWrapper<WorkCalendarObject> queryWrapper = new WorkCalendarObject.Builder().createQueryWrapper()
				.groupCodeEq(updateVO.getGroupCode()).calendarIdEq(updateVO.getCalendarId())
				.projectIdEq(updateVO.getProjectId()).objectIdIn(updateVO.getObjIds()).builderQueryWrapper();
		boolean result = this.workCalendarObjectService.remove(queryWrapper);
		return result ? ResponseUtil.successResult("删除成功") : ResponseUtil.errorResult("删除失败");
	}
	
    /**
     * 对象变更所属工作历
     */
    @RequestMapping(value = "changeCalendarObject")
    public ResponseResult changeCalendarObject(@RequestBody @Validated WorkCalendarObjectUpdateVO updateVO) {
    	if (StringUtil.isBlank(updateVO.getCalendarId())) {
			return ResponseUtil.errorResult(ResponseCode.A0402.getCode(), "工作历ID不可为空");
		}
    	if (CollectionUtil.isEmpty(updateVO.getObjIds())) {
			return ResponseUtil.errorResult(ResponseCode.A0402.getCode(), "对象ID集合不可为空");
		}
    	WorkCalendarObject calendarObject = new WorkCalendarObject();
    	BeanUtils.copyProperties(updateVO, calendarObject);
    	calendarObject.setUpdateUser(updateVO.getUserId());
    	calendarObject.setCreateTime(DateUtil.format(new Date(), DateUtil.FORMAT_DATE_YYYYMMDDHHMMSS));
    	boolean result = this.workCalendarObjectService.replaceCalendarObject(calendarObject, updateVO.getObjIds());
    	return result ? ResponseUtil.successResult("操作成功") : ResponseUtil.errorResult("操作失败");
    }
	
}
