package com.yonge.cooleshow.tenant.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.microsvc.toolkit.common.response.paging.PageInfo;
import com.microsvc.toolkit.common.response.paging.QueryInfo;
import com.microsvc.toolkit.common.webportal.exception.BizException;
import com.yonge.cooleshow.biz.dal.entity.SysArea;
import com.yonge.cooleshow.biz.dal.service.SysAreaService;
import com.yonge.cooleshow.biz.dal.wrapper.SysAreaWrapper;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.tenant.io.request.SysAreaVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Validated
@RestController
@RequestMapping("/sysArea")
@Api(tags = "区域表")
public class SysAreaController {

    @Autowired
    private SysAreaService sysAreaService;

	/**
	 * 查询单条
	 * @param id 详情ID
	 * @return R<SysAreaVo.SysArea>
	 */
	@ApiOperation(value = "详情", notes = "传入id")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", dataType = "long")
    })
    @GetMapping("/detail/{id}")
    public HttpResponseResult<SysAreaWrapper.SysArea> detail(@PathVariable("id") Long id) {

        return HttpResponseResult.succeed(sysAreaService.detail(id));
	}

	/**
	 * 根据code查询
	 * @param code 详情ID
	 * @return R<SysAreaVo.SysArea>
	 */
	@ApiOperation(value = "根据code查询", notes = "传入code")
    @GetMapping("/queryByCode/{code}")
    public HttpResponseResult<SysArea> queryByCode(@PathVariable("code") Integer code) {

		List<Integer> codeList = new ArrayList<Integer>();
		codeList.add(code);
		List<SysArea> list = sysAreaService.queryByCodes(codeList);

		if(list == null || list.size() == 0){
			throw BizException.from("根据code查询区域表失败");
		}

        return HttpResponseResult.succeed(list.get(0));
	}

    /**
	 * 查询分页
	 * @param query SysAreaVo.SysAreaQuery
	 * @return R<PageInfo<SysAreaVo.SysAreaList>>
	 */
    @ApiOperation(value = "查询分页", notes = "传入sysAreaSearch")
//    @PreAuthorize("@auditsvc.hasPermissions('sysArea/page', {'BACKEND'})")
    @PostMapping("/page")
    public HttpResponseResult<PageInfo<SysAreaWrapper.SysArea>> page(@RequestBody SysAreaWrapper.SysAreaQuery query) {

        IPage<SysAreaWrapper.SysArea> pages = sysAreaService.selectPage(QueryInfo.getPage(query), query);

        return HttpResponseResult.succeed(QueryInfo.pageInfo(pages));
	}

    /**
     * 查询全部区域
     * @return R<List<SysAreaVo.Province>>
     */
    @ApiOperation(value = "查询全部区域", notes = "查询全部区域")
    @GetMapping("/queryAllProvince")
    public HttpResponseResult<List<SysAreaVo.Province>> queryAllProvince() {

        List<SysAreaVo.Province> provinces = Lists.newArrayList();

        // 全部城市信息
        Map<Integer, List<SysArea>> areaMap = sysAreaService.lambdaQuery().list().stream()
            .filter(x -> x.getDelFlag().equals("0"))
            .collect(Collectors.groupingBy(SysArea::getParentOrganId));

        SysAreaVo.Province provinceVo;
        SysAreaVo.City cityVo;
        for (SysArea province : areaMap.get(0)) {

            provinceVo = JSON.parseObject(JSON.toJSONString(province), SysAreaVo.Province.class)
                .cities(Lists.newArrayList());
            provinces.add(provinceVo);

            // 城市信息
            for (SysArea city : areaMap.get(province.getId())) {

                cityVo = JSON.parseObject(JSON.toJSONString(city), SysAreaVo.City.class);
                provinceVo.getAreas().add(cityVo);

                if (areaMap.containsKey(city.getId())) {
                    cityVo.setAreas(JSON.parseArray(JSON.toJSONString(areaMap.get(city.getId())), SysAreaVo.District.class));
                }
            }
        }

        return HttpResponseResult.succeed(provinces);
    }
}
