/*
 * Copyright (c) 京北方信息技术股份有限公司 Corporation 2021 . All rights reserved.
 *
 */
package net.northking.cctp.testbug.api.service;

import com.alibaba.fastjson.JSONObject;
import net.northking.cctp.common.db.BasicService;
import net.northking.cctp.common.db.Pagination;
import net.northking.cctp.common.db.annotation.DatabaseReadOnly;
import net.northking.cctp.common.db.annotation.DatabaseWriteOnly;
import net.northking.cctp.common.db.excel.AbstractExcelService;
import net.northking.cctp.common.db.excel.ExcelHeader;
import net.northking.cctp.common.exception.PlatformRuntimeException;
import net.northking.cctp.common.http.QueryByPage;
import net.northking.cctp.common.security.authentication.NKSecurityContext;
import net.northking.cctp.common.util.UUIDUtil;

import net.northking.cctp.testbug.constants.TestBugError;
import net.northking.cctp.testbug.db.service.BugSearchService;
import net.northking.cctp.testbug.db.entity.BugSearch;

import net.northking.cctp.testbug.dto.BugSearchAddDto;
import net.northking.cctp.testbug.dto.BugSearchDetailDto;
import net.northking.cctp.testbug.dto.BugSearchQueryDto;
import net.northking.cctp.testbug.dto.BugSearchUpdateDto;
import net.northking.cctp.testbug.dto.bug.SearchDetailDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 缺陷条件搜索表服务实现类
 *
 * @author maven-cctp-plugin
 * @since 1.0
 */

@Service
@ConditionalOnMissingBean(name = "BugSearchApiServiceImpl")
public class BugSearchApiServiceImpl extends AbstractExcelService<BugSearch> implements BugSearchApiService {
    /**
     * 日志
     */
    private final static Logger logger = LoggerFactory.getLogger(BugSearchApiServiceImpl.class);

    @Autowired
    private BugSearchService bugSearchService;

    @Autowired
    private BugSearchApiService bugSearchApiService;

    //= Excel 导入导出相关代码 start ==================//
    @Override
    public BasicService<BugSearch> getService() {
        return this.bugSearchService;
    }

    @Override
    public ExcelHeader[] excelHeaders() {
        ExcelHeader id = new ExcelHeader("", "id", String.class);
        ExcelHeader bugTitle = new ExcelHeader("缺陷标题", "bugTitle", String.class);
        ExcelHeader bugGrade = new ExcelHeader("缺陷等级", "bugGrade", String.class);
        ExcelHeader bugType = new ExcelHeader("缺陷类型", "bugType", String.class);
        ExcelHeader emergency = new ExcelHeader("严重程度", "emergency", String.class);
        ExcelHeader isReapper = new ExcelHeader("可重现：Y是,N否", "isReapper", String.class);
        ExcelHeader status = new ExcelHeader("缺陷状态", "status", String.class);
        ExcelHeader receiver = new ExcelHeader("分配人", "receiver", String.class);
        ExcelHeader createdUser = new ExcelHeader("缺陷创建人", "createdUser", String.class);
        ExcelHeader createdDate = new ExcelHeader("缺陷创建时间", "createdDate", String.class);
        ExcelHeader repairTime = new ExcelHeader("缺陷修复时间", "repairTime", String.class);
        ExcelHeader repairUser = new ExcelHeader("缺陷修复人", "repairUser", String.class);
        ExcelHeader closeTime = new ExcelHeader("缺陷关闭时间", "closeTime", String.class);
        ExcelHeader errorMessage = new ExcelHeader("错误信息描述", "errorMessage", String.class);
        ExcelHeader message = new ExcelHeader("注释", "message", String.class);
        ExcelHeader expands = new ExcelHeader("自定义字段", "expands", String.class);
        ExcelHeader roundId = new ExcelHeader("轮次", "roundId", String.class);
        ExcelHeader moduleId = new ExcelHeader("模块", "moduleId", String.class);
        ExcelHeader systemId = new ExcelHeader("系统", "systemId", String.class);
        ExcelHeader proId = new ExcelHeader("系统", "proId", String.class);
        ExcelHeader other = new ExcelHeader("其他搜索条件", "other", String.class);
        ExcelHeader createdBy = new ExcelHeader("创建人", "createdBy", String.class);
        ExcelHeader createdTime = new ExcelHeader("创建时间", "createdTime", Date.class);
        ExcelHeader updatedBy = new ExcelHeader("修改人", "updatedBy", String.class);
        ExcelHeader updatedTime = new ExcelHeader("修改时间", "updatedTime", Date.class);
        ExcelHeader tenantId = new ExcelHeader("租户id", "tenantId", String.class);
        // TODO 定义表头及顺序
        return new ExcelHeader[]{};
    }

    /**
     * Excel导入，入库之前的处理
     *
     * @param records 从Excel读取到的记录
     * @return 待入库的记录
     */
    @Override
    protected List<BugSearch> beforeInsertBatch(List<BugSearch> records) {
        for (BugSearch record : records) {
            record.setId(UUIDUtil.create32UUID());
        }
        return records;
    }

    /**
     * 写入Excel之前的处理<br>
     * 数据的特殊处理在此处加工处理
     *
     * @param record 来自数据库记录
     * @return 待写入Excel的记录
     */
    @Override
    protected BugSearch beforeWriteExcel(BugSearch record) {
        return record;
    }

