package com.sundot.airport.web.controller.item;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.github.pagehelper.PageInfo;
import com.sundot.airport.system.domain.SysPost;
import com.sundot.airport.system.domain.BasePosition;
import com.sundot.airport.system.service.ISysPostService;
import com.sundot.airport.system.service.IBasePositionService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.sundot.airport.common.annotation.Log;
import com.sundot.airport.common.core.controller.BaseController;
import com.sundot.airport.common.core.domain.AjaxResult;
import com.sundot.airport.common.enums.BusinessType;
import com.sundot.airport.item.domain.FailedMatchItem;
import com.sundot.airport.item.service.IFailedMatchItemService;
import com.sundot.airport.common.utils.poi.ExcelUtil;
import com.sundot.airport.common.core.page.TableDataInfo;

/**
 * 匹配失败物品Controller
 *
 * @author airport
 * @date 2025-11-21
 */
@RestController
@RequestMapping("/item/failedMatch")
public class FailedMatchItemController extends BaseController {
    @Autowired
    private IFailedMatchItemService failedMatchItemService;

    @Autowired
    private ISysPostService sysPostService;

    @Autowired
    private IBasePositionService basePositionService;

    /**
     * 查询当前用户的匹配失败物品列表（分页）
     * 只查询未编辑的记录（app_edited=0或null）
     */
    @GetMapping("/myList")
    public TableDataInfo getMyList(FailedMatchItem failedMatchItem) {
        // 获取当前登录用户ID
        Long currentUserId = getUserId();

        // 设置查询条件为当前用户ID
        failedMatchItem.setUserId(currentUserId);

        // 只查询未编辑的记录（app_edited=0或null）
        failedMatchItem.setAppEdited(false);

        // 开启分页
        startPage();

        // 查询列表（按 update_time 降序排列）
        List<FailedMatchItem> list = failedMatchItemService.selectFailedMatchItemList(failedMatchItem);

        return getDataTable(list);
    }

    /**
     * 查询匹配失败物品列表（管理员）
     */
    @PreAuthorize("@ss.hasPermi('item:failedMatch:list')")
    @GetMapping("/list")
    public TableDataInfo list(FailedMatchItem failedMatchItem) {
        startPage();
        List<FailedMatchItem> list = failedMatchItemService.selectFailedMatchItemList(failedMatchItem);
        return getDataTable(list);
    }

    /**
     * 导出匹配失败物品列表
     */
    @PreAuthorize("@ss.hasPermi('item:failedMatch:export')")
    @Log(title = "匹配失败物品", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FailedMatchItem failedMatchItem) {
        List<FailedMatchItem> list = failedMatchItemService.selectFailedMatchItemList(failedMatchItem);
        ExcelUtil<FailedMatchItem> util = new ExcelUtil<FailedMatchItem>(FailedMatchItem.class);
        util.exportExcel(response, list, "匹配失败物品数据");
    }

    /**
     * 获取匹配失败物品详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        return success(failedMatchItemService.selectFailedMatchItemById(id));
    }

    /**
     * 新增匹配失败物品
     */
    @PreAuthorize("@ss.hasPermi('item:failedMatch:add')")
    @Log(title = "匹配失败物品", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FailedMatchItem failedMatchItem) {
        return toAjax(failedMatchItemService.insertFailedMatchItem(failedMatchItem));
    }

    /**
     * 修改匹配失败物品
     */
    @PreAuthorize("@ss.hasPermi('item:failedMatch:edit')")
    @Log(title = "匹配失败物品", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FailedMatchItem failedMatchItem) {
        return toAjax(failedMatchItemService.updateFailedMatchItem(failedMatchItem));
    }

