package org.springblade.datamigration.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.gson.JsonObject;
import lombok.AllArgsConstructor;
import org.apache.xmlbeans.impl.jam.mutable.MMember;
import org.springblade.community.entity.Room;
import org.springblade.community.feign.IRoomClient;
import org.springblade.core.tool.api.R;
import org.springblade.datamigration.constant.UrlConstants;
import org.springblade.datamigration.util.TokenUtil;
import org.springblade.datamigration.util.WuyeSystemHttpUtil;
import org.springblade.estate.entity.ApplyUser;
import org.springblade.person.entity.HouseUser;
import org.springblade.person.entity.Member;
import org.springblade.person.feign.IHouseUserClient;
import org.springblade.person.feign.IMemberClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lidexi
 * @date 2021/6/21 10:17
 * 人员管理数据迁移
 */
@RestController
@RequestMapping("/data/migration/person")
@AllArgsConstructor
public class PersonDataMigrationController {
	private final IMemberClient memberClient;
	private final IHouseUserClient houseUserClient;
	private final IRoomClient roomClient;

	@PostMapping("/member")
	public R member(){

		String token = TokenUtil.getWuyeSystemToken();
		Map<String, Object> map = new HashMap<>();
		map.put("size", Integer.MAX_VALUE);
		map.put("current",1);
		R r = WuyeSystemHttpUtil.postQuery(JSONUtil.toJsonStr(map), UrlConstants.personService.MEMBER.getUrl(), token);
		Map data = (Map) r.getData();
		data = (Map) data.get("data");
		JSONArray records = JSONUtil.parseArray(data.get("records"));
		records.forEach(item -> {
			JSONObject jsonObject = JSONUtil.parseObj(item);
			Long id = Long.valueOf(jsonObject.get("id").toString());
			Member isExist = memberClient.getById(id);
			Member member = this.buildMember(jsonObject);
			if (isExist == null) {//新增

				memberClient.save(member);
			} else {
				memberClient.update(member);
			}
		});

		return R.data(true);
	}

	@PostMapping("/houseuser")
	public R houseuser(){

		String token = TokenUtil.getWuyeSystemToken();
		Map<String, Object> map = new HashMap<>();
		map.put("size", Integer.MAX_VALUE);
		map.put("current",1);
		map.put("desensitize",true);
		R r = WuyeSystemHttpUtil.getQuery(JSONUtil.toJsonStr(map), UrlConstants.personService.HOUSEUSER.getUrl(), token);
		Map data = (Map) r.getData();
		data = (Map) data.get("data");
		JSONArray records = JSONUtil.parseArray(data.get("records"));
		records.forEach(item -> {
			JSONObject jsonObject = JSONUtil.parseObj(item);
			Long id = Long.valueOf(jsonObject.get("id").toString());
			HouseUser isExist = houseUserClient.getById(id);
			HouseUser houseUser = this.buildHouseUser(jsonObject);
			if (isExist == null) {//新增

				houseUserClient.save(houseUser);
			} else {
				houseUserClient.update(houseUser);
			}
		});

		return R.data(true);
	}

	private HouseUser buildHouseUser(JSONObject jsonObject) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		HouseUser houseUser = new HouseUser();
		houseUser.setId(jsonObject.getLong("id"));
		houseUser.setName(jsonObject.get("name") != null ? jsonObject.getStr("name") : null);
		houseUser.setSex(jsonObject.get("sex") != null ? jsonObject.getInt("sex") : null);
		houseUser.setType(jsonObject.get("type") != null ? jsonObject.getInt("type") : null);
		houseUser.setRegionProvince(jsonObject.get("regionProvince") != null ? jsonObject.getStr("regionProvince") : null);
		houseUser.setRegionCity(jsonObject.get("regionCity") != null ? jsonObject.getStr("regionCity") : null);
		houseUser.setRegionArea(jsonObject.get("regionArea") != null ? jsonObject.getStr("regionArea") : null);
		houseUser.setPhone(jsonObject.get("tel") != null ? jsonObject.getStr("tel") : null);
		houseUser.setRemark(jsonObject.get("remark") != null ? jsonObject.getStr("remark") : null);

