package com.casic.missiles.controller.equipment;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.casic.missiles.core.base.controller.ExportController;
import com.casic.missiles.core.page.PageFactory;
import com.casic.missiles.core.page.PageInfoBT;
import com.casic.missiles.dto.IdDTO;
import com.casic.missiles.dto.ReturnDTO;
import com.casic.missiles.dto.ReturnUtil;
import com.casic.missiles.dto.equipment.EquipmentOrSampleDto;
import com.casic.missiles.dto.equipment.FixedAssetRequest;
import com.casic.missiles.dto.equipment.RemindQuantityDTO;
import com.casic.missiles.dto.equipment.StandardSupportEquipmentExcelData;
import com.casic.missiles.enums.ExportEnum;
import com.casic.missiles.exception.BusinessException;
import com.casic.missiles.model.equipment.*;
import com.casic.missiles.model.exception.enums.CoreExceptionEnum;
import com.casic.missiles.service.equipment.IEquipmentFixedAssetsService;
import com.casic.missiles.utils.ConvertUtils;
import com.casic.missiles.utils.DictCodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  固定资产Controller
 * </p>
 *
 * @author cuicheng
 * @since 2022-12-07
 */
@Api(tags = "固定资产管理接口")
@RestController
@RequestMapping("/meter/assets")
public class EquipmentFixedAssetsController extends ExportController {

    @Autowired
    private IEquipmentFixedAssetsService iEquipmentFixedAssetsService;

    /**
     * 固定资产列表
     */
    @ApiOperation("固定资产（分页）")
    @PostMapping("/listPage")
    @ResponseBody
    public ReturnDTO<PageInfoBT<EquipmentFixedAssets>> listPage(@RequestBody @Valid FixedAssetRequest request) throws Exception {
        Page<EquipmentFixedAssets> page = PageFactory.defaultPage();
        DictCodeUtils.validDictCode(request);
        return ReturnUtil.success(super.packForBT(iEquipmentFixedAssetsService.listPage(page, request)));
    }

    /**
     * 新增固定资产
     */
    @ApiOperation("固定资产新增")
    @PostMapping("/add")
    @ResponseBody
    public ReturnDTO add(@RequestBody @Valid EquipmentFixedAssets equipmentFixedAssets) throws Exception {
        DictCodeUtils.validDictCode(equipmentFixedAssets);
        return iEquipmentFixedAssetsService.addFixedAsset(equipmentFixedAssets);
    }
    /**
     * 固定资产更新
     */
    @ApiOperation("固定资产更新")
    @PostMapping("/update")
    @ResponseBody
    public ReturnDTO update(@RequestBody EquipmentFixedAssets equipmentFixedAssets) throws Exception {
        DictCodeUtils.validDictCode(equipmentFixedAssets);
        return iEquipmentFixedAssetsService.updateFixedAsset(equipmentFixedAssets);
    }
    /**
     * 固定资产详情
     */
    @ApiOperation("固定资产详情")
    @PostMapping("/detail")
    @ResponseBody
    public ReturnDTO<EquipmentFixedAssets> detail(@RequestBody @Valid IdDTO idDTO) throws Exception {
        return ReturnUtil.success(iEquipmentFixedAssetsService.getById(idDTO.getId()));
    }

    /**
     * 刪除固定资产
     *
     * 标准配套设备/检定设备/测量工装-删除：修改设备属性标志
     * 测量设备/固定资产-删除：删除设备
     */
    @ApiOperation("删除固定资产(测量设备/固定资产-删除)")
    @PostMapping("/delete")
    @ResponseBody
    public ReturnDTO delete(@RequestBody @Valid IdDTO idDTO) {
        return iEquipmentFixedAssetsService.deleteByFixedAssetId(idDTO.getId());
    }

