package xiaoqu.home.open.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
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.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import xiaoqu.home.open.aop.AvoidRepeatSubmit;
import xiaoqu.home.open.controller.export.WorkGroupExport;
import xiaoqu.home.open.controller.input.workgroup.WorkGroupInsertInput;
import xiaoqu.home.open.controller.input.workgroup.WorkGroupPageInput;
import xiaoqu.home.open.controller.input.workgroup.WorkGroupToPrincipalInput;
import xiaoqu.home.open.controller.input.workgroup.WorkGroupToPrincipalPageInput;
import xiaoqu.home.open.controller.insert.WorkGroupToPrincipalInsertInput;
import xiaoqu.home.open.controller.output.WorkGroupOutput;
import xiaoqu.home.open.model.db1.District;
import xiaoqu.home.open.model.db1.User;
import xiaoqu.home.open.model.db2.FieldWebpageAuthority;
import xiaoqu.home.open.model.db2.WorkGroup;
import xiaoqu.home.open.model.db2.WorkGroupToPrincipal;
import xiaoqu.home.open.publicBean.BaseOutput;
import xiaoqu.home.open.publicBean.IdEntity;
import xiaoqu.home.open.publicBean.PageOutput;
import xiaoqu.home.open.service.db1.DistrictService;
import xiaoqu.home.open.service.db1.UserService;
import xiaoqu.home.open.service.db2.FieldWebpageAuthorityService;
import xiaoqu.home.open.service.db2.ModifyLogService;
import xiaoqu.home.open.service.db2.WorkGroupService;
import xiaoqu.home.open.service.db2.WorkGroupToPrincipalService;
import xiaoqu.home.open.utils.ClassCompareUtil;
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 = "/workGroup")
@Api(value = "班组管理", description = "班组管理")
@Slf4j(topic = "Controller")
public class WorkGroupController {
	@Autowired
	private DistrictService districtService;
	@Autowired
	private FieldWebpageAuthorityService fieldWebpageAuthorityService;
	@Autowired
	private UserService userService;
	@Autowired
	private WorkGroupService workGroupService;
	@Autowired
	private WorkGroupToPrincipalService workGroupToPrincipalService;

	@ApiOperation(value = "分页查询")
	@ResponseBody
	@RequestMapping(value = "/pageList", method = RequestMethod.POST)
	public BaseOutput<PageOutput<WorkGroupOutput>> pageList(HttpServletRequest request, @RequestBody WorkGroupPageInput input) {
		PageOutput<WorkGroupOutput> output = new PageOutput<WorkGroupOutput>();
		Long districtId = input.getDistrictId();
		if (StringUtil.isNull(districtId)) {
			return ResultResponseBeanUtil.fail("请选择站点");
		}
		QueryWrapper<WorkGroup> wrapper = WrapperUtils.getWrapper(false);
		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<WorkGroup> pageList = new Page<WorkGroup>(input.getPage(), input.getRows());
		List<WorkGroup> entityList = workGroupService.page(pageList, wrapper).getRecords();
		List<WorkGroupOutput> outList = new ArrayList<WorkGroupOutput>();
		for (WorkGroup bean : entityList) {
			WorkGroupOutput outputBean = new WorkGroupOutput();
			BeanUtils.copyProperties(bean, outputBean);
//			@ApiModelProperty(value = "班组成员数量")
//			private Integer groupMemberCount;
			QueryWrapper<WorkGroupToPrincipal> workGroupToPrincipalWrapper = WrapperUtils.getWrapper(false);
			workGroupToPrincipalWrapper.eq("work_group_id", outputBean.getId());
			outputBean.setGroupMemberCount(workGroupToPrincipalService.count(workGroupToPrincipalWrapper));
//			@ApiModelProperty(value = "班组负责人")
//			private String groupPrincipal;
			workGroupToPrincipalWrapper.eq("principal_flag", 1);
			List<WorkGroupToPrincipal> workGroupToPrincipalList = workGroupToPrincipalService.list(workGroupToPrincipalWrapper);
			outputBean.setGroupPrincipal(workGroupToPrincipalList.stream().map(workGroupToPrincipal -> workGroupToPrincipal.getUserName()).collect(Collectors.joining(",")));
			outList.add(outputBean);
		}
		output.setPage(pageList.getCurrent());
		output.setRecords(pageList.getTotal());
		output.setTotal(pageList.getPages());
		output.setRows(outList);
		return ResultResponseBeanUtil.success(output);
	}

