package com.testor.module.contractor.manage.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.common.core.utils.StringUtils;
import com.testor.common.excel.ExcelResult;
import com.testor.common.util.excel.EasyExcelUtil;
import com.testor.module.contractor.ledger.model.domain.TContractorPerson;
import com.testor.module.contractor.ledger.service.TContractorPersonService;
import com.testor.module.contractor.manage.model.domain.TContractorPreparationAnalysis;
import com.testor.module.contractor.manage.model.dto.TContractorPreparationAnalysisDelParam;
import com.testor.module.contractor.manage.model.dto.TContractorPreparationAnalysisParam;
import com.testor.module.contractor.manage.model.template.PreparationAnalysisTemplate;
import com.testor.module.contractor.manage.service.TContractorPreparationAnalysisService;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BaseResponseList;
import com.tongtech.tfw.backend.common.biz.models.BizGeneralResponse;
import com.tongtech.tfw.backend.common.constants.enumeration.BaseStatusEnum;
import com.tongtech.tfw.backend.common.models.supers.SuperController;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.TypeHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 开工准备-风险分析和控制措施Controller
 *
 * @author testor-framework
 * @date 2024-11-24 13:19:48
 */
@RestController
@RequestMapping("/contractorManage/preparationAnalysis")
@Api(value = "TContractorPreparationAnalysis", tags = "开工准备-风险分析和控制措施")
@Slf4j
public class TContractorPreparationAnalysisController extends SuperController {
    @Autowired
    private TContractorPreparationAnalysisService tContractorPreparationAnalysisService;
    @Autowired
    private TContractorPersonService tContractorPersonService;

