package com.persagy.calendar.controller;

import java.util.List;

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.persagy.calendar.constant.WorkCalendarConstant;
import com.persagy.calendar.handle.WorkCalendarRuleHandler;
import com.persagy.calendar.pojo.dto.WorkCalendar;
import com.persagy.calendar.pojo.dto.WorkCalendarRule;
import com.persagy.calendar.pojo.vo.CustomCalendarVO;
import com.persagy.calendar.pojo.vo.WorkCalendarRuleCreateVO;
import com.persagy.calendar.pojo.vo.WorkCalendarRuleDeleteVO;
import com.persagy.calendar.pojo.vo.WorkCalendarRuleQueryVO;
import com.persagy.calendar.pojo.vo.WorkCalendarRuleUpdateVO;
import com.persagy.calendar.service.IWorkCalendarDictService;
import com.persagy.calendar.service.IWorkCalendarRuleService;
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 18:26:14
 */

@Api(tags = "工作历规则")
@RestController
@RequestMapping(value = "/v2.0/workCalendarRule", method = RequestMethod.POST)
public class WorkCalendarRuleController {

	@Value("${integrated.calendar.group-code:BR}")
	private String defaultGroupCode;
	
	@Autowired
    private IWorkCalendarService workCalendarService;
    
    @Autowired
    private WorkCalendarRuleHandler workCalendarRuleHandler;
    
    @Autowired
    private IWorkCalendarRuleService workCalendarRuleService;
    
    @Autowired
	private IWorkCalendarDictService workCalendarDictService;
    
    /**
     * 普通列表查询
     */
    @ApiOperation(value = "普通列表查询")
    @RequestMapping(value = "queryWorkCalendarRuleList")
    public ResponseResult queryWorkCalendarRuleList(@RequestBody @Validated WorkCalendarRuleQueryVO queryVO) {
    	if (StringUtil.isBlank(queryVO.getGroupCode())) {
			queryVO.setGroupCode(defaultGroupCode);
		}
    	
    	int dictTypeLevel = this.workCalendarDictService.getDictTypeLevel(queryVO.getGroupCode(), queryVO.getDictType());
    	
    	QueryWrapper<WorkCalendarRule> queryWrapper = new WorkCalendarRule.Builder().createQueryWrapper().groupCodeEq(queryVO.getGroupCode())
    			.idEq(queryVO.getId()).calendarIdEq(queryVO.getCalendarId(), dictTypeLevel).projectIdEq(queryVO.getProjectId(), dictTypeLevel)
    			.dictTypeEq(queryVO.getDictType()).dictCodeIn(queryVO.getDictCode())
    			.delFlagEq(WorkCalendarConstant.WORK_CALENDAR_DEL_FLAG_NOR).builderQueryWrapper();
    	List<WorkCalendarRule> list = this.workCalendarRuleService.list(queryWrapper);
    	return ResponseUtil.successResult(list, CollectionUtil.isEmpty(list) ? 0L : list.size());
    }
    
    /**
     * 新增
     */
	@ApiOperation(value = "保存")
	@RequestMapping(value = "createWorkCalendarRule")
    public ResponseResult createWorkCalendarRule(@RequestBody @Validated CustomCalendarVO<WorkCalendarRuleCreateVO> createVO) {
		if (StringUtil.isBlank(createVO.getGroupCode())) {
			createVO.setGroupCode(defaultGroupCode);
		}
		
		this.workCalendarRuleHandler.batchCreateCalednarRule(createVO);
        return ResponseUtil.successResult("保存成功");
    }
    
    /**
     * 更新
     */
	@ApiOperation(value = "更新")
	@RequestMapping(value = "updateWorkCalendarRule")
    public ResponseResult updateWorkCalendarRule(@RequestBody @Validated CustomCalendarVO<WorkCalendarRuleUpdateVO> updateVO) {
		if (StringUtil.isBlank(updateVO.getGroupCode())) {
			updateVO.setGroupCode(defaultGroupCode);
		}
		
		this.workCalendarRuleHandler.batchUpdateCalednarRule(updateVO);
        return ResponseUtil.successResult("更新成功");
    }

    /**
     * 删除
     */
    @ApiOperation(value = "删除")
    @RequestMapping(value = "deleteWorkCalendarRule")
    public ResponseResult deleteWorkCalendarRule(@RequestBody @Validated WorkCalendarRuleDeleteVO deleteVO) {
    	if (StringUtil.isBlank(deleteVO.getGroupCode())) {
			deleteVO.setGroupCode(defaultGroupCode);
		}
    	
    	// 规则ID和工作历ID必须存在其一
    	String ruleId = deleteVO.getId();
    	String calendarId = deleteVO.getCalendarId();
    	if (StringUtil.isBlank(ruleId) && StringUtil.isBlank(calendarId)) {
    		return ResponseUtil.errorResult(ResponseCode.A0400.getCode(), "规则ID和工作历ID至少存在其一");
		}
    	if (StringUtil.isNotBlank(ruleId)) {
    		//先判断原规则数据是否存在
    		WorkCalendarRule calendarRule = this.workCalendarRuleService.getById(ruleId);
    		if (calendarRule == null) {
    			return ResponseUtil.errorResult(ResponseCode.C0320.getCode(), "规则信息不存在");
    		}
		}
    	
    	boolean result = false;
    	Integer dictTypeLevel = null;
    	if (StringUtil.isNotBlank(calendarId)) {
    		// 获取项目下所有的工作历信息
    		QueryWrapper<WorkCalendar> queryWrapper = new WorkCalendar.Builder().createQueryWrapper().groupCodeEq(deleteVO.getGroupCode())
    				.projectIdEq(deleteVO.getProjectId()).builderQueryWrapper();
    		List<WorkCalendar> workCalendars = this.workCalendarService.list(queryWrapper);
    		if (CollectionUtil.isEmpty(workCalendars)) {
    			return ResponseUtil.errorResult(ResponseCode.C0320.getCode(), "工作历主信息不存在");
    		}
    		// 判断此项目下，还有没有额外的工作历类型了，没有，删除项目下全部
    		for (WorkCalendar workCalendar : workCalendars) {
				if (calendarId.equals(workCalendar.getId())) {
					result = true;
					break;
				}
			}
    		if (!result) {
    			return ResponseUtil.errorResult(ResponseCode.C0320.getCode(), "工作历主信息不存在");
			}
    		dictTypeLevel = workCalendars.size() == 1 ? 1 : 2;
		}
    	
    	WorkCalendarRule workCalendarRule = new WorkCalendarRule();
    	BeanUtils.copyProperties(deleteVO, workCalendarRule);
    	workCalendarRule.setUpdateUser(deleteVO.getUserId());
    	result = workCalendarRuleService.deleteWorkCalendarRule(workCalendarRule, dictTypeLevel);
        return result ? ResponseUtil.successResult("删除成功") : ResponseUtil.errorResult("删除失败");
    }
    
}
