package com.palmnest.webapp.controller.backstage;

import cn.superdesk.libs.common.json.JsonUtils;

import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.AppConstants;
import com.palmnest.application.Constants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.core.util.HttpKit;
import com.palmnest.application.core.util.PropertiesKit;
import com.palmnest.application.dto.OrgDto;
import com.palmnest.application.dto.WebPageResultDto;
import com.palmnest.application.dto.input.RepairTypeDetialDto;
import com.palmnest.application.dto.output.ElementDto;
import com.palmnest.application.dto.output.RepairParamDto;
import com.palmnest.model.Element;
import com.palmnest.model.OrgElement;
import com.palmnest.model.User;
import com.palmnest.service.AppUserService;
import com.palmnest.service.ElementGroupManager;
import com.palmnest.service.repair.RepairBillManager;

import org.apache.commons.lang.StringUtils;
import org.directwebremoting.util.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import scala.annotation.meta.param;

import javax.servlet.http.HttpServletRequest;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 服务之窗1L- RepairBillTypeController
 *
 * @Description TODO
 * @author: jiangyong
 * @since: 2020/8/11 15:20
 */
@Controller
@RequestMapping(value = "/repairType")
public class RepairTypeController {
    private Logger LOG = Logger.getLogger(RepairTypeController.class);
    private String hostUrl = PropertiesKit.readPropertiesValue("hostUrl", "wechat.properties");

    @Autowired
    private RepairBillManager repairBillManager;
    @Autowired
    private AppUserService appUserService;
    @Autowired
    private ElementGroupManager elementGroupManager;

