/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.security.trans.applyAndReport.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.security.common.Constant;
import org.security.common.util.ExcelUtil;
import org.security.flow.core.constant.ProcessConstant;
import org.security.flow.core.entity.BladeFlow;
import org.security.flow.core.entity.BladeFlowDef;
import org.security.flow.core.feign.IFlowClient;
import org.security.flow.core.utils.FlowUtil;
import org.security.system.feign.ISysClient;
import org.security.trans.applyAndReport.dto.DutyRecordsDTO;
import org.security.trans.applyAndReport.entity.DutyRecords;
import org.security.trans.applyAndReport.entity.DutyRecordsLines;
import org.security.trans.applyAndReport.service.IDutyRecordsLinesService;
import org.security.trans.applyAndReport.vo.DutyRecordsVO;
import org.security.trans.applyAndReport.mapper.DutyRecordsMapper;
import org.security.trans.applyAndReport.service.IDutyRecordsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.security.trans.applyAndReport.vo.ExportRecordsVO;
import org.security.trans.basic.service.IEmployeeService;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.support.Kv;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.Func;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 值班记录表 服务实现类
 *
 * @author BladeX
 * @since 2022-07-13
 */
@Service
@AllArgsConstructor
@Slf4j
public class DutyRecordsServiceImpl extends ServiceImpl<DutyRecordsMapper, DutyRecords> implements IDutyRecordsService {
	private final IDutyRecordsLinesService dutyRecordsLinesService;
	private final IFlowClient flowClient;
	private final ISysClient sysClient;
	private final IEmployeeService employeeService;

