/*
 *      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.system.street.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.google.gson.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import javax.validation.Valid;

import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.sysarea.controller.SysAreaController;
import org.springblade.sysarea.entity.SysArea;
import org.springblade.sysarea.service.ISysAreaService;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.support.incrementer.HsqlMaxValueIncrementer;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.system.street.entity.Street;
import org.springblade.system.street.vo.StreetVO;
import org.springblade.system.street.wrapper.StreetWrapper;
import org.springblade.system.street.service.IStreetService;
import org.springblade.core.boot.ctrl.BladeController;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  控制器
 *
 * @author BladeX
 * @since 2020-11-25
 */
@RestController
@AllArgsConstructor
@RequestMapping("system_street/street")
@Api(value = "", tags = "接口")
public class StreetController extends BladeController {

	private IStreetService streetService;
	private ISysAreaService sysAreaService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入street")
	public R<StreetVO> detail(Street street) {
		Street detail = streetService.getOne(Condition.getQueryWrapper(street));
		return R.data(StreetWrapper.build().entityVO(detail));
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入street")
	public R<IPage<StreetVO>> list(Street street, Query query,BladeUser bladeUser) {
		IPage<Street> pages = streetService.page(Condition.getPage(query), Condition.getQueryWrapper(street).lambda());
		return R.data(StreetWrapper.build().pageVO(pages));
	}


	/**
	 * 自定义分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入street")
	public R<IPage<StreetVO>> page(StreetVO street, Query query) {
		IPage<StreetVO> pages = streetService.selectStreetPage(Condition.getPage(query), street);
		return R.data(pages);
	}

	/**
	 * 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入street")
	public R save(@Valid @RequestBody Street street) {
		//先根据街道名称和所属区域查询是否已存在
		Street detail = streetService.getOne(Condition.getQueryWrapper(street));
		if(null != detail){
			return R.data("街道已存在");
		}else{
			boolean save = streetService.save(street);
			if(save){
				LambdaQueryWrapper<Street> wrapper = new QueryWrapper<>(new Street()).lambda();
				wrapper.eq(Street::getName,street.getName());
				wrapper.eq(Street::getAreaCode,street.getAreaCode());
				Street street1 = streetService.getOne(wrapper);
				street1.setOrgPosition("/"+street1.getId().toString());
				return R.status(streetService.updateById(street1));
			}else {
				return R.status(false);
			}
		}
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入street")
	public R update(@Valid @RequestBody Street street) {
		return R.status(streetService.updateById(street));
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入street")
	public R submit(@Valid @RequestBody Street street) {
		if(street.getId()!= null){
			street.setOrgPosition("/"+street.getProvinceCode()+"/"+street.getCityCode()+"/"+street.getAreaCode()+"/"+street.getId());
			return R.status(streetService.updateById(street));
		}else{
			streetService.save(street);
			street.setOrgPosition("/"+street.getProvinceCode()+"/"+street.getCityCode()+"/"+street.getAreaCode()+"/"+street.getId());
			return R.status(streetService.updateById(street));
		}
//		return R.status(streetService.saveOrUpdate(street));
	}


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

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

		JsonParser parse =new JsonParser();  //创建json解析器
		try {
			JsonObject json=(JsonObject) parse.parse(new FileReader(System.getProperty("user.dir")+"/src/main/resources/json/area.json"));  //创建jsonObject对象
			System.out.println();
			JsonArray provinceArray = json.get("children").getAsJsonArray();

			for (int i =0 ;i<provinceArray.size();i++){
				JsonObject provinceObject = (JsonObject)provinceArray.get(i);
				//省code
				String provinceCode1 = provinceObject.get("code").getAsString();
				String provinceCode = numberAfterFillZero(provinceCode1, 6);
				//获取市
				JsonArray cityArray = provinceObject.get("children").getAsJsonArray();
				for(int j=0;j<cityArray.size();j++){
					JsonObject cityObject = (JsonObject)cityArray.get(j);
					//市code
					String cityCode1 = cityObject.get("code").getAsString();
					String cityCode = numberAfterFillZero(cityCode1, 6);
					//获取区
					JsonArray areaArray = cityObject.get("children").getAsJsonArray();
					for(int k = 0 ;k<areaArray.size();k++){
						JsonObject areaObject = (JsonObject)areaArray.get(k);
						//获取区code
						String areaCode1 = areaObject.get("code").getAsString();
						String areaCode = numberAfterFillZero(areaCode1, 6);

						//获取街道
						JsonArray streetArray = areaObject.get("children").getAsJsonArray();
						for(int m=0;m<streetArray.size();m++){
							JsonObject streetObject = streetArray.get(m).getAsJsonObject();
							Street street = new Street();
							String code = streetObject.get("code").getAsString();
							String name = streetObject.get("name").getAsString();

							street.setCode(code);
							street.setName(name);
							street.setProvinceCode(provinceCode);
							street.setCityCode(cityCode);
							street.setAreaCode(areaCode);
							street.setOrgPosition("/"+provinceCode+"/"+cityCode+"/"+areaCode+"/"+code);

							streetService.save(street);
						}
					}
				}

			}


		} catch (JsonIOException e) {
			e.printStackTrace();
		} catch (JsonSyntaxException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		return new R();
	}



	public static String numberAfterFillZero(String str, int length) {
		StringBuffer buffer = new StringBuffer(str);
		if (buffer.length() >= length) {
			return buffer.toString();
		} else {
			while (buffer.length() < length) {
				buffer.append("0");
			}
		}
		return buffer.toString();
	}

	@GetMapping(value = "/getAllStreetByAreaCodeList")
	public List<Map<String, Object>> getAllStreetByAreaCodeList(){
		List<Map<String, Object>> list = new ArrayList<>();
		List<String> areaList = sysAreaService.getAreaList();

		areaList.forEach(areaCode -> {
			Map<String, Object> map = new HashMap<>();
			SysArea area = sysAreaService.getDetailByCode(Long.parseLong(areaCode));
			Street wrapper = new Street();
			wrapper.setAreaCode(areaCode);
			List<Street> streetList = streetService.list(Condition.getQueryWrapper(wrapper));
			if (area != null && streetList != null && streetList.size() > 0){
				List<String> streetStrList = new ArrayList<>();
				streetList.forEach(street -> {
					streetStrList.add(street.getName() + "_" + street.getCode());
				});

				map.put(area.getSName() + "_" + areaCode, streetStrList);

				list.add(map);
			}
		});

		Map<String, Object> t = new HashMap<>();
		t.put("allAreaList", list);
		JSONObject test = new JSONObject(t);
		String str = test.toString();
		System.out.println(str);
 		return list;
	}

}
