package com.ozs.web.controller.accountmanagment;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ozs.common.annotation.Log;
import com.ozs.common.core.controller.BaseController;
import com.ozs.common.core.domain.AjaxResult;
import com.ozs.common.core.domain.entity.SysDictData;
import com.ozs.common.enums.BusinessType;
import com.ozs.common.utils.IdempotenceUtils;
import com.ozs.common.utils.StringUtils;
import com.ozs.common.utils.file.FileUtils;
import com.ozs.common.utils.poi.ExcelUtil;
import com.ozs.entity.BaseCameraManagement;
import com.ozs.entity.BaseRailwayManagement;
import com.ozs.entity.vo.BaseRailwayManagementVo;
import com.ozs.service.BaseCameraManagementService;
import com.ozs.service.BaseRailwayManagementService;
import com.ozs.system.service.ISysDictTypeService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 线路管理表前端控制器
 * </p>
 *
 * @author ozs
 * @since 2023-02-17
 */
@RestController
@RequestMapping("/service/baseRailwayManagement")
@Slf4j
public class BaseRailwayManagementController extends BaseController {
    @Resource
    BaseRailwayManagementService baseRailwayManagementService;
    @Autowired
    private ISysDictTypeService dictTypeService;
    @Autowired
    private BaseCameraManagementService baseCameraManagementService;
    @Autowired
    private IdempotenceUtils idempotenceUtils;

    /**
     * 线路管理表分页
     *
     * @param baseRailwayManagementVo
     * @return
     */
    @ApiOperation(value = "线路管理表分页")
    @PostMapping("/list")
    @Log(title = "线路台账管理", businessType = BusinessType.SELECT)
    public AjaxResult selectBaseLineManagement(@RequestBody BaseRailwayManagementVo baseRailwayManagementVo) {
        LambdaQueryWrapper<BaseRailwayManagement> lw = new LambdaQueryWrapper<BaseRailwayManagement>();
        if (!StringUtils.isBlank(baseRailwayManagementVo.getRailwayCode())) {
            lw.like(BaseRailwayManagement::getRailwayCode, "%" + baseRailwayManagementVo.getRailwayCode() + "%");
        }
        if (!ObjectUtils.isEmpty(baseRailwayManagementVo.getRailwayType()) && baseRailwayManagementVo.getRailwayType() != 0) {
            lw.eq(BaseRailwayManagement::getRailwayType, baseRailwayManagementVo.getRailwayType());
        }
        IPage<BaseRailwayManagement> page = baseRailwayManagementService.page(new Page<BaseRailwayManagement>(baseRailwayManagementVo.getPageNum(), baseRailwayManagementVo.getPageSize()), lw);
        List<SysDictData> data = dictTypeService.selectDictDataByType("railway_type");
        if (!ObjectUtils.isEmpty(page) && !ObjectUtils.isEmpty(page.getRecords())) {
            List<BaseRailwayManagement> dto1 = page.getRecords().stream().map(o -> {
                for (SysDictData datum : data) {
                    if (datum.getDictValue().equals(o.getRailwayType().toString())) {
                        o.setRailwayTypeName(datum.getDictLabel());
                    }
                }
                return o;
            }).collect(Collectors.toList());
            page.setRecords(dto1);
        }
        return AjaxResult.success(page);
    }

