package com.hxhq.business.controller;

import java.io.IOException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hxhq.business.domain.GspRkjl;
import com.hxhq.business.domain.StorageLocationJcgj;
import com.hxhq.business.domain.YqJcgj;
import com.hxhq.business.dto.gsp.ImportGspRkjlDto;
import com.hxhq.business.dto.storage.ImportStorageLocationDto;
import com.hxhq.business.form.gsp.GspRkjlForm;
import com.hxhq.business.form.yq.StorageLocationForm;
import com.hxhq.business.form.yq.StorageLocationSearchForm;
import com.hxhq.business.service.IStorageLocationJcgjService;
import com.hxhq.common.core.exception.ServiceException;
import com.hxhq.common.core.utils.StringUtils;
import com.hxhq.common.core.utils.poi.ExcelUtil;
import com.hxhq.common.security.annotation.RequiresPermissions;
import com.hxhq.common.security.utils.SecurityUtils;
import com.hxhq.system.api.domain.SysDept;
import com.hxhq.system.api.domain.SysDictData;
import com.hxhq.system.service.ISysDeptService;
import com.hxhq.system.service.ISysDictDataService;
import com.hxhq.system.service.ISysUserService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.hxhq.business.domain.StorageLocation;
import com.hxhq.business.service.IStorageLocationService;
import com.hxhq.common.core.web.controller.BaseController;
import com.hxhq.common.core.web.domain.AjaxResult;
import com.hxhq.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;


/**
 * 存储位置Controller
 *
 * @author hxhq
 * @date 2026-03-02
 */
@RestController
@RequestMapping("/business/storageLocation")
public class StorageLocationController extends BaseController
{
    @Autowired
    private IStorageLocationService storageLocationService;

    @Autowired
    private IStorageLocationJcgjService storageLocationJcgjService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysDeptService sysDeptService;


    /**
     * 查询仪器稽查轨迹列表
     */
    @RequiresPermissions("business:resource:yq:list")
    @GetMapping("/jcgj/list")
    public TableDataInfo list(Long id) {
        if(id == null ) {
            return getDataTable(new ArrayList<>());
        }
        startPage();
        StorageLocationJcgj jcgj = new StorageLocationJcgj();
        jcgj.setStorageLocationId(id);
        List<StorageLocationJcgj> list = storageLocationJcgjService.queryList(jcgj);
        return getDataTable(list);
    }


    /**
     * 查询存储位置列表
     */
    @GetMapping("/list")
    @RequiresPermissions("business:storageLocation:list")
    public TableDataInfo list(StorageLocationSearchForm form)
    {
        startPage();
        List<StorageLocation> list = storageLocationService.queryList(form);
        return getDataTable(list);
    }

    /**
     * 获取存储位置详细信息
     */
    @GetMapping(value = "/info")
    public AjaxResult getInfo(Long id)
    {
        return AjaxResult.success(storageLocationService.queryInfo(id));
    }

