package com.yc.ship.module.resource.controller.admin.machine;

import cn.hutool.core.util.ObjUtil;
import com.yc.ship.framework.common.exception.ServiceException;
import com.yc.ship.framework.common.pojo.CommonResult;
import com.yc.ship.framework.common.pojo.PageParam;
import com.yc.ship.framework.common.pojo.PageResult;
import com.yc.ship.framework.common.util.object.BeanUtils;
import com.yc.ship.framework.excel.core.util.ExcelUtils;
import com.yc.ship.framework.operatelog.core.annotations.OperateLog;
import com.yc.ship.module.resource.controller.admin.machine.vo.ScenicMachinePageReqVO;
import com.yc.ship.module.resource.controller.admin.machine.vo.ScenicMachineRespVO;
import com.yc.ship.module.resource.controller.admin.machine.vo.ScenicMachineSaveReqVO;
import com.yc.ship.module.resource.convert.machine.MachineConvert;
import com.yc.ship.module.resource.dal.dataobject.channel.ScenicChannelDO;
import com.yc.ship.module.resource.dal.dataobject.machine.ScenicMachineDO;
import com.yc.ship.module.resource.dal.dataobject.site.ScenicSiteDO;
import com.yc.ship.module.resource.service.channel.ScenicChannelService;
import com.yc.ship.module.resource.service.machine.ScenicMachineService;
import com.yc.ship.module.resource.service.site.ScenicSiteService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.MapUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import static com.yc.ship.framework.common.pojo.CommonResult.success;
import static com.yc.ship.framework.common.util.collection.CollectionUtils.convertList;
import static com.yc.ship.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;


@Tag(name = "管理后台 - 设备")
@RestController
@RequestMapping("/resource/scenic-machine")
@Validated
public class ScenicMachineController {

    @Resource
    private ScenicSiteService scenicSiteService;

    @Resource
    private ScenicChannelService scenicChannelService;

    @Resource
    private ScenicMachineService scenicMachineService;

    @PostMapping("/create")
    @Operation(summary = "创建设备")
    @PreAuthorize("@ss.hasPermission('product:scenic-machine:create')")
    public CommonResult<Long> createScenicMachine(@Valid @RequestBody ScenicMachineSaveReqVO createReqVO) {
        verifyConflict(createReqVO);
        return success(scenicMachineService.createScenicMachine(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新设备")
    @PreAuthorize("@ss.hasPermission('product:scenic-machine:update')")
    public CommonResult<Boolean> updateScenicMachine(@Valid @RequestBody ScenicMachineSaveReqVO updateReqVO) {
        verifyConflict(updateReqVO);
        scenicMachineService.updateScenicMachine(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除设备")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('product:scenic-machine:delete')")
    public CommonResult<Boolean> deleteScenicMachine(@RequestParam("id") Long id) {
        scenicMachineService.deleteScenicMachine(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得设备")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('product:scenic-machine:query')")
    public CommonResult<ScenicMachineRespVO> getScenicMachine(@RequestParam("id") Long id) {
        ScenicMachineDO scenicMachine = scenicMachineService.getScenicMachine(id);
        // 查询通道
        ScenicChannelDO channelDO = scenicChannelService.getScenicChannel(scenicMachine.getChannelId());
        // 查询站点
        ScenicSiteDO siteDO = scenicSiteService.getScenicSite(channelDO.getSiteId());
        ScenicMachineRespVO machineRespVO = BeanUtils.toBean(scenicMachine, ScenicMachineRespVO.class);
        machineRespVO.setChannelName(channelDO.getName());
        machineRespVO.setSiteId(siteDO.getId());
        machineRespVO.setSiteName(siteDO.getName());
        machineRespVO.setSiteType(siteDO.getSiteType());
        return success(machineRespVO);
    }

    @GetMapping("/page")
    @Operation(summary = "获得设备分页")
    @PreAuthorize("@ss.hasPermission('product:scenic-machine:query')")
    public CommonResult<PageResult<ScenicMachineRespVO>> getScenicMachinePage(@Valid ScenicMachinePageReqVO pageReqVO) {
        PageResult<ScenicMachineDO> pageResult = scenicMachineService.getScenicMachinePage(pageReqVO);
        Map<Long, ScenicChannelDO> channelMap = scenicChannelService.getChannelMap(
                convertList(pageResult.getList(), ScenicMachineDO::getChannelId));
        return success(new PageResult<>(MachineConvert.INSTANCE.convertList(pageResult.getList(), channelMap),
                pageResult.getTotal()));
//        return success(BeanUtils.toBean(pageResult, ScenicMachineRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出设备 Excel")
    @PreAuthorize("@ss.hasPermission('product:scenic-machine:export')")
    @OperateLog(type = EXPORT,enable = false)
    public void exportScenicMachineExcel(@Valid ScenicMachinePageReqVO pageReqVO,
                                         HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ScenicMachineDO> list = scenicMachineService.getScenicMachinePage(pageReqVO).getList();
        List<ScenicMachineRespVO> excelList = BeanUtils.toBean(list, ScenicMachineRespVO.class);

        Map channelMap = scenicChannelService.getChannelMap(
                convertList(excelList, ScenicMachineRespVO::getChannelId));
        excelList = MachineConvert.INSTANCE.convertRespList(excelList, channelMap);
        Map siteMap = scenicSiteService.getSiteMap(
                convertList(excelList, ScenicMachineRespVO::getSiteId));
        excelList = MachineConvert.INSTANCE.convertRespList(excelList, siteMap);
        // 导出 Excel
        ExcelUtils.write(response, "设备数据.xls", "数据", ScenicMachineRespVO.class, excelList);
    }

    private void verifyConflict(ScenicMachineSaveReqVO reqVO) {
        Long id = reqVO.getId();
        String machineId = reqVO.getMachineId();
        // 查询通道
        ScenicChannelDO channelDO = scenicChannelService.getScenicChannel(reqVO.getChannelId());
        // 查询站点
        ScenicSiteDO siteDO = scenicSiteService.getScenicSite(channelDO.getSiteId());
        List<Map<String, Object>> mapList = scenicMachineService.getMachineSiteInfos(machineId, siteDO.getSiteType(), siteDO.getTenantId());
        // 排除自己
        if (mapList != null && !mapList.isEmpty()) {
            mapList.removeIf(item -> ObjUtil.equal(item.get("id"), id));
            if (!mapList.isEmpty()) {
                throw new ServiceException(1, "该设备编码【" + machineId + "】与【" + MapUtils.getString(mapList.get(0), "name") + "】设备编码冲突！");
            }
        }
    }
}
