package com.yeejoin.equipmanage.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import com.yeejoin.equipmanage.common.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.equipmanage.common.dto.MaintenanceResourceDataDto;
import com.yeejoin.equipmanage.common.entity.MaintenanceResourceData;
import com.yeejoin.equipmanage.common.entity.publics.CommonResponse;
import com.yeejoin.equipmanage.common.utils.CommonResponseUtil;
import com.yeejoin.equipmanage.common.utils.NameUtils;
import com.yeejoin.equipmanage.common.vo.MaintenanceResourceDataVo;
import com.yeejoin.equipmanage.service.IMaintenanceResourceDataService;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 消防设施资源数据Controller
 *
 * @author gaojianqiang
 * @date 2021-07-16
 */
@RestController
@RequestMapping("/maintenanceResourceData")
public class MaintenanceResourceDataController extends AbstractBaseController {

    @Autowired
    private IMaintenanceResourceDataService maintenanceResourceDataService;

    /**
     * 查询维保设施资源数据列表
     */
    @GetMapping("/list")
    public ResponseModel list(MaintenanceResourceData maintenanceResource) {
//        startPage();
        List<MaintenanceResourceData> list = maintenanceResourceDataService.selectMaintenanceResourceDataList(maintenanceResource);
        return CommonResponseUtil.success(list);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "导出维保设施资源数据列表", notes = "导出维保设施资源数据列表")
    @PostMapping(value = "/export")
    public void export(HttpServletResponse response, @RequestBody List<Long> ids) throws IOException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
        MaintenanceResourceDataVo vo = new MaintenanceResourceDataVo();
     //   ExcelUtils.exportExcel(list, "消防维保", "消防维保信息", MaintenanceResourceDataVo.class, simpleDateFormat.format(new Date()) + ".xls", response);
      /*bug3088 维保设施（业），数据无法成功导出 chenzhao 2021-10-13 */
        String fileName = simpleDateFormat.format(new Date()) ;
        response.setContentType("multipart/form-data");
        response.setCharacterEncoding("utf-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName+ ".xlsx");
        String sheetName = "消防维保信息";
        ExcelWriter writer = new ExcelWriter(response.getOutputStream(), ExcelTypeEnum.XLSX);
        Sheet sheet = new Sheet(1, 0,MaintenanceResourceDataVo.class);
        List<MaintenanceResourceDataVo> list = maintenanceResourceDataService.findByIds(ids);
        sheet.setSheetName(sheetName);
        writer.write(list, sheet);
        writer.finish();
        /*bug3088 维保设施（业），数据无法成功导出 chenzhao 2021-10-13 */
    }

