package org.dromara.zhishu.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaIgnore;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.web.core.BaseController;
import org.dromara.zhishu.domain.bo.TDistrictBo;
import org.dromara.zhishu.domain.vo.DistrictsVo;
import org.dromara.zhishu.domain.vo.TDistrictVo;
import org.dromara.zhishu.service.ITDistrictService;
import org.dromara.zhishu.util.JsonExporterUtils;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/district")
public class TDistrictController extends BaseController {

    private final ITDistrictService tDistrictService;

    /**
     * 查询【请填写功能名称】列表
     */
    @SaCheckPermission("system:district:list")
    @GetMapping("/list")
    public TableDataInfo<TDistrictVo> list(TDistrictBo bo, PageQuery pageQuery) {
        return tDistrictService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @SaCheckPermission("system:district:export")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TDistrictBo bo, HttpServletResponse response) {
        List<TDistrictVo> list = tDistrictService.queryList(bo);
        ExcelUtil.exportExcel(list, "【请填写功能名称】", TDistrictVo.class, response);
    }

    /**
     * 获取【请填写功能名称】详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("system:district:query")
    @GetMapping("/{id}")
    public R<TDistrictVo> getInfo(@NotNull(message = "主键不能为空") @PathVariable Long id) {
        return R.ok(tDistrictService.queryById(id));
    }

    /**
     * 新增【请填写功能名称】
     */
    @SaCheckPermission("system:district:add")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody TDistrictBo bo) {
        return toAjax(tDistrictService.insertByBo(bo));
    }

    /**
     * 修改【请填写功能名称】
     */
    @SaCheckPermission("system:district:edit")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TDistrictBo bo) {
        return toAjax(tDistrictService.updateByBo(bo));
    }

    /**
     * 删除【请填写功能名称】
     *
     * @param ids 主键串
     */
    @SaCheckPermission("system:district:remove")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) {
        return toAjax(tDistrictService.deleteWithValidByIds(List.of(ids), true));
    }

    @GetMapping("/getDistrictTree")
    public List<Map<String, Object>> getDistrictTree(){
        List<Map<String,Object>> mapList = new ArrayList<>();
        List<TDistrictVo> list = tDistrictService.selectDistrictByPid("0");
        for(TDistrictVo districtVo : list){
            Map<String, Object> map = new HashMap<>();
            map.put("value", districtVo.getId());
            map.put("label", districtVo.getName());
            //获取市
            List<Map<String,Object>> childrenMapList = new ArrayList<>();
            List<TDistrictVo> childrenList = tDistrictService.selectDistrictByPid(String.valueOf(districtVo.getId()));
            for(TDistrictVo children : childrenList){
                Map<String, Object> childrenMap = new HashMap<>();
                childrenMap.put("value", children.getId());
                childrenMap.put("label", children.getName());

                List<Map<String,Object>> childrenMapTwoList = new ArrayList<>();
                List<TDistrictVo> childrenTwoList = tDistrictService.selectDistrictByPid(String.valueOf(children.getId()));
                for (TDistrictVo childrenTwo : childrenTwoList){
                    Map<String, Object> childrenTwoMap = new HashMap<>();
                    childrenTwoMap.put("value", childrenTwo.getId());
                    childrenTwoMap.put("label", childrenTwo.getName());
                    childrenMapTwoList.add(childrenTwoMap);
                }
                childrenMap.put("children", childrenMapTwoList);

                childrenMapList.add(childrenMap);
            }
            map.put("children", childrenMapList);
            mapList.add(map);
        }
        return mapList;
    }

    /**
     * 获取所有省级数据
     */
    @SaIgnore
    @GetMapping("/provinces")
    public R<List<TDistrictVo>> getProvinces() {
        TDistrictBo bo = new TDistrictBo();
        bo.setLevel(0L); // 省级数据level=0
        bo.setStatus(0L); // 状态正常
        return R.ok(tDistrictService.selectList());
    }

    /**
     * 根据省ID获取市级数据
     *
     * @param provinceId 省ID
     */
    @SaIgnore
    @GetMapping("/cities/{provinceId}")
    public R<List<TDistrictVo>> getCitiesByProvinceId(@PathVariable Long provinceId) {
        TDistrictVo vo = new TDistrictVo();
        vo.setPid(provinceId); // 父ID为省ID
        vo.setLevel(1L); // 市级数据level=1
        vo.setStatus(0L); // 状态正常
        return R.ok(tDistrictService.selectCityList(vo));
    }

    /**
     * 根据市ID获取区县级数据
     *
     * @param cityId 市ID
     */
    @SaIgnore
    @GetMapping("/districts/{cityId}")
    public R<List<TDistrictVo>> getDistrictsByCityId(@PathVariable Long cityId) {
        TDistrictVo vo = new TDistrictVo();
        vo.setPid(cityId); // 父ID为市ID
        vo.setLevel(2L); // 区县级数据level=2
        vo.setStatus(0L); // 状态正常
        return R.ok(tDistrictService.selectAreaList(vo));
    }

    /**
     * 导出地址数据JSON文件
     */
    @SaIgnore
    @GetMapping(value = "/districts", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<InputStreamResource> getDistricts() throws IOException {
        // 获取地区数据
        TDistrictVo vo = new TDistrictVo();
        vo.setStatus(0L); // 状态正常
        // 查询区划信息数据
        List<DistrictsVo> districtsList = tDistrictService.selectDistricts(vo);
        // 使用json导出工具类，传入导出数据对象并指定文件名称
        return JsonExporterUtils.exportJsonAsFile(districtsList, "districts.json");
    }

    /**
     * 根据区划名称查询区划列表
     */
    @SaIgnore
    @PostMapping("/queryListByName")
    public List<TDistrictVo> queryListByName(@RequestBody List<String> districtNames) {
        return tDistrictService.queryListByName(districtNames);
    }

}