package com.yeejoin.amos.boot.module.hygf.biz.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.entity.BaseEntity;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.hygf.api.Enum.PeasantHouseholdEnum;
import com.yeejoin.amos.boot.module.hygf.api.config.UserEmpower;
import com.yeejoin.amos.boot.module.hygf.api.config.UserLimits;
import com.yeejoin.amos.boot.module.hygf.api.dto.PeasantHouseholdDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.PowerStationEngineeringInfoAllDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.SurveyInformationDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.UserUnitInformationDto;
import com.yeejoin.amos.boot.module.hygf.api.entity.PeasantHousehold;
import com.yeejoin.amos.boot.module.hygf.api.entity.PowerStation;
import com.yeejoin.amos.boot.module.hygf.api.mapper.PersonnelBusinessMapper;
import com.yeejoin.amos.boot.module.hygf.api.util.CommonResponseNewUtil;
import com.yeejoin.amos.boot.module.hygf.biz.service.impl.PeasantHouseholdServiceImpl;
import com.yeejoin.amos.boot.module.hygf.biz.service.impl.SurveyInformationServiceImpl;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.RegionModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * 农户信息
 *
 * @author system_generator
 * @date 2023-07-07
 */
@RestController
@Api(tags = "农户信息Api")
@RequestMapping(value = "/peasant-household")
public class PeasantHouseholdController extends BaseController {

	@Autowired
	SurveyInformationServiceImpl surveyInformationServiceImpl;

    @Autowired
    PeasantHouseholdServiceImpl peasantHouseholdServiceImpl;

	@Autowired
	RedisUtils redisUtils;

