package com.yeejoin.amos.fas.business.controller;

import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.fas.business.param.ImgParam;
import com.yeejoin.amos.fas.business.service.intfc.IEquipmentService;
import com.yeejoin.amos.fas.business.util.ExcelUtils;
import com.yeejoin.amos.fas.core.common.request.CommonPageable;
import com.yeejoin.amos.fas.core.common.request.CommonRequest;
import com.yeejoin.amos.fas.core.util.*;
import com.yeejoin.amos.fas.dao.entity.Equipment;
import com.yeejoin.amos.fas.dao.entity.EquipmentExcelData;
import com.yeejoin.amos.fas.dao.entity.EquipmentFireEquipment;
import com.yeejoin.amos.fas.dao.entity.PreplanPicture;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.CollectionUtils;
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 javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping(value = "/api/impEquip")
@Api(tags = "重点设备api")
public class EquipmentController extends AbstractBaseController {
    @Autowired
    private IEquipmentService iEquipService;

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "添加重点设备", notes = "添加重点设备")
    @RequestMapping(value = "", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse create(@RequestBody Equipment equipment) throws Exception {

    	
		ReginParams reginParams =getSelectedOrgInfo();
		String compCode=getOrgCode(reginParams);
        equipment.setCreateBy(getUserId());
        equipment.setCreateDate(new Date());
        equipment.setOrgCode(compCode);
        return CommonResponseUtil.success(iEquipService.save(equipment));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "PUT", value = "编辑重点设备", notes = "编辑重点设备")
    @RequestMapping(value = "/{id}", produces = "application/json;charset=UTF-8", method = RequestMethod.PUT)
    public CommonResponse udpate(@PathVariable Long id, @RequestBody Equipment equipment) {
        equipment.setId(id);
        return CommonResponseUtil.success(iEquipService.save(equipment));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询单个重点设备", notes = "查询单个重点设备")
    @RequestMapping(value = "/{id}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse query(@PathVariable Long id) {

        return CommonResponseUtil.success(iEquipService.queryOne(id));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "DELETE", value = "删除重点设备", notes = "查询单个重点设备")
    @RequestMapping(value = "/{ids}", produces = "application/json;charset=UTF-8", method = RequestMethod.DELETE)
    public CommonResponse delete(@PathVariable String ids) throws Exception {
        String[] idArray = ids.split(",");
        
        if(iEquipService.countFemaRelation(idArray) > 0) {
        	return CommonResponseUtil.failure("该重点设备已被FMEA绑定，请先删除绑定关系");
        }
        return CommonResponseUtil.success(iEquipService.delete(idArray));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "重点设备查询", notes = "重点设备查询")
    @RequestMapping(value = "/list", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse queryImpEquipPage(
            @ApiParam(value = "查询条件", required = false)
            @RequestBody(required = false) List<CommonRequest> queryRequests,
            @ApiParam(value = "分页参数", required = true) CommonPageable commonPageable) {
        List<DaoCriteria> criterias = buildDaoCriterias(queryRequests);
        Page<Equipment> carList = iEquipService.queryImpEquip(criterias, commonPageable);
        return CommonResponseUtil.success(carList);
    }


    /**
     * 现场图查询
     *
     * @param id
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    //@Authorization(ingore = true)
    @ApiOperation(httpMethod = "GET", value = "现场图查询", notes = "现场图查询")
    @RequestMapping(value = "/pre-picture", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse queryImpEquipImg(
            @ApiParam(value = "设备id", required = true) @RequestParam(value = "equipId", required = true) Long id,
            @ApiParam(value = "图类型", required = false) @RequestParam(value = "type", required = false) String type) {
        List<CommonRequest> queryRequests = new ArrayList<>();
        CommonRequest request1 = new CommonRequest();
        request1.setName("equipmentId");
        request1.setValue(id);
        if (StringUtil.isNotEmpty(type)) {
            CommonRequest request2 = new CommonRequest();
            request2.setName("type");
            request2.setValue(type);
            queryRequests.add(request2);
        }
        queryRequests.add(request1);
        List<DaoCriteria> criterias = buildDaoCriterias(queryRequests);
        List<PreplanPicture> list = iEquipService.queryImgByIdAndType(criterias);
        return CommonResponseUtil.success(list);
    }

    /**
     * 保护对象查询查询，不分页
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "保护对象查询不分页", notes = "保护对象查询不分页")
    @RequestMapping(value = "/all-list", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse queryImpEquipNoPage() {
        List<Equipment> list = iEquipService.queryEquipNoPage();
        return CommonResponseUtil.success(list);
    }


    /**
     * 绑定消防设备
     * @param equipmentId
     * @param equipmentFireEquipment
     * @return
     * @throws Exception
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    //@Authorization(ingore = true)
    @ApiOperation(httpMethod = "POST", value = "绑定消防设备", notes = "绑定消防设备")
    @RequestMapping(value = "/{id}/fireeqmt", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse bindFireEqumt(@PathVariable("id") Long equipmentId, @RequestBody List<EquipmentFireEquipment> equipmentFireEquipment) throws Exception {
        if (CollectionUtils.isEmpty(equipmentFireEquipment))
            throw new Exception("数据校验失败");
        return CommonResponseUtil.success(iEquipService.bindFireEqumt(equipmentId, equipmentFireEquipment));
    }


    /**
     * 解除绑定消防设备
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    //@Authorization(ingore = true)
    @ApiOperation(httpMethod = "DELETE", value = "解除绑定消防设备", notes = "解除绑定消防设备")
    @RequestMapping(value = "/{equipmentId}/fireeqmt/{fireEquipmentIds}", produces = "application/json;charset=UTF-8", method = RequestMethod.DELETE)
    public CommonResponse bindFireEqumt(
            @PathVariable("equipmentId") Long equipmentId,
            @PathVariable("fireEquipmentIds") String fireEquipmentIds) {

        String[] idArray = fireEquipmentIds.split(",");
        return CommonResponseUtil.success(iEquipService.removeFireEqmtBind(equipmentId, idArray));
    }


    /**
     * 查询指定重点设备已经绑定的消防设备
     *
     * @param equipmentId
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询指定重点设备已经绑定的消防设备", notes = "查询指定重点设备已经绑定的消防设备")
    @RequestMapping(value = "/{equipmentId}/fireeqmt/page", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse queryBindFirEqumtList(
            @PathVariable("equipmentId") Long equipmentId,
            @ApiParam(value = "当前页码", required = false) @RequestParam int pageNumber,
            @ApiParam(value = "页面大小", required = false) @RequestParam int pageSize) {

        CommonPageable commonPageable = null;
        if (pageNumber > -1 && pageSize > -1) {
            commonPageable = new CommonPageable(pageNumber, pageSize);
        }
        return CommonResponseUtil.success(iEquipService.queryBindFirEqumtList(commonPageable, equipmentId));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询有预案的重点设备分页", notes = "查询有预案的重点设备分页")
    @RequestMapping(value = "/reservePage", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public ResponseModel reservePage(
            @ApiParam(value = "当前页码", required = false) @RequestParam int pageNum,
            @ApiParam(value = "页面大小", required = false) @RequestParam int pageSize) {

        CommonPageable commonPageable = null;
        if (pageNum > -1 && pageSize > -1) {
            commonPageable = new CommonPageable(pageNum, pageSize);
        }
        ResponseModel<Equipment> responseModel = new ResponseModel<>();
        Page page = iEquipService.reservePage(commonPageable);
        return CommonResponseUtil2.success(page);
    }


    /**
     * 新增、编辑装备及上传现场图
     *
     * @param equipment 现场装备参数
     * @param img1      电源负荷图
     * @param img2      电缆沟封堵图
     * @param img3      消防车进站行车路线图
     * @param img4      消防取水图
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    //@Authorization(ingore = true)
    @ApiOperation(httpMethod = "POST", value = "编辑装备及上传现场图", notes = "编辑装备及上传现场图")
    @RequestMapping(value = "/uploadEquipmentImg", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse uploadEquipmentImg(
            @ApiParam(value = "装备现场图", required = false) @RequestParam(value = "img1", required = false) MultipartFile img1,
            @RequestParam(value = "img2", required = false) MultipartFile img2,
            @RequestParam(value = "img3", required = false) MultipartFile img3,
            @RequestParam(value = "img4", required = false) MultipartFile img4,
            @RequestParam(value = "equipmentPic", required = false) MultipartFile equipmentPic, Equipment equipment) {
    	ReginParams reginParams =getSelectedOrgInfo();
		String compCode=getOrgCode(reginParams);
        ImgParam[] imgs = new ImgParam[5];
        ImgParam imgParam1 = new ImgParam();
        imgParam1.setFile(img1);
        imgParam1.setType(1);
        ImgParam imgParam2 = new ImgParam();
        imgParam2.setFile(img2);
        imgParam2.setType(2);
        ImgParam imgParam3 = new ImgParam();
        imgParam3.setFile(img3);
        imgParam3.setType(3);
        ImgParam imgParam4 = new ImgParam();
        imgParam4.setFile(img4);
        imgParam4.setType(4);
        ImgParam eqImg = new ImgParam();
        eqImg.setFile(equipmentPic);
        eqImg.setType(5);
        imgs[0] = imgParam1;
        imgs[1] = imgParam2;
        imgs[2] = imgParam3;
        imgs[3] = imgParam4;
        imgs[4] = eqImg;

        equipment.setOrgCode(compCode);
        equipment.setCreateBy(getUserId());
        iEquipService.saveEquipmentAndImg(imgs, equipment);
        return CommonResponseUtil.success();
    }

    /**
     * 查询指定重点设备已经绑定的消防设备
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    //@Authorization(ingore = true)
    @ApiOperation(httpMethod = "GET", value = "查询指定重点设备已经绑定的消防设备", notes = "查询指定重点设备已经绑定的消防设备")
    @GetMapping(value = "/videos", produces = "application/json;charset=UTF-8")
    public CommonResponse findVideoList() {
        return CommonResponseUtil.success(iEquipService.findEquipVideoList());
    }

    /**
     * 重点装备详情
     *
     * @param equipmentId
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    //@Authorization(ingore = true)
    @ApiOperation(httpMethod = "GET", value = "重点装备详情", notes = "重点装备详情")
    @GetMapping(value = "/detail/{equipmentId}", produces = "application/json;charset=UTF-8")
    public CommonResponse findEquipDetail(@PathVariable Long equipmentId) {
        return CommonResponseUtil.success(iEquipService.findEquipDetailsById(getToken(),getProduct(),getAppKey(),equipmentId));
    }

    /**
     * 获取所有重点装备
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    //@Authorization(ingore = true)
    @ApiOperation(httpMethod = "GET", value = "获取所有重点装备无分页", notes = "获取所有重点装备无分页")
    @GetMapping(value = "/all", produces = "application/json;charset=UTF-8")
    public CommonResponse findAll() {
        return CommonResponseUtil.success(iEquipService.findAll());
    }

//	
//	@ApiOperation(httpMethod = "POST",value = "添加重点设备", notes = "添加重点设备")
//	@RequestMapping(value = "/point", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
//	public CommonResponse point(@RequestBody List<EquipmentPlanPoint> point)  throws Exception{
//		iEquipService.savePlanPoint(point);
//		return CommonResponseUtil.success();
//	}
//	
//	@ApiOperation(httpMethod = "DELETE",value = "删除重点设备", notes = "查询单个重点设备")
//	@RequestMapping(value = "/point/{ids}", produces = "application/json;charset=UTF-8", method = RequestMethod.DELETE)
//	public CommonResponse deletePoint(@PathVariable Long[]  ids) throws Exception {
//		iEquipService.deletePoints(ids);
//		return CommonResponseUtil.success();
//	}

    /**
     * 获取设备数据
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    //@Authorization(ingore = true)
    @ApiOperation(httpMethod = "GET", value = "获取设备数据", notes = "获取设备数据")
    @RequestMapping(value = "/queryEquipmentDate/{code}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse queryEquipmentData(@PathVariable String code) {
        return CommonResponseUtil.success(iEquipService.findFireEquipDataByPointCode(code));
    }

    /**
     * 模板下载
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/downTemplate")
    @ApiOperation(httpMethod = "GET", value = "下载模板", notes = "下载模板")
    public void downTemplate(HttpServletResponse response) {
        ExcelUtils.exportExcel(new ArrayList<EquipmentExcelData>(), "电力设备信息", "导入模板", EquipmentExcelData.class, "电力设备模板.xls", response);
    }

    /**
     * 电力设备信息导入
     *
     * @return
     */
    @RequestMapping(value = "/uploadList")
    @ApiOperation(httpMethod = "POST", value = "导入", notes = "导入")
    public Object uploadList(MultipartFile file) {
        List<EquipmentExcelData> list = ExcelUtils.importExcel(file, 1, 1, EquipmentExcelData.class);
        iEquipService.uploadList(list, getOrgCode(getSelectedOrgInfo()));
        return CommonResponseUtil.success();
    }

}
