package xiaoqu.home.open.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
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.ResponseBody;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import xiaoqu.home.open.controller.export.PunchRecordExport;
import xiaoqu.home.open.controller.input.PunchRecordPageInput;
import xiaoqu.home.open.controller.input.task.GridAndSceneInput;
import xiaoqu.home.open.controller.output.PunchRecordOutput;
import xiaoqu.home.open.model.db1.User;
import xiaoqu.home.open.model.db2.FieldWebpageAuthority;
import xiaoqu.home.open.model.db2.PunchRecord;
import xiaoqu.home.open.publicBean.BaseOutput;
import xiaoqu.home.open.publicBean.PageOutput;
import xiaoqu.home.open.service.db2.FieldWebpageAuthorityService;
import xiaoqu.home.open.service.db2.PunchRecordService;
import xiaoqu.home.open.utils.ResultResponseBeanUtil;
import xiaoqu.home.open.utils.StringUtil;
import xiaoqu.home.open.utils.UserUtils;
import xiaoqu.home.open.utils.WrapperUtils;
import xiaoqu.home.open.utils.poi.ExcelUtil;

@Controller
@RequestMapping(value = "/punchRecord")
@Api(value = "打卡记录接口", description = "打卡记录接口")
public class PunchRecordController {
	@Autowired
	private PunchRecordService punchRecordService;
	@Autowired
	private FieldWebpageAuthorityService fieldWebpageAuthorityService;

	@ApiOperation(value = "分页查询")
	@ResponseBody
	@RequestMapping(value = "/pageList", method = RequestMethod.POST)
	public BaseOutput<PageOutput<PunchRecordOutput>> pageList(HttpServletRequest request, @RequestBody PunchRecordPageInput input) {
		PageOutput<PunchRecordOutput> output = new PageOutput<PunchRecordOutput>();
		Long districtId = input.getDistrictId();
		if (StringUtil.isNull(districtId)) {
			return ResultResponseBeanUtil.fail("请选择站点");
		}
		if (StringUtil.isNotEmpty(input.getPunchTimeStart())) {
			input.setPunchTimeStart(input.getPunchTimeStart()+" 00:00:00");
			input.setPunchTimeEnd(input.getPunchTimeEnd()+" 23:59:59");
		}
		QueryWrapper<PunchRecord> wrapper = WrapperUtils.getWrapper(false);
		if (StringUtil.isNotEmpty(input.getGridAndScenes())) {
			Set<Long> taskIds = GetQueryCiteria(input);
			if (taskIds.size() == 0) {
				return ResultResponseBeanUtil.success(output);
			} else {
				wrapper.in("id", taskIds);
			}
			input.setGridAndScenes(null);
		}
		wrapper = WrapperUtils.beanToWrapper(wrapper, input);
		User user = UserUtils.getUser(request);
		List<FieldWebpageAuthority> fieldList = fieldWebpageAuthorityService.getFieldList(input.getWebId(), user.getPropertyAuthorityId());
		String[] columns = WrapperUtils.entityToColumns(fieldList);
		wrapper.select(columns);
		Page<PunchRecord> pageList = new Page<PunchRecord>(input.getPage(), input.getRows());
		List<PunchRecord> entityList = punchRecordService.page(pageList, wrapper).getRecords();
		List<PunchRecordOutput> outList = new ArrayList<PunchRecordOutput>();
		for (PunchRecord bean : entityList) {
			PunchRecordOutput outputBean = new PunchRecordOutput();
			BeanUtils.copyProperties(bean, outputBean);
			outList.add(outputBean);
		}
		output.setPage(pageList.getCurrent());
		output.setRecords(pageList.getTotal());
		output.setTotal(pageList.getPages());
		output.setRows(outList);
		return ResultResponseBeanUtil.success(output);
	}
	/********
	 * 查询列表和导出统一处理查询条件
	 * 
	 * @param input
	 * @return
	 */
	private Set<Long> GetQueryCiteria(PunchRecordPageInput input) {
		Set<Long> taskIds = new HashSet<Long>();
		List<GridAndSceneInput> gridAndScenes = input.getGridAndScenes();
		for (GridAndSceneInput gridAndSceneInput : gridAndScenes) {
			QueryWrapper<PunchRecord> wrapper = WrapperUtils.getWrapper(false);
			wrapper.eq("district_id", input.getDistrictId());
			Integer level = gridAndSceneInput.getLevel();
			Long gridId = gridAndSceneInput.getGridId();
			Long sceneId = gridAndSceneInput.getSceneId();
			Integer isscene = gridAndSceneInput.getIsscene();
			if (isscene == 0) {
				switch (level) {
				case 1:
					wrapper.eq("building_id", gridId);
					break;
				case 2:
					wrapper.eq("floor_id", gridId);
					break;
				default:
					wrapper.eq("multistage_grid_id", gridId);
					break;
				}
			} else {
				wrapper.eq("scenes_id", sceneId);
				wrapper.eq("scenes_level", level);
			}
			if (StringUtil.isNotEmpty(input.getPunchTimeStart())) {
				wrapper.ge("punch_time", input.getPunchTimeStart());
				wrapper.le("punch_time", input.getPunchTimeEnd());
			}
			List<PunchRecord> punchRecordS = punchRecordService.list(wrapper);
			taskIds.addAll(punchRecordS.stream().map(punchRecord -> punchRecord.getId()).collect(Collectors.toSet()));
		}
		return taskIds;
	}
	@ApiOperation(value = "导出")
	@PostMapping("/export")
	public void export(HttpServletRequest request, HttpServletResponse response, @RequestBody PunchRecordPageInput input) throws IOException {
		Long districtId = input.getDistrictId();
		if (districtId == null || districtId == 0) {
			return;
		}
		if (StringUtil.isNotEmpty(input.getPunchTimeStart())) {
			input.setPunchTimeStart(input.getPunchTimeStart()+" 00:00:00");
			input.setPunchTimeEnd(input.getPunchTimeEnd()+" 23:59:59");
		}
		List<PunchRecordExport> outList = new ArrayList<PunchRecordExport>();
		User user = UserUtils.getUser(request);
		QueryWrapper<PunchRecord> wrapper = WrapperUtils.getWrapper(false);
		if (StringUtil.isNotEmpty(input.getGridAndScenes())) {
			Set<Long> taskIds = GetQueryCiteria(input);
			if (taskIds.size() == 0) {
				return;
			} else {
				wrapper.in("id", taskIds);
			}
			input.setGridAndScenes(null);
		}
		wrapper = WrapperUtils.beanToWrapper(wrapper, input);
		List<PunchRecord> entityList = punchRecordService.list(wrapper);
		for (PunchRecord bean : entityList) {
			PunchRecordExport outputBean = new PunchRecordExport();
			BeanUtils.copyProperties(bean, outputBean);
			outList.add(outputBean);
		}
		List<FieldWebpageAuthority> fieldList = fieldWebpageAuthorityService.getExportFieldList(input.getWebId(), user.getPropertyAuthorityId());
		String[] exportColumns = WrapperUtils.entityToColumns(fieldList);
		ExcelUtil<PunchRecordExport> util = new ExcelUtil<PunchRecordExport>(PunchRecordExport.class);
		util.exportExcelByColumns(response, outList, "打卡记录", exportColumns);
	}
}
