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.TContractorEmergencyMaterial;
import com.testor.module.contractor.ledger.model.dto.TContractorEmergencyMaterialDelParam;
import com.testor.module.contractor.ledger.model.dto.TContractorEmergencyMaterialParam;
import com.testor.module.contractor.ledger.model.template.EmergencyMaterialTemplate;
import com.testor.module.contractor.ledger.service.TContractorEmergencyMaterialService;
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:25:06
 */
@RestController
@RequestMapping("/contractor/emergencyMaterial")
@Api(value = "TContractorEmergencyMaterial", tags = "承包商管理-应急物资台账")
@Slf4j
public class TContractorEmergencyMaterialController extends SuperController {
    @Autowired
    private TContractorEmergencyMaterialService tContractorEmergencyMaterialService;

    @Autowired
    private NewSysDictDataService newSysDictDataService;

    @Autowired
    private NewSysOrgService newSysOrgService;

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

    @ApiOperation(value = "获取 承包商管理-应急物资台账 ", notes = "Get TContractorEmergencyMaterial By Id")
    @GetMapping(value = "/get")
    public BaseResponse<TContractorEmergencyMaterial> getById(String id) {
        BaseResponse<TContractorEmergencyMaterial> baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(id)) {
            // TODO 按需求添加业务异常判断
            TContractorEmergencyMaterial data = tContractorEmergencyMaterialService.getById(id);

            // 设置应急物资名称下拉框值，默认为“应急物资名称name”，当应急物资名称name值不在“承包商管理-应急物资台账-名称”字典表中时，设置为“其他”
            String dictId = newSysDictDataService.getDictId("contractor_emergency_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 TContractorEmergencyMaterial By Id")
    @PutMapping(value = "/update")
    public BaseResponse<BizGeneralResponse> updateEntity(@RequestBody TContractorEmergencyMaterial updateRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(updateRequest) && StringHelper.isNotEmpty(updateRequest.getId())) {
            // TODO 按需求添加数据去重，特殊值设定，业务异常
            TContractorEmergencyMaterial data = BeanHelper.beanToBean(updateRequest,
                    TContractorEmergencyMaterial.class);
            boolean result = tContractorEmergencyMaterialService.updateById(data);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

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

    @ApiOperation(value = "批量删除承包商管理-应急物资台账", notes = "delete TContractorEmergencyMaterial by batch Id")
    @PutMapping(value = "/batch_delete")
    public BaseResponse<BizGeneralResponse> deleteEntityBatch(
            @RequestBody TContractorEmergencyMaterialDelParam deleteRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && (!deleteRequest.getIds().isEmpty())) {
            /* 批量删除 */
            List<TContractorEmergencyMaterial> tContractorEmergencyMaterialList = new ArrayList<>();
            for (String id : deleteRequest.getIds()) {
                TContractorEmergencyMaterial data = new TContractorEmergencyMaterial();
                data.setId(id);
                data.setStatus(BizConstants.STATUS_DELETE);
                tContractorEmergencyMaterialList.add(data);
            }
            boolean result = tContractorEmergencyMaterialService.updateBatchById(tContractorEmergencyMaterialList);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

    @ApiOperation(value = "获取 承包商管理-应急物资台账 分页列表", notes = "List TContractorEmergencyMaterial with page")
    @GetMapping(value = "/list")
    public BaseResponse<BaseResponseList<TContractorEmergencyMaterial>> listEntity(TContractorEmergencyMaterialParam param) {
        BaseResponse<BaseResponseList<TContractorEmergencyMaterial>> 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<TContractorEmergencyMaterial> resultPage = new Page<>(page, limit);
        // TODO 根据需求修改查询条件及查询参数
        QueryWrapper<TContractorEmergencyMaterial> queryWrapper = this.createQuery(param);
        Page<TContractorEmergencyMaterial> resultList = tContractorEmergencyMaterialService.page(resultPage,
                queryWrapper);
        BaseResponseList<TContractorEmergencyMaterial> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(resultList.getRecords());
        baseResponseList.setTotal(resultList.getTotal());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    @ApiOperation(value = "获取 承包商管理-应急物资台账 列表", notes = "List TContractorEmergencyMaterial all")
    @GetMapping(value = "/datas")
    public BaseResponse<BaseResponseList<TContractorEmergencyMaterial>> listAllEntity(TContractorEmergencyMaterialParam param) {
        BaseResponse<BaseResponseList<TContractorEmergencyMaterial>> baseResponse = new BaseResponse<>();
        // TODO 根据需求修改查询条件及查询参数
        QueryWrapper<TContractorEmergencyMaterial> queryWrapper = this.createQuery(param);
        List<TContractorEmergencyMaterial> resultList = tContractorEmergencyMaterialService.list(queryWrapper);
        BaseResponseList<TContractorEmergencyMaterial> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(resultList);
        baseResponseList.setTotal(resultList.size());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

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

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

        List<TContractorEmergencyMaterial> dataList = BeanHelper.listToList(list, TContractorEmergencyMaterial.class);

        UserInfo userInfo =  ContextUtils.getLoginUser();
        for (TContractorEmergencyMaterial data : dataList) {
            data.setOrgId(userInfo.getOrgId());
        }
        // 批量保存
        tContractorEmergencyMaterialService.saveBatch(dataList);

        return baseResponse;
    }

    /* Private Methods */

    /**
     * 列表查询条件及查询参数
     */
    private QueryWrapper<TContractorEmergencyMaterial> createQuery(TContractorEmergencyMaterialParam queryParam) {
        QueryWrapper<TContractorEmergencyMaterial> queryWrapper = new QueryWrapper<>();
        UserInfo loginUser = ContextUtils.getLoginUser();
        String orgId = loginUser.getOrgId();
        List<String> idsChildrenById = newSysOrgService.getIdsChildrenById(orgId);
        //查询下级机构id
        queryWrapper.in("org_id", idsChildrenById);

        if (StringHelper.isNotEmpty(queryParam.getName())) {
            queryWrapper.like(TContractorEmergencyMaterial.NAME, queryParam.getName());
        }
        if (StringHelper.isNotEmpty(queryParam.getTypeId())) {
            queryWrapper.eq(TContractorEmergencyMaterial.TYPE_ID, queryParam.getTypeId());
        }
        if (StringHelper.isNotEmpty(queryParam.getType())) {
            queryWrapper.eq(TContractorEmergencyMaterial.TYPE, queryParam.getType());
        }
        if (ObjectHelper.isNotEmpty(queryParam.getNum())) {
            queryWrapper.eq(TContractorEmergencyMaterial.NUM, queryParam.getNum());
        }
        if (StringHelper.isNotEmpty(queryParam.getPurpose())) {
            queryWrapper.eq(TContractorEmergencyMaterial.PURPOSE, queryParam.getPurpose());
        }
        if (StringHelper.isNotEmpty(queryParam.getStorageLocation())) {
            queryWrapper.eq(TContractorEmergencyMaterial.STORAGE_LOCATION, queryParam.getStorageLocation());
        }
        if (StringHelper.isNotEmpty(queryParam.getRespPerson())) {
            queryWrapper.eq(TContractorEmergencyMaterial.RESP_PERSON, queryParam.getRespPerson());
        }
        if (StringHelper.isNotEmpty(queryParam.getTel())) {
            queryWrapper.eq(TContractorEmergencyMaterial.TEL, queryParam.getTel());
        }
        if (StringHelper.isNotEmpty(queryParam.getOrgId())) {
            queryWrapper.eq(TContractorEmergencyMaterial.ORG_ID, queryParam.getOrgId());
        }
        if (StringHelper.isNotEmpty(queryParam.getStatus())) {
            queryWrapper.eq(TContractorEmergencyMaterial.STATUS, queryParam.getStatus());
        } else {
            queryWrapper.ne(TContractorEmergencyMaterial.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(TContractorEmergencyMaterial.UPDATE_DATE);
        }
        return queryWrapper;
    }
}
