package com.yeejoin.equipmanage.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.equipmanage.common.dto.FaultCaseImportParam;
import com.yeejoin.equipmanage.common.entity.Equipment;
import com.yeejoin.equipmanage.common.entity.FaultCase;
import com.yeejoin.equipmanage.common.entity.SignalClassify;
import com.yeejoin.equipmanage.common.entity.vo.EquiplistSpecificBySystemVO;
import com.yeejoin.equipmanage.common.enums.EmergencyLevelEum;
import com.yeejoin.equipmanage.common.utils.CommonResponseUtil;
import com.yeejoin.equipmanage.common.utils.StringUtil;
import com.yeejoin.equipmanage.common.vo.EquipmentManageVo;
import com.yeejoin.equipmanage.service.*;
import com.yeejoin.equipmanage.utils.FileHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 信号分类量测枚举表
 *
 * @author system_generator
 * @date 2022-02-18
 */
@RestController
@Api(tags = "信号分类量测枚举表Api")
@RequestMapping(value = "/fault/case", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class FaultCaseController extends AbstractBaseController {

    @Autowired
	IFaultCaseService faultCaseService;

	@Autowired
	ISignalClassifyService signalClassifyService;

	@Autowired
	IFireFightingSystemService fireFightingSystemService;

	@Autowired
	IEquipmentSpecificSerivce equipmentSpecificService;

	@Autowired
	IEquipmentService iEquipmentService;

    /**
     * 新增信号分类量测枚举表
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@PostMapping(value = "/save")
	@ApiOperation(httpMethod = "POST", value = "新增信号分类量测枚举表", notes = "新增信号分类量测枚举表")
	public ResponseModel<FaultCase> save(@RequestBody FaultCase model) {
	    faultCaseService.save(model);
	    return ResponseHelper.buildResponse(model);
	}

	/**
     * 根据id更新
     *
     * @param
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@PutMapping(value = "/update")
	@ApiOperation(httpMethod = "PUT", value = "根据id更新故障案例", notes = "根据id更新故障案例")
	public ResponseModel<FaultCase> updateByIdWlFaultCase(@RequestBody FaultCase model) {
//		model.setFaultLevel(StringUtil.isNotEmpty(model.getFaultLevel()) ? EmergencyLevelEum.getCodeByName(model.getFaultLevel()) : "");
	    faultCaseService.updateById(model);
	    return ResponseHelper.buildResponse(model);
	}

	/**
     * 根据id删除
     *
     * @param id 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @DeleteMapping(value = "/{id}")
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除故障案例", notes = "根据id删除故障案例")
    public ResponseModel<Boolean> deleteOneById(HttpServletRequest request, @PathVariable(value = "id") Long id){
        return ResponseHelper.buildResponse(faultCaseService.removeById(id));
    }

    /**
     * 根据id查询
     *
	 * @param id  主键
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/{id}")
	@ApiOperation(httpMethod = "GET",value = "根据id查询单个故障案例",  notes = "根据id查询单个故障案例")
	public ResponseModel<FaultCase> selectOne(@PathVariable Long id) {
	    return ResponseHelper.buildResponse(faultCaseService.getById(id));
	}

	/**
	 * 列表全部数据查询
     *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET",value = "故障案例列表全部数据查询",   notes = "故障案例列表全部数据查询")
	@GetMapping(value = "/list")
	public ResponseModel<List<FaultCase>> selectForList() {
		return ResponseHelper.buildResponse(faultCaseService.query().list());
	}

	/**
	 * 列表全部数据查询
     *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET",value = "故障案例列表全部数据查询",   notes = "故障案例列表全部数据查询")
	@GetMapping(value = "/page")
	public Page<FaultCase> selectForList(Page page,
										  @RequestParam(value = "systemId",required = false) String systemId,
										  @RequestParam(value = "faultLevel",required = false) String faultLevel,
										  @RequestParam(value = "faultType",required = false) String faultType,
										 @RequestParam(value = "name",required = false) String name) {
		FaultCase dto = new FaultCase();
		dto.setSystemId(systemId);
		dto.setFaultLevel(faultLevel);
		dto.setFaultType(faultType);
		dto.setSearchName(name);
		return faultCaseService.listPage(page, dto);
	}

	/**
	 * 模板导出
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET",value = "模板导出",   notes = "模板导出")
	@GetMapping(value = "/export")
	public ResponseModel<List<FaultCase>> exportTemplate(HttpServletResponse response) {
		String fileName = "故障案例模板.xls"; //模板名称
		String[] handers = {"消防系统","部件","故障类型","故障等级","故障描述","处理建议","故障影响","预防措施"}; //列标题
		List<String[]> downData = new ArrayList();
		List<EquipmentManageVo> systems = fireFightingSystemService.getSystemCategory();
		if(0 < systems.size()) {
			List<String> sysList = new ArrayList<>();
			for (EquipmentManageVo entity : systems) {
				String str = entity.getName() + "@" + entity.getId();
				sysList.add(str);
			}
			// 消防系统
			downData.add(sysList.toArray(new String[sysList.size()]));
		}

		List<Equipment> categories = iEquipmentService.getAll();
		List<String> equipList = new ArrayList<>();
		for (Equipment entity : categories) {
			String str = entity.getName() + "@" + entity.getCode();
			equipList.add(str);
		}
		// 部件
		downData.add(equipList.toArray(new String[equipList.size()]));


		List<SignalClassify> singles = signalClassifyService.getList();
		if(0 < singles.size()) {
			List<String> classList = new ArrayList<>();
			for (SignalClassify signalClassify : singles) {
				String str = signalClassify.getTypeName();
				classList.add(str);
			}
			// 故障类型s
			downData.add(classList.toArray(new String[classList.size()]));
		}
		// 故障等级
		List<String> levels = EmergencyLevelEum.getDropDownList();
		downData.add(levels.toArray(new String[levels.size()]));
		String [] downRows = {"0","1","2","3"}; //下拉的列序号数组(序号从0开始)
		try {
			FileHelper.createExcelTemplate(fileName, handers, downData, downRows, response);
		} catch (Exception e) {
			CommonResponseUtil.failure(e.getMessage());
		}
		return CommonResponseUtil.success();
	}

	/**
	 * 导入
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@PostMapping(value = "/import")
	@ApiOperation(httpMethod = "POST", value = "模板填充数据导入", notes = "模板填充数据导入")
	public ResponseModel importFaultCase(@ApiParam(value="导入数据文件", required=true) MultipartFile file) {
		String fileName = file.getOriginalFilename();
		if (!fileName.endsWith(".xls")) {
			return CommonResponseUtil.failure("文件格式错误");
		}
		try {
			List<FaultCaseImportParam> list = FileHelper.importExcel(file, 0, 1, FaultCaseImportParam.class);
			if (0 < list.size()) {
				List<FaultCase> cases = new ArrayList<>();
				for (FaultCaseImportParam dto : list) {
					FaultCase faultCase = new FaultCase();
					BeanUtils.copyProperties(dto, faultCase);
					if (StringUtil.isNotEmpty(dto.getSystemInfo())) {
						String[] strings = dto.getSystemInfo().split("@");
						faultCase.setSystemName(strings[0]);
						faultCase.setSystemId(strings[1]);
					} else {
						return CommonResponseUtil.failure("请补充消防系统信息！");
					}

					if (StringUtil.isNotEmpty(dto.getEquipInfo())) {
						String[] strings = dto.getEquipInfo().split("@");
						if(2 > strings.length) {
							return CommonResponseUtil.failure("部件支持的导入格式错误，正确格式例如：部件名称@部件编码 !");
						} else {
							List<Equipment> eqes = iEquipmentService.getAllByCode(faultCase.getSystemId());
							if (0 < eqes.size()) {
								List<Equipment> tempList = eqes.stream().filter(x -> x.getCode().equalsIgnoreCase(strings[1])).collect(Collectors.toList());
								if (0 < tempList.size()) {
									faultCase.setEquipName(strings[0]);
									faultCase.setEquipCode(strings[1]);
								} else {
									return CommonResponseUtil.failure("请注意当前系统下不存在此类部件 !");
								}
							}
						}
					} else {
						return CommonResponseUtil.failure("请补充部件信息！");
					}

					if (StringUtil.isNotEmpty(dto.getFaultLevel())) {
						String[] levels = dto.getFaultLevel().split("@");
						faultCase.setFaultLevel(levels[1]);
					} else {
						return CommonResponseUtil.failure("请补充故障等级信息！");
					}

					cases.add(faultCase);
				}
				faultCaseService.saveOrUpdateBatch(cases);
			}
			return CommonResponseUtil.success();
		} catch (Exception e) {
			e.printStackTrace();
			return CommonResponseUtil.failure(e.getLocalizedMessage());
		}
	}

	/**
	 * 统计导出
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET",value = "统计列表",   notes = "统计导出")
	@GetMapping(value = "/system/list")
	public ResponseModel<List<Map<String, Object>>> getFaultCaseList() {
		return CommonResponseUtil.success(faultCaseService.getFaultCaseList());
	}

	/**
	 * 统计导出
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET",value = "装备定义列表不分页",   notes = "装备定义列表不分页")
	@GetMapping(value = "/equip/list")
	public ResponseModel<List<EquiplistSpecificBySystemVO>> getEquipList(@RequestParam(value = "systemId", required = false) String systemId) {
		return CommonResponseUtil.success(iEquipmentService.getAllByCode(systemId));
	}
}
