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

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

import cn.hutool.core.util.ObjectUtil;
import com.sundot.airport.common.dto.UserInfo;
import com.sundot.airport.common.exception.ServiceException;
import com.sundot.airport.common.utils.DictUtils;
import com.sundot.airport.common.utils.StringUtils;
import com.sundot.airport.web.core.utils.DataPermissionUtils;
import com.sundot.airport.item.domain.ItemSeizureItems;
import com.sundot.airport.item.domain.ItemSeizureRecordDTO;
import com.sundot.airport.item.domain.vo.ItemSeizureRecordExportVO;
import com.sundot.airport.system.service.ISysDeptService;
import com.sundot.airport.system.service.ISysPostService;
import com.sundot.airport.web.core.cache.UserCache;
import com.sundot.airport.common.core.domain.DataPermissionResult;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
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.ItemSeizureRecord;
import com.sundot.airport.item.service.IItemSeizureRecordService;
import com.sundot.airport.common.utils.poi.ExcelUtil;
import com.sundot.airport.common.core.page.TableDataInfo;

/**
 * 查获记录Controller
 *
 * @author ruoyi
 * @date 2025-07-08
 */
@RestController
@RequestMapping("/item/record")
public class ItemSeizureRecordController extends BaseController {
    @Autowired
    private UserCache userCache;
    @Autowired
    private ISysPostService sysPostService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private IItemSeizureRecordService itemSeizureRecordService;

    /**
     * 查询查获记录列表
     */
    @PreAuthorize("@ss.hasPermi('item:record:list')")
    @GetMapping("/list")
    public TableDataInfo list(ItemSeizureRecordDTO itemSeizureRecord) {
        // 应用数据权限过滤
        DataPermissionResult dataPermission = DataPermissionUtils.getDataPermission(getUserId(), getDeptId(), getLoginUser());
        switch (dataPermission.getPermissionType()) {
            case SELF:
                itemSeizureRecord.setInspectUserId(dataPermission.getValue());
                break;
            case STATION:
                itemSeizureRecord.setInspectStationId(dataPermission.getValue());
                break;
            case BRIGADE:
                itemSeizureRecord.setInspectBrigadeId(dataPermission.getValue());
                break;
            case DEPARTMENT:
                itemSeizureRecord.setInspectDepartmentId(dataPermission.getValue());
                break;
            case TEAM:
                itemSeizureRecord.setInspectTeamId(dataPermission.getValue());
                break;
            case ALL:
            default:
                // 不设置过滤条件，查看所有数据
                break;
        }

        startPage();
        List<ItemSeizureRecord> list = itemSeizureRecordService.selectItemSeizureRecordList(itemSeizureRecord);
        return getDataTable(list);
    }

    /**
     * 导出查获记录列表
     */
    @PreAuthorize("@ss.hasPermi('item:record:export')")
    @Log(title = "查获记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ItemSeizureRecordDTO itemSeizureRecord) {
        // 应用数据权限过滤
        DataPermissionResult dataPermission = DataPermissionUtils.getDataPermission(getUserId(), getDeptId(), getLoginUser());
        switch (dataPermission.getPermissionType()) {
            case SELF:
                itemSeizureRecord.setInspectUserId(dataPermission.getValue());
                break;
            case STATION:
                itemSeizureRecord.setInspectStationId(dataPermission.getValue());
                break;
            case BRIGADE:
                itemSeizureRecord.setInspectBrigadeId(dataPermission.getValue());
                break;
            case DEPARTMENT:
                itemSeizureRecord.setInspectDepartmentId(dataPermission.getValue());
                break;
            case TEAM:
                itemSeizureRecord.setInspectTeamId(dataPermission.getValue());
                break;
            case ALL:
            default:
                // 不设置过滤条件，查看所有数据
                break;
        }

        List<ItemSeizureRecord> list = itemSeizureRecordService.selectItemSeizureRecordListForExport(itemSeizureRecord);
        exportData(response, list);
    }