	private static final String regionRedis="app_region_redis";
    @Autowired
    PersonnelBusinessMapper personnelBusinessMapper;
    /**
     * 新增农户信息
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/save")
	@ApiOperation(httpMethod = "POST", value = "新增农户信息", notes = "新增农户信息")
	public ResponseModel<PeasantHouseholdDto> save(@RequestBody PeasantHouseholdDto model) {
		AgencyUserModel userInfo = getUserInfo();
		SurveyInformationDto surveyInformationDto = new SurveyInformationDto();
		surveyInformationServiceImpl.createWithModel(surveyInformationDto);
		JSONArray regionName = getRegionName();
		List<RegionModel> list = JSONArray.parseArray(regionName.toJSONString(), RegionModel.class);
		// 处理项目地址
		String area = "";
		if(model.getProjectAddress().size() != 0) {
			for (Integer reg : model.getProjectAddress())
				for (RegionModel re : list) {
					if (re.getRegionCode().equals(reg)) {
						area = area + re.getRegionName() + "/";
					}
				}
			model.setProjectAddressName(area.substring(0, area.length() - 1));
			if ("1".equals(model.getIsPermanent())) {
				model.setPermanentAddress(model.getProjectAddress());
				model.setPermanentAddressDetail(model.getProjectAddressDetail());
				model.setPermanentAddressName(area.substring(0, area.length() - 1));
			}else {
				// 处理常住地址
				String permanent = "";
				if(model.getPermanentAddress().size() != 0) {
					for (Integer reg : model.getPermanentAddress())
						for (RegionModel re : list) {
							if (re.getRegionCode().equals(Integer.valueOf(reg))) {
								permanent = permanent + re.getRegionName() + "/";
							}
						}
					model.setPermanentAddressName(permanent.substring(0, permanent.length() - 1));
				}
			}
		}

		model.setSurveyInformationId(surveyInformationDto.getSequenceNbr());
		model.setSurveyOrNot(0);
		model.setReview(0);
		model.setDeveloperCode(userInfo.getCompanys().get(0).getOrgCode());
        model.setDeveloperId(userInfo.getCompanys().get(0).getSequenceNbr());
		model.setDeveloperName(userInfo.getOrgNamesWithoutRole());
		if(StringUtils.isEmpty(model.getDeveloper())){
			model.setDeveloper(userInfo.getRealName());
		}
		if(model.getCreationTime() == null){
			model.setCreationTime(new Date());
		}
		PeasantHouseholdDto householdDto = peasantHouseholdServiceImpl.createWithModel(model);
	    return ResponseHelper.buildResponse(householdDto);
	}

	/**
     * 根据sequenceNbr更新
     *
     * @param sequenceNbr 主键
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PutMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "PUT", value = "根据sequenceNbr更新农户信息", notes = "根据sequenceNbr更新农户信息")
	public ResponseModel<PeasantHouseholdDto> updateBySequenceNbrPeasantHousehold(@RequestBody PeasantHouseholdDto model,@PathVariable(value = "sequenceNbr") Long sequenceNbr) {
	    model.setSequenceNbr(sequenceNbr);
		JSONArray regionName = getRegionName();
		List<RegionModel> list = JSONArray.parseArray(regionName.toJSONString(), RegionModel.class);
		if(model.getProjectAddress().size()>0){
			// 处理项目地址
			String projectAddressName = "";
			for (Integer reg : model.getProjectAddress())
				for (RegionModel re : list) {
					if (re.getRegionCode().equals(Integer.valueOf(reg))) {
						projectAddressName = projectAddressName + re.getRegionName() + "/";
					}
				}
			model.setProjectAddressName(projectAddressName.substring(0, projectAddressName.length() - 1));
		}
		if ("1".equals(model.getIsPermanent())) {
			model.setPermanentAddress(model.getProjectAddress());
			model.setPermanentAddressDetail(model.getProjectAddressDetail());
		}
		if(model.getPermanentAddress().size()>0){
			// 处理常驻地址
			String permanentAddressName = "";
			for (Integer reg : model.getPermanentAddress())
				for (RegionModel re : list) {
					if (re.getRegionCode().equals(Integer.valueOf(reg))) {
						permanentAddressName = permanentAddressName + re.getRegionName() + "/";
					}
				}
			model.setPermanentAddressName(permanentAddressName.substring(0, permanentAddressName.length() - 1));
		}
		PeasantHouseholdDto peasantHouseholdDto = peasantHouseholdServiceImpl.queryBySeq(sequenceNbr);
		BeanUtils.copyProperties(model,peasantHouseholdDto);
		return ResponseHelper.buildResponse(peasantHouseholdServiceImpl.updateWithModel(peasantHouseholdDto));
	}

	/**
	 * 根据sequenceNbr更新
	 *
	 * @param sequenceNbr 主键
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PutMapping(value = "/updateAddress/{sequenceNbr}")
	@ApiOperation(httpMethod = "PUT", value = "根据sequenceNbr更新农户地址", notes = "根据sequenceNbr更新农户地址")
	public ResponseModel updateAddress(@RequestBody PeasantHouseholdDto model,@PathVariable(value = "sequenceNbr") Long sequenceNbr) {
		peasantHouseholdServiceImpl.updateAddress(model,sequenceNbr);
		return CommonResponseNewUtil.success();
	}

	/**
     * 根据sequenceNbr删除
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @DeleteMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "DELETE", value = "根据sequenceNbr删除农户信息", notes = "根据sequenceNbr删除农户信息")
    public ResponseModel<Boolean> deleteBySequenceNbr(HttpServletRequest request, @PathVariable(value = "sequenceNbr") Long sequenceNbr){
        return ResponseHelper.buildResponse(peasantHouseholdServiceImpl.deletePeasantHouseholdBySequenceNbr(sequenceNbr));
    }

    /**
     * 根据sequenceNbr查询
     *
	 * @param sequenceNbr  主键
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "GET",value = "根据sequenceNbr查询单个农户信息",  notes = "根据sequenceNbr查询单个农户信息")
	public ResponseModel<PeasantHouseholdDto> selectOne(@PathVariable Long sequenceNbr) {
		PeasantHouseholdDto peasantHouseholdDto = peasantHouseholdServiceImpl.queryBySeq(sequenceNbr);
		if(JSON.toJSONString(peasantHouseholdDto.getProjectAddress()).equals(JSON.toJSONString(peasantHouseholdDto.getPermanentAddress()))){
			peasantHouseholdDto.setIsPermanent("1");
		}else {
			peasantHouseholdDto.setIsPermanent("0");
		}
		return ResponseHelper.buildResponse(peasantHouseholdDto);
	}

	/**
     * 列表分页查询
     *
     * @param current 当前页
     * @param current 每页大小
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/page")
	@ApiOperation(httpMethod = "GET",value = "农户信息分页查询",  notes = "农户信息分页查询")
	@UserLimits()
	public ResponseModel<Page<PeasantHousehold>> queryForPage(@RequestParam(value = "current") int current,
															  @RequestParam(value = "size") int size,
															  @RequestParam(value = "ownersName",required = false)String ownersName,
															  @RequestParam(value = "preparationMoneyState",required = false)String preparationMoneyState,
															  @RequestParam(value = "isHistory",required = false)String isHistory,
															  @RequestParam(value = "developerId",required = false)Long developerId,
															  @RequestParam(value = "regionalCompaniesSeq",required = false)String regionalCompaniesSeq,
															  @RequestParam(value = "peasantHouseholdNo",required = false) String peasantHouseholdNo,
															  @RequestParam(value = "province",required = false) String province,
															  @RequestParam(value = "routhPathId",required = false) String routhPathId) {
	    Page<PeasantHousehold> page = new Page<PeasantHousehold>();
	    page.setCurrent(current);
	    page.setSize(size);
		AgencyUserModel userInfo = getUserInfo();


//        //获取用户所在经销商单位
//        UserUnitInformationDto userUnitInformationDto=personnelBusinessMapper.getUserUnitInformationDto(userInfo.getUserId());
//
//        String orgCode = userUnitInformationDto.getAmosDealerOrgCode();

		Integer isCertified = PeasantHouseholdEnum.已认证.getCode();
		return ResponseHelper.buildResponse(peasantHouseholdServiceImpl.queryForPeasantHouseholdPage(page, null,ownersName,developerId,isCertified,preparationMoneyState, peasantHouseholdNo,province,isHistory,regionalCompaniesSeq,routhPathId));
	}

	/**
	 * 列表全部数据查询
     *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET",value = "农户信息列表全部数据查询",   notes = "农户信息列表全部数据查询")
	@GetMapping(value = "/list")
	public ResponseModel<List<PeasantHouseholdDto>> selectForList() {
		Integer isCertified = PeasantHouseholdEnum.已认证.getCode();
	    return ResponseHelper.buildResponse(peasantHouseholdServiceImpl.queryForPeasantHouseholdList(isCertified));
	}

	public JSONArray getRegionName(){
		JSONArray jsonArray = new JSONArray();
		if (redisUtils.hasKey(regionRedis)) {
			jsonArray= JSONArray.parseArray(redisUtils.get(regionRedis).toString());
		}else {
			Collection<RegionModel> regionChild = new ArrayList<>();
			RegionModel regionModel1 = new RegionModel();
			regionChild.add(regionModel1);
			FeignClientResult<Collection<RegionModel>> collectionFeignClientResult = Systemctl.regionClient.queryForTreeParent(610000L);
			Collection<RegionModel> result = collectionFeignClientResult.getResult();
			for (RegionModel regionModel : result) {
				if(null != regionModel && null != regionModel.getChildren()) {
					for (RegionModel child : regionModel.getChildren()) {
						if(null != child && null != child.getChildren()) {
							for (RegionModel childChild : child.getChildren()) {
								jsonArray.add(childChild);
							}
							child.setChildren(regionChild);
							jsonArray.add(child);
						}
					}
					regionModel.setChildren(regionChild);
					jsonArray.add(regionModel);
				}
			}

			redisUtils.set(regionRedis,jsonArray);
		}
		return jsonArray;
	}



	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET",value = "农户信息列表根据ids查询",   notes = "农户信息列表根据ids查询")
	@GetMapping(value = "/getInfoByIds")
	public ResponseModel<List<PeasantHousehold>> getInfoByIds(String ids) {

		return ResponseHelper.buildResponse(peasantHouseholdServiceImpl.getInfoByIds(ids));
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET",value = "农户信息列表根据ids查询历史电站",   notes = "农户信息列表根据ids查询历史电站")
	@GetMapping(value = "/getInfoByIdsHistory")
	public ResponseModel<List<PeasantHousehold>> getInfoByIdsHistory(String ids) {

		return ResponseHelper.buildResponse(peasantHouseholdServiceImpl.getInfoByIdsHistory(ids));
	}

	/**
	 * 根据sequenceNbr和userId删除用户信息
	 * sequenceNbr 唯一标识
	 * @param peasantHouseholdNo 电站编号
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@DeleteMapping(value = "/{sequenceNbr}/{peasantHouseholdNo}")
	@ApiOperation(httpMethod = "DELETE",value = "根据场站编号删除用户信息和合同",  notes = "根据场站编号删除用户信息和合同")
	public ResponseModel<Boolean> deleteUser(@PathVariable String sequenceNbr, @PathVariable String peasantHouseholdNo) {
		return ResponseHelper.buildResponse(peasantHouseholdServiceImpl.deleteUser(sequenceNbr, peasantHouseholdNo));
	}

//	@TycloudOperation(ApiLevel = UserType.AGENCY)
//	@ApiOperation(httpMethod = "POST",value = "更新详情信息",   notes = "更新详情信息")
//	@PostMapping(value = "/saveHistory")
//	public ResponseModel updateDetail(@RequestBody PowerStationEngineeringInfoAllDto powerStationEngineeringInfoAllDto,@RequestParam(value = "operationType") String operationType) {
//
//		peasantHouseholdServiceImpl.saveHistoryPeasantHousehold(powerStationEngineeringInfoAllDto,operationType);
//		return ResponseHelper.buildResponse(null);
//	}


	/**
	 * 批量删除
	 *
	 * @param sequenceNbrList 主键
	 * @return 返回结果
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@DeleteMapping(value = "/deleteBatch")
	@ApiOperation(httpMethod = "DELETE", value = "批量删除", notes = "批量删除")
	public ResponseModel<Boolean> batchDeleteBySequenceNbrList(@RequestParam List<Long> sequenceNbrList) {
		for (Long aLong : sequenceNbrList) {
			peasantHouseholdServiceImpl.deletePeasantHouseholdBySequenceNbr(aLong);
		}
		return ResponseHelper.buildResponse(null);
	}

}
