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

import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.patrol.business.constants.XJConstant;
import com.yeejoin.amos.patrol.business.feign.JcsFeignClient;
import com.yeejoin.amos.patrol.business.param.PlanInfoPageParam;
import com.yeejoin.amos.patrol.business.service.intfc.IPlanService;
import com.yeejoin.amos.patrol.business.util.CommonResponse;
import com.yeejoin.amos.patrol.business.util.CommonResponseUtil;
import com.yeejoin.amos.patrol.business.util.PlanPageParamUtil;
import com.yeejoin.amos.patrol.core.common.request.CommonPageable;
import com.yeejoin.amos.patrol.core.common.request.CommonRequest;
import com.yeejoin.amos.patrol.dao.entity.Plan;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import javax.persistence.Column;
import java.util.*;

@RestController
@RequestMapping(value = "/api/plan")
@Api(tags = "巡检计划api")
public class PlanController extends AbstractBaseController {
    private final Logger log = LoggerFactory.getLogger(PlanController.class);
    @Autowired
    private IPlanService planService;

    @Autowired
    JcsFeignClient jcsFeignClient;

    /**
     * 新加接口
     *
     * **/
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "巡检计划查询", notes = "巡检计划查询")
    @RequestMapping(value = "/listNew", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse qryCheckInfoPageNew(@ApiParam(value = "查询条件", required = false)
                                              @RequestBody(required = false)PlanInfoPageParam queryRequests,
                                              @ApiParam(value = "分页参数", required = true) CommonPageable commonPageable) {
        ReginParams reginParams = getSelectedOrgInfo();

        queryRequests.setBizOrgCode(reginParams.getPersonIdentity().getCompanyBizOrgCode());
        if(commonPageable !=null){
            queryRequests.setPageNumber(commonPageable.getPageNumber()-1);
            queryRequests.setPageSize(commonPageable.getPageSize());
        }
        Page<HashMap<String, Object>> list = planService.getPlanInfo(queryRequests);
        return CommonResponseUtil.success(list);
    }





    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "查询计划列表(<font color='blue'>手机app</font>)", notes = "查询计划列表(<font color='blue'>手机app</font>)")
    @RequestMapping(value = "/queryPlanListNew", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse queryPlanListNew() {
        ReginParams reginParams = getSelectedOrgInfo();
        String loginOrgCode =reginParams.getPersonIdentity().getBizOrgCode();
        List<HashMap<String, Object>> list = planService.queryPlanListByOrgCode(loginOrgCode);
        return CommonResponseUtil.success(list);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "巡检计划查询", notes = "巡检计划查询")
    @RequestMapping(value = "/queryPlanByOrgCodeNew", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse qryCheckInfoNew() {

        PlanInfoPageParam param =new PlanInfoPageParam();
        ReginParams reginParams = getSelectedOrgInfo();
        param.setBizOrgCode(reginParams.getPersonIdentity().getBizOrgCode());
        List<HashMap<String, Object>> list = planService.getPlanInfoNoPage(param);
        return CommonResponseUtil.success(list);
    }











    /**
     * 巡检计划查询
     *
     * @param
     * @param param
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "巡检计划查询", notes = "巡检计划查询")
    @RequestMapping(value = "/list", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse qryCheckInfoPage(@ApiParam(value = "查询条件", required = false) @RequestBody(required = false) List<CommonRequest> queryRequests,
                                           @ApiParam(value = "分页参数", required = true) CommonPageable commonPageable) {
        ReginParams reginParams = getSelectedOrgInfo();
        String loginOrgCode = getOrgCode(reginParams);
        String roleTypeName = getRoleTypeName(reginParams);
        String deptId = "";
        String userId = "";

        HashMap<String, Object> paramMap = buildMybatisCriterias(loginOrgCode, roleTypeName);
        if (XJConstant.ROLE_NAME_DEPTADMIN.equals(roleTypeName)) {
            deptId = getDepartmentId(reginParams);
            if (deptId != null && !("").equals(deptId.trim()))
                paramMap.put("departmentId", deptId);
        } else if (XJConstant.ROLE_NAME_PERSON.equals(roleTypeName)) {
            userId = getUserId();
            if (userId != null && !("").equals(userId.trim()))
                paramMap.put("userId", userId);
        }
        PlanInfoPageParam param = PlanPageParamUtil.fillPlanInfoParam(queryRequests, commonPageable, paramMap);
        Page<HashMap<String, Object>> list = planService.getPlanInfo(param);
        return CommonResponseUtil.success(list);
    }

    /**
     * 巡检计划新增
     *
     * @param param
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "巡检计划新增及编辑", notes = "巡检计划新增及编辑")
    @RequestMapping(value = "/addPlan", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse checkPlanAdd(@ApiParam(value = "巡检计划", required = true) @RequestBody Plan param) {
        try {


            if ( param.getDayBegin().getTime()> param.getDayEnd().getTime()){
                throw new BadRequest("开始时间不能大于结束时间");
            }

            String userId = getUserId();
            ReginParams reginParams = getSelectedOrgInfo();
            String loginOrgCode = getOrgCode(reginParams);
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("org_code", loginOrgCode);
            map.put("user_id", userId);
            Map<String, String> deptMap = new HashMap<>();
            Set<String> departmentIds = new HashSet<>();
            List<String> depts = Arrays.asList(param.getUserDept().split(","));
            depts.stream().forEach(dept -> {
                deptMap.put(dept.substring(0, dept.indexOf("@")), dept.substring(dept.indexOf("@") + 1));
            });
            for (String entry : deptMap.keySet()) {
                String entryValue = deptMap.get(entry);
                departmentIds.add(entryValue);
            }

            StringBuffer departmentIdBuffer = new StringBuffer();
            Iterator<String> it = departmentIds.iterator();
            while (it.hasNext()) {
                departmentIdBuffer.append(it.next()).append(",");
            }

            if(departmentIds.size() > 0){
                FeignClientResult<List<Map<String, Object>>> departmentModeldate=   jcsFeignClient.selectByIdDeptList
                        (departmentIdBuffer.toString().substring(0, departmentIdBuffer.toString().length() - 1));
                List<Map<String, Object>> departmentModels = departmentModeldate.getResult();
                if(departmentModels!=null&&departmentModels.size()>0){
                    Map<String, Object> mapj= departmentModels.get(0);
                    param.setBizOrgCode(mapj.get("bizOrgCode").toString());
                    param.setBizOrgName(mapj.get("bizOrgName").toString());
                }
            }
            map.put("param", param);
            return CommonResponseUtil.success(planService.addPlan(map));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResponseUtil.failure("巡检计划新增失败");
        }
    }

    /**
     * 巡检计划删除（支持批量）
     *
     * @param param
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "删除巡检计划", notes = "删除巡检计划")
    @RequestMapping(value = "/deletePlanById", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse deletePlanById(
            @ApiParam(value = "巡检计划ID", required = true) @RequestParam Integer[] param) {
        try {
            planService.delPlanById(param);
            return CommonResponseUtil.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResponseUtil.failure("删除巡检计划失败");
        }
    }


    /**
     * 编辑巡检另存(支持批量)
     *
     * @param param
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "另存巡检计划", notes = "另存巡检计划")
    @RequestMapping(value = "/saveAs", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse planSaveAs(@ApiParam(value = "参数", required = true) @RequestParam Integer[] param) {
        try {
            planService.planSaveAs(param);
            return CommonResponseUtil.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResponseUtil.failure("另存巡检计划失败");
        }
    }

    /**
     * 根据id查询巡检计划
     *
     * @param id
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "查询巡检计划明细", notes = "查询巡检计划明细")
    @RequestMapping(value = "/detail/{id}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse queryPointById(@ApiParam(value = "计划id", required = true) @PathVariable(name = "id") Long id) {

        Plan plan = planService.queryPlanById(id);
        return CommonResponseUtil.success(plan);

    }

    /**
     * 巡检计划查询
     *
     * @param
     * @param param
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "巡检计划查询", notes = "巡检计划查询")
    @RequestMapping(value = "/queryPlanByOrgCode", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse qryCheckInfo(@ApiParam(value = "查询条件", required = false) @RequestBody(required = false) List<CommonRequest> queryRequests) {
        ReginParams reginParams = getSelectedOrgInfo();
        String roleTypeName = getRoleTypeName(reginParams);
        String loginOrgCode = getOrgCode(reginParams);
        HashMap<String, Object> paramMap = buildMybatisCriterias(loginOrgCode, roleTypeName);
        PlanInfoPageParam param = PlanPageParamUtil.fillPlanInfoParam(queryRequests, null, paramMap);
        List<HashMap<String, Object>> list = planService.getPlanInfoNoPage(param);
        return CommonResponseUtil.success(list);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "查询计划列表(<font color='blue'>手机app</font>)", notes = "查询计划列表(<font color='blue'>手机app</font>)")
    @RequestMapping(value = "/queryPlanList", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse queryPlanList() {
        ReginParams reginParams = getSelectedOrgInfo();
        String loginOrgCode = getOrgCode(reginParams);
        List<HashMap<String, Object>> list = planService.queryPlanListByOrgCode(loginOrgCode);
        return CommonResponseUtil.success(list);
    }

}
