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

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.ObjectUtils;
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.RequestBody;
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.springframework.web.multipart.MultipartFile;

import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.maintenance.business.dao.repository.IInputItemDao;
import com.yeejoin.amos.maintenance.business.param.InputItemPageParam;
import com.yeejoin.amos.maintenance.business.param.InputItemParam;
import com.yeejoin.amos.maintenance.business.service.intfc.IInputItemService;
import com.yeejoin.amos.maintenance.business.util.CommonResponse;
import com.yeejoin.amos.maintenance.business.util.CommonResponseUtil;
import com.yeejoin.amos.maintenance.business.util.DaoCriteria;
import com.yeejoin.amos.maintenance.business.util.ExcelUtils;
import com.yeejoin.amos.maintenance.business.util.InputItemParamUtil;
import com.yeejoin.amos.maintenance.business.vo.InputItemTemplateVo;
import com.yeejoin.amos.maintenance.business.vo.InputItemVo;
import com.yeejoin.amos.maintenance.business.vo.PointInputItemVo;
import com.yeejoin.amos.maintenance.common.enums.DictTypeEnum;
import com.yeejoin.amos.maintenance.core.common.request.CommonPageable;
import com.yeejoin.amos.maintenance.core.common.request.CommonRequest;
import com.yeejoin.amos.maintenance.core.enums.QueryOperatorEnum;
import com.yeejoin.amos.maintenance.core.framework.Permission;
import com.yeejoin.amos.maintenance.core.util.StringUtil;
import com.yeejoin.amos.maintenance.dao.entity.InputItem;

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

/**
 * 检查项
 *
 * @author gaodongdong
 */
@RestController
@RequestMapping(value = "/api/inputItem")
@Api(tags = "巡检项api")
public class InputItemController extends AbstractBaseController {

    private final Logger log = LoggerFactory.getLogger(InputItemController.class);

    @Autowired
    IInputItemService inputItemService;
    @Autowired
    IInputItemDao inputItemDao;