		houseUser.setRoomId(jsonObject.get("roomId") != null ? jsonObject.getLong("roomId") : null);
		houseUser.setRoomName(jsonObject.get("roomName") != null ? jsonObject.getStr("roomName") : null);
		houseUser.setBuildingId(jsonObject.get("buildingId") != null ? jsonObject.getLong("buildingId") : null);
		houseUser.setBuildingName(jsonObject.get("buildingName") != null ? jsonObject.getStr("buildingName"): null);
		houseUser.setFloorId(jsonObject.get("floorId") != null ? jsonObject.getLong("floorId") : null);
		houseUser.setFloorName(jsonObject.get("floorName") != null ? jsonObject.getStr("floorName"): null);
		houseUser.setAuditStatus(jsonObject.get("checkState") != null ? jsonObject.getInt("checkState"): null);
		houseUser.setCheckOpinion(jsonObject.get("checkOpinion") != null ? jsonObject.getStr("checkOpinion") : null);
		houseUser.setFaceUrl(jsonObject.get("imageUri") != null ? jsonObject.getStr("imageUri") : null);
		try {
			if (null != jsonObject.get("faceBeginDate"))
				houseUser.setFaceBeginDate(sdf.parse(jsonObject.getStr("faceBeginDate")));
			if(null != jsonObject.get("faceEndDate"))
				houseUser.setFaceEndDate(sdf.parse(jsonObject.getStr("faceEndDate")));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		houseUser.setImageMd5(jsonObject.get("faceCode") != null ? jsonObject.getStr("faceCode") : null);
		houseUser.setUnitId(jsonObject.get("unitId") != null ? jsonObject.getLong("unitId") : null);
		houseUser.setUnitName(jsonObject.get("unitName") != null ? jsonObject.getStr("unitName") : null);
		houseUser.setResidentialId(jsonObject.get("residentialId") != null ? jsonObject.getLong("residentialId") : null);
		houseUser.setResidentialName(jsonObject.get("residentialName") != null ? jsonObject.getStr("residentialName") : null);
		houseUser.setCreateType(jsonObject.get("createType") != null ? jsonObject.getInt("createType") : null);
		houseUser.setNationality(jsonObject.get("nationality") != null ? jsonObject.getInt("nationality") : null);
		houseUser.setIdCard(jsonObject.get("idCard") != null ? jsonObject.getStr("idCard") : null);
		houseUser.setNativePlace(jsonObject.get("birthPlace") != null ? jsonObject.getStr("birthPlace") : null);
		houseUser.setPassportImgUri(jsonObject.get("passportImgUri") != null ? jsonObject.getStr("passportImgUri") : null);
		houseUser.setEntryImgUri(jsonObject.get("entryImgUri") != null ? jsonObject.getStr("entryImgUri") : null);
		houseUser.setFaceEnable(jsonObject.get("faceEnable")  != null ? jsonObject.getInt("faceEnable") : null);
		Room room = roomClient.getById(houseUser.getRoomId());
		if(null != room){
			houseUser.setAgencyName(room.getAgencyName());
			houseUser.setAgencyId(room.getAgencyId());
			houseUser.setOrgPosition(room.getOrgPosition()+"/"+houseUser.getId());
		}else{
			houseUser.setRemark(houseUser.getRemark()+":"+"找不到对应的房间");
		}

		return houseUser;
	}


	private Member buildMember(JSONObject jsonObject){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Member member = new Member();
		member.setId(jsonObject.getLong("id"));
		member.setName(jsonObject.get("name") != null ? jsonObject.getStr("name") : null);
		member.setPhone(jsonObject.get("tel") != null ? jsonObject.getStr("tel") : null);
		member.setTelType(jsonObject.get("telType") != null ? jsonObject.getStr("telType") : null);
		member.setPassword(jsonObject.get("password") != null ? jsonObject.getStr("password") : null);
		member.setSex(jsonObject.get("sex") != null ? jsonObject.getInt("sex") : null);
		member.setIsDeleted(jsonObject.get("status") != null ? jsonObject.getInt("status") : null);
		member.setState(jsonObject.get("state") != null ? jsonObject.getInt("state") : null);
		member.setOpenid(jsonObject.get("openid") != null ? jsonObject.getStr("openid") : null);
		member.setCreateType(jsonObject.get("createType") != null ? jsonObject.getInt("createType") : null);
		member.setCreateIp(jsonObject.get("createIp") != null ? jsonObject.getStr("createIp") : null);
		try {
			if (null != jsonObject.get("createDate"))
				member.setCreateTime(sdf.parse(jsonObject.getStr("createDate")));
			if(null != jsonObject.get("birthday"))
				member.setBirthday(LocalDate.parse(jsonObject.getDate("birthday").toString()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		member.setHeadImage(jsonObject.get("headImage") != null ? jsonObject.getStr("headImage") : null);
		member.setIdcard(jsonObject.get("idcard") != null ? jsonObject.getStr("idcard") : null);
		member.setErrorFlag(jsonObject.get("errorFlag")!= null ? jsonObject.getInt("errorFlag")==1?true:false : false);
		member.setEnable(jsonObject.get("enable") != null ? jsonObject.getInt("enable") == 1 ? true : false :true);
		return member;
	}
}
