package xiaoqu.home.open.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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.EscalationUserExport;
import xiaoqu.home.open.controller.input.EscalationUserPageInput;
import xiaoqu.home.open.controller.input.grid.GridSelectInput3;
import xiaoqu.home.open.controller.input.task.GridAndSceneInput;
import xiaoqu.home.open.controller.insert.EscalationUserInsertInput;
import xiaoqu.home.open.controller.insert.EscalationUserUpdateInput;
import xiaoqu.home.open.controller.output.EscalationUserOutput;
import xiaoqu.home.open.model.db1.District;
import xiaoqu.home.open.model.db1.User;
import xiaoqu.home.open.model.db2.EscalationServiceArea;
import xiaoqu.home.open.model.db2.EscalationUser;
import xiaoqu.home.open.model.db2.FieldWebpageAuthority;
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.EscalationServiceAreaService;
import xiaoqu.home.open.service.db2.EscalationUserService;
import xiaoqu.home.open.service.db2.FieldWebpageAuthorityService;
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 = "/escalationUser")
@Api(value = "用户中心服务", description = "用户中心服务")
@Slf4j(topic = "Controller")
public class EscalationUserController {
	@Autowired
	private EscalationUserService escalationUserService;
	@Autowired
	private EscalationServiceAreaService escalationServiceAreaService;

	@Autowired
	private DistrictService districtService;

	@Autowired
	private FieldWebpageAuthorityService fieldWebpageAuthorityService;

	@ApiOperation(value = "分页查询")
	@ResponseBody
	@RequestMapping(value = "/pageList", method = RequestMethod.POST)
	public BaseOutput<PageOutput<EscalationUserOutput>> pageList(HttpServletRequest request, @RequestBody EscalationUserPageInput input) {
		PageOutput<EscalationUserOutput> output = new PageOutput<EscalationUserOutput>();
		Long districtId = input.getDistrictId();
		if (StringUtil.isNull(districtId)) {
			return ResultResponseBeanUtil.fail("请选择站点");
		}
		District district = districtService.getById(districtId);
		if (StringUtil.isNull(district)) {
			return ResultResponseBeanUtil.fail("选择的站点不存在");
		}

		QueryWrapper<EscalationUser> 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<EscalationUser> pageList = new Page<EscalationUser>(input.getPage(), input.getRows());
		List<EscalationUser> EscalationUserList = escalationUserService.page(pageList, wrapper).getRecords();
		List<EscalationUserOutput> outputBeans = new ArrayList<EscalationUserOutput>();
		for (EscalationUser escalationUser : EscalationUserList) {
			EscalationUserOutput escalationUserOutputOutput = new EscalationUserOutput();
			BeanUtils.copyProperties(escalationUser, escalationUserOutputOutput);
//			@ApiModelProperty(value = "服务区域个数")
			QueryWrapper<EscalationServiceArea> escalationServiceAreaWrapper = WrapperUtils.getWrapper(false);
			escalationServiceAreaWrapper.eq("user_id", escalationUserOutputOutput.getUserId());
			escalationServiceAreaWrapper.eq("district_id", districtId);
			List<EscalationServiceArea> escalationServiceAreaList = escalationServiceAreaService.list(escalationServiceAreaWrapper);
			escalationUserOutputOutput.setManageAreaCount(escalationServiceAreaList.size());
			List<GridSelectInput3> serviceAreas = new ArrayList<GridSelectInput3>();
			for (EscalationServiceArea userToServiceArea : escalationServiceAreaList) {
				GridSelectInput3 gridSelectInput2 = new GridSelectInput3();
				if (userToServiceArea.getServiceType() == 0) {
					gridSelectInput2.setId(userToServiceArea.getServiceAreaId() + "_" + userToServiceArea.getGridScenesLevel());
				} else {
					gridSelectInput2.setId(userToServiceArea.getServiceAreaId() + "_s" + userToServiceArea.getGridScenesLevel());
				}
				serviceAreas.add(gridSelectInput2);
			}
			escalationUserOutputOutput.setServiceAreas(serviceAreas);
			outputBeans.add(escalationUserOutputOutput);
		}
		output.setPage(pageList.getCurrent());
		output.setRecords(pageList.getTotal());
		output.setTotal(pageList.getPages());
		output.setRows(outputBeans);
		return ResultResponseBeanUtil.success(output);
	}