    /* Generated Method*/
    @ApiOperation(value = "新增 开工准备-风险分析和控制措施", notes = "Add TContractorPreparationAnalysis")
    @PostMapping(value = "/add")
    public BaseResponse<TContractorPreparationAnalysis> addEntity(@RequestBody TContractorPreparationAnalysis addRequest) {
        BaseResponse<TContractorPreparationAnalysis> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(addRequest)) {
            // TODO 按需求添加数据去重，特殊值设定，业务异常
            String id = IdHelper.getId32bit();
            TContractorPreparationAnalysis data = BeanHelper.beanToBean(addRequest, TContractorPreparationAnalysis.class);
            data.setId(id);
            boolean result = tContractorPreparationAnalysisService.save(data);
            if (result) {
                TContractorPreparationAnalysis newEntity = new TContractorPreparationAnalysis();
                newEntity.setId(id);
                baseResponse.setData(newEntity);
            }
        }
        return baseResponse;
    }

    @ApiOperation(value = "获取 开工准备-风险分析和控制措施 ", notes = "Get TContractorPreparationAnalysis By Id")
    @GetMapping(value = "/get")
    public BaseResponse<TContractorPreparationAnalysis> getById(String id) {
        BaseResponse<TContractorPreparationAnalysis> baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(id)) {
            // TODO 按需求添加业务异常判断
            TContractorPreparationAnalysis data = tContractorPreparationAnalysisService.getById(id);
            String personId = data.getPersonId();
            if (StringHelper.isNotEmpty(personId)) {
                TContractorPerson person = tContractorPersonService.getById(personId);
                String personName = person == null ? "" : person.getName();
                data.setPersonName(personName);
            }
            baseResponse.setData(data);
        }
        return baseResponse;
    }

    @ApiOperation(value = "修改 开工准备-风险分析和控制措施 ", notes = "Update TContractorPreparationAnalysis By Id")
    @PutMapping(value = "/update")
    public BaseResponse<BizGeneralResponse> updateEntity(@RequestBody TContractorPreparationAnalysis updateRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(updateRequest) && StringHelper.isNotEmpty(updateRequest.getId())) {
            // TODO 按需求添加数据去重，特殊值设定，业务异常
            TContractorPreparationAnalysis data = BeanHelper.beanToBean(updateRequest, TContractorPreparationAnalysis.class);
            boolean result = tContractorPreparationAnalysisService.updateById(data);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

    @ApiOperation(value = "删除 开工准备-风险分析和控制措施 ", notes = "delete TContractorPreparationAnalysis By Id")
    @PutMapping(value = "/delete")
    public BaseResponse<BizGeneralResponse> deleteEntity(@RequestBody TContractorPreparationAnalysisDelParam deleteRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && StringHelper.isNotEmpty(deleteRequest.getId())) {
            // TODO 按需求添加数据去重，特殊值设定，业务异常
            TContractorPreparationAnalysis data = new TContractorPreparationAnalysis();
            data.setId(deleteRequest.getId());
            data.setStatus(BizConstants.STATUS_DELETE);
            boolean result = tContractorPreparationAnalysisService.updateById(data);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

    @ApiOperation(value = "批量删除开工准备-风险分析和控制措施", notes = "delete TContractorPreparationAnalysis by batch Id")
    @PutMapping(value = "/batch_delete")
    public BaseResponse<BizGeneralResponse> deleteEntityBatch(
            @RequestBody TContractorPreparationAnalysisDelParam deleteRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && (!deleteRequest.getIds().isEmpty())) {
            /* 批量删除 */
            List<TContractorPreparationAnalysis> tContractorPreparationAnalysisList = new ArrayList<>();
            for (String id : deleteRequest.getIds()) {
                TContractorPreparationAnalysis data = new TContractorPreparationAnalysis();
                data.setId(id);
                data.setStatus(BizConstants.STATUS_DELETE);
                tContractorPreparationAnalysisList.add(data);
            }
            boolean result = tContractorPreparationAnalysisService.updateBatchById(tContractorPreparationAnalysisList);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

    @ApiOperation(value = "获取 开工准备-风险分析和控制措施 分页列表", notes = "List TContractorPreparationAnalysis with page")
    @GetMapping(value = "/list")
    public BaseResponse<BaseResponseList<TContractorPreparationAnalysis>> listEntity(TContractorPreparationAnalysisParam param) {
        BaseResponse<BaseResponseList<TContractorPreparationAnalysis>> baseResponse = new BaseResponse<>();
        Page<TContractorPreparationAnalysis> resultList = tContractorPreparationAnalysisService.listEntity(param);
        BaseResponseList<TContractorPreparationAnalysis> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(resultList.getRecords());
        baseResponseList.setTotal(resultList.getTotal());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    @ApiOperation(value = "获取 开工准备-风险分析和控制措施 列表", notes = "List TContractorPreparationAnalysis all")
    @GetMapping(value = "/datas")
    public BaseResponse<BaseResponseList<TContractorPreparationAnalysis>> listAllEntity(TContractorPreparationAnalysisParam param) {
        BaseResponse<BaseResponseList<TContractorPreparationAnalysis>> baseResponse = new BaseResponse<>();
        List<TContractorPreparationAnalysis> resultList = tContractorPreparationAnalysisService.listAllEntity(param);
        BaseResponseList<TContractorPreparationAnalysis> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(resultList);
        baseResponseList.setTotal(resultList.size());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    @ApiOperation(value = "下载 开工准备-风险分析和控制措施 导入模板", notes = "Download TContractorPreparationAnalysis import template")
    @GetMapping(value = "/importTemplate")
    public void importTemplate(HttpServletResponse response, String fileDowName) throws Exception {
        List<PreparationAnalysisTemplate> templates = new ArrayList<>();
        templates.add(new PreparationAnalysisTemplate());
        EasyExcelUtil.writeExcelBySelect(response, "开工准备-风险分析和控制措施导入模板", "风险分析和控制措施", templates);
    }

    @ApiOperation(value = "导入 开工准备-风险分析和控制措施 ", notes = "Import TContractorPreparationAnalysis")
    @PostMapping(value = "/importPreparationAnalysis")
    public BaseResponse<String> importPreparationAnalysis(@RequestParam("file") MultipartFile file, @RequestParam("preparationId") String preparationId) throws Exception {
        BaseResponse<String> baseResponse = new BaseResponse<>();
        if (file == null || StringUtils.isBlank(preparationId)) {
            baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
            baseResponse.setMsg(BaseStatusEnum.UN_DATA.msg());
            return baseResponse;
        }
        // 导入Excel文件，将文件流转换为 PreparationAnalysisTemplate 对象列表
        ExcelResult<PreparationAnalysisTemplate> preparationAnalysisTemplateExcelResult = EasyExcelUtil.importExcel(file.getInputStream(), PreparationAnalysisTemplate.class, true);
        // 获取 PreparationAnalysisTemplate 对象列表
        List<PreparationAnalysisTemplate> list = preparationAnalysisTemplateExcelResult.getList();
        // 将 PreparationAnalysisTemplate 对象列表转换为 TContractorPreparationAnalysis 对象列表，并批量保存
        List<TContractorPreparationAnalysis> analysisList = BeanHelper.listToList(list, TContractorPreparationAnalysis.class);
        analysisList = analysisList.stream().map(analysis -> {
            analysis.setPreparationId(preparationId);
            return analysis;
        }).collect(Collectors.toList());
        tContractorPreparationAnalysisService.saveBatch(analysisList);

        return baseResponse;
    }

}
