package cn.iocoder.yudao.module.inspection.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.inspection.service.AppInspectionPartnerService;
import cn.iocoder.yudao.module.inspection.vo.InspectionEqInfoImportVo;
import cn.iocoder.yudao.module.inspection.vo.StaffImportExcelVO;
import cn.iocoder.yudao.module.shop.entity.ShopMallPartners;
import cn.iocoder.yudao.module.system.api.dict.DictDataApi;
import cn.iocoder.yudao.module.system.api.dict.dto.DictDataRespDTO;
import cn.iocoder.yudao.util.ExcelUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import cn.iocoder.yudao.module.core.controller.BaseController;
import cn.iocoder.yudao.module.inspection.entity.InspectionEquInfo;
import cn.iocoder.yudao.module.inspection.service.IInspectionEquInfoService;
import org.springframework.web.multipart.MultipartFile;

import static cn.iocoder.yudao.framework.excel.core.util.ExcelUtils.exportBlankTemplate;

/**
 * equInfoController
 *
 * @author zcy
 * @date 2023-10-13
 */
@RestController
@RequestMapping("/admin-api/system/equInfo")
public class InspectionEquInfoController extends BaseController {
    @Autowired
    private IInspectionEquInfoService inspectionEquInfoService;
    @Autowired
    private AppInspectionPartnerService partnerService;
    @Autowired
    private DictDataApi dictDataApi;

    /**
     * 查询equInfo列表
     */
    @GetMapping("/list")
    public CommonResult list(Integer pageNum, Integer pageSize, InspectionEquInfo inspectionEquInfo) throws Exception {

        Page page = new Page(pageNum, pageSize);
//        if (ObjectUtil.isNull(inspectionEquInfo.getPartnerId())) {
////            ShopMallPartners partners = partnerService.shopInfoByUserId();
////            inspectionEquInfo.setPartnerId(partners.getPartnerId());
//        }
        IPage<InspectionEquInfo> list = inspectionEquInfoService.selectInspectionEquInfoList(page, inspectionEquInfo);
        return success(list);
    }

    /**
     * 导出equInfo列表
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, InspectionEquInfo inspectionEquInfo) {
        Page page = new Page(1, 100000);
        IPage<InspectionEquInfo> list = inspectionEquInfoService.selectInspectionEquInfoList(page, inspectionEquInfo);
        ExcelUtil<InspectionEquInfo> util = new ExcelUtil<InspectionEquInfo>(InspectionEquInfo.class);
        util.exportExcel(response, list.getRecords(), "equInfo数据");
    }

    /**
     * 获取equInfo详细信息
     */
    @GetMapping(value = "/{id}")
    public CommonResult getInfo(@PathVariable("id") Long id) {
        return success(inspectionEquInfoService.selectInspectionEquInfoById(id));
    }

    /**
     * 新增equInfo
     */
    @PostMapping("/add")
    public CommonResult add(@RequestBody InspectionEquInfo inspectionEquInfo) throws Exception {
        ShopMallPartners partners = partnerService.shopInfo();
        inspectionEquInfo.setPartnerId(partners.getPartnerId());
        return toAjax(inspectionEquInfoService.insertInspectionEquInfo(inspectionEquInfo));
    }

    /**
     * 修改equInfo
     */
    @PostMapping("/edit")
    public CommonResult edit(@RequestBody InspectionEquInfo inspectionEquInfo) throws Exception {
        ShopMallPartners partners = partnerService.shopInfo();
        InspectionEquInfo inspectionEquInfo1 = inspectionEquInfoService.selectInspectionEquInfoById(inspectionEquInfo.getId());
        if (!partners.getPartnerId().equals(inspectionEquInfo1.getPartnerId())) {
            return null;
        }
        return toAjax(inspectionEquInfoService.updateInspectionEquInfo(inspectionEquInfo));
    }

    /**
     * 删除equInfo
     */
    @DeleteMapping("/{id}")
    public CommonResult remove(@PathVariable Long id) throws Exception {
        ShopMallPartners partners = partnerService.shopInfo();
        InspectionEquInfo inspectionEquInfo1 = inspectionEquInfoService.selectInspectionEquInfoById(id);
        if (!partners.getPartnerId().equals(inspectionEquInfo1.getPartnerId())) {
            return null;
        }
        return toAjax(inspectionEquInfoService.deleteInspectionEquInfoById(id));
    }

    /**
     * 导入模板
     *
     * @param response 响应
     * @throws IOException IOException
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        // 表头
        String[] head = {"设备名称", "设备类型", "型号", "出厂编号", "校准日期", "复校日期", "证书编号", "制造商", "校准单位", "电话", "地址", "邮编", "电子邮箱"};

        // 下拉框列及选项：列索引 -> 下拉框选项
        Map<Integer, String[]> dropdownColumns = new HashMap<>();

        // 查询设备类型
        List<DictDataRespDTO> eqType = dictDataApi.getDictDataList("ins_equ_type");
        if (eqType != null && !eqType.isEmpty()) {
            String[] array1 = eqType.stream()
                    .map(DictDataRespDTO::getLabel)
                    .toArray(String[]::new);
            dropdownColumns.put(1, array1);  // 设备类型列
        }

        // 示例数据（此处为自定义示例行，可根据实际需求修改）
        List<List<String>> exampleDataList = Arrays.asList(
                Arrays.asList("示例设备", "请在下拉框中选择", "示例型号", "示例出厂编号", "2023/1/1", "2023/12/31", "123456", "示例制造商", "示例校准单位", "1234567890", "示例地址", "12345", "example@email.com")
        );

        // 调用方法导出空白模板
        exportBlankTemplate(response, "eq_template.xlsx", "设备信息", head, dropdownColumns, true, null, null);
    }


    /**
     * 导入设备信息
     *
     * @param file 文件
     * @return 导入结果
     */
    @PostMapping("/importEquipment")
    public CommonResult<Map<String, Object>> importEquipment(@RequestParam("file") MultipartFile file) {
        try {
            List<InspectionEqInfoImportVo> list = ExcelUtils.read(file, InspectionEqInfoImportVo.class);
            return success(inspectionEquInfoService.importStaff(list));
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 添加设备文件夹
     *
     * @param id 设备id
     * @return 文件夹id
     */
    @PostMapping("/addFolder")
    public CommonResult<?> addFolder(@RequestBody Long id) {
        return success(inspectionEquInfoService.addFolder(id));
    }

    @PostMapping("/addDeviceFolder")
    public CommonResult<?> addDeviceFolder(@RequestParam Long id, @RequestParam String servicePackageId, @RequestParam String defaultKey) {
        return success(inspectionEquInfoService.addDeviceFolder(id, servicePackageId, defaultKey));
    }

    /**
     * 查询设备数量根据分类
     *
     * @return
     */
    @GetMapping("/queryEquipmentCountByCategory")
    public CommonResult<?> queryEquipmentCountByCategory() {
        return success(inspectionEquInfoService.queryEquipmentCountByCategory());
    }

    @GetMapping("/queryEquipmentCountByPackageId")
    public CommonResult<?> queryEquipmentCountByPackageId(@RequestParam String servicePackageId, @RequestParam String dictType) {
        return success(inspectionEquInfoService.queryEquipmentCountByPackageId(servicePackageId, dictType));
    }

}
