package com.persagy.calendar.controller;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.persagy.calendar.constant.WorkCalendarConstant;
import com.persagy.calendar.handle.WorkCalendarHandler;
import com.persagy.calendar.pojo.dto.WorkCalendar;
import com.persagy.calendar.pojo.dto.WorkCalendar.Builder;
import com.persagy.calendar.pojo.dto.WorkCalendarObject;
import com.persagy.calendar.pojo.vo.BaseUpdateVO;
import com.persagy.calendar.pojo.vo.WorkCalendarQueryVO;
import com.persagy.calendar.pojo.vo.WorkCalendarUpdateVO;
import com.persagy.calendar.service.IWorkCalendarObjectService;
import com.persagy.calendar.service.IWorkCalendarService;
import com.persagy.common.enums.ResponseCode;
import com.persagy.common.utils.ResponseResult;
import com.persagy.common.utils.ResponseUtil;
import com.persagy.common.utils.StringUtil;

import cn.hutool.core.collection.CollectionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 工作历主表
 * 
 * @version 1.0.0
 * @company persagy 
 * @author zhangqiankun
 * @date 2020-10-02 11:33:00
 */

@Api(tags = "工作历类型")
@RestController
@RequestMapping(value = "/v2.0/workCalendar", method = RequestMethod.POST)
public class WorkCalendarController {
    
	@Value("${integrated.calendar.group-code:BR}")
	private String defaultGroupCode;
	
    @Autowired
    private IWorkCalendarService workCalendarService;
    
    @Autowired
    private WorkCalendarHandler workCalendarHandler;
    
    @Autowired
    private IWorkCalendarObjectService workCalendarObjectService;
    
