/*
 *      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.springblade.jobs.reportjob.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springblade.community.agency.entity.Agency;
import org.springblade.community.agency.service.IAgencyService;
import org.springblade.community.houseuser.entity.Houseuser;
import org.springblade.community.houseuser.service.IHouseuserService;
import org.springblade.community.residential.entity.Residential;
import org.springblade.community.residential.service.IResidentialService;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.jobs.reportjob.entity.ReportJob;
import org.springblade.jobs.reportjob.service.IReportJobService;
import org.springblade.jobs.reportjob.vo.ReportJobVO;
import org.springblade.openinterface.dto.estate.EstateRepairPushDto;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.validation.Valid;
import java.net.URI;
import java.util.List;
import java.util.Map;

/**
 * 报事工单 控制器
 *
 * @author BladeX
 * @since 2020-10-17
 */
@RestController
@AllArgsConstructor
@RequestMapping("jobs/reportjob")
@Api(value = "报事工单", tags = "报事工单接口")
public class ReportJobController extends BladeController {

	private IReportJobService reportJobService;
	private IAgencyService agencyService;
	private IResidentialService residentialService;
	private IHouseuserService houseuserService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入reportJob")
	public R<ReportJob> detail(ReportJob reportJob) {
		ReportJob detail = reportJobService.getOne(Condition.getQueryWrapper(reportJob));
		return R.data(detail);
	}

	/**
	 * 分页 报事工单
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入reportJob")
	public R<IPage<ReportJob>> list(@RequestParam Map<String,Object> reportJob, Query query) {

		Object agencyId = reportJob.get("agencyId");
		if (agencyId != null){
			Agency agency = this.agencyService.getById(Long.parseLong(agencyId.toString()));
			reportJob.put("orgPosition", agency.getOrgPosition());
			reportJob.remove("agencyId");
		}
		Object residentialId = reportJob.get("residentialId");
		if (residentialId != null){
			Residential residential = this.residentialService.getById(Long.parseLong(residentialId.toString()));
			reportJob.put("orgPosition", residential.getOrgPosition());
			reportJob.remove("residentialId");
		}

		IPage<ReportJob> pages = reportJobService.page(Condition.getPage(query), Condition.getQueryWrapper(reportJob,ReportJob.class));
		return R.data(pages);
	}

	/**
	 * 自定义分页 报事工单
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入reportJob")
	public R<IPage<ReportJobVO>> page(ReportJobVO reportJob, Query query) {
		IPage<ReportJobVO> pages = reportJobService.selectReportJobPage(Condition.getPage(query), reportJob);
		return R.data(pages);
	}

	/**
	 * 新增 报事工单
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入reportJob")
	public R save(@Valid @RequestBody ReportJob reportJob) {
		return R.status(reportJobService.save(reportJob));
	}

	/**
	 * 修改 报事工单
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入reportJob")
	public R update(@Valid @RequestBody ReportJob reportJob) {
		return R.status(reportJobService.updateById(reportJob));
	}

	/**
	 * 新增或修改 报事工单
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入reportJob")
	public R submit(@Valid @RequestBody ReportJob reportJob) {
		return R.status(reportJobService.saveOrUpdate(reportJob));
	}


	/**
	 * 删除 报事工单
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(reportJobService.deleteLogic(Func.toLongList(ids)));
	}



	/**
	 * 批量同步物业系统报事工单
	 */
	@GetMapping("/sync")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "批量同步物业系统报事工单")
	public R sync() {
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity responseEntity = null;
		ParameterizedTypeReference<Object> reference = new ParameterizedTypeReference<Object>() {
		};
		String url = "http://localhost:9083/grid/estateRepair/sync";
		URI uri = URI.create(url);
		responseEntity = restTemplate.exchange(uri, HttpMethod.GET, null, reference);

		List<Map> estateRepairPushDtos = (List<Map>) responseEntity.getBody();
		for (Map map: estateRepairPushDtos){
			EstateRepairPushDto estateRepairPushDto = JSON.parseObject(JSON.toJSONString(map),EstateRepairPushDto.class);
			ReportJob reportJob = new ReportJob();
			List<ReportJob> isExist = reportJobService.getBaseMapper().selectList(new QueryWrapper<>(reportJob).lambda().eq(ReportJob::getOldId, estateRepairPushDto.getId()));
			if(isExist.size()>0){//已存在，更新
				reportJob = isExist.get(0);
				reportJob.setPic(estateRepairPushDto.getPic());
				reportJob.setBeginTime(estateRepairPushDto.getBeginTime());
				reportJob.setEndTime(estateRepairPushDto.getEndTime());
				reportJob.setReportDetail(estateRepairPushDto.getReportDetail());
				reportJob.setReportPosition(estateRepairPushDto.getReportPosition());
				reportJob.setEstimateStatus(estateRepairPushDto.getEstimateStatus());
				reportJob.setJobStatus(estateRepairPushDto.getHandleStatus()+1);
				reportJob.setComment(estateRepairPushDto.getComment());
				reportJob.setHandleTime(estateRepairPushDto.getHandleTime());
				reportJob.setReportPhone(estateRepairPushDto.getPhone());
				Houseuser houseuser = houseuserService.getByOldId(estateRepairPushDto.getUserId().toString());
				if(houseuser != null){
					reportJob.setReportor(houseuser.getName());
				}
				reportJobService.updateById(reportJob);
			}else{//新增
				reportJob.setOldId(estateRepairPushDto.getId());
				reportJob.setPic(estateRepairPushDto.getPic());
				reportJob.setBeginTime(estateRepairPushDto.getBeginTime());
				reportJob.setEndTime(estateRepairPushDto.getEndTime());
				reportJob.setReportDetail(estateRepairPushDto.getReportDetail());
				reportJob.setReportPosition(estateRepairPushDto.getReportPosition());
				reportJob.setEstimateStatus(estateRepairPushDto.getEstimateStatus());
				reportJob.setJobStatus(estateRepairPushDto.getHandleStatus()+1);
				reportJob.setComment(estateRepairPushDto.getComment());
				reportJob.setHandleTime(estateRepairPushDto.getHandleTime());
				reportJob.setTenantId("000000");//物业系统都为社区
				reportJob.setReportor(estateRepairPushDto.getUserName());
				reportJob.setReportPhone(estateRepairPushDto.getPhone());
				reportJob.setJobNo(estateRepairPushDto.getRepairNo());
				Houseuser houseuser = houseuserService.getByOldId(estateRepairPushDto.getUserId().toString());
				if(houseuser != null){
					reportJob.setReportor(houseuser.getName());
				}
				List<Residential> residentials = residentialService.getBaseMapper().selectList(new QueryWrapper<>(new Residential()).lambda().eq(Residential::getOldId, estateRepairPushDto.getResidentialId()));
				if(residentials.size()>0){
					reportJob.setResidentialId(residentials.get(0).getId());
					reportJob.setResidentialName(residentials.get(0).getName());
					reportJob.setOrgPosition(residentials.get(0).getOrgPosition());
				}
				reportJob.setReportTime(estateRepairPushDto.getCreateTime());
				reportJobService.save(reportJob);
			}
		}
		return R.data(null);
	}
}