	@Autowired
	private ModifyLogService modifyLogService;

	@ApiOperation(value = "新增或更新工作组")
	@ResponseBody
	@AvoidRepeatSubmit
	@RequestMapping(value = "/addOrUpdate", method = RequestMethod.POST)
	public BaseOutput<String> addOrUpdate(HttpServletRequest request, @RequestBody WorkGroupInsertInput input) {
		log.info("工作组添加=" + JSON.toJSONString(input));
		User user = UserUtils.getUser(request);
		Long districtId = input.getDistrictId();
		if (StringUtil.isNull(districtId)) {
			return ResultResponseBeanUtil.fail("请选择站点");
		}
		District district = districtService.getById(districtId);
		if (StringUtil.isNull(district)) {
			return ResultResponseBeanUtil.fail("选择的站点不存在");
		}
		if (StringUtil.isNotNull(input.getId())) {// 修改
			WorkGroup workGroup = workGroupService.getById(input.getId());
			if (!workGroup.getWorkGroupName().equals(input.getWorkGroupName())) {
				QueryWrapper<WorkGroup> wrapperB = WrapperUtils.getWrapper(false);
				wrapperB.eq("work_group_name", input.getWorkGroupName());
				wrapperB.eq("district_id", input.getDistrictId());
				int countB = workGroupService.count(wrapperB);
				if (countB > 0) {
					return ResultResponseBeanUtil.fail("记录已存在，请修改后再提交");
				}
			}
			WorkGroup workGroupTemp = workGroupService.getById(input.getId());
			if (StringUtil.isNull(workGroup)) {
				return ResultResponseBeanUtil.fail("该工作组不存在,请确认");
			}
			BeanUtils.copyProperties(input, workGroup);
			workGroup.setModifyName(user.getName());
			workGroup.setModifyId(user.getId());
			workGroup.setModifyTime(new Date());
			workGroup.setDistrictName(district.getDistrictName());
			workGroupService.updateById(workGroup);
			modifyLogService.addLog("班组管理", JSON.toJSONString(ClassCompareUtil.compareFields(workGroupTemp, workGroup, null)), 0, 1);
		} else {
			WorkGroup workGroup = new WorkGroup();
			QueryWrapper<WorkGroup> wrapperB = WrapperUtils.getWrapper(false);
			wrapperB.eq("work_group_name", input.getWorkGroupName());
			wrapperB.eq("district_id", input.getDistrictId());
			int countB = workGroupService.count(wrapperB);
			if (countB > 0) {
				return ResultResponseBeanUtil.fail("记录已存在，请修改后再提交");
			}
			BeanUtils.copyProperties(input, workGroup);
			workGroup.setCreateName(user.getName());
			workGroup.setCreateId(user.getId());
			workGroup.setCreateTime(new Date());
//		    @ApiModelProperty(value = "所属代理ID")
			workGroup.setAgentId(district.getAgentId());
//		    @ApiModelProperty(value = "所属物业ID")
			workGroup.setPropertyId(district.getPropertyId());
//		    @ApiModelProperty(value = "所属站点ID")
			workGroup.setDistrictId(districtId);
			workGroup.setDistrictName(district.getDistrictName());
			workGroupService.save(workGroup);
		}
		return ResultResponseBeanUtil.success("操作成功");
	}

	@ApiOperation(value = "成员查询")
	@ResponseBody
	@RequestMapping(value = "/memberList", method = RequestMethod.POST)
	public BaseOutput<List<WorkGroupToPrincipalInput>> memberList(HttpServletRequest request, @RequestBody WorkGroupToPrincipalPageInput input) {
		Long workGroupId = input.getWorkGroupId();
		if (StringUtil.isNull(workGroupId)) {
			return ResultResponseBeanUtil.fail("请选择班组");
		}
		QueryWrapper<WorkGroupToPrincipal> wrapper = WrapperUtils.getWrapper(false);
		wrapper = WrapperUtils.beanToWrapper(wrapper, input);
		List<WorkGroupToPrincipal> entityList = workGroupToPrincipalService.list(wrapper);
		List<WorkGroupToPrincipalInput> outList = new ArrayList<WorkGroupToPrincipalInput>();
		for (WorkGroupToPrincipal bean : entityList) {
			WorkGroupToPrincipalInput outputBean = new WorkGroupToPrincipalInput();
			BeanUtils.copyProperties(bean, outputBean);
			outputBean.setId(bean.getUserId());
			outputBean.setMobile(bean.getMobile());
			outputBean.setName(bean.getUserName());
			outputBean.setPrincipalFlag(bean.getPrincipalFlag());
			outList.add(outputBean);
		}
		return ResultResponseBeanUtil.success(outList);
	}