    /**
     * 维修类型页跳转
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/maintenanceTypeManger")
    public ModelAndView repairDetail(HttpServletRequest request) {
        //报修方式 区域 类型 小类型
        Model model = new ExtendedModelMap();
        return new ModelAndView("/admin/engineeringRepair/maintenanceTypeManger", model.asMap());
    }


    /**
     * 查询维修类列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public WebPageResultDto getRepairTypeList(HttpServletRequest request) throws Exception {

        LOG.info("RepairBillTypeController.getRepairTypeList");

        int pageSize = Integer.parseInt(StringUtils.trim(request.getParameter("limit")));
        int pageNo = Integer.parseInt(StringUtils.trim(request.getParameter("page")));
        String orgId = request.getParameter("orgId");
        String groupName = request.getParameter("groupName");
        String groupCode = request.getParameter("groupCode");
        String itemCode = request.getParameter("itemCode");
        String itemName = request.getParameter("itemName");

        Map<String, String> param = new HashMap<>();
        param.put("orgId", orgId == null ? "" : orgId);
        param.put("groupName", groupName == null ? "" : groupName);
        param.put("groupCode1", groupCode == null ? "" : groupCode);
        param.put("itemCode", itemCode == null ? "" : itemCode);
        param.put("itemName", itemName == null ? "" : itemName);

        //请求新框架服务
        StringBuilder paramStr = new StringBuilder();
        paramStr.append("&orgId=").append(orgId)
                .append("&pageNo=").append(pageNo)
                .append("&pageSize=").append(pageSize);

        if (StringUtils.isNotEmpty(itemCode)) {
            paramStr.append("&itemCode=").append(itemCode);
        }
        if (StringUtils.isNotEmpty(itemName)) {
            paramStr.append("&itemName=").append(itemName);
        }
        if (StringUtils.isNotEmpty(groupCode)) {
            paramStr.append("&groupCode=").append(groupCode);
        }
        if (StringUtils.isNotEmpty(groupName)) {
            paramStr.append("&groupName=").append(groupName);
        }

        String url = hostUrl + "/super_cloud/api/basesetting/repairType/list";

        String result = HttpKit.Post(paramStr.toString(), url);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject.getString("code").equals("200")) {
            String dataStr = jsonObject.getString("data");
            List<Map> items = JsonUtils.toList(dataStr, Map.class);

            WebPageResultDto dto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", items);
            dto.setCount(Long.parseLong(jsonObject.getString("count")));
            return dto;
        } else {
            WebPageResultDto dto = repairBillManager.findAllTree(pageNo, pageSize, param, Constants.REPAIR_TYPE_CODE);
            return dto;
        }
    }


    @RequestMapping(value = "/getTypeList")
    @ResponseBody
    public WebPageResultDto getTypeList(HttpServletRequest request) {
        String orgId = request.getParameter("orgId");
        LOG.info("RepairBillTypeController.getTypeList orgId:{" + orgId + "}");

        if (!StringUtils.isNotEmpty(orgId)) {
            return new WebPageResultDto(AppConstants.REPAIR_BILL_TYPE_LIST_ERROR, "项目id不能为空", null);
        }

        RepairParamDto dto = new RepairParamDto();
        //大类
        List<ElementDto> elementDtos = elementGroupManager.getOrgElementGroupInfoV2(orgId, Constants.REPAIR_TYPE_CODE);
        dto.setRepairTypeGroup(elementDtos);

        if (null != elementDtos && elementDtos.size() > 0) {
            //小类
            List<Element> repairTypeaDetailGroup = elementGroupManager.getElementsByGroupName(elementDtos.get(0).getItemcode());
            dto.setRepairTypeaDetailGroup(elementGroupManager.convert(repairTypeaDetailGroup));
        }
        return new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", dto);
    }

    @RequestMapping(value = "/getTypeItemList")
    @ResponseBody
    public AppResultDto getTypeItemList(@RequestParam("repairTypeId") Long repairTypeId) {
        LOG.info("RepairBillTypeController.getTypeItemList repairTypeId:{" + repairTypeId + "}");
        Element       element                = elementGroupManager.getElementId(repairTypeId);
        List<Element> repairTypeaDetailGroup = elementGroupManager.getElementsByGroupName(element.getItemcode());
        return AppResultUtil.createSuccesDto(repairTypeaDetailGroup);
    }
    /**
     * 获取大类小类详情
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getDetail")
    @ResponseBody
    public WebPageResultDto getDetail(HttpServletRequest request) {
        String orgId = request.getParameter("orgId");
        String itemId = request.getParameter("id");

        LOG.info("RepairBillTypeController.getDetail orgId:{" + orgId + "},id:{" + itemId + "}");

        if (!StringUtils.isNotEmpty(orgId)) {
            return new WebPageResultDto(AppConstants.REPAIR_BILL_TYPE_LIST_ERROR, "项目id不能为空", null);
        }

        if (!StringUtils.isNotEmpty(itemId)) {
            return new WebPageResultDto(AppConstants.REPAIR_BILL_TYPE_LIST_ERROR, "大类id不能为空", null);
        }
        
        try{
        	if(StringUtils.isNotBlank(itemId)){
            	Integer.parseInt(itemId);
            }
        	if(StringUtils.isNotBlank(orgId)){
            	Integer.parseInt(orgId);
            }
        }catch(Exception e){
        	 WebPageResultDto dto = new WebPageResultDto(AppConstants.ERROR_CODE, "参数异常", null);
             return dto;
        }

        //请求新框架服务
        RepairTypeDetialDto dto;
        String url = hostUrl + "/super_cloud/api/basesetting/repairType/getDetail";

        StringBuilder paramStr = new StringBuilder();
        paramStr.append("&orgId=").append(orgId)
                .append("&id=").append(itemId);

        String result = HttpKit.Post(paramStr.toString(), url);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject.getString("code").equals("200")) {
            String dataStr = jsonObject.getString("data");
            dto = JsonUtils.toObject(dataStr, RepairTypeDetialDto.class);
        } else {
            dto = repairBillManager.getDetail(itemId, orgId);
        }

        return new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", dto);
    }

    /**
     * 保存维修类型 （新增大类，小类，修改大类小类，删除小类）
     *
     * @param param
     * @param request
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public WebPageResultDto save(@RequestBody RepairTypeDetialDto param, HttpServletRequest request) {
        LOG.info("RepairBillTypeController.save \n " + JsonUtils.toJson(param));
        User user = (User) request.getSession().getAttribute("UserCache");

        if (StringUtils.isEmpty(param.getItemCode())) {
            return new WebPageResultDto(AppConstants.REPAIR_BILL_LIST_ERROR, "大类编号不能为空", null);
        }

        if (StringUtils.isEmpty(param.getItemName())) {
            return new WebPageResultDto(AppConstants.REPAIR_BILL_LIST_ERROR, "大类名称不能为空", null);
        }

        if (null==param.getOrgId()) {
            return new WebPageResultDto(AppConstants.REPAIR_BILL_LIST_ERROR, "项目不能为空", null);
        }
        //请求新框架服务
        String url = hostUrl + "/super_cloud/api/basesetting/repairType/save";

        StringBuilder paramStr = new StringBuilder();
        paramStr.append("&param=").append(JsonUtils.toJson(param));

        String result = HttpKit.Post(paramStr.toString(), url);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if("400".equals(jsonObject.getString("code"))){
        	WebPageResultDto dto = new WebPageResultDto(AppConstants.ERROR_CODE, jsonObject.getString("msg"), null);
            return dto;
        }else if (!"200".equals(jsonObject.getString("code"))) {
        	Element oe=repairBillManager.findByCodeAndId(param.getItemCode(), param.getOrgId(),param.getItemId());
        	if(null!=oe){
        		return new WebPageResultDto(AppConstants.REPAIR_BILL_LIST_ERROR, "大类编码不能重复", null);
        	}
            repairBillManager.saveRepair(param, user);
        }
        WebPageResultDto dto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", null);
        return dto;
    }

    /***
     * 删除维修大类
     * @param request
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public WebPageResultDto delete(HttpServletRequest request) {
        //大类id
        String itemId = request.getParameter("itemId");
        String orgId = request.getParameter("orgId");
        LOG.info("RepairBillTypeController.delete itemId：" + itemId+";orgId:"+orgId);
        User user = (User) request.getSession().getAttribute("UserCache");
        
        try{
        	if(StringUtils.isNotBlank(itemId)){
            	Integer.parseInt(itemId);
            }
        	if(StringUtils.isNotBlank(orgId)){
            	Integer.parseInt(orgId);
            }
        }catch(Exception e){
        	 WebPageResultDto dto = new WebPageResultDto(AppConstants.ERROR_CODE, "参数异常", null);
             return dto;
        }
        

        //请求新框架服务
        String url = hostUrl + "/super_cloud/api/basesetting/repairType/delete";

        StringBuilder paramStr = new StringBuilder();
        paramStr.append("&itemId=").append(itemId).append("&orgId=").append(orgId);

        String result = HttpKit.Post(paramStr.toString(), url);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (!jsonObject.getString("code").equals("200")) {
            repairBillManager.delete(itemId, user);
        }

        WebPageResultDto dto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", null);
        return dto;
    }


}