    /**
     * 删除线路管理表信息
     *
     * @param lineIds
     * @return
     */
    @DeleteMapping("/{lineIds}")
    @ApiOperation("删除线路管理表信息")
    @Log(title = "线路台账管理", businessType = BusinessType.DELETE)
    public AjaxResult removeLineManagement(@PathVariable List<Long> lineIds) {
        for (Long lineId : lineIds) {
            BaseRailwayManagement baseRailwayManagement1 = baseRailwayManagementService.getById(lineId);
            if (ObjectUtils.isEmpty(baseRailwayManagement1)) {
                return error("主键" + lineId + ":不存在");
            }
            LambdaQueryWrapper<BaseCameraManagement> wrapper = new LambdaQueryWrapper();
            wrapper.eq(BaseCameraManagement::getRailwayCode, baseRailwayManagement1.getRailwayCode());
            List<BaseCameraManagement> list = baseCameraManagementService.list(wrapper);
            if (list.size() > 0) {
                return error("主键" + lineId + "已绑定相机，不能删除");
            }
        }
        if (baseRailwayManagementService.removeByIds(lineIds)) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    /**
     * 新增线路管理表信息
     *
     * @param baseRailwayManagement
     * @return
     */
    @PostMapping("/saveRailwayManagement")
    @ApiOperation("新增线路管理表信息")
    @Log(title = "线路台账管理", businessType = BusinessType.INSERT)
    public AjaxResult saveLineManagement(@RequestBody BaseRailwayManagement baseRailwayManagement) {
        String idempotence = idempotenceUtils.getIdempotence(baseRailwayManagement.getRailwayCode());
        if (StringUtils.isNotEmpty(idempotence)) {
            return error("你的网络卡顿,请不要一直添加!!!");
        }
        idempotenceUtils.createIdempotence(baseRailwayManagement.getRailwayCode());

        LambdaQueryWrapper<BaseRailwayManagement> lw = new LambdaQueryWrapper<BaseRailwayManagement>();
        if (!ObjectUtils.isEmpty(baseRailwayManagement.getRailwayCode())) {
            lw.eq(BaseRailwayManagement::getRailwayCode, baseRailwayManagement.getRailwayCode());
            BaseRailwayManagement railwayManagement = baseRailwayManagementService.getOne(lw);
            if (!ObjectUtils.isEmpty(railwayManagement)) {
                idempotenceUtils.deleteIdempotence(baseRailwayManagement.getRailwayCode());
                return error("线路编码已存在,不能重复添加");
            }
        }
        if (!ObjectUtils.isEmpty(baseRailwayManagement.getRailwayName())) {
            lw.eq(BaseRailwayManagement::getRailwayName, baseRailwayManagement.getRailwayName());
            BaseRailwayManagement railwayManagement = baseRailwayManagementService.getOne(lw);
            if (!ObjectUtils.isEmpty(railwayManagement)) {
                idempotenceUtils.deleteIdempotence(baseRailwayManagement.getRailwayCode());
                return error("线路名称已存在,不能重复添加");
            }
        }

        baseRailwayManagement.setCreateBy(getUserId());
        baseRailwayManagement.setUpdateBy(getUserId());
        if (baseRailwayManagementService.save(baseRailwayManagement)) {
            idempotenceUtils.deleteIdempotence(baseRailwayManagement.getRailwayCode());
            return AjaxResult.success();
        }
        idempotenceUtils.deleteIdempotence(baseRailwayManagement.getRailwayCode());
        return AjaxResult.error();
    }

    /**
     * 修改线路管理表信息
     *
     * @param baseRailwayManagement
     * @return
     */
    @PutMapping("/editRailwayManagement")
    @ApiOperation("修改线路管理表信息")
    @Log(title = "线路台账管理", businessType = BusinessType.UPDATE)
    public AjaxResult editLineManagement(@RequestBody BaseRailwayManagement baseRailwayManagement) {
        BaseRailwayManagement baseRailwayManagement1 = baseRailwayManagementService.getById(baseRailwayManagement.getId());
        if (ObjectUtils.isEmpty(baseRailwayManagement1)) {
            return error("主键不存在");
        }
        LambdaQueryWrapper<BaseRailwayManagement> lw = new LambdaQueryWrapper<BaseRailwayManagement>();
        if (!ObjectUtils.isEmpty(baseRailwayManagement.getRailwayCode())) {
            lw.eq(BaseRailwayManagement::getRailwayCode, baseRailwayManagement.getRailwayCode());
            BaseRailwayManagement railwayManagement = baseRailwayManagementService.getOne(lw);
            if (!ObjectUtils.isEmpty(railwayManagement) && !baseRailwayManagement.getId().equals(railwayManagement.getId())) {
                return error("线路编码已存在,不能进行修改操作");
            }
        }
        if (!ObjectUtils.isEmpty(baseRailwayManagement.getRailwayName())) {
            lw.eq(BaseRailwayManagement::getRailwayName, baseRailwayManagement.getRailwayName());
            BaseRailwayManagement railwayManagement = baseRailwayManagementService.getOne(lw);
            if (!ObjectUtils.isEmpty(railwayManagement) && !baseRailwayManagement.getId().equals(railwayManagement.getId())) {
                return error("线路名称已存在,不能进行修改操作");
            }
        }
        if (!baseRailwayManagement1.getRailwayCode().equals(baseRailwayManagement.getRailwayCode())) {
            LambdaQueryWrapper<BaseCameraManagement> wrapper = new LambdaQueryWrapper();
            wrapper.eq(BaseCameraManagement::getRailwayCode, baseRailwayManagement1.getRailwayCode());
            List<BaseCameraManagement> list = baseCameraManagementService.list(wrapper);
            if (list.size() > 0) {
                return error("当前线路编码已绑定相机，不能修改");
            }
        }
        baseRailwayManagement.setUpdateBy(getUserId());
        if (baseRailwayManagementService.updateById(baseRailwayManagement)) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @GetMapping(value = "/{id}")
    @ApiOperation("根据台账ID获取线路管理表详细信息")
    @Log(title = "线路台账管理", businessType = BusinessType.MESSAGE)
    public AjaxResult getInfo(@PathVariable Long id) {
        BaseRailwayManagement baseRailwayManagement = baseRailwayManagementService.getById(id);
        if (StringUtils.isEmpty(baseRailwayManagement)) {
            return AjaxResult.error("id不存在！");
        }
        List<SysDictData> data = dictTypeService.selectDictDataByType("railway_type");
        for (SysDictData datum : data) {
            if (datum.getDictValue().equals(baseRailwayManagement.getRailwayType().toString())) {
                baseRailwayManagement.setRailwayTypeName(datum.getDictLabel());
            }
        }
        return AjaxResult.success(baseRailwayManagement);
    }

    /**
     * 线路管理表信息导入
     *
     * @param file
     * @param updateSupport
     * @return
     * @throws Exception
     */
    @ApiOperation("线路管理表信息导入")
    @PostMapping("/importBaseLineManagement")
    @Log(title = "线路台账管理", businessType = BusinessType.IMPORT)
    public AjaxResult importBaseLineManagement(MultipartFile file, boolean updateSupport) throws Exception {
        String message = null;
        ExcelUtil<BaseRailwayManagement> util = new ExcelUtil<BaseRailwayManagement>(BaseRailwayManagement.class);
        List<BaseRailwayManagement> accountManageList = util.importExcel(file.getInputStream());
        log.info("importBaseLineManagement----accountManageList" + accountManageList);
        message = baseRailwayManagementService.importBaseLineManagement(accountManageList, updateSupport, getUserId());
        log.info("importBaseLineManagement----message" + message);
        return AjaxResult.success(message);
    }

    /**
     * 导出线路管理表信息
     *
     * @param response
     */
    @ApiOperation("导出线路管理表信息")
    @PostMapping("/exportBaseLineManagement")
    @Log(title = "线路台账管理", businessType = BusinessType.EXPORT)
    public void exportBaseLineManagement(HttpServletResponse response, @RequestBody BaseRailwayManagementVo baseRailwayManagementVo) {
        LambdaQueryWrapper<BaseRailwayManagement> lw = new LambdaQueryWrapper<BaseRailwayManagement>();
        if (!StringUtils.isBlank(baseRailwayManagementVo.getRailwayCode())) {
            lw.like(BaseRailwayManagement::getRailwayCode, "%" + baseRailwayManagementVo.getRailwayCode() + "%");
        }
        if (!ObjectUtils.isEmpty(baseRailwayManagementVo.getRailwayType())) {
            lw.eq(BaseRailwayManagement::getRailwayType, baseRailwayManagementVo.getRailwayType());
        }
        List<BaseRailwayManagement> list = baseRailwayManagementService.list(lw);
        ExcelUtil<BaseRailwayManagement> util = new ExcelUtil<>(BaseRailwayManagement.class);
        util.exportExcel(response, list, "线路台账数据");
    }

    @ApiOperation("线路管理表信息模板下载")
    @GetMapping("/downloaExcel")
    @Log(title = "线路台账管理", businessType = BusinessType.OTHER)
    public void downloadZip(HttpServletResponse response) {
        try {
            InputStream resourceAsStream = this.getClass().getResourceAsStream("/template/baseRailwayManagement.xlsx");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, "线路管理表信息导入模板.xlsx");
            FileUtils.writeBytesByInput(resourceAsStream, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 线路下拉
     */
    @ApiOperation(value = "线路下拉")
    @GetMapping("/query")
    @Log(title = "线路台账管理", businessType = BusinessType.SELECT)
    public AjaxResult query() {
        return AjaxResult.success(baseRailwayManagementService.list());
    }
}

