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

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.testor.common.core.utils.StringUtils;
import com.testor.module.contractor.ledger.model.domain.TContractorEmergencyMaterial;
import com.testor.module.contractor.ledger.service.TContractorEmergencyMaterialService;
import com.testor.module.contractor.manage.model.dto.ContractorPreparationEmergencyDto;
import com.testor.module.contractor.manage.model.dto.TContractorPreparationEmergencyAddParam;
import com.tongtech.tfw.backend.common.constants.enumeration.BaseStatusEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.extern.slf4j.Slf4j;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.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.models.exceptions.ApiException;
import com.tongtech.tfw.backend.common.models.supers.SuperController;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import com.tongtech.tfw.backend.core.helper.TypeHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;

import com.testor.module.contractor.manage.model.domain.TContractorPreparationEmergency;
import com.testor.module.contractor.manage.model.dto.TContractorPreparationEmergencyParam;
import com.testor.module.contractor.manage.model.dto.TContractorPreparationEmergencyDelParam;
import com.testor.module.contractor.manage.service.TContractorPreparationEmergencyService;

/**
 * 开工准备-应急物资关系Controller
 *
 * @author testor-framework
 * @date 2024-11-24 13:20:08
 */
@RestController
@RequestMapping("/contractorManage/preparationEmergency")
@Api(value = "TContractorPreparationEmergency", tags = "开工准备-应急物资关系")
@Slf4j
public class TContractorPreparationEmergencyController extends SuperController {
    @Autowired
    private TContractorPreparationEmergencyService tContractorPreparationEmergencyService;

    @Autowired
    private TContractorEmergencyMaterialService tContractorEmergencyMaterialService;