	@ApiOperation(value = "新增或修改组成员")
	@ResponseBody
	@AvoidRepeatSubmit
	@RequestMapping(value = "/addorUpdateMember", method = RequestMethod.POST)
	public BaseOutput<String> addorUpdateMember(HttpServletRequest request, @RequestBody WorkGroupToPrincipalInsertInput input) {
		Long workGroupId = input.getWorkGroupId();
		User user1 = UserUtils.getUser(request);
		if (StringUtil.isNull(workGroupId)) {
			return ResultResponseBeanUtil.fail("请选择班组");
		}
		List<WorkGroupToPrincipalInput> workMember = input.getWorkMember();
		if (StringUtil.isEmpty(workMember)) {
			return ResultResponseBeanUtil.fail("请选择班组成员");
		}
		UpdateWrapper<WorkGroupToPrincipal> updateWrapperWm = Wrappers.update();
		updateWrapperWm.eq("work_group_id", workGroupId);
		updateWrapperWm.eq("soft_delete", 0);
		updateWrapperWm.setSql("soft_delete=1" + ",modify_time= NOW(),modify_id=" + user1.getId());
		workGroupToPrincipalService.update(updateWrapperWm);
		for (WorkGroupToPrincipalInput workGroupToPrincipalInput : workMember) {
			WorkGroupToPrincipal workGroupToPrincipal = new WorkGroupToPrincipal();
			User user = userService.getById(workGroupToPrincipalInput.getId());
			if (user == null) {
				continue;
			}
			BeanUtils.copyProperties(user, workGroupToPrincipal, "id", "modify_name", "modify_id");
			workGroupToPrincipal.setWorkGroupId(workGroupId);
			workGroupToPrincipal.setUserId(workGroupToPrincipalInput.getId());
			workGroupToPrincipal.setUserName(workGroupToPrincipalInput.getName());
			workGroupToPrincipal.setMobile(workGroupToPrincipalInput.getMobile());
			workGroupToPrincipal.setPrincipalFlag(workGroupToPrincipalInput.getPrincipalFlag());
			WorkGroup WorkGroup = workGroupService.getById(workGroupId);
			workGroupToPrincipal.setWorkGroupName(WorkGroup.getWorkGroupName());
			workGroupToPrincipal.setDistrictId(WorkGroup.getDistrictId());
			workGroupToPrincipal.setAgentId(WorkGroup.getAgentId());
			workGroupToPrincipal.setAgentName(WorkGroup.getAgentName());
			workGroupToPrincipal.setPropertyId(WorkGroup.getPropertyId());
			workGroupToPrincipal.setPropertyName(WorkGroup.getPropertyName());
			workGroupToPrincipal.setDistrictName(WorkGroup.getDistrictName());
			workGroupToPrincipalService.save(workGroupToPrincipal);
		}
		return ResultResponseBeanUtil.success("操作成功");
	}

	@ApiOperation(value = "更新组成员")
	@ResponseBody
	@AvoidRepeatSubmit
	@RequestMapping(value = "/updateMember", method = RequestMethod.POST)
	public BaseOutput<String> updateMember(HttpServletRequest request, @RequestBody WorkGroupToPrincipalInput input) {
		Long id = input.getId();
		WorkGroupToPrincipal workGroupToPrincipal = workGroupToPrincipalService.getById(id);
		if (workGroupToPrincipal == null) {
			return ResultResponseBeanUtil.fail("记录不存在");
		}
		workGroupToPrincipal.setPrincipalFlag(input.getPrincipalFlag());
		workGroupToPrincipalService.updateById(workGroupToPrincipal);
		return ResultResponseBeanUtil.success("操作成功");
	}