    //= Excel 导入导出相关代码 end =======================//

    //= 增删改查 相关代码 start ==================//

    /**
     * 查询缺陷条件搜索表列表
     *
     * @param queryByPage 查询条件
     * @return 查询结果列表
     */
    @Override
    public Pagination<BugSearchDetailDto> pagingQuery(QueryByPage<BugSearchQueryDto> queryByPage) {
        return null;
    }

    @Override
    @DatabaseWriteOnly
    @Transactional(rollbackFor = Exception.class)
    public String add(BugSearchAddDto dto) {
        String uuid = UUIDUtil.create32UUID();
        try {
            BugSearch entity = new BugSearch();
            dto.setTenantId(NKSecurityContext.getTenantId());
            dto.setSchemaSuffix(null);
            dto.setTableSuffix(null);
            dto.setId(uuid);
            entity.setId(uuid);
            entity.setSchemeName(dto.getSchemeName());
            entity.setProId(dto.getProId());
            entity.setTenantId(NKSecurityContext.getTenantId());
            entity.setCreatedBy(NKSecurityContext.getUserId());
            //对象转化成json字符串
            entity.setExpands(JSONObject.toJSONString(dto));
            this.bugSearchService.insert(entity);
        } catch (Exception e) {
            logger.error("add", e);
            throw new PlatformRuntimeException(TestBugError.ADD_BUG_SEARCH_FAILED);
        }
        return uuid;
    }

    @Override
    @DatabaseWriteOnly
    @Transactional(rollbackFor = Exception.class)
    public String addDto(SearchDetailDto dto) {
        String uuid = UUIDUtil.create32UUID();
        try {
            BugSearch entity = new BugSearch();
            dto.setTenantId(NKSecurityContext.getTenantId());
            dto.setId(uuid);
            entity.setId(uuid);
            entity.setSchemeName(dto.getSchemeName());
            entity.setProId(dto.getProId());
            entity.setTenantId(NKSecurityContext.getTenantId());
            entity.setCreatedBy(NKSecurityContext.getUserId());
            //对象转化成json字符串
            entity.setExpands(JSONObject.toJSONString(dto));
            this.bugSearchService.insert(entity);
        } catch (Exception e) {
            logger.error("add", e);
            throw new PlatformRuntimeException(TestBugError.ADD_BUG_SEARCH_FAILED);
        }
        return uuid;
    }

    @Override
    @DatabaseWriteOnly
    @Transactional(rollbackFor = Exception.class)
    public Integer updateByPK(BugSearchUpdateDto dto) throws IllegalAccessException {
        int count = 0;
        try {
            BugSearch entity = new BugSearch();
            BeanUtils.copyProperties(dto, entity);
            count = this.bugSearchService.updateByPrimaryKey(entity);
        } catch (Exception e) {
            logger.error("updateByPK");
            throw new PlatformRuntimeException(TestBugError.UPDATE_BUG_SEARCH_FAILED);
        }
        return count;
    }

    @Override
    @DatabaseWriteOnly
    @Transactional(rollbackFor = Exception.class)
    public Integer updateSearch(SearchDetailDto dto) {

        int count = 0;
        try {
            BugSearch entity = new BugSearch();
            BeanUtils.copyProperties(dto, entity);
            count = this.bugSearchService.updateByPrimaryKey(entity);
        } catch (Exception e) {
            logger.error("updateSearch");
            throw new PlatformRuntimeException(TestBugError.UPDATE_BUG_SEARCH_FAILED);
        }
        return count;
    }

    @Override
    @DatabaseReadOnly
    public BugSearchDetailDto findByPK(String uuid) {
        BugSearch example = new BugSearch();
        example.setId(uuid);
        List<BugSearch> entitys = this.bugSearchService.query(example);
        if (entitys.isEmpty()) {
            return null;
        }

        BugSearchDetailDto dto = new BugSearchDetailDto();
        BeanUtils.copyProperties(entitys.get(0), dto);
        return dto;
    }

    @Override
    @DatabaseWriteOnly
    @Transactional(rollbackFor = Exception.class)
    public Integer deleteByPK(String uuid) {
        BugSearch entity = new BugSearch();
        entity.setId(uuid);
        return this.bugSearchService.deleteByExample(entity);
    }

    @Override
    public List<String> addBatch(List<BugSearchAddDto> batch) {
        List<String> result = new ArrayList<>();
        for (BugSearchAddDto dto : batch) {
            result.add(bugSearchApiService.add(dto));
        }
        return result;
    }

    @Override
    public Integer updateBatch(List<BugSearchUpdateDto> batch) throws IllegalAccessException {
        int sum = 0;
        for (BugSearchUpdateDto dto : batch) {
            sum = sum + bugSearchApiService.updateByPK(dto);
        }
        return sum;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer deleteBatch(List<Object> batch) {
        int count = 0;
        try {
            count = this.bugSearchService.deleteByPrimaryKeys(batch);
        } catch (Exception e) {
            logger.error("delete", e);
            throw new PlatformRuntimeException(TestBugError.DELETE_BUG_SEARCH_FAILED);
        }
        return count;
    }

    @Override
    public List<BugSearchDetailDto> pagingQuery2(BugSearchQueryDto queryByPage) {
        return bugSearchService.pagingQueryNew(queryByPage);
    }

}