    /* Generated Method*/
    @ApiOperation(value = "新增 开工准备-应急物资关系", notes = "Add TContractorPreparationEmergency")
    @PostMapping(value = "/add")
    public BaseResponse<TContractorPreparationEmergency> addEntity(@RequestBody TContractorPreparationEmergency addRequest) {
        BaseResponse<TContractorPreparationEmergency> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(addRequest)) {
            // TODO 按需求添加数据去重，特殊值设定，业务异常
            String id = IdHelper.getId32bit();
            TContractorPreparationEmergency data = BeanHelper.beanToBean(addRequest, TContractorPreparationEmergency.class);
            data.setId(id);
            boolean result = tContractorPreparationEmergencyService.save(data);
            if (result) {
                TContractorPreparationEmergency newEntity = new TContractorPreparationEmergency();
                newEntity.setId(id);
                baseResponse.setData(newEntity);
            }
        }
        return baseResponse;
    }

    @ApiOperation(value = "批量新增 开工准备-应急物资关系", notes = "Batch Add TContractorPreparationEmergency")
    @PostMapping(value = "/batch_add")
    public BaseResponse<TContractorPreparationEmergency> batchAddEntity(@RequestBody TContractorPreparationEmergencyAddParam addRequest) {
        BaseResponse<TContractorPreparationEmergency> baseResponse = new BaseResponse<>();
        if (addRequest == null || StringUtils.isEmpty(addRequest.getEmergencyIds()) || StringUtils.isBlank(addRequest.getPreparationId())) {
            baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
            baseResponse.setMsg(BaseStatusEnum.UN_DATA.msg());
            return baseResponse;
        }
        tContractorPreparationEmergencyService.batchAddEntity(addRequest);
        return baseResponse;
    }

    @ApiOperation(value = "获取 开工准备-应急物资关系 ", notes = "Get TContractorPreparationEmergency By Id")
    @GetMapping(value = "/get")
    public BaseResponse<TContractorPreparationEmergency> getById(String id) {
        BaseResponse<TContractorPreparationEmergency> baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(id)) {
            // TODO 按需求添加业务异常判断
            TContractorPreparationEmergency data = tContractorPreparationEmergencyService.getById(id);
            baseResponse.setData(data);
        }
        return baseResponse;
    }

    @ApiOperation(value = "修改 开工准备-应急物资关系 ", notes = "Update TContractorPreparationEmergency By Id")
    @PutMapping(value = "/update")
    public BaseResponse<BizGeneralResponse> updateEntity(@RequestBody TContractorPreparationEmergency updateRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(updateRequest) && StringHelper.isNotEmpty(updateRequest.getId())) {
            // TODO 按需求添加数据去重，特殊值设定，业务异常
            TContractorPreparationEmergency data = BeanHelper.beanToBean(updateRequest, TContractorPreparationEmergency.class);
            boolean result = tContractorPreparationEmergencyService.updateById(data);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

    @ApiOperation(value = "删除 开工准备-应急物资关系 ", notes = "delete TContractorPreparationEmergency By Id")
    @PutMapping(value = "/delete")
    public BaseResponse<BizGeneralResponse> deleteEntity(@RequestBody TContractorPreparationEmergencyDelParam deleteRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && StringHelper.isNotEmpty(deleteRequest.getId())) {
            boolean result = tContractorPreparationEmergencyService.removeById(deleteRequest.getId());
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

    @ApiOperation(value = "批量删除开工准备-应急物资关系", notes = "delete TContractorPreparationEmergency by batch Id")
    @PutMapping(value = "/batch_delete")
    public BaseResponse<BizGeneralResponse> deleteEntityBatch(
            @RequestBody TContractorPreparationEmergencyDelParam deleteRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && (!deleteRequest.getIds().isEmpty())) {
            boolean result = tContractorPreparationEmergencyService.removeByIds(deleteRequest.getIds());
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

    @ApiOperation(value = "获取 开工准备-应急物资关系 分页列表", notes = "List TContractorPreparationEmergency with page")
    @GetMapping(value = "/list")
    public BaseResponse<BaseResponseList<ContractorPreparationEmergencyDto>> listEntity(TContractorPreparationEmergencyParam param) {
        BaseResponse<BaseResponseList<ContractorPreparationEmergencyDto>> baseResponse = new BaseResponse<>();
        Long page =
                StringHelper.isEmpty(param.getPage()) ? BizConstants.PAGE : Long.valueOf(param.getPage());
        Long limit =
                StringHelper.isEmpty(param.getLimit()) ? BizConstants.LIMIT : Long.valueOf(param.getLimit());
        Page<TContractorPreparationEmergency> resultPage = new Page<>(page, limit);
        // TODO 根据需求修改查询条件及查询参数
        QueryWrapper<TContractorPreparationEmergency> queryWrapper = this.createQuery(param);
        Page<TContractorPreparationEmergency> resultList = tContractorPreparationEmergencyService.page(resultPage, queryWrapper);
        BaseResponseList<ContractorPreparationEmergencyDto> baseResponseList = new BaseResponseList<>();
        List<TContractorPreparationEmergency> dataList = resultList.getRecords();
        List<ContractorPreparationEmergencyDto> dtoList = dataList.parallelStream().map(entity -> {
            String emergencyId = entity.getEmergencyId();
            TContractorEmergencyMaterial contractorPreparationEmergency = tContractorEmergencyMaterialService.getById(emergencyId);
            ContractorPreparationEmergencyDto dto = BeanHelper.beanToBean(entity, ContractorPreparationEmergencyDto.class);
            dto.setContractorEmergencyMaterial(contractorPreparationEmergency);
            return dto;
        }).collect(Collectors.toList());
        baseResponseList.setData(dtoList);
        baseResponseList.setTotal(resultList.getTotal());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    @ApiOperation(value = "获取 开工准备-应急物资关系 列表", notes = "List TContractorPreparationEmergency all")
    @GetMapping(value = "/datas")
    public BaseResponse<BaseResponseList<TContractorPreparationEmergency>> listAllEntity(TContractorPreparationEmergencyParam param) {
        BaseResponse<BaseResponseList<TContractorPreparationEmergency>> baseResponse = new BaseResponse<>();
        // TODO 根据需求修改查询条件及查询参数
        QueryWrapper<TContractorPreparationEmergency> queryWrapper = this.createQuery(param);
        List<TContractorPreparationEmergency> resultList = tContractorPreparationEmergencyService.list(queryWrapper);
        BaseResponseList<TContractorPreparationEmergency> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(resultList);
        baseResponseList.setTotal(resultList.size());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    /* Private Methods */

    /**
     * 列表查询条件及查询参数
     */
    private QueryWrapper<TContractorPreparationEmergency> createQuery(TContractorPreparationEmergencyParam queryParam) {
        QueryWrapper<TContractorPreparationEmergency> queryWrapper = new QueryWrapper<>();
        if (StringHelper.isNotEmpty(queryParam.getPreparationId())) {
            queryWrapper.eq(TContractorPreparationEmergency.PREPARATION_ID, queryParam.getPreparationId());
        }
        if (StringHelper.isNotEmpty(queryParam.getEmergencyId())) {
            queryWrapper.eq(TContractorPreparationEmergency.EMERGENCY_ID, queryParam.getEmergencyId());
        }
        if (StringHelper.isNotEmpty(queryParam.getBizId())) {
            queryWrapper.eq(TContractorPreparationEmergency.BIZ_ID, queryParam.getBizId());
        }
        if (StringHelper.isNotEmpty(queryParam.getContractorId())) {
            queryWrapper.eq(TContractorPreparationEmergency.CONTRACTOR_ID, queryParam.getContractorId());
        }
        if (StringHelper.isNotEmpty(queryParam.getProjId())) {
            queryWrapper.eq(TContractorPreparationEmergency.PROJ_ID, queryParam.getProjId());
        }
        if (StringHelper.isNotEmpty(queryParam.getStatus())) {
            queryWrapper.eq(TContractorPreparationEmergency.STATUS, queryParam.getStatus());
        } else {
            queryWrapper.ne(TContractorPreparationEmergency.STATUS, BizConstants.STATUS_DELETE);
        }
        if (StringHelper.isNotEmpty(queryParam.getOrderBy())) {
            if (StringHelper.isNotEmpty(queryParam.getOrderType())
                    && BizConstants.ASC.equals(queryParam.getOrderType())) {
                queryWrapper.orderByAsc(queryParam.getOrderBy());
            } else {
                queryWrapper.orderByDesc(queryParam.getOrderBy());
            }
        } else {
            queryWrapper.orderByDesc(TContractorPreparationEmergency.UPDATE_DATE);
        }
        return queryWrapper;
    }
}