	@ApiOperation(value = "导出")
	@PostMapping("/export")
	public void export(HttpServletRequest request, HttpServletResponse response, @RequestBody EscalationUserPageInput input) throws IOException {
		Long districtId = input.getDistrictId();
		if (districtId == null || districtId == 0) {
			return;
		}
		User user = UserUtils.getUser(request);
		District district = districtService.getById(districtId);
		if (district == null) {
			return;
		}
		List<EscalationUserExport> outList = new ArrayList<EscalationUserExport>();
		QueryWrapper<EscalationUser> wrapper = WrapperUtils.getWrapper(false);
		wrapper = WrapperUtils.beanToWrapper(wrapper, input);

		List<EscalationUser> escalationUserList = escalationUserService.list(wrapper);
		for (EscalationUser escalationUser : escalationUserList) {
			EscalationUserExport escalationUserExport = new EscalationUserExport();
			BeanUtils.copyProperties(escalationUser, escalationUserExport);
			QueryWrapper<EscalationServiceArea> escalationServiceAreaWrapper = WrapperUtils.getWrapper(false);
			escalationServiceAreaWrapper.eq("user_id", escalationUser.getUserId());
			escalationServiceAreaWrapper.eq("district_id", districtId);
			List<EscalationServiceArea> escalationServiceAreaList = escalationServiceAreaService.list(escalationServiceAreaWrapper);
			escalationUserExport.setManageAreaCount(escalationServiceAreaList.size());
			outList.add(escalationUserExport);
		}
		List<FieldWebpageAuthority> fieldList = fieldWebpageAuthorityService.getExportFieldList(input.getWebId(), user.getPropertyAuthorityId());
		String[] exportColumns = WrapperUtils.entityToColumns(fieldList);
		ExcelUtil<EscalationUserExport> util = new ExcelUtil<EscalationUserExport>(EscalationUserExport.class);
		util.exportExcelByColumns(response, outList, "用户上报管理人", exportColumns);
	}
	@Autowired
	private UserService userService;

	@ApiOperation(value = "编辑")
	@ResponseBody
	@AvoidRepeatSubmit
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public BaseOutput<String> update(HttpServletRequest request, @RequestBody EscalationUserUpdateInput input) {
		User user = UserUtils.getUser(request);
		Long districtId = input.getDistrictId();
		Long userId = input.getUserId();
		if (districtId == null || districtId == 0) {
			return ResultResponseBeanUtil.fail("请选择站点");
		}
		District district = districtService.getById(districtId);
		if (district == null) {
			return ResultResponseBeanUtil.fail("选择的站点不存在");
		}
		QueryWrapper<EscalationUser> wrapper = WrapperUtils.getWrapper(false);
		wrapper.eq("user_id", userId);
		wrapper.eq("district_id", districtId);
		wrapper.last("limit 1");
		EscalationUser temp = escalationUserService.getOne(wrapper);
		if (temp != null) {
			temp.setModifyName(user.getName());
			temp.setModifyId(user.getId());
			temp.setModifyTime(new Date());
			escalationUserService.updateById(temp);
// 			先删除之前的
			UpdateWrapper<EscalationServiceArea> updateWrapperUa = Wrappers.update();
			updateWrapperUa.eq("user_id", userId);
			updateWrapperUa.eq("soft_delete", 0);
			updateWrapperUa.eq("district_id", districtId);
			updateWrapperUa.setSql("soft_delete=1" + ",modify_time= NOW(),modify_id=" + user.getId());
			escalationServiceAreaService.update(updateWrapperUa);
			List<GridAndSceneInput> serviceAreas = input.getServiceAreas();
			if (StringUtil.isNotEmpty(serviceAreas)) {
				for (GridAndSceneInput gridSelectInput : serviceAreas) {
					EscalationServiceArea userToServiceArea = new EscalationServiceArea();
					userToServiceArea.setUserId(userId);
					userToServiceArea.setCreateId(user.getId());
					userToServiceArea.setCreateTime(new Date());
					userToServiceArea.setServiceAreaId(gridSelectInput.getGridId());
					if (gridSelectInput.getIsscene() == 1) {
						userToServiceArea.setServiceAreaId(gridSelectInput.getSceneId());
					}
					userToServiceArea.setServiceAreaName(gridSelectInput.getName());
					userToServiceArea.setServiceType(gridSelectInput.getIsscene());
					userToServiceArea.setGridScenesLevel(gridSelectInput.getLevel());
					userToServiceArea.setDistrictId(districtId);
					escalationServiceAreaService.save(userToServiceArea);
				}
			}
		}else {
			return ResultResponseBeanUtil.fail("该记录不存在");
		}
		return ResultResponseBeanUtil.success("操作成功");
	}
	@ApiOperation(value = "删除")
	@ResponseBody
	@AvoidRepeatSubmit
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public BaseOutput<String> delete(HttpServletRequest request, @RequestBody IdEntity input) {
		User user = UserUtils.getUser(request);
		EscalationUser temp = escalationUserService.getById(input.getId());
		if (temp != null) {
			temp.setModifyName(user.getName());
			temp.setModifyId(user.getId());
			temp.setModifyTime(new Date());
			temp.setSoftDelete(1);
			escalationUserService.updateById(temp);
// 			先删除之前的
			UpdateWrapper<EscalationServiceArea> updateWrapperUa = Wrappers.update();
			updateWrapperUa.eq("user_id", temp.getUserId());
			updateWrapperUa.eq("soft_delete", 0);
			updateWrapperUa.eq("district_id", temp.getDistrictId());
			updateWrapperUa.setSql("soft_delete=1" + ",modify_time= NOW(),modify_id=" + user.getId());
			escalationServiceAreaService.update(updateWrapperUa);
		}else {
			return ResultResponseBeanUtil.fail("该记录不存在");
		}
		return ResultResponseBeanUtil.success("删除成功");
	}
	
