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

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.TContractorTools;
import com.testor.module.contractor.ledger.model.dto.TContractorToolsDelParam;
import com.testor.module.contractor.ledger.model.dto.TContractorToolsParam;
import com.testor.module.contractor.ledger.model.template.ToolsTemplate;
import com.testor.module.contractor.ledger.service.TContractorToolsService;
import com.testor.module.sys.service.NewSysDictDataService;
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.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.supers.SuperController;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
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;

/**
 * 工器具台账Controller
 *
 * @author testor-framework
 * @date 2024-11-19 10:30:09
 */
@RestController
@RequestMapping("/contractor/tools")
@Api(value = "TContractorTools", tags = "工器具台账")
@Slf4j
public class TContractorToolsController extends SuperController
{
    @Autowired
    private TContractorToolsService tContractorToolsService;

	@Autowired
	private NewSysDictDataService newSysDictDataService;

    /* Generated Method*/
	@ApiOperation(value = "新增 工器具台账", notes = "Add TContractorTools")
	@PostMapping(value = "/add")
	public BaseResponse<TContractorTools>addEntity(@RequestBody TContractorTools addRequest) {
		BaseResponse<TContractorTools> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(addRequest)){
			// TODO 按需求添加数据去重，特殊值设定，业务异常
			String id = IdHelper.getId32bit();
            TContractorTools data=BeanHelper.beanToBean(addRequest,  TContractorTools.class);
			data.setId(id);
			UserInfo loginUser = ContextUtils.getLoginUser();
			data.setOrgId(loginUser.getOrgId());
			boolean result= tContractorToolsService.save(data);
			if(result){
                TContractorTools newEntity = new TContractorTools();
				newEntity.setId(id);
				baseResponse.setData(newEntity);
			}
		}
		return baseResponse;
	}

	@ApiOperation(value = "获取 工器具台账 ", notes = "Get TContractorTools By Id")
	@GetMapping(value = "/get")
	public BaseResponse<TContractorTools> getById(String id){
		BaseResponse<TContractorTools> baseResponse=new BaseResponse<>();
		if(StringHelper.isNotEmpty(id)){
			// TODO 按需求添加业务异常判断
            TContractorTools data= tContractorToolsService.getById(id);

			// 设置界面工器具名称下拉框值，默认为“工器具名称toolsName”，当名称toolsName不在“承包商管理-工器具台账-名称”字典表中时，设置为“其他”
			String dictId = newSysDictDataService.getDictId("contractor_tools_name",data.getToolsName(),null);
			String nameSelect = data.getToolsName();
			if(StringUtils.isBlank(dictId)){
				nameSelect = "其他";
			}
			data.setNameSelect(nameSelect);

			baseResponse.setData(data);
		}
		return baseResponse;
	}

	@ApiOperation(value = "修改 工器具台账 ", notes = "Update TContractorTools By Id")
	@PutMapping(value = "/update")
	public BaseResponse<BizGeneralResponse> updateEntity(@RequestBody TContractorTools updateRequest){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(updateRequest)&&StringHelper.isNotEmpty(updateRequest.getId())){
			// TODO 按需求添加数据去重，特殊值设定，业务异常
            TContractorTools data=BeanHelper.beanToBean(updateRequest, TContractorTools.class);
			boolean result= tContractorToolsService.updateById(data);
			baseResponse.setData(
					BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
		}
		return baseResponse;
	}

	@ApiOperation(value = "删除 工器具台账 ", notes = "delete TContractorTools By Id")
	@PutMapping(value = "/delete")
	public BaseResponse<BizGeneralResponse> deleteEntity(@RequestBody TContractorToolsDelParam deleteRequest){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(deleteRequest)&&StringHelper.isNotEmpty(deleteRequest.getId())){
			// TODO 按需求添加数据去重，特殊值设定，业务异常
            TContractorTools data= new TContractorTools();
			data.setId(deleteRequest.getId());
			data.setStatus(BizConstants.STATUS_DELETE);
			boolean result= tContractorToolsService.updateById(data);
			baseResponse.setData(
					BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
		}
		return baseResponse;
	}

	@ApiOperation(value = "批量删除工器具台账", notes = "delete TContractorTools by batch Id")
	@PutMapping(value = "/batch_delete")
	public BaseResponse<BizGeneralResponse> deleteEntityBatch(
			@RequestBody TContractorToolsDelParam deleteRequest) {
		BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
		if (ObjectHelper.isNotEmpty(deleteRequest) && (!deleteRequest.getIds().isEmpty())) {
            /* 批量删除 */
			List<TContractorTools> tContractorToolsList = new ArrayList<>();
            for(String id: deleteRequest.getIds()){
                TContractorTools data= new TContractorTools();
				data.setId(id);
				data.setStatus(BizConstants.STATUS_DELETE);
                tContractorToolsList.add(data);
			}
			boolean result = tContractorToolsService.updateBatchById(tContractorToolsList);
			baseResponse.setData(
					BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
		}
		return baseResponse;
	}

	@ApiOperation(value = "获取 工器具台账 分页列表", notes = "List TContractorTools with page")
	@GetMapping(value = "/list")
	public  BaseResponse<BaseResponseList<TContractorTools>>listEntity(TContractorToolsParam param){
		BaseResponse<BaseResponseList<TContractorTools>>baseResponse=new BaseResponse<>();

		Page<TContractorTools> resultList= tContractorToolsService.listEntity(param);
		BaseResponseList<TContractorTools> baseResponseList=new BaseResponseList<>();
		baseResponseList.setData(resultList.getRecords());
		baseResponseList.setTotal(resultList.getTotal());
		baseResponse.setData(baseResponseList);
		return baseResponse;
	}

	@ApiOperation(value = "获取 工器具台账 列表", notes = "List TContractorTools all")
	@GetMapping(value = "/datas")
	public  BaseResponse<BaseResponseList<TContractorTools>>listAllEntity(TContractorToolsParam param){
		BaseResponse<BaseResponseList<TContractorTools>>baseResponse=new BaseResponse<>();
		List<TContractorTools> resultList=tContractorToolsService.listAllEntity(param);
		BaseResponseList<TContractorTools> baseResponseList=new BaseResponseList<>();
		baseResponseList.setData(resultList);
		baseResponseList.setTotal(resultList.size());
		baseResponse.setData(baseResponseList);
		return baseResponse;
	}

	@ApiOperation(value = "下载 工器具台账 导入模板", notes = "Download TContractorTools import template")
    @GetMapping(value = "/importTemplate")
    public void importTemplate (HttpServletResponse response, String fileDowName) throws Exception {
		String fileName = StringUtils.isNotEmpty(fileDowName) ? fileDowName : "工器具台账导入模板";
		List<ToolsTemplate> templates = new ArrayList<>();
		templates.add(new ToolsTemplate());
		EasyExcelUtil.writeExcelBySelect(response,fileName,"工器具台账",templates);
    }

	@ApiOperation(value = "导入 工器具台账 ", notes = "Import TContractorTools")
	@PostMapping(value = "/importToolsLedger")
	public BaseResponse<String> importToolsLedger(@RequestParam("file") MultipartFile file) throws Exception{
		BaseResponse<String>  baseResponse = new BaseResponse<>();
		UserInfo userInfo = ContextUtils.getLoginUser();
		// 导入Excel文件，将文件流转换为 ToolsTemplate 对象列表
		ExcelResult<ToolsTemplate> toolsTemplateExcelResult = EasyExcelUtil.importExcel(file.getInputStream(), ToolsTemplate.class, true);
		// 获取 ToolsTemplate 对象列表
		List<ToolsTemplate> list = toolsTemplateExcelResult.getList();
		List<TContractorTools> toolsList = BeanHelper.listToList(list, TContractorTools.class);
		for(TContractorTools tools : toolsList){
			tools.setOrgId(userInfo.getOrgId());
		}
		// 将 ToolsTemplate 对象列表转换为 TContractorTools 对象列表，并批量保存
		tContractorToolsService.saveBatch(toolsList);

		return baseResponse;
	}
}