    @ApiOperation("删除标准配套设备")
    @PostMapping("/removeStandardSupportEquipment")
    @ResponseBody
    public ReturnDTO removeStandardSupportEquipment(@RequestBody @Valid IdDTO idDTO) {
        return iEquipmentFixedAssetsService.removeStandardSupportEquipment(idDTO.getId());
    }

    @ApiOperation("删除检定设备")
    @PostMapping("/removeCalibrationTestEquipment")
    @ResponseBody
    public ReturnDTO removeCalibrationTestEquipment(@RequestBody @Valid IdDTO idDTO) {
        return iEquipmentFixedAssetsService.removeCalibrationTestEquipment(idDTO.getId());
    }

    @ApiOperation("删除测量工装")
    @PostMapping("/removeMeasureAccount")
    @ResponseBody
    public ReturnDTO removeMeasureAccount(@RequestBody @Valid IdDTO idDTO) {
        return iEquipmentFixedAssetsService.removeMeasureAccount(idDTO.getId());
    }

    /**
     * 导出固定资产
     */
    @ApiOperation("导出excel")
    @PostMapping("/exportExcel")
    @ResponseBody
    public void exportExcel(@RequestBody @Valid FixedAssetRequest request) throws Exception {
        List<EquipmentFixedAssets> list;
        DictCodeUtils.validDictCode(request);
        if(!CollectionUtils.isEmpty(request.getIds())){
            FixedAssetRequest fixedAssetRequest = new FixedAssetRequest();
            fixedAssetRequest.setIds(request.getIds());
            list = iEquipmentFixedAssetsService.list(fixedAssetRequest);
        }else{
            list = iEquipmentFixedAssetsService.list(request);
        }
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        Objects.equals(request.getIsStandardSupportEquipment(), 1);
        if (Objects.equals(request.getIsStandardSupportEquipment(), 1)) {
            super.exportExcel(StandardSupportEquipmentExcelData.class, getResulList(StandardSupportEquipmentExcelData.class, list), ExportEnum.STANDARD_SUPPORT_EQUIPMENT.getDescription());
        } else if (Objects.equals(request.getIsFixedAssets(),1)) {
            super.exportExcel(EquipmentFixedAssets.class, getResulList(EquipmentFixedAssets.class, list), ExportEnum.FIXED_ASSETS.getDescription());
        } else if (Objects.equals(request.getIsCalibrationTestEquipment(), 1)) {
            super.exportExcel(EquipmentExcelData.class, getResulList(EquipmentExcelData.class, list), ExportEnum.METER_EQUIPMENT.getDescription());
        } else if (Objects.equals(request.getIsMeasureAccount(), 1)) {
            super.exportExcel(EquipmentExcelData.class, getResulList(EquipmentExcelData.class, list), ExportEnum.METER_EQUIPMENT.getDescription());
        } else {
            super.exportExcel(EquipmentExcelData.class, getResulList(EquipmentExcelData.class, list), ExportEnum.METER_EQUIPMENT.getDescription());
        }
    }

    /**
     *
     * @param cls
     * @param list
     * @return
     * @throws Exception
     */
    private List getResulList(Class<?> cls, List<EquipmentFixedAssets> list) throws Exception{
        List resultList = new ArrayList();
        for (EquipmentFixedAssets item : list) {
            Object obj = cls.newInstance();
            BeanUtils.copyProperties(item, obj);
            resultList.add(obj);
        }
        return resultList;
    }


    /**
     * 批量导入测量设备信息
     */
    @ApiOperation("批量导入测量设备信息")
    @PostMapping(value = "/importMeterEquipment", headers = "content-type=multipart/form-data")
    @ResponseBody
    public ReturnDTO importMeterEquipment(@RequestParam MultipartFile[] multipartFile) throws Exception {
        List<EquipmentFixedAssetsImport> sourceList = new ArrayList<>();
        for (MultipartFile file : multipartFile) {
            List<EquipmentFixedAssetsImport> list =  super.importExcel(EquipmentFixedAssetsImport.class, file, null, null);
            sourceList.addAll(list);
        }
        List<EquipmentFixedAssets> targetList = ConvertUtils.sourceToTarget(sourceList, EquipmentFixedAssets.class);
        return iEquipmentFixedAssetsService.addFixedAssetList(targetList);
    }