	@ApiOperation(value = "新增")
	@ResponseBody
	@AvoidRepeatSubmit
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public BaseOutput<String> add(HttpServletRequest request, @RequestBody EscalationUserInsertInput input) {
		log.info("上报管理人添加=" + JSON.toJSONString(input));
		User user = UserUtils.getUser(request);
		Long districtId = input.getDistrictId();
		if (districtId == null || districtId == 0) {
			return ResultResponseBeanUtil.fail("请选择站点");
		}
		District district = districtService.getById(districtId);
		if (district == null) {
			return ResultResponseBeanUtil.fail("选择的站点不存在");
		}
		List<Long> userIds = input.getUserIds();
		if (StringUtil.isEmpty(userIds)) {
			return ResultResponseBeanUtil.fail("选择管理人员");
		}
		for (Long userId : userIds) {

			QueryWrapper<EscalationUser> wrapper = WrapperUtils.getWrapper(false);
			wrapper.eq("user_id", userId);
			wrapper.eq("district_id", districtId);
			wrapper.last("limit 1");
			EscalationUser temp = escalationUserService.getOne(wrapper);
			if (temp != null) {
				temp.setModifyName(user.getName());
				temp.setModifyId(user.getId());
				temp.setModifyTime(new Date());
				escalationUserService.updateById(temp);
//	 			先删除之前的
				UpdateWrapper<EscalationServiceArea> updateWrapperUa = Wrappers.update();
				updateWrapperUa.eq("user_id", userId);
				updateWrapperUa.eq("soft_delete", 0);
				updateWrapperUa.eq("district_id", districtId);
				updateWrapperUa.setSql("soft_delete=1" + ",modify_time= NOW(),modify_id=" + user.getId());
				escalationServiceAreaService.update(updateWrapperUa);
				List<GridAndSceneInput> serviceAreas = input.getServiceAreas();
				if (StringUtil.isNotEmpty(serviceAreas)) {
					for (GridAndSceneInput gridSelectInput : serviceAreas) {
						EscalationServiceArea userToServiceArea = new EscalationServiceArea();
						userToServiceArea.setUserId(userId);
						userToServiceArea.setCreateId(user.getId());
						userToServiceArea.setCreateTime(new Date());
						userToServiceArea.setServiceAreaId(gridSelectInput.getGridId());
						if (gridSelectInput.getIsscene() == 1) {
							userToServiceArea.setServiceAreaId(gridSelectInput.getSceneId());
						}
						userToServiceArea.setServiceAreaName(gridSelectInput.getName());
						userToServiceArea.setServiceType(gridSelectInput.getIsscene());
						userToServiceArea.setGridScenesLevel(gridSelectInput.getLevel());
						userToServiceArea.setDistrictId(districtId);
						escalationServiceAreaService.save(userToServiceArea);
					}
				}
			} else {
				EscalationUser escalationUserNew = new EscalationUser();
				escalationUserNew.setCreateName(user.getName());
				escalationUserNew.setCreateId(user.getId());
				escalationUserNew.setCreateTime(new Date());
				escalationUserNew.setDistrictId(districtId);
				escalationUserNew.setDistrictName(district.getDistrictName());
				User temPUser = userService.getById(userId);
				escalationUserNew.setUserId(userId);
				escalationUserNew.setMobile(temPUser.getMobile());
				escalationUserNew.setUserName(temPUser.getName());
				escalationUserService.save(escalationUserNew);
				List<GridAndSceneInput> serviceAreas = input.getServiceAreas();
				if (StringUtil.isNotEmpty(serviceAreas)) {
					for (GridAndSceneInput gridSelectInput : serviceAreas) {
						EscalationServiceArea userToServiceArea = new EscalationServiceArea();
						userToServiceArea.setUserId(userId);
						userToServiceArea.setCreateId(user.getId());
						userToServiceArea.setCreateTime(new Date());
						userToServiceArea.setServiceAreaId(gridSelectInput.getGridId());
						if (gridSelectInput.getIsscene() == 1) {
							userToServiceArea.setServiceAreaId(gridSelectInput.getSceneId());
						}
						userToServiceArea.setServiceAreaName(gridSelectInput.getName());
						userToServiceArea.setServiceType(gridSelectInput.getIsscene());
						userToServiceArea.setGridScenesLevel(gridSelectInput.getLevel());
						userToServiceArea.setDistrictId(districtId);
						escalationServiceAreaService.save(userToServiceArea);
					}
				}
			}

		}
		return ResultResponseBeanUtil.success("操作成功");
	}

}
