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.AppendUtils;
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 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.math.BigDecimal;
import java.math.RoundingMode;
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 {
    public static final String PATTERN = "^(\\d+.\\d{1,3}|\\d+)$";
    @Resource
    BaseRailwayManagementService baseRailwayManagementService;
    @Autowired
    private ISysDictTypeService dictTypeService;
    @Autowired
    private BaseCameraManagementService baseCameraManagementService;
    @Autowired
    private IdempotenceUtils idempotenceUtils;

    /**
     * 线路管理表分页
     *
     * @param baseRailwayManagementVo
     * @return
     */
    @PostMapping("/list")
    @Log(title = "线路台账管理", businessType = BusinessType.SELECT)
    public AjaxResult selectBaseLineManagement(@RequestBody BaseRailwayManagementVo baseRailwayManagementVo) {
        LambdaQueryWrapper<BaseRailwayManagement> lw = new LambdaQueryWrapper<>();
        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<>(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());
                    }
                }
                if (!ObjectUtils.isEmpty(o.getEndMileage())) {
                    BigDecimal divide = new BigDecimal(o.getEndMileage()).divide(new BigDecimal("1000"), 3, BigDecimal.ROUND_DOWN);
                    String string = divide.toString();
                    if (string.charAt(string.length()-1)!='0'){
                        o.setEndMileageBD(divide);
                    }else {
                        if (string.charAt(string.length()-2)!='0'){
                            String substring = string.substring(0, string.length() - 1);
                            o.setEndMileageBD(new BigDecimal(substring));
                        }else {
                            if (string.charAt(string.length()-3)!='0') {
                                String substring = string.substring(0, string.length() - 2);
                                o.setEndMileageBD(new BigDecimal(substring));
                            }else {
                                BigDecimal begin = divide.setScale(0, RoundingMode.HALF_UP);
                                o.setEndMileageBD(begin);
                            }
                        }
                    }
                }
                if (!ObjectUtils.isEmpty(o.getInitialMileage())) {
                    BigDecimal divide = new BigDecimal(o.getInitialMileage()).divide(new BigDecimal("1000"), 3, BigDecimal.ROUND_DOWN);
                    String string = divide.toString();
                    if (string.charAt(string.length()-1)!='0'){
                        o.setInitialMileageBD(divide);
                    }else {
                        if (string.charAt(string.length()-2)!='0'){
                            String substring = string.substring(0, string.length() - 1);
                            o.setInitialMileageBD(new BigDecimal(substring));
                        }else {
                            if (string.charAt(string.length()-3)!='0') {
                                String substring = string.substring(0, string.length() - 2);
                                o.setInitialMileageBD(new BigDecimal(substring));
                            }else {
                                BigDecimal begin = divide.setScale(0, RoundingMode.HALF_UP);
                                o.setInitialMileageBD(begin);
                            }
                        }
                    }
                }
                String end = "";
                if (!StringUtils.isEmptySunhh(o.getInitialMileage())) {
                    end = AppendUtils.stringAppend(o.getInitialMileage());
                }
                String begin = "";
                if (!StringUtils.isEmptySunhh(o.getEndMileage())) {
                    begin = AppendUtils.stringAppend(o.getEndMileage());
                }
                o.setMilesRange(end + "~" + begin);
                return o;
            }).collect(Collectors.toList());
            page.setRecords(dto1);
        }
        return AjaxResult.success(page);
    }

    /**
     * 删除线路管理表信息
     *
     * @param lineIds
     * @return
     */
    @RequestMapping("/remove/{lineIds}")
    @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")
    @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());

        if (!baseRailwayManagement.getInitialMileageBD().toString().matches(PATTERN) || !baseRailwayManagement.getEndMileageBD().toString().matches(PATTERN)) {
            idempotenceUtils.deleteIdempotence(baseRailwayManagement.getRailwayCode());
            return error("里程位置填写格式不正确,请填写数字或小数");
        }else {
            baseRailwayManagement.setInitialMileage(baseRailwayManagement.getInitialMileageBD().multiply(new BigDecimal("1000")).intValue());
            baseRailwayManagement.setEndMileage(baseRailwayManagement.getEndMileageBD().multiply(new BigDecimal("1000")).intValue());
        }

        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
     */
    @RequestMapping("/editRailwayManagement")
    @Log(title = "线路台账管理", businessType = BusinessType.UPDATE)
    public AjaxResult editLineManagement(@RequestBody BaseRailwayManagement baseRailwayManagement) {
        BaseRailwayManagement baseRailwayManagement1 = baseRailwayManagementService.getById(baseRailwayManagement.getId());
        if (ObjectUtils.isEmpty(baseRailwayManagement1)) {
            return error("主键不存在");
        }

        if (!baseRailwayManagement.getInitialMileageBD().toString().matches(PATTERN) || !baseRailwayManagement.getEndMileageBD().toString().matches(PATTERN)) {
            return error("里程位置填写格式不正确,请填写数字或小数");
        }else {
            baseRailwayManagement.setInitialMileage(baseRailwayManagement.getInitialMileageBD().multiply(new BigDecimal("1000")).intValue());
            baseRailwayManagement.setEndMileage(baseRailwayManagement.getEndMileageBD().multiply(new BigDecimal("1000")).intValue());
        }
        
        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}")
    @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());
            }
        }
        String end = "";
        if (!StringUtils.isEmptySunhh(baseRailwayManagement.getInitialMileage())) {
            end = AppendUtils.stringAppend(baseRailwayManagement.getInitialMileage());
        }
        String begin = "";
        if (!StringUtils.isEmptySunhh(baseRailwayManagement.getEndMileage())) {
            begin = AppendUtils.stringAppend(baseRailwayManagement.getEndMileage());
        }
        baseRailwayManagement.setMilesRange(begin + "-" + end);
        return AjaxResult.success(baseRailwayManagement);
    }

    /**
     * 线路管理表信息导入
     *
     * @param file
     * @param updateSupport
     * @return
     * @throws Exception
     */
    @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
     */
    @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());
        }
        if (baseRailwayManagementVo.getIds().size() > 0) {
            lw.in(BaseRailwayManagement::getId, baseRailwayManagementVo.getIds());
        }
        List<BaseRailwayManagement> list = baseRailwayManagementService.list(lw);
        ExcelUtil<BaseRailwayManagement> util = new ExcelUtil<>(BaseRailwayManagement.class);
        util.exportExcel(response, list, "线路台账数据");
    }

    @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);
        }
    }

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

