package com.ruoyi.web.bst;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

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.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.bst.area.domain.Area;
import com.ruoyi.bst.area.domain.AreaQuery;
import com.ruoyi.bst.area.domain.AreaVO;
import com.ruoyi.bst.area.service.AreaAssembler;
import com.ruoyi.bst.area.service.AreaConverter;
import com.ruoyi.bst.area.service.AreaService;
import com.ruoyi.bst.area.service.AreaValidator;
import com.ruoyi.bst.areaJoin.domain.enums.AreaJoinPermission;
import com.ruoyi.bst.areaSub.domain.AreaSubVO;
import com.ruoyi.bst.areaSub.service.AreaSubService;
import com.ruoyi.bst.areaSub.utils.AreaSubUtil;
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.page.TableDataInfo;
import com.ruoyi.common.core.validate.ValidGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.LogBizType;
import com.ruoyi.common.utils.collection.CollectionUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.user.service.UserValidator;

/**
 * 运营区Controller
 *
 * @author ruoyi
 * @date 2025-03-14
 */
@RestController
@RequestMapping("/bst/area")
public class AreaController extends BaseController
{
    @Autowired
    private AreaService areaService;

    @Autowired
    private AreaAssembler areaAssembler;

    @Autowired
    private AreaValidator areaValidator;

    @Autowired
    private AreaConverter areaConverter;

    @Autowired
    private UserValidator userValidator;

    @Autowired
    private AreaSubService areaSubService;

    /**
     * 查询运营区列表
     */
    @PreAuthorize("@ss.hasPermi('bst:area:list')")
    @GetMapping("/list")
    public TableDataInfo list(AreaQuery query)
    {
        startPage();
        startOrderBy();
        query.setScope(true);
        query.addAreaPermission(AreaJoinPermission.AREA_VIEW.getCode());
        List<AreaVO> list = areaService.selectAreaList(query);
        areaAssembler.assembleSubAreaCount(list);
        return getDataTable(list);
    }

    /**
     * 查询运营区简单数据
     */
    @PreAuthorize("@ss.hasPermi('bst:area:list')")
    @GetMapping("/simpleList")
    public AjaxResult simpleList(AreaQuery query)
    {
        query.setScope(true);
        query.addAreaPermission(AreaJoinPermission.AREA_VIEW.getCode());
        List<AreaVO> list = areaService.selectSimpleList(query);
        return success(list);
    }

    /**
     * 通过ID列表查询简单数据
     * @param response
     * @param query
     */
    @PreAuthorize("@ss.hasPermi('bst:area:list')")
    @PostMapping("/simpleListByIds")
    public AjaxResult simpleListByIds(@RequestBody List<Long> ids) {
        if (CollectionUtils.isEmptyElement(ids)) {
            return success(Collections.emptyList());
        }
        AreaQuery query = new AreaQuery();
        query.setIds(ids);
        query.setScope(true);
        query.addAreaPermission(AreaJoinPermission.AREA_VIEW.getCode());
        return success(areaService.selectSimpleList(query));
    }

    /**
     * 导出运营区列表
     */
    @PreAuthorize("@ss.hasPermi('bst:area:export')")
    @Log(title = "运营区", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AreaQuery query)
    {
        query.setScope(true);
        query.addAreaPermission(AreaJoinPermission.AREA_VIEW.getCode());
        List<AreaVO> list = areaService.selectAreaList(query);
        ExcelUtil<AreaVO> util = new ExcelUtil<AreaVO>(AreaVO.class);
        util.exportExcel(response, list, "运营区数据");
    }

    /**
     * 获取运营区详细信息
     */
    @PreAuthorize("@ss.hasPermi('bst:area:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(areaService.selectAreaById(id, true));
    }

    /**
     * 新增运营区
     */
    @PreAuthorize("@ss.hasPermi('bst:area:add')")
    @Log(title = "新增运营区", businessType = BusinessType.INSERT, bizIdName = "arg0", bizType = LogBizType.AREA)
    @PostMapping
    public AjaxResult add(@RequestBody @Validated(ValidGroup.Create.class) Area area){
        // 若不能操作他人，则设置为当前用户
        if (!userValidator.canView(area.getUserId())) {
            area.setUserId(getUserId());
        }
        area.setCreateId(getUserId());
        area = areaConverter.toPoByCreate(area);
        return toAjax(areaService.insertArea(area));
    }

    /**
     * 修改运营区
     */
    @PreAuthorize("@ss.hasPermi('bst:area:edit')")
    @Log(title = "修改运营区", businessType = BusinessType.UPDATE, bizIdName = "arg0", bizType = LogBizType.AREA)
    @PutMapping
    public AjaxResult edit(@RequestBody @Validated(ValidGroup.Update.class) Area area)
    {
        if (!areaValidator.canEdit(area.getId())) {
            return AjaxResult.error("您没有权限修改ID为" + area.getId() + "的运营区");
        }
        // 若不能操作他人，则不修改用户ID
        if (!userValidator.canView(area.getUserId())) {
            area.setUserId(null);
        }
        area = areaConverter.toPoByUpdate(area);
        return toAjax(areaService.updateArea(area));
    }

    /**
     * 删除运营区
     */
    @PreAuthorize("@ss.hasPermi('bst:area:remove')")
    @Log(title = "删除运营区", businessType = BusinessType.DELETE, bizIdName = "arg0", bizType = LogBizType.AREA)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids)
    {
        if (!areaValidator.canDeleteAll(ids)) {
            return AjaxResult.error("您没有权限删除ID为" + ids + "的运营区");
        }
        return toAjax(areaService.logicDel(ids));
    }

    /**
     * 获取定位所属区域信息（Debug）
     * @param lon 经度
     * @param lat 纬度
     * @param areaId 运营区ID
     * @return 定位所属区域信息
     */
    @PreAuthorize("@ss.hasPermi('bst:area:locationArea')")
    @GetMapping("/locationArea")
    public AjaxResult locationArea(BigDecimal lon, BigDecimal lat, Long areaId) {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("ride", areaService.selectLocationArea(lon, lat, areaId));

        AreaVO area = areaService.selectAreaById(areaId);
        List<AreaSubVO> areaSubList = areaSubService.selectParkingAreaByAreaId(areaId);
        AreaSubVO deviceAreaSub = AreaSubUtil.getInAreaSub(areaSubList, lon, lat, area.getError());
        ajax.put("return", deviceAreaSub);

        return ajax;
    }
}