    /**
     * 新增存储位置信息
     */
    @PostMapping("/save")
    @RequiresPermissions("business:storageLocation:add")
    public AjaxResult save(@RequestBody StorageLocationForm form)
    {
        form.setQmrId(SecurityUtils.getUserId());
        LambdaQueryWrapper<StorageLocation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StorageLocation::getName, form.getName());
        long count = storageLocationService.count(queryWrapper);
        if(count > 0) {
            return error("【" + form.getName() + "】已存在");
        }
        storageLocationService.addStorageLocation(form);
        return success();
    }

    /**
     * 新增存储位置信息
     */
    @PostMapping("/edit")
    @RequiresPermissions("business:storageLocation:edit")
    public AjaxResult edit(@RequestBody StorageLocationForm form)
    {
        form.setQmrId(SecurityUtils.getUserId());
        LambdaQueryWrapper<StorageLocation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StorageLocation::getName, form.getName());
        StorageLocation storageLocation = storageLocationService.getOne(queryWrapper);
        if(storageLocation != null && !storageLocation.getId().equals(form.getId())) {
            return error("【" + form.getName() + "】已存在");
        }
        storageLocationService.updateStorageLocation(form);
        return success();
    }

    @PostMapping("/importTemplate")
    @RequiresPermissions("business:storageLocation:import")
    public void importTemplate(HttpServletResponse response) throws IOException
    {
        ExcelUtil<ImportStorageLocationDto> util = new ExcelUtil<ImportStorageLocationDto>(ImportStorageLocationDto.class);
        util.importTemplateExcel(response, "【模板】存储位置");
    }


    @PostMapping("/importData")
    @RequiresPermissions("business:storageLocation:import")
    public AjaxResult importData(MultipartFile file, StorageLocationForm form, HttpServletResponse response) throws IOException
    {
        form.setQmrId(SecurityUtils.getUserId());
        sysUserService.checkPassword(SecurityUtils.getUserId(), form.getQmrmm(), false);

        List<SysDept> sysDepts = sysDeptService.selectDeptList(new SysDept());
        Map<String, Long> sysDeptMap = new HashMap<>();
        for (SysDept sysDept : sysDepts) {
            sysDeptMap.put(sysDept.getDeptName(), sysDept.getDeptId());
        }

        List<StorageLocation> list = storageLocationService.list();
        List<String> storageLocationNameList = list.stream().map(StorageLocation::getName).collect(Collectors.toList());


        ExcelUtil<ImportStorageLocationDto> util = new ExcelUtil<ImportStorageLocationDto>(ImportStorageLocationDto.class);
        List<ImportStorageLocationDto> storageLocationDtos = util.importExcel(file.getInputStream());
        if(CollectionUtils.isEmpty(storageLocationDtos)) {
            throw new ServiceException("导入数据表格为空");
        }
        int i = 2;
        List<String> importList = new ArrayList<>();
        List<StorageLocation> importDataList =  new ArrayList<>();
        for (ImportStorageLocationDto importStorageLocationDto : storageLocationDtos) {
            if(StringUtils.isEmpty(importStorageLocationDto.getLocation())) {
                throw new ServiceException("第【" + i + "】行放置地点不能为空");
            }
            if(StringUtils.isEmpty(importStorageLocationDto.getName())) {
                throw new ServiceException("第【" + i + "】行设备名称或编号不能为空");
            }
            if(storageLocationNameList.contains(importStorageLocationDto.getName())) {
                throw new ServiceException("第【" + i + "】行设备名称或编号【" + importStorageLocationDto.getName() +  "】已存在");
            }
            if(StringUtils.isEmpty(importStorageLocationDto.getShelfPlacement())) {
                throw new ServiceException("第【" + i + "】行放置货架不能为空");
            }
            if(StringUtils.isEmpty(importStorageLocationDto.getCompartment())) {
                throw new ServiceException("第【" + i + "】行温层不能为空");
            }
            if(StringUtils.isEmpty(importStorageLocationDto.getDeptName())) {
                throw new ServiceException("第【" + i + "】行所属部门不能为空");
            }
            Long deptId = sysDeptMap.get(importStorageLocationDto.getDeptName());
            if(deptId == null) {
                throw new ServiceException("第【" + i + "】行所属部门【" + importStorageLocationDto.getDeptName() + "】名称有误,无法匹配对应数据");
            }
            if(importList.contains(importStorageLocationDto.getName())) {
                throw new ServiceException("第【" + i + "】行存在重复数据【" + importStorageLocationDto.getName() +  "】");
            }
            importList.add(importStorageLocationDto.getName());
            StorageLocation storageLocationForm = new StorageLocation();
            BeanUtils.copyProperties(importStorageLocationDto, storageLocationForm);
            storageLocationForm.setDeptId(deptId);
            storageLocationForm.setStatus(10);
            importDataList.add(storageLocationForm);
        }
        storageLocationService.addBatch(importDataList, form);

        return success();
    }
}