    /**
     * 获取维保设施资源数据详细信息
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/{id}")
    public ResponseModel getInfo(@PathVariable("id") Long id) {
        return CommonResponseUtil.success(maintenanceResourceDataService.selectMaintenanceResourceDataById(id));
    }

    /**
     * 新增维保设施资源数据
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping
    public ResponseModel add(@RequestBody MaintenanceResourceData maintenanceResource) {
        return CommonResponseUtil.success(maintenanceResourceDataService.insertMaintenanceResourceData(maintenanceResource));
    }

    /**
     * 修改维保设施资源数据
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PutMapping
    public ResponseModel edit(@RequestBody MaintenanceResourceData maintenanceResource) {
        return CommonResponseUtil.success(maintenanceResourceDataService.updateMaintenanceResourceData(maintenanceResource));
    }

    /**
     * 获取维保消防设施选择列表
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getMaintenanceResourceDataList")
    public ResponseModel getMaintenanceResourceDataList() {
        String orgCode = getOrgCode();
        return CommonResponseUtil.success(maintenanceResourceDataService.getMaintenanceResourceDataList(orgCode));
    }

    /**
     * 删除维保设施资源数据
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @DeleteMapping("/{ids}")
    public ResponseModel remove(@PathVariable Long[] ids) {
        return CommonResponseUtil.success(maintenanceResourceDataService.deleteMaintenanceResourceDataByIds(ids));
    }

    /**
     * 业主单位批量关联消防设施，反推已有消防系统
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping("/relationMainResData")
    public ResponseModel relationMainResData(@RequestBody List<MaintenanceResourceData> list) {
        return CommonResponseUtil.success(maintenanceResourceDataService.relationMainResData(getAppKey(), getProduct(), getToken(), list));
    }

    /**
     * 列表分页查询
     *
     * @return
     */
    @RequestMapping(value = "/page", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
    public IPage<MaintenanceResourceData> listPage(Integer pageNum, Integer pageSize, MaintenanceResourceDataVo resourceData) {
        MaintenanceResourceData data = new MaintenanceResourceData();
        List<Long> buildingIds = resourceData.getBuildingIds();
        BeanUtils.copyProperties(resourceData, data);
        Page<MaintenanceResourceData> pageBean;
        QueryWrapper<MaintenanceResourceData> queryWrapper = new QueryWrapper<>();
        Class<? extends MaintenanceResourceData> aClass = data.getClass();
        Arrays.stream(aClass.getDeclaredFields()).forEach(field -> {
            try {
                field.setAccessible(true);
                Object o = field.get(data);
                if (o != null) {
                    Class<?> type = field.getType();
                    String name = NameUtils.camel2Underline(field.getName());
                    Object o1 = field.get(data);
                    if (o1 != null && !"".equals(o1)) {
                        if (type.equals(Integer.class)) {
                            Integer fileValue = (Integer) field.get(data);
                            queryWrapper.eq(name, fileValue);
                        } else if (type.equals(Long.class)) {
                            Long fileValue = (Long) field.get(data);
                            queryWrapper.eq(name, fileValue);
                        } else if (type.equals(String.class)) {
                            String fileValue = (String) field.get(data);
                            queryWrapper.like(name, fileValue);
                        } else {
                            String fileValue = (String) field.get(data);
                            queryWrapper.eq(name, fileValue);
                        }
                    }
                }
            } catch (Exception e) {
            }
        });

        if (!CollectionUtils.isEmpty(buildingIds)) {
            queryWrapper.in("building_id", buildingIds);
        }
        IPage<MaintenanceResourceData> page;
        if (pageNum != null && pageSize != null) {
            pageBean = new Page<>(pageNum, pageSize);
        } else {
            pageBean = new Page<>(0, Long.MAX_VALUE);
        }
        page = maintenanceResourceDataService.page(pageBean, queryWrapper);
        page.getRecords().stream().forEach(e->{
            String add = "";
            if (!ValidationUtil.isEmpty(e.getBuildingName())){
                 add = add+e.getBuildingName();
             };
             if (!ValidationUtil.isEmpty(e.getLocation())){
                 add = add+e.getLocation();
             }
            e.setLocation(add);
        }
        );
        return page;
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation("获取移动端维保设施分类分页")
    @GetMapping(value = "/getClassifyPage")
    public IPage<MaintenanceResourceDataDto> getClassifyPage(
            @RequestParam(value = "current") int current,
            @RequestParam(value = "size") int size,
            @RequestParam(required = false) Long maintenanceCompanyId,
            @RequestParam(required = false) Long ownerUnitId,
            @RequestParam(required = false) Long fireFightSysId,
            @RequestParam(required = false) String expirationTimeSort) {
        Page page = new Page();
        page.setCurrent(current);
        if (-1 == size) {
            page.setSize(Integer.MAX_VALUE);
        } else {
            page.setSize(size);
        }
        return maintenanceResourceDataService.getClassifyPage(page, maintenanceCompanyId, ownerUnitId, fireFightSysId, expirationTimeSort);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation("获取移动端维保设施分页")
    @GetMapping(value = "/getFireFacilityPage")
    public IPage<MaintenanceResourceDataDto> getFireFacilityPage(
            @RequestParam(value = "current") int current,
            @RequestParam(value = "size") int size,
            @RequestParam(required = false) Long maintenanceCompanyId,
            @RequestParam(required = false) Long ownerUnitId,
            @RequestParam(required = false) Long fireFightSysId,
            @RequestParam(required = false) Long classifyId,
            @RequestParam(required = false) List<Long> buildingId,
            @RequestParam(required = false) String status) {
        Page page = new Page();
        page.setCurrent(current);
        if (-1 == size) {
            page.setSize(Integer.MAX_VALUE);
        } else {
            page.setSize(size);
        }
        return maintenanceResourceDataService.getFireFacilityPage(page, maintenanceCompanyId, ownerUnitId, fireFightSysId, classifyId, buildingId, status);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation("获取移动端维保信息分页")
    @GetMapping(value = "/getMaintenanceInfoPage")
    public CommonResponse getMaintenanceInfoPage(
            @RequestHeader String appKey,
            @RequestHeader String product,
            @RequestHeader String token,
            @ApiParam(value = "查询范围") @RequestParam(value = "userId", required = false) String userId,
            @ApiParam(value = "时间范围") @RequestParam(value = "timeType", required = false) String timeType,
            @ApiParam(value = "维保结果") @RequestParam(value = "result", required = false) String result,
            @ApiParam(value = "排序规则") @RequestParam(value = "orderRule", required = false) String orderRule,
            @ApiParam(value = "开始时间") @RequestParam(value = "beginTime", required = false) String beginTime,
            @ApiParam(value = "结束时间") @RequestParam(value = "endTime", required = false) String endTime,
            @ApiParam(value = "维保人员") @RequestParam(value = "personId", required = false) String person,
            @ApiParam(value = "业主单位") @RequestParam(value = "teamId", required = false) String teamId,
            @ApiParam(value = "设施Id") @RequestParam(value = "equipId", required = false) String equipId,
            @ApiParam(value = "当前页") @RequestParam(value = "pageNumber") int pageNumber,
            @ApiParam(value = "页大小") @RequestParam(value = "pageSize") int pageSize) {
        return maintenanceResourceDataService.getMaintenanceInfoPage(appKey, product, token, userId, timeType, result, orderRule, beginTime, endTime, person, teamId, equipId, pageNumber, pageSize);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation("获取移动端维保设施集合")
    @GetMapping(value = "/getFireFacilityList")
    public List<MaintenanceResourceData> getFireFacilityList(
            @RequestParam(required = false) Integer type,
            @RequestParam(required = false) Long id) {
        return maintenanceResourceDataService.getFireFacilityList(id, type);
    }

}