    /**
     * 列表查询
     */
    @ApiOperation(value = "普通列表查询")
    @RequestMapping(value = "queryWorkCalendarList")
    public ResponseResult queryWorkCalendarList(@RequestBody @Validated WorkCalendarQueryVO queryVO) {
    	if (StringUtil.isBlank(queryVO.getGroupCode())) {
			queryVO.setGroupCode(defaultGroupCode);
		}
    	
    	if (StringUtil.isNotBlank(queryVO.getObjId()) && StringUtil.isBlank(queryVO.getId())) {
    		QueryWrapper<WorkCalendarObject> 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());
			}
			queryVO.setId(calendarObject.getCalendarId());
		}
    	// 默认只查正常的
    	Builder builder = new WorkCalendar.Builder().createQueryWrapper();
    	QueryWrapper<WorkCalendar> queryWrapper = builder.idEq(queryVO.getId()).groupCodeEq(queryVO.getGroupCode())
    		.projectIdEq(queryVO.getProjectId()).calendarNameLike(queryVO.getCalendarName())
    		.delFlagEq(WorkCalendarConstant.WORK_CALENDAR_DEL_FLAG_NOR).builderQueryWrapper();
    	List<WorkCalendar> list = workCalendarService.list(queryWrapper);
    	return ResponseUtil.successResult(list, CollectionUtil.isEmpty(list) ? 0L : list.size());
    }
    
    /**
	 * 根据原有的工作历ID创建新的工作历信息和规则信息
	 */
    @ApiOperation(value = "根据原有的工作历创建")
    @RequestMapping(value = "createWorkCalendarFromId")
    public ResponseResult createWorkCalendarFromId(@RequestBody @Validated WorkCalendarUpdateVO updateVO) {
    	if (StringUtil.isBlank(updateVO.getGroupCode())) {
			updateVO.setGroupCode(defaultGroupCode);
		}
    	
    	String oldProjectId = updateVO.getProjectId();
    	if (StringUtil.isBlank(updateVO.getFromId())) {
			return ResponseUtil.errorResult(ResponseCode.A0400.getCode(), "工作历来源ID不可为空");
		}
    	// 判断原有的工作历信息是否存在
		WorkCalendar workCalendar = workCalendarService.getById(updateVO.getFromId(), updateVO.getGroupCode(), oldProjectId);
		if (workCalendar == null) {
			return ResponseUtil.errorResult(ResponseCode.C0320.getCode(), "原工作历信息不存在");
		}
		// 验证projectId和name是否联合唯一
		boolean result = workCalendarService.checkProjetcIdAndName(null, oldProjectId, updateVO.getGroupCode(), updateVO.getCalendarName());
		if (!result) {
			return ResponseUtil.errorResult(ResponseCode.C0341.getCode(), "工作历名称已存在");
		}
		workCalendar = new WorkCalendar();
		BeanUtils.copyProperties(updateVO, workCalendar);
		workCalendar.setId(null);	// 置空
		workCalendar.setUpdateUser(updateVO.getUserId());
		if (StringUtil.isNotBlank(updateVO.getNewProjectId())) {
			workCalendar.setProjectId(updateVO.getNewProjectId());
		}
    	return this.workCalendarHandler.createWorkCalendarFromId(workCalendar, updateVO.getFromId(), oldProjectId);
    }
    
    /**
     * 新增
     */
	@ApiOperation(value = "新增")
	@RequestMapping(value = "createWorkCalendar")
    public ResponseResult createWorkCalendar(@RequestBody @Validated WorkCalendarUpdateVO updateVO) {
		if (StringUtil.isBlank(updateVO.getGroupCode())) {
			updateVO.setGroupCode(defaultGroupCode);
		}
		
		// 判断projectId和name是否联合唯一
		boolean result = workCalendarService.checkProjetcIdAndName(null, updateVO.getProjectId(), updateVO.getGroupCode(), updateVO.getCalendarName());
		if (!result) {
			return ResponseUtil.errorResult(ResponseCode.C0341.getCode(), "名称重复");
		}
		
		WorkCalendar workCalendar = new WorkCalendar();
		BeanUtils.copyProperties(updateVO, workCalendar);
		workCalendar.setId(null);	// 置空
		workCalendar.setUpdateUser(updateVO.getUserId());
        result = this.workCalendarService.createWorkCalendar(workCalendar, updateVO.getObjIds());
        return result ? ResponseUtil.successResult("新增成功", workCalendar.getId()) : ResponseUtil.errorResult("新增失败");
    }
    
    /**
     * 更新
     */
	@ApiOperation(value = "更新")
	@RequestMapping(value = "updateWorkCalendar")
    public ResponseResult updateWorkCalendar(@RequestBody @Validated WorkCalendarUpdateVO updateVO) {
		if (StringUtil.isBlank(updateVO.getGroupCode())) {
			updateVO.setGroupCode(defaultGroupCode);
		}
		
		if (StringUtil.isBlank(updateVO.getId())) {
			return ResponseUtil.errorResult(ResponseCode.A0400.getCode(), "工作历ID不可为空");
		}
		// 判断原数据是否存在
		WorkCalendar calendar = workCalendarService.getById(updateVO.getId(), updateVO.getGroupCode(), updateVO.getProjectId());
		if (calendar == null) {
			return ResponseUtil.errorResult(ResponseCode.C0320.getCode(), ResponseCode.C0320.getDesc());
		}
		
		// 判断projectId和name是否联合唯一
		boolean result = workCalendarService.checkProjetcIdAndName(updateVO.getId(), updateVO.getProjectId(), updateVO.getGroupCode(), updateVO.getCalendarName());
		if (!result) {
			return ResponseUtil.errorResult(ResponseCode.C0341.getCode(), "数据重复");
		}
		
		WorkCalendar workCalendar = new WorkCalendar();
		BeanUtils.copyProperties(updateVO, workCalendar);
		workCalendar.setUpdateUser(updateVO.getUserId());
        result = workCalendarService.updateWorkCalendar(workCalendar);
        return result ? ResponseUtil.successResult("更新成功") : ResponseUtil.errorResult("更新失败");
    }

    /**
     * 逻辑删除，且级联删除
     */
    @ApiOperation(value = "删除")
    @RequestMapping(value = "deleteWorkCalendar")
    public ResponseResult deleteWorkCalendar(@RequestBody @Validated BaseUpdateVO baseUpdateVO) {
    	if (StringUtil.isBlank(baseUpdateVO.getGroupCode())) {
			baseUpdateVO.setGroupCode(defaultGroupCode);
		}
    	
    	// 获取此集团下所有的工作历类型，并判断原数据是否存在
    	QueryWrapper<WorkCalendar> queryWrapper = new WorkCalendar.Builder().createQueryWrapper()
    			.groupCodeEq(baseUpdateVO.getGroupCode()).builderQueryWrapper();
    	List<WorkCalendar> workCalendars = this.workCalendarService.list(queryWrapper);
		if (CollectionUtil.isEmpty(workCalendars)) {
			return ResponseUtil.errorResult(ResponseCode.C0320.getCode(), ResponseCode.C0320.getDesc());
		}
		boolean result = false;
		String projectId = baseUpdateVO.getProjectId();
		Set<String> allCalendarIds = new HashSet<String>();
		for (WorkCalendar workCalendar : workCalendars) {
			if (projectId.equals(workCalendar.getProjectId())) {
				allCalendarIds.add(workCalendar.getId());
				
				if (!result && baseUpdateVO.getId().equals(workCalendar.getId())) {
					result = true;
				}
			}
		}
		if (!result) {
			return ResponseUtil.errorResult(ResponseCode.C0320.getCode(), ResponseCode.C0320.getDesc());
		}
		// 执行级联删除
		return workCalendarHandler.deleteWorkCalendar(baseUpdateVO, workCalendars.size() == 1, allCalendarIds.size() == 1);
    }
    
}