	@ApiOperation(value = "删除组成员")
	@ResponseBody
	@AvoidRepeatSubmit
	@RequestMapping(value = "/deleteMember", method = RequestMethod.POST)
	public BaseOutput<String> deleteMember(HttpServletRequest request, @RequestBody IdEntity input) {
		Long id = input.getId();
		WorkGroupToPrincipal workGroupToPrincipal = workGroupToPrincipalService.getById(id);
		if (workGroupToPrincipal == null) {
			return ResultResponseBeanUtil.fail("记录不存在");
		}
		if (workGroupToPrincipal.getSoftDelete() == 1) {
			return ResultResponseBeanUtil.fail("记录不存在");
		}
		workGroupToPrincipal.setSoftDelete(1);
		workGroupToPrincipalService.updateById(workGroupToPrincipal);
		return ResultResponseBeanUtil.success("操作成功");
	}

	@ApiOperation(value = "删除工作组")
	@ResponseBody
	@AvoidRepeatSubmit
	@RequestMapping(value = "/deleteWorkGroup", method = RequestMethod.POST)
	public BaseOutput<String> deleteWorkGroup(HttpServletRequest request, @RequestBody IdEntity input) {
		Long id = input.getId();
		WorkGroup workGroup = workGroupService.getById(id);
		if (workGroup == null) {
			return ResultResponseBeanUtil.fail("记录不存在");
		}
		if (workGroup.getSoftDelete() == 1) {
			return ResultResponseBeanUtil.fail("记录不存在");
		}
		workGroup.setSoftDelete(1);
		workGroupService.updateById(workGroup);
		QueryWrapper<WorkGroupToPrincipal> workGroupToPrincipalWrapper = WrapperUtils.getWrapper(false);
		workGroupToPrincipalWrapper.eq("work_group_id", id);
		List<WorkGroupToPrincipal> workGroupToPrincipalList = workGroupToPrincipalService.list(workGroupToPrincipalWrapper);
		for (WorkGroupToPrincipal workGroupToPrincipal : workGroupToPrincipalList) {
			workGroupToPrincipal.setSoftDelete(1);
			workGroupToPrincipalService.updateById(workGroupToPrincipal);
		}
		return ResultResponseBeanUtil.success("操作成功");
	}

	@ApiOperation(value = "班组导出")
	@PostMapping("/groupExport")
	public void groupExport(HttpServletRequest request, HttpServletResponse response, @RequestBody WorkGroupPageInput input) throws IOException {
		Long districtId = input.getDistrictId();
		if (StringUtil.isNull(districtId)) {
			return;
		}
		User user = UserUtils.getUser(request);
		QueryWrapper<WorkGroup> wrapper = WrapperUtils.getWrapper(false);
		wrapper = WrapperUtils.beanToWrapper(wrapper, input);
		List<WorkGroup> entityList = workGroupService.list(wrapper);
		List<WorkGroupExport> outList = new ArrayList<WorkGroupExport>();
		for (WorkGroup bean : entityList) {
			WorkGroupExport outputBean = new WorkGroupExport();
			BeanUtils.copyProperties(bean, outputBean);
			QueryWrapper<WorkGroupToPrincipal> workGroupToPrincipalWrapper = WrapperUtils.getWrapper(false);
			workGroupToPrincipalWrapper.eq("work_group_id", outputBean.getId());
			outputBean.setGroupMemberCount(workGroupToPrincipalService.count(workGroupToPrincipalWrapper));
			workGroupToPrincipalWrapper.eq("principal_flag", 1);
			List<WorkGroupToPrincipal> workGroupToPrincipalList = workGroupToPrincipalService.list(workGroupToPrincipalWrapper);
			outputBean.setGroupPrincipal(workGroupToPrincipalList.stream().map(workGroupToPrincipal -> workGroupToPrincipal.getUserName()).collect(Collectors.joining(",")));
			outList.add(outputBean);
		}
		List<FieldWebpageAuthority> fieldList = fieldWebpageAuthorityService.getExportFieldList(input.getWebId(), user.getPropertyAuthorityId());
		String[] exportColumns = WrapperUtils.entityToColumns(fieldList);
		ExcelUtil<WorkGroupExport> util = new ExcelUtil<WorkGroupExport>(WorkGroupExport.class);
		util.exportExcelByColumns(response, outList, "班组管理", exportColumns);
	}

}