	/**
	 * 查询分页信息
	 *
	 * @param dutyRecordsDTO
	 * @param query
	 * @return
	 */
	@Override
	public IPage<DutyRecordsVO> selectDutyRecordsPage(DutyRecordsDTO dutyRecordsDTO, Query query) {
		IPage<DutyRecords> page = Condition.getPage(query);
		QueryWrapper<DutyRecords> queryWrapper = Condition.getQueryWrapper(BeanUtil.copyProperties(dutyRecordsDTO, DutyRecords.class));
		queryWrapper.lambda().orderByDesc(DutyRecords::getCreatedTime);
		IPage<DutyRecords> iPage = this.page(page, queryWrapper);
		IPage<DutyRecordsVO> res = new Page<>();
		List<DutyRecordsVO> Dvos = BeanUtil.copyProperties(iPage.getRecords(), DutyRecordsVO.class);
		res.setTotal(iPage.getTotal());
		res.setSize(iPage.getSize());
		res.setCurrent(iPage.getCurrent());
		res.setRecords(Dvos);
		return res;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean saveOrUpdateDutyRecords(DutyRecordsDTO dutyRecordsDTO) {
		DutyRecords dutyRecords = Func.copy(dutyRecordsDTO, DutyRecords.class);
		dutyRecords.setState(Constant.HANDIN_STATE_DRAFT);
		this.saveOrUpdate(dutyRecords);
		//明细表信息
		List<DutyRecordsLines> dutyRecordsLinesList = dutyRecordsDTO.getDutyRecordsLinesList();
		if (Func.isNotEmpty(dutyRecordsLinesList)) {
			dutyRecordsLinesList.forEach(item -> {
				item.setFormId(dutyRecords.getId());
			});
			//更新明细表数据
			dutyRecordsLinesService.saveOrUpdateBatch(dutyRecordsLinesList);
		}
		return this.saveOrUpdate(dutyRecords);
	}

	@Override
	public boolean handin(DutyRecordsDTO dutyRecordsDTO) {
		DutyRecords dutyRecords = Func.copy(dutyRecordsDTO, DutyRecords.class);
		R<BladeFlowDef> definitionRes = flowClient.getLatestProcessDefinitionByKey(ProcessConstant.DUTY_RECORDS_KEY);
		if (definitionRes.isSuccess()) {
			dutyRecords.setProcessDefinitionId(definitionRes.getData().getId());
		} else {
			throw new ServiceException("开启流程失败");
		}
		dutyRecords.setState(Constant.HANDIN_STATE_AUDIT);
		this.saveOrUpdate(dutyRecords);

		String businessTable = FlowUtil.getBusinessTable(DutyRecords.class);
		R<Integer> deptCategory = sysClient.getDeptCategory(Long.valueOf(AuthUtil.getUser().getDeptId()));
		if (!deptCategory.isSuccess()) {
			throw new ServiceException("查询部门类型失败，请检查后再试！");
		}
		Kv variables = Kv.create()
			.set("deptCategory", deptCategory.getData())
			.set(ProcessConstant.BUSINESS_ID_KEY, dutyRecords.getId())
			.set(ProcessConstant.START_PROC_USER_ID, AuthUtil.getUserId());
		if (1 == deptCategory.getData()) {
			variables.set(ProcessConstant.PASS_KEY, true);
		}
		R<BladeFlow> result = flowClient.startProcessInstanceById(dutyRecords.getProcessDefinitionId(), FlowUtil.getBusinessKey(businessTable, String.valueOf(dutyRecords.getId())), variables);
		if (result.isSuccess()) {
			log.debug("流程已启动,流程ID:" + result.getData().getProcessInstanceId());
			DutyRecords afterStartRecords = this.getById(dutyRecords.getId());
			// 返回流程id写入dutyRecords
			afterStartRecords.setProcessInstanceId(result.getData().getProcessInstanceId());

			//明细表信息
			List<DutyRecordsLines> dutyRecordsLinesList = dutyRecordsDTO.getDutyRecordsLinesList();
			if (Func.isNotEmpty(dutyRecordsLinesList)) {
				dutyRecordsLinesList.forEach(item -> {
					item.setFormId(afterStartRecords.getId());
				});
				//更新明细表数据
				dutyRecordsLinesService.saveOrUpdateBatch(dutyRecordsLinesList);
			}
			updateById(afterStartRecords);
			return true;
		} else {
			throw new ServiceException("开启流程失败");
		}
	}

	@Override
	public void exportData(HttpServletResponse httpServletResponse, List<String> idList) {
		log.info("---------------值班备勤导出开始---------------");
		List<DutyRecords> list;
		//导出用户选中数据
		if (Func.isNotEmpty(idList) && idList.size() > 0) {
			list = this.list(new QueryWrapper<DutyRecords>().lambda().in(DutyRecords::getId, idList));
		}//用户不选择任何数据，则导出该登录用户所属机构的值班数据
		else {
			list = this.list(new QueryWrapper<DutyRecords>().lambda().eq(DutyRecords::getDeptId, AuthUtil.getDeptId()));
		}
		//获取相关值班人员明细
		if (Func.isNotEmpty(list)) {
			log.info("值班备勤导出数据:[{}]",list);
			List<ExportRecordsVO> vos = new ArrayList<>();
			list.forEach(item -> {
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				ExportRecordsVO vo = Func.copy(item, ExportRecordsVO.class);
				vo.setStartTime(format.format(item.getStartTime()));
				vo.setEndTime(format.format(item.getEndTime()));
				vo.setType("1".equals(vo.getType()) ? "工作日" : "非工作日");
				vo.setPersonInCharge(employeeService.getById(item.getPersonInCharge()).getName());
				List<DutyRecordsLines> lines = dutyRecordsLinesService.list(new QueryWrapper<DutyRecordsLines>().lambda().eq(DutyRecordsLines::getFormId, item.getId()));
				List<String> personnelOnDuties = new ArrayList<>();
				if (Func.isNotEmpty(lines)) {
					lines.forEach(line -> {
						line.setPerson(employeeService.getById(line.getPerson()).getName());
						personnelOnDuties.add(line.getPerson().concat("-").concat(line.getPhone()));
					});
				}
				vo.setPersonnelOnDuties(Func.join(personnelOnDuties).replace(",","\n"));
				vos.add(vo);
			});
			//导出excel
			ExcelUtil.export(httpServletResponse, "值班备勤表", "sheet1", vos, ExportRecordsVO.class);
			log.info("---------------值班备勤导出结束---------------");
		}
	}

	@Override
	public DutyRecordsVO getDetailById(String id) {
		DutyRecords dutyRecords = super.getById(id);
		DutyRecordsVO dutyRecordsVO = Func.copy(dutyRecords, DutyRecordsVO.class);
		//获取明细信息
		List<DutyRecordsLines> lineList = dutyRecordsLinesService.list(new QueryWrapper<DutyRecordsLines>().eq("FORM_ID", id));
		if (Func.isNotEmpty(lineList)) {
			dutyRecordsVO.setDutyRecordsLinesList(lineList);
		}
		return dutyRecordsVO;
	}

}