    /**
     * 新增巡检项
     *
     * @param param
     * @return
     */
    @Permission
    @ApiOperation(value = "新增检查项", notes = "新增检查项")
    @RequestMapping(value = "/addItem", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse addNewItem(@ApiParam(value = "检查项信息") @RequestBody InputItemParam param) {
        if (ObjectUtils.isEmpty(param.getId())) {
            return updateItem(param);
        }
        AgencyUserModel user = getUserInfo();
        if (ObjectUtils.isEmpty(user)) {
            return CommonResponseUtil.failure("用户session过期");
        }
        try {
            InputItem inputItem = new InputItem();
            ReginParams reginParams = getSelectedOrgInfo();
            String loginOrgCode = getLoginOrgCode(reginParams);
            BeanUtils.copyProperties(param, inputItem);
            inputItem.setOrgCode(loginOrgCode);
            inputItem.setCreateBy(user.getUserId());
            inputItemService.addNewInputItem(inputItem);
            return CommonResponseUtil.success();
        } catch (Exception e) {
            return CommonResponseUtil.failure("检查项新增失败: " + e.getMessage());
        }
    }

    /**
     * 查询巡检项详情
     *
     * @param itemID
     * @return
     */
    @Permission
    @ApiOperation(value = "检查项ID", notes = "检查项详情")
    @RequestMapping(value = "/queryItem", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse queryItemDetail(@ApiParam(value = "巡检项ID") @RequestParam(required = true) Long itemID) {
        InputItem bo = inputItemService.queryInputItemDetail(itemID);
        return CommonResponseUtil.success(bo);
    }

    /**
     * @param param
     * @return
     */
    @Permission
    @ApiOperation(value = "更新检查项", notes = "更新检查项")
    @RequestMapping(value = "/updateItem", produces = "application/json;charset=UTF-8", method = RequestMethod.PUT)
    public CommonResponse updateItem(@ApiParam(value = "检查项详情", required = false) @RequestBody InputItemParam param) {
        if (ObjectUtils.isEmpty(param.getId())) {
            return addNewItem(param);
        }
        AgencyUserModel user = getUserInfo();
        if (ObjectUtils.isEmpty(user)) {
            return CommonResponseUtil.failure("用户session过期");
        }
        try {
            InputItem inputItem = new InputItem();
            BeanUtils.copyProperties(param, inputItem);
            inputItem.setId(param.getId());
            inputItemService.updateInputItem(inputItem);
            return CommonResponseUtil.success();
        } catch (Exception e) {
            return CommonResponseUtil.failure("检查项新增失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除检查项
     *
     * @param
     * @return
     */
    @Permission
    @ApiOperation(value = "批量删除检查项", notes = "批量删除检查项")
    @RequestMapping(value = "/batchDelItem", produces = "application/json;charset=UTF-8", method = RequestMethod.DELETE)
    public CommonResponse batchDelItem(
            @ApiParam(value = "巡检项ID(检查项id以英文半角逗号分割。如： 1,2)") @RequestParam(required = true) String itemIDs) {
        try {
            if (ObjectUtils.isEmpty(itemIDs)) {
                return CommonResponseUtil.failure("请选择要删除的检查项");
            }
            String[] ids = itemIDs.split(",");
            inputItemService.batchDelInputItem(ids);
            return CommonResponseUtil.success();
        } catch (Exception e) {
            return CommonResponseUtil.failure("检查项新增失败: " + e.getMessage());
        }
    }

    /**
     * 删除检查项
     *
     * @param itemID
     * @return
     */
    @Permission
    @ApiOperation(value = "删除检查项", notes = "删除检查项")
    @RequestMapping(value = "/delItem", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse delItem(@ApiParam(value = "巡检项ID") @RequestParam(required = true) Long itemID) {
        try {
            inputItemService.delInputItem(itemID);
            return CommonResponseUtil.success();
        } catch (Exception e) {
            return CommonResponseUtil.failure("检查项新增失败: " + e.getMessage());
        }
    }

    /**
     * 检查项另存为
     *
     * @param
     * @return
     */
    @Permission
    @ApiOperation(value = "检查项另存为", notes = "检查项另存为")
    @RequestMapping(value = "/saveAs", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse saveAs(@ApiParam(value = "巡检项ID") @RequestParam(required = true) String itemIDs) {
        AgencyUserModel user = getUserInfo();
        if (ObjectUtils.isEmpty(user)) {
            return CommonResponseUtil.failure("用户session过期");
        }
        try {
            if (ObjectUtils.isEmpty(itemIDs)) {
                return CommonResponseUtil.failure("请选择要另存的检查项");
            }
            String[] ids = itemIDs.split(",");
            inputItemService.saveAs(ids, user.getUserId());
            return CommonResponseUtil.success();
        } catch (Exception e) {
            return CommonResponseUtil.failure("检查项另存为失败: " + e.getMessage());
        }
    }

    /**
     * 分页查询检查项
     *
     * @param queryRequests
     * @param pageable
     * @return
     */
    @Permission
    @ApiOperation(value = "分页查询检查项", notes = "分页查询检查项")
    @RequestMapping(value = "/queryItemByPage", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse queryItemByPage(
            @ApiParam(value = "组合查询条件", required = false, defaultValue = "[]") @RequestBody(required = false) List<CommonRequest> queryRequests,
            @ApiParam(value = "分页参数", required = false, defaultValue = "current=0&pageSize=10或pageNumber0&pageSize=10") CommonPageable pageable) {
        ReginParams reginParams = getSelectedOrgInfo();
        String loginOrgCode = getLoginOrgCode(reginParams);
        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("orgCode", loginOrgCode);
        InputItemPageParam criterias = InputItemParamUtil.fillInputItemPageParam(queryRequests, pageable, paramMap);
        Page<InputItemVo> page = inputItemService.queryInputItemByPage(criterias);
        return CommonResponseUtil.success(page);
    }

    /**
     * 条件查询检查项
     *
     * @param queryRequests
     * @return
     */
    @Permission
    @PostMapping(value = "/queryItemByCondition", produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "条件查询检查项", notes = "条件查询检查项")
    public CommonResponse queryItemByCondition(
            @ApiParam(value = "组合查询条件", required = false, defaultValue = "[]") @RequestBody(required = false) List<CommonRequest> queryRequests) {
        // 1.组织查询条件数据
        ReginParams reginParams = getSelectedOrgInfo();
        String loginOrgCode = getLoginOrgCode(reginParams);
        List<DaoCriteria> criterias = buildDaoCriterias(queryRequests, false, loginOrgCode, null);
        // 2.组织数据权限过滤条件，基础数据不管roleType，全按照选择的公司orgCode过滤
        DaoCriteria compDaoCriteria = new DaoCriteria();
        compDaoCriteria.setPropertyName("orgCode");
        compDaoCriteria.setOperator(QueryOperatorEnum.EQUAL.getName());
        compDaoCriteria.setValue(loginOrgCode);
        criterias.add(compDaoCriteria);
        List<InputItem> list = inputItemService.queryInputItemByCondition(criterias);
        return CommonResponseUtil.success(list);
    }

    /**
     * 条件查询检查项
     *
     * @param params
     * @return
     */
    @Permission
    @PostMapping(value = "/queryCustomInputItem", produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "条件查询检查项", notes = "条件查询检查项")
    public CommonResponse queryCustomInputItem(@RequestBody HashMap<String, Object> params) {
        ReginParams reginParams = getSelectedOrgInfo();
        String orgCode = getLoginOrgCode(reginParams);
        List<PointInputItemVo> list = inputItemService.queryCustomInputItem(params, orgCode);
        return CommonResponseUtil.success(list);
    }

    /**
     * 条件查询检查项
     *
     * @param queryRequests 查询条件
     * @return
     */
    @Permission
    @PostMapping(value = "/queryItemByCondition1", produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "条件查询检查项", notes = "条件查询检查项")
    public CommonResponse queryItemByCondition1(
            @ApiParam(value = "组合查询条件", required = false, defaultValue = "[]") @RequestBody(required = false) List<CommonRequest> queryRequests) {
        // 组织数据权限过滤条件，基础数据不管roleType，全按照选择的公司orgCode过滤
        ReginParams reginParams = getSelectedOrgInfo();
        String loginOrgCode = getLoginOrgCode(reginParams);
        List<InputItem> list = null;
        if (ObjectUtils.isEmpty(queryRequests)) {
            list = inputItemDao.findAllByLevel(loginOrgCode);
        } else {
            String level = null;
            for (CommonRequest quest : queryRequests) {
                if (quest.getName().equals("level")) {
                    if (StringUtil.isNotEmpty(quest.getValue())) {
                        //如果前台传过来等级条件为-0，数据库则存储为空
                        if (quest.getValue().toString().equals("-0")) {
                            level = null;
                        } else {
                            level = quest.getValue().toString();
                        }
                    }

                }
            }
            if (ObjectUtils.isEmpty(level)) {
                list = inputItemDao.findByLevelNull(loginOrgCode);
            } else {
                list = inputItemDao.findByLevel(loginOrgCode, level);
            }
        }
        return CommonResponseUtil.success(list);
    }

    /**
     * 查询检查项编号信息
     *
     * @param itemId        检查项id,如果为新增，则为-1
     * @param queryRequests 查询条件
     * @return
     */
    @Permission
    @ApiOperation(value = "查询巡检点编号信息", notes = "查询巡检点编号信息")
    @GetMapping(value = "/queryItemNo/{itemId}", produces = "application/json;charset=UTF-8")
    public CommonResponse queryItemNoList(
            @ApiParam(value = "巡检点id", required = true) @PathVariable(name = "itemId") Long itemId,
            @ApiParam(value = "查询条件", required = false) @RequestBody(required = false) List<CommonRequest> queryRequests) {
        ReginParams reginParams = getSelectedOrgInfo();
        String loginOrgCode = getLoginOrgCode(reginParams);
        if (ObjectUtils.isEmpty(reginParams)) {
            return CommonResponseUtil.failure("用户session过期");
        }
        try {
            CommonRequest commonRequest = new CommonRequest();
            commonRequest.setName("orgCode");
            commonRequest.setValue(loginOrgCode);
            if (queryRequests == null) {
                queryRequests = new ArrayList<>();
            }
            queryRequests.add(commonRequest);
            List<DaoCriteria> criterias = buildDaoCriterias(queryRequests, false, loginOrgCode, null);
            List<String> pointNoList = inputItemService.qryItemNoList(criterias, itemId);
            return CommonResponseUtil.success(pointNoList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResponseUtil.failure("查询检查项编号信息失败");
        }
    }


    @ApiOperation(value = "获取维保项分类", notes = "获取维保项分类")
    @GetMapping(value = "/classify")
    public CommonResponse getMaintenanceClassify() {
        return CommonResponseUtil.success(inputItemService.getMaintenanceClassify(getToken(), getProduct(), getAppKey(), DictTypeEnum.MAINTENANCE_CLASSIFY.getCode()));
    }

    /**
     * 下载模板
     *
     * @return
     * @Since 2021-3-10
     */
    @GetMapping(value = "/downTemplate")
    @ApiOperation(httpMethod = "POST", value = "下载模板", notes = "下载模板")
    public void downTemplate(HttpServletResponse response) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
        List<InputItemTemplateVo> inputItemTemplateVoList = new ArrayList<>();
        ExcelUtils.exportExcel(inputItemTemplateVoList, "维保内容", "维保内容", InputItemTemplateVo.class, simpleDateFormat.format(new Date()) + ".xls", response);
    }

    /**
     * 维保项内容导入
     *
     * @return
     * @Since 2021-3-10
     */
    @Permission
    @PostMapping(value = "/uploadListByTemplate")
    @ApiOperation(httpMethod = "POST", value = "维保项信息导入", notes = "维保项信息导入")
    public CommonResponse uploadListByTemplate(MultipartFile file) throws Exception {
        try {
            InputStream inputStream = null;
            Workbook workbook = null;
            inputStream = file.getInputStream();
            workbook = WorkbookFactory.create(inputStream);
            inputStream.close();
            Sheet sheet = workbook.getSheetAt(0);
            String a = sheet.getRow(0).getCell(0).getStringCellValue();
            String b = sheet.getRow(1).getCell(1).getStringCellValue();
            if (!"维保内容".equals(a) || !"维保项编号".equals(b)) {
                throw new Exception();
            }
        } catch (Exception e) {
            throw new Exception("请使用指定模板进行上传");
        }
        ReginParams reginParams = getSelectedOrgInfo();
        String orgCode = getLoginOrgCode(reginParams);
        String userId = getUserId();
        List<InputItemTemplateVo> itemTemplateVoList = ExcelUtils.importExcel(file, 1, 1, InputItemTemplateVo.class);
        return CommonResponseUtil.success(inputItemService.uploadListByTemplate(itemTemplateVoList, orgCode, userId));
    }
}