    /**
     * 导出查获记录数据
     *
     * @param response 响应对象
     * @param list     查获记录列表
     */
    private void exportData(HttpServletResponse response, List<ItemSeizureRecord> list) {
        List<ItemSeizureRecordExportVO> exportList = new ArrayList<>();

        // 直接使用已查询到的记录，避免再次查询数据库
        for (ItemSeizureRecord record : list) {
            if (record != null) {
                // 处理没有物品的记录
                if (record.getItemSeizureItemsList() == null || record.getItemSeizureItemsList().isEmpty()) {
                    ItemSeizureRecordExportVO exportVO = new ItemSeizureRecordExportVO();
                    // 基本信息
                    exportVO.setInspectUserName(record.getInspectUserName());
                    exportVO.setSeizureTime(record.getSeizureTime());
                    StringBuilder sb = new StringBuilder();
                    if (StringUtils.isNotEmpty(record.getTerminlName())) {
                        sb.append(record.getTerminlName()).append("/");
                    }
                    if (StringUtils.isNotEmpty(record.getRegionalName())) {
                        sb.append(record.getRegionalName()).append("/");
                    }
                    if (StringUtils.isNotEmpty(record.getChannelName())) {
                        sb.append(record.getChannelName());
                    }
                    exportVO.setChannelName(sb.toString());
                    exportVO.setCheckMethodDesc(record.getCheckMethodDesc());
                    exportVO.setInspectTeamName(record.getInspectTeamName());
                    exportVO.setAttendanceTeamName(record.getAttendanceTeamName());
                    exportVO.setPowerOnInstruction(record.getPowerOnInstruction());
                    exportVO.setXrayOperator(record.getXrayOperatorName());
                    exportVO.setProcessStatus(record.getProcessStatus());

                    // 物品信息为空
                    exportVO.setCategoryNameTwo("");
                    exportVO.setQuantity(null);
                    exportVO.setCheckPositionNameTwo("");
                    exportVO.setHandlingMethod("");
                    exportVO.setIsActiveConcealmentDesc("");
                    exportVO.setCommonContraband(null);
                    exportVO.setContrabandDesc("");
                    exportList.add(exportVO);
                } else {
                    // 处理有物品的记录
                    for (ItemSeizureItems item : record.getItemSeizureItemsList()) {
                        ItemSeizureRecordExportVO exportVO = new ItemSeizureRecordExportVO();
                        // 基本信息
                        exportVO.setInspectUserName(record.getInspectUserName());
                        exportVO.setSeizureTime(record.getSeizureTime());
                        StringBuilder sb = new StringBuilder();
                        if (StringUtils.isNotEmpty(record.getTerminlName())) {
                            sb.append(record.getTerminlName()).append("/");
                        }
                        if (StringUtils.isNotEmpty(record.getRegionalName())) {
                            sb.append(record.getRegionalName()).append("/");
                        }
                        if (StringUtils.isNotEmpty(record.getChannelName())) {
                            sb.append(record.getChannelName());
                        }
                        exportVO.setChannelName(sb.toString());
                        exportVO.setCheckMethodDesc(record.getCheckMethodDesc());
                        exportVO.setInspectTeamName(record.getInspectTeamName());
                        exportVO.setAttendanceTeamName(record.getAttendanceTeamName());
                        exportVO.setPowerOnInstruction(record.getPowerOnInstruction());
                        exportVO.setXrayOperator(record.getXrayOperatorName());
                        exportVO.setProcessStatus(record.getProcessStatus());

                        // 物品信息
                        exportVO.setCategoryNameTwo(item.getCategoryNameOne() + "/" + item.getCategoryNameTwo());
                        exportVO.setQuantity(item.getQuantity());
                        exportVO.setCheckPositionNameTwo(item.getCheckPositionNameOne() + "/" + item.getCheckPositionNameTwo());
                        //处理方式查字典
                        String handlingMethodLabel = DictUtils.getDictLabel("item_handling_method", item.getHandlingMethod());
                        exportVO.setHandlingMethod(StringUtils.isNotEmpty(handlingMethodLabel) ? handlingMethodLabel : item.getHandlingMethod());
                        exportVO.setIsActiveConcealmentDesc("1".equals(String.valueOf(item.getIsActiveConcealment())) ? "是" : "否");
                        exportVO.setCommonContraband(item.getCommonContraband());
                        exportVO.setContrabandDesc(item.getContrabandDesc());
                        exportList.add(exportVO);
                    }
                }
            }
        }

        ExcelUtil<ItemSeizureRecordExportVO> util = new ExcelUtil<ItemSeizureRecordExportVO>(ItemSeizureRecordExportVO.class);
        util.exportExcel(response, exportList, "查获记录数据");
    }

    /**
     * 获取查获记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('item:record:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(itemSeizureRecordService.selectItemSeizureRecordById(id));
    }

    /**
     * 新增查获记录
     */
    @PreAuthorize("@ss.hasPermi('item:record:add')")
    @Log(title = "查获记录", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody ItemSeizureRecord itemSeizureRecord) {
        itemSeizureRecord.setCreateBy(getUsername());
        UserInfo userInfo = userCache.getUserInfo(itemSeizureRecord.getInspectUserId());
        if (ObjectUtil.isNull(userInfo) || ObjectUtil.isNull(userInfo.getStationId()) || ObjectUtil.isNull(userInfo.getDepartmentId()) || ObjectUtil.isNull(userInfo.getTeamsId())) {
            throw new ServiceException("操作失败,检查人员非班组成员");
        }
        itemSeizureRecord.setInspectStationId(userInfo.getStationId());
        itemSeizureRecord.setInspectStationName(userInfo.getStationName());
        itemSeizureRecord.setInspectBrigadeId(userInfo.getBrigadeId());
        itemSeizureRecord.setInspectBrigadeName(userInfo.getBrigadeName());
        itemSeizureRecord.setInspectDepartmentId(userInfo.getDepartmentId());
        itemSeizureRecord.setInspectDepartmentName(userInfo.getDepartmentName());
        itemSeizureRecord.setInspectTeamId(userInfo.getTeamsId());
        itemSeizureRecord.setInspectTeamName(userInfo.getTeamsName());
        itemSeizureRecord.getItemSeizureItemsList().forEach(itemSeizureItems -> itemSeizureItems.setCreateBy(getUsername()));
        return success(itemSeizureRecordService.insertItemSeizureRecord(itemSeizureRecord));
    }

    /**
     * 修改查获记录
     */
    @PreAuthorize("@ss.hasPermi('item:record:edit')")
    @Log(title = "查获记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ItemSeizureRecord itemSeizureRecord) {
        itemSeizureRecord.setUpdateBy(getUsername());
        return toAjax(itemSeizureRecordService.updateItemSeizureRecord(itemSeizureRecord));
    }

    /**
     * 删除查获记录
     */
    @PreAuthorize("@ss.hasPermi('item:record:remove')")
    @Log(title = "查获记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(itemSeizureRecordService.deleteItemSeizureRecordByIds(ids));
    }
}