package com.testor.module.contractor.ledger.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.TContractorMaterial;
import com.testor.module.contractor.ledger.model.dto.TContractorMaterialDelParam;
import com.testor.module.contractor.ledger.model.dto.TContractorMaterialParam;
import com.testor.module.contractor.ledger.model.template.MaterialTemplate;
import com.testor.module.contractor.ledger.service.TContractorMaterialService;
import com.testor.module.sys.service.NewSysDictDataService;
import com.testor.module.sys.service.NewSysOrgService;
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.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;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 物料台账Controller
 *
 * @author testor-framework
 * @date 2024-11-19 10:29:21
 */
@RestController
@RequestMapping("/contractor/material")
@Api(value = "TContractorMaterial", tags = "物料台账")
@Slf4j
public class TContractorMaterialController extends SuperController
{
    @Autowired
    private TContractorMaterialService tContractorMaterialService;

	@Autowired
	private NewSysDictDataService newSysDictDataService;



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

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

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

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

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

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

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

	@ApiOperation(value = "获取 物料台账 分页列表", notes = "List TContractorMaterial with page")
	@GetMapping(value = "/list")
	public  BaseResponse<BaseResponseList<TContractorMaterial>>listEntity(TContractorMaterialParam param){
		BaseResponse<BaseResponseList<TContractorMaterial>>baseResponse=new BaseResponse<>();

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

	@ApiOperation(value = "获取 物料台账 列表", notes = "List TContractorMaterial all")
	@GetMapping(value = "/datas")
	public  BaseResponse<BaseResponseList<TContractorMaterial>>listAllEntity(TContractorMaterialParam param){
		BaseResponse<BaseResponseList<TContractorMaterial>>baseResponse=new BaseResponse<>();
		// TODO 根据需求修改查询条件及查询参数
		List<TContractorMaterial> resultList=tContractorMaterialService.listAllEntity(param);
		BaseResponseList<TContractorMaterial> baseResponseList=new BaseResponseList<>();
		baseResponseList.setData(resultList);
		baseResponseList.setTotal(resultList.size());
		baseResponse.setData(baseResponseList);
		return baseResponse;
	}

	@ApiOperation(value = "下载 承包商管理-物料台账 导入模板", notes = "Download TContractorMaterial import template")
	@GetMapping(value = "/importTemplate")
	public void importTemplate (HttpServletResponse response, String fileDowName) throws Exception {
		List<MaterialTemplate> templates = new ArrayList<>();
		templates.add(new MaterialTemplate());
		EasyExcelUtil.writeExcelBySelect(response,"物料台账导入模板","物料台账",templates);
	}

	@ApiOperation(value = "导入 承包商管理-物料台账 ", notes = "Import TContractorMaterial")
	@PostMapping(value = "/importMaterialLedger")
	public BaseResponse<String> importMaterialLedger(@RequestParam("file") MultipartFile file) throws Exception{
		BaseResponse<String>  baseResponse = new BaseResponse<>();
		// 导入Excel文件，将文件流转换为 MaterialTemplate 对象列表
		ExcelResult<MaterialTemplate> materialTemplateExcelResult = EasyExcelUtil.importExcel(file.getInputStream(), MaterialTemplate.class, true);
		// 获取 MaterialTemplate 对象列表
		List<MaterialTemplate> list = materialTemplateExcelResult.getList();

		List<TContractorMaterial> dataList = BeanHelper.listToList(list, TContractorMaterial.class);
		UserInfo userInfo = ContextUtils.getLoginUser();
		for(TContractorMaterial data:dataList){
			data.setOrgId(userInfo.getOrgId());
		}
		// 批量保存
		tContractorMaterialService.saveBatch(dataList);

		return baseResponse;
	}

    /* Private Methods */

}
