package com.ruoyi.web.controller.system;

import com.baomidou.mybatisplus.annotation.TableField;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.BaseLongitudeLatitude;
import com.ruoyi.common.core.domain.entity.TbSysArea;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.vo.AreaResultDTO;
import com.ruoyi.system.domain.vo.AreaTreeResultDTO;
import com.ruoyi.system.service.ITbSysAreaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 区域Controller
 *
 * @author ruoyi
 * @date 2023-08-01
 */
@Api(tags = "PC区域管理")
@RestController
@RequestMapping("/system/area")
public class TbSysAreaController extends BaseController {
    @Autowired
    private ITbSysAreaService tbSysAreaService;

    /**
     * 查询区域列表
     */
    @ApiOperation("查询区域列表")
    //TODO 20230920PreAuthorize("@ss.hasPermi('system:area:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysAreaDTO sysAreaDTO) {
        TbSysArea tbSysArea = new TbSysArea(sysAreaDTO.getAreaName(), sysAreaDTO.getParentId(), sysAreaDTO.getCurrentLnglatList(), sysAreaDTO.getUserIdList());
        tbSysArea.setCompanyCode(getLoginUser().getCompanyCode());
        startPage();
        List<TbSysArea> list = tbSysAreaService.selectTbSysAreaList(tbSysArea);
//        return getDataTable(list);
        TableDataInfo dataTable = getDataTable(list);
        return dataTable;
    }

    /**
     *
     *  param mapArray 区域管理的列表中添加坐标数组
     * @return
     */
    @ApiOperation("查询区域树")
    @GetMapping("/tree")
    public List<AreaResultDTO> tree() {
//        return tbSysAreaService.getAreaTree(mapArray);
        return tbSysAreaService.getAreaTree();
    }


    @ApiOperation("查询区域树（data包裹一层）")
    @GetMapping("/areaTree")
    public AjaxResult areaTree() {

        List<AreaTreeResultDTO> areaTree = null;
        try {
            areaTree = tbSysAreaService.areaTree();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
//        @ApiModelProperty("区域ID")
//        private Long id;
//
//        @ApiModelProperty("区域名称")
//        private String areaName;
//
//        @ApiModelProperty("区域父级ID")
//        private Long parentId;
//
//
//        @ApiModelProperty("子级区域集合")
//        private List<AreaTreeResultDTO> child;

        /*List<AreaTreeResultDTO> list = new ArrayList<>();
        for (AreaResultDTO dto : areaTree) {
            AreaTreeResultDTO data = new AreaTreeResultDTO();
            data.setId(dto.getId());
            data.setName(dto.getAreaName());
            data.setParentId(dto.getParentId());

            List<AreaResultDTO> childList = dto.getChildList();
            if(!CollectionUtils.isEmpty(childList)){
                for (AreaResultDTO child : childList) {
                    AreaTreeResultDTO dataChild = new AreaTreeResultDTO();
                    dataChild.setId(child.getId());
                    dataChild.setName(child.getAreaName());
                    dataChild.setParentId(child.getParentId());
//                    dataChild.setChildren();
                }
            }



//            data.setChildren();
            list.add(data);

        }*/

        return AjaxResult.success(areaTree);
    }

    /**
     * 导出区域列表
     */
    @ApiOperation("导出区域列表")
    //TODO 20230920PreAuthorize("@ss.hasPermi('system:area:export')")
    @Log(title = "区域", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysAreaDTO sysAreaDTO) {
        TbSysArea tbSysArea = new TbSysArea(sysAreaDTO.getAreaName(), sysAreaDTO.getParentId(), sysAreaDTO.getCurrentLnglatList(), sysAreaDTO.getUserIdList());
        tbSysArea.setCompanyCode(getLoginUser().getUser().getCompanyCode());

        List<TbSysArea> list = tbSysAreaService.selectTbSysAreaList(tbSysArea);
        ExcelUtil<TbSysArea> util = new ExcelUtil<TbSysArea>(TbSysArea.class);
        util.exportExcel(response, list, "区域数据");
    }

    /**
     * 获取区域详细信息
     */
    @ApiOperation("获取区域详细信息")
    //TODO 20230920PreAuthorize("@ss.hasPermi('system:area:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(tbSysAreaService.selectTbSysAreaById(id));
    }

    /**
     * 新增区域
     */
    @ApiOperation("新增区域")
    //TODO 20230920PreAuthorize("@ss.hasPermi('system:area:add')")
    @Log(title = "区域", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysAreaDTO sysAreaDTO) {
        Long userId = getUserId();
//        TbSysArea tbSysArea = new TbSysArea(sysAreaDTO.getAreaName(), sysAreaDTO.getLongitude(), sysAreaDTO.getLatitude(), sysAreaDTO.getParentId(), sysAreaDTO.getUserIdList());
        TbSysArea tbSysArea = new TbSysArea(sysAreaDTO.getAreaName(), sysAreaDTO.getParentId(), sysAreaDTO.getCurrentLnglatList(), sysAreaDTO.getUserIdList());
        // 前端没有设置经度和维度，后台写死
//        tbSysArea.setLongitude(new BigDecimal(1.0));
//        tbSysArea.setLatitude(new BigDecimal(2.0));
        tbSysArea.setAreaCode(sysAreaDTO.getAreaCode());
        tbSysArea.setPostId(sysAreaDTO.getPostId());
        tbSysArea.setCompanyCode(getLoginUser().getUser().getCompanyCode());
        tbSysArea.setUpdateUserId(userId);
        tbSysArea.setCreateUserId(userId);
        return toAjax(tbSysAreaService.insertTbSysArea(tbSysArea));
    }

    /**
     * 修改区域
     */
    @ApiOperation("修改区域")
    //TODO 20230920PreAuthorize("@ss.hasPermi('system:area:edit')")
    @Log(title = "区域", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysAreaDTO sysAreaDTO) {

        Long userId = getUserId();
//        TbSysArea tbSysArea = new TbSysArea(sysAreaDTO.getAreaName(), sysAreaDTO.getLongitude(), sysAreaDTO.getLatitude(), sysAreaDTO.getParentId(), sysAreaDTO.getUserIdList());
        TbSysArea tbSysArea = new TbSysArea(sysAreaDTO.getAreaName(), sysAreaDTO.getParentId(), sysAreaDTO.getCurrentLnglatList(), sysAreaDTO.getUserIdList());
        // 前端没有设置经度和维度，后台写死
//        tbSysArea.setLongitude(new BigDecimal(1.0));
//        tbSysArea.setLatitude(new BigDecimal(2.0));

        tbSysArea.setId(sysAreaDTO.getId());
        tbSysArea.setAreaCode(sysAreaDTO.getAreaCode());
        tbSysArea.setPostId(sysAreaDTO.getPostId());
        tbSysArea.setUpdateUserId(userId);
        return toAjax(tbSysAreaService.updateTbSysArea(tbSysArea));
    }

    /**
     * 删除区域
     */
    @ApiOperation("批量删除区域")
    //TODO 20230920PreAuthorize("@ss.hasPermi('system:area:remove')")
    @Log(title = "区域", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tbSysAreaService.deleteTbSysAreaByIds(ids));
    }
}