    /**
     * 用于选择下拉检查设备查询
     */
    @ApiOperation("用于选择下拉检查设备查询")
    @PostMapping("/querySelectList")
    @ResponseBody
    public ReturnDTO querySelectList()  {
        return iEquipmentFixedAssetsService.querySelectList();
    }

    /**
     * 根据使用部门查询测量设备
     */
    @ApiOperation("根据使用部门查询测量设备")
    @PostMapping("/queryListByDept")
    @ResponseBody
    public ReturnDTO queryListByDept(@RequestBody @Valid IdDTO idDTO) throws Exception {
        return iEquipmentFixedAssetsService.queryListByDept(idDTO.getId());
    }

    /**
     * 通过设备id查询出使用记录
     */
    @ApiOperation("通过设备id查询出使用记录")
    @PostMapping("/queryUseLogList")
    @ResponseBody
    public ReturnDTO<EquipmentUseLog> queryUseLogLis(@RequestBody @Valid IdDTO idDTO) throws Exception {
        return iEquipmentFixedAssetsService.queryUseLogList(idDTO.getId());
    }

    /**
     * 通过设备id查询出状态变更记录
     */
    @ApiOperation("通过设备id查询出状态变更记录")
    @PostMapping("/queryStateChangeLogList")
    @ResponseBody
    public ReturnDTO<EquipmentStateChangeLog> queryStateChangeLogList(@RequestBody @Valid IdDTO idDTO) throws Exception {
        return iEquipmentFixedAssetsService.queryStateChangeLogList(idDTO.getId());
    }
    /**
     * 通过名字/编号查询设备与样品
     */
    @ApiOperation("通过名字/编号查询设备与样品")
    @PostMapping("/queryEquipment")
    @ResponseBody
    public ReturnDTO<PageInfoBT<EquipmentOrSampleDto>> queryEquipment(@RequestBody @Valid EquipmentOrSampleDto request, BindingResult bindingResult) throws Exception{
        if(bindingResult.hasErrors()){
            throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        Page<EquipmentOrSampleDto> page = PageFactory.defaultPage();
        return ReturnUtil.success(super.packForBT(iEquipmentFixedAssetsService.queryEquipment(page, request)));
    }

    @ApiOperation("设备到期列表")
    @PostMapping("/remindListPage")
    @ResponseBody
    public ReturnDTO<PageInfoBT<EquipmentFixedAssets>> remindListPage(@RequestBody @Valid FixedAssetRequest request) throws Exception {
        Page<EquipmentFixedAssets> page = PageFactory.defaultPage();
        return ReturnUtil.success(super.packForBT(iEquipmentFixedAssetsService.remindListPage(page, request)));
    }

    @ApiOperation("到期提醒数量")
    @GetMapping("/remindQuantity")
    @ResponseBody
    public ReturnDTO<RemindQuantityDTO> remindQuantity() {
        return ReturnUtil.success(iEquipmentFixedAssetsService.remindQuantity());
    }

    /**
     * 设备到期列表导出
     */
    @ApiOperation("设备到期列表导出")
    @PostMapping("/exportList")
    @ResponseBody
    public void exportList(@RequestBody @Valid FixedAssetRequest request, HttpServletResponse response) throws Exception{
        iEquipmentFixedAssetsService.exportList(request,response);
    }


    /**
     * 催办会产生催办消息，对相关操作人员进行消息提示
     */
    @ApiOperation("催办")
    @PostMapping("/remindWorker")
    public ReturnDTO remindWorker(@RequestBody @Valid IdDTO idDTO, BindingResult bindingResult) {
        if(bindingResult.hasErrors()){
            throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        return iEquipmentFixedAssetsService.remindWorker(idDTO);
    }

}
