package com.sckw.slope.detection.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sckw.core.exception.SystemException;
import com.sckw.core.model.constant.Global;
import com.sckw.core.model.constant.NumberConstant;
import com.sckw.core.model.enums.CompanyTypeEnum;
import com.sckw.core.model.enums.CompanyStatusEnum;
import com.sckw.core.model.enums.MessageLogEnum;
import com.sckw.core.model.page.PageRes;

import com.sckw.core.utils.IdWorker;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.response.HttpResult;
import com.sckw.slope.detection.dao.mysql.KwsCompanyMapper;
import com.sckw.slope.detection.model.dos.mysql.*;
import com.sckw.slope.detection.model.dto.HeaderData;
import com.sckw.slope.detection.model.param.CompanyAdd;
import com.sckw.slope.detection.model.param.CompanyQuery;
import com.sckw.slope.detection.model.param.DeviceAdd;
import com.sckw.slope.detection.model.vo.DeviceVo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author sky
 * @description 矿山公司service
 * @date 2023-11-09 14:11:21
 */
@Slf4j
@Service
public class CompanyService {

    @Autowired
    KwsCompanyMapper companyMapper;

    @Autowired
    CommonService commonService;



    public PageRes select(CompanyQuery query, HttpServletRequest request) {
        HeaderData headerData = commonService.getHeaderData(request);
        PageHelper.startPage(query.getPage(), query.getPageSize());
        List<KwsCompany> company = companyMapper.selectList(new LambdaQueryWrapper<KwsCompany>()
                .eq(StringUtils.isNotBlank(headerData.getCompanyId()), KwsCompany::getCompanyId, headerData.getCompanyId())
                .eq(KwsCompany::getDelFlag, NumberConstant.ZERO)
                .like(StringUtils.isNotBlank(query.getName()), KwsCompany::getName, query.getName())
                        .orderByDesc(KwsCompany::getCreateTime)
        );

        PageInfo<KwsCompany> info = new PageInfo<>(company);
        if (CollectionUtils.isEmpty(company)) {
            return PageRes.build(info, company);
        }
        for(KwsCompany co : company){
            co.setType(CompanyTypeEnum.getName(co.getType()));
            co.setStatus(CompanyStatusEnum.getName(co.getStatus()));
            co.setCreateByName(co.getCreateBy());
        }

        return PageRes.build(info, company);
    }

    /**
     * 新增矿山
     *
     * @param add 请求参数
     * @param request   http流
     * @return 返回值
     */
    @Transactional
    public HttpResult add(CompanyAdd add, HttpServletRequest request) {
        HeaderData headerData = commonService.getHeaderData(request);
        KwsCompany companyHas = companyMapper.selectOne(new LambdaQueryWrapper<KwsCompany>()
                .eq(KwsCompany::getName, add.getName())
                .eq(KwsCompany::getDelFlag, NumberConstant.ZERO)
                .eq(KwsCompany::getCompanyId, headerData.getCompanyId())
        );
        if (!Objects.isNull(companyHas)) {
            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.COMPANY_SN_EXISTS);
        }

        KwsCompany company = new KwsCompany();
        BeanUtils.copyProperties(add, company);
        LocalDateTime now = LocalDateTime.now();
        long id = new IdWorker(NumberConstant.ONE).nextId();
        company.setId(id);
        company.setCreateBy(Long.parseLong(headerData.getCreateBy()));
        company.setCreateTime(now);
        company.setCompanyId(headerData.getCompanyId());
        company.setUpdateBy(Long.parseLong(headerData.getUpdateBy()));
        company.setUpdateTime(now);
        int code = 0;
        while(true){
            code = 1000 + new Random().nextInt(9000);
            KwsCompany codeHas = companyMapper.selectOne(new LambdaQueryWrapper<KwsCompany>()
                    .eq(KwsCompany::getCompanyCode, code)
            );
            if(Objects.isNull(codeHas)){
                break;
            }
        }
        company.setCompanyCode(String.valueOf(code));
        company.setCompanyAllCode(company.getCode()+company.getType().toString()+String.valueOf(code));
        companyMapper.insert(company);

        Map<String, Object> logMap = new HashMap<>(NumberConstant.SIXTEEN);
        logMap.put("name", add.getName());
        logMap.put("type", CompanyTypeEnum.getName(add.getType()));
        commonService.insertLog(MessageLogEnum.COMPANY_ADD, headerData, logMap, Long.parseLong(headerData.getUpdateBy()));
        return HttpResult.ok();
    }

    /**
     * 修改矿山
     *
     * @param add 请求参数
     * @param request   http流
     * @return 返回值
     */
    @Transactional
    public HttpResult update(CompanyAdd add, HttpServletRequest request) {
        HeaderData headerData = commonService.getHeaderData(request);
        KwsCompany companyHas = companyMapper.selectOne(new LambdaQueryWrapper<KwsCompany>()
                .eq(KwsCompany::getId, add.getId()));
        if (Objects.isNull(companyHas)) {
            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.COMPANY_NOT_EXISTS);
        }
        KwsCompany companyHas1 = companyMapper.selectOne(new LambdaQueryWrapper<KwsCompany>()
                .ne(KwsCompany::getId, add.getId())
                .eq(KwsCompany::getName, add.getName())
                .eq(KwsCompany::getDelFlag, NumberConstant.ZERO)
                .eq(KwsCompany::getCompanyId, headerData.getCompanyId())
        );
        if (!Objects.isNull(companyHas1)) {
            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.COMPANY_SN_EXISTS);
        }

        KwsCompany company = new KwsCompany();
        BeanUtils.copyProperties(add, company);
        company.setId(add.getId());
        LocalDateTime now = LocalDateTime.now();

        company.setUpdateBy(Long.parseLong(headerData.getUpdateBy()));
        company.setUpdateTime(now);
        Integer updateStatus = companyMapper.updateById(company);
        Map<String, Object> logMap = new HashMap<>(NumberConstant.SIXTEEN);
        logMap.put("name", add.getName());
        logMap.put("type", CompanyTypeEnum.getName(add.getType()));
        commonService.insertLog(MessageLogEnum.COMPANY_UPDATE, headerData, logMap, Long.parseLong(headerData.getUpdateBy()));
        return HttpResult.ok();
    }

    /**
     * 矿山详情
     *
     * @param id 请求参数
     * @param response   http流
     * @return 返回值
     */

    public HttpResult detail(Long id, HttpServletRequest response) {
        KwsCompany companyHas = companyMapper.selectOne(new LambdaQueryWrapper<KwsCompany>()
                .eq(KwsCompany::getId, id));
        CompanyAdd vo = new CompanyAdd();
        BeanUtils.copyProperties(companyHas, vo);
        vo.setTypeText(CompanyTypeEnum.getName(vo.getType()));
        vo.setStatusText(CompanyStatusEnum.getName(vo.getStatus()));
        return HttpResult.ok(vo);
    }
}