    /**
     * 标记匹配失败物品为已编辑（App端提交后调用）
     */
    @Log(title = "标记匹配失败物品为已编辑", businessType = BusinessType.UPDATE)
    @PutMapping("/markEdited/{id}")
    public AjaxResult markEdited(@PathVariable Integer id, @RequestBody Map<String, Object> params) {
        // 创建更新对象
        FailedMatchItem failedMatchItem = new FailedMatchItem();
        failedMatchItem.setId(id);

        // 设置基本字段
        if (params.containsKey("name") && params.get("name") != null) {
            failedMatchItem.setName(params.get("name").toString());
        }
        if (params.containsKey("categoryCode") && params.get("categoryCode") != null) {
            failedMatchItem.setCategoryCode(params.get("categoryCode").toString());
        }
        if (params.containsKey("categoryName") && params.get("categoryName") != null) {
            failedMatchItem.setCategoryName(params.get("categoryName").toString());
        }
        if (params.containsKey("extractedQuantity") && params.get("extractedQuantity") != null) {
            failedMatchItem.setExtractedQuantity(params.get("extractedQuantity").toString());
        }
        if (params.containsKey("extractedLocation") && params.get("extractedLocation") != null) {
            failedMatchItem.setExtractedLocation(params.get("extractedLocation").toString());
        }
        if (params.containsKey("teamId") && params.get("teamId") != null) {
            failedMatchItem.setTeamId(Long.valueOf(params.get("teamId").toString()));
        }
        if (params.containsKey("teamName") && params.get("teamName") != null) {
            failedMatchItem.setTeamName(params.get("teamName").toString());
        }
        if (params.containsKey("checkPointId") && params.get("checkPointId") != null) {
            failedMatchItem.setCheckPointId(Integer.valueOf(params.get("checkPointId").toString()));
        }
        if (params.containsKey("checkPointName") && params.get("checkPointName") != null) {
            failedMatchItem.setCheckPointName(params.get("checkPointName").toString());
        }
        if (params.containsKey("isActiveConcealment") && params.get("isActiveConcealment") != null) {
            failedMatchItem.setIsActiveConcealment(Integer.valueOf(params.get("isActiveConcealment").toString()));
        }

        // 处理 postCode：通过 postCode 查询 sys_post 表获取 position_id 和 position_name
        if (params.containsKey("postCode") && params.get("postCode") != null) {
            String postCode = params.get("postCode").toString();
            SysPost post = new SysPost();
            post.setPostCode(postCode);
            List<SysPost> postList = sysPostService.selectPostList(post);
            if (postList != null && !postList.isEmpty()) {
                SysPost foundPost = postList.get(0);
                failedMatchItem.setPositionId(foundPost.getPostId());
                failedMatchItem.setPositionName(foundPost.getPostName());
            }
        }

        // 处理查获位置三层结构：航站楼、区域、通道
        // terminalId, regionalId, channelId 前端传的是 base_position 的 code 字段
        // 需要查询 base_position 表获取对应的 id 和 name
        if (params.containsKey("terminalId") && params.get("terminalId") != null && !params.get("terminalId").toString().isEmpty()) {
            String terminalCode = params.get("terminalId").toString();
            BasePosition terminalQuery = new BasePosition();
            terminalQuery.setCode(terminalCode);
            List<BasePosition> terminalList = basePositionService.selectBasePositionList(terminalQuery);
            if (terminalList != null && !terminalList.isEmpty()) {
                BasePosition terminal = terminalList.get(0);
                failedMatchItem.setTerminalId(terminal.getId());
                failedMatchItem.setTerminalName(terminal.getName());
            }
        }

        if (params.containsKey("regionalId") && params.get("regionalId") != null && !params.get("regionalId").toString().isEmpty()) {
            String regionalCode = params.get("regionalId").toString();
            BasePosition regionalQuery = new BasePosition();
            regionalQuery.setCode(regionalCode);
            List<BasePosition> regionalList = basePositionService.selectBasePositionList(regionalQuery);
            if (regionalList != null && !regionalList.isEmpty()) {
                BasePosition regional = regionalList.get(0);
                failedMatchItem.setRegionalId(regional.getId());
                failedMatchItem.setRegionalName(regional.getName());
            }
        }

        if (params.containsKey("channelId") && params.get("channelId") != null && !params.get("channelId").toString().isEmpty()) {
            String channelCode = params.get("channelId").toString();
            BasePosition channelQuery = new BasePosition();
            channelQuery.setCode(channelCode);
            List<BasePosition> channelList = basePositionService.selectBasePositionList(channelQuery);
            if (channelList != null && !channelList.isEmpty()) {
                BasePosition channel = channelList.get(0);
                failedMatchItem.setChannelId(channel.getId());
                failedMatchItem.setChannelName(channel.getName());
            }
        }

        // 标记为已编辑
        failedMatchItem.setAppEdited(true);

        // 更新记录
        return toAjax(failedMatchItemService.updateFailedMatchItem(failedMatchItem));
    }

    /**
     * 删除匹配失败物品
     */
//    @PreAuthorize("@ss.hasPermi('item:failedMatch:remove')")
    @Log(title = "匹配失败物品", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(failedMatchItemService.deleteFailedMatchItemByIds(ids));
    }
}