class SysAreaDTO implements Serializable {
    private static final long serialVersionUID = 1L;

    private Long id;

    /**
     * 区域编码
     */
    private String areaCode;

    private String areaName;

//    private BigDecimal longitude;

//    private BigDecimal latitude;

    /**
     * 经纬度的集合
     */
    @TableField(exist = false)
    private List<BaseLongitudeLatitude> currentLnglatList;

    private Long parentId;

    private Long postId;

    public Long getPostId() {
        return postId;
    }

    public void setPostId(Long postId) {
        this.postId = postId;
    }

    private List<Long> userIdList = new ArrayList<>();

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }

    public List<BaseLongitudeLatitude> getCurrentLnglatList() {
        return currentLnglatList;
    }

    public void setCurrentLnglatList(List<BaseLongitudeLatitude> currentLnglatList) {
        this.currentLnglatList = currentLnglatList;
    }

    public Long getParentId() {
        return parentId;
    }

    public void setParentId(Long parentId) {
        this.parentId = parentId;
    }

    public List<Long> getUserIdList() {
        return userIdList;
    }

    public void setUserIdList(List<Long> userIdList) {
        this.userIdList = userIdList;
    }

    public String getAreaCode() {
        return areaCode;
    }

    public void setAreaCode(String areaCode) {
        this.areaCode = areaCode;
    }
}
