package com.house365.ws.interfaces.rest;

import com.google.common.base.Strings;
import com.house365.beans.entity.ProjectEntity;
import com.house365.beans.system.QueryParams;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.IllegalServiceParameterException;
import com.house365.rest.exception.ServiceRunException;
import com.house365.rest.parameter.House365RestObject;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.ws.service.interfaces.ICustomerProjectService;
import com.house365.ws.service.interfaces.IProjectService;
import com.house365.ws.system.ReturnAppResult;
import com.house365.ws.util.Constant;
import com.house365.ws.util.OperateLogUtils;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service("updateProjectInfo")
public class UpdateProjectInfoImpl implements UpdateProjectInfo {

    private static final Logger LOGGER = LoggerFactory.getLogger("sysLog");

    @Autowired
    IProjectService<ProjectEntity> projectService;

    @Autowired
    ICustomerProjectService customerProjectService;

    @Autowired
    private OperateLogUtils logUtils;

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<ProjectEntity> response = new House365RestResponse<>();
        // 业务校验统一入口
        try {
            checkInterfaceParameter(map, Constant.ProjectContractCode);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }
        // 业务层统一处理
        try {
            House365RestObject<ProjectEntity> data = doBusiness(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        return result;
    }

    @Transactional
    private House365RestObject<ProjectEntity> doBusiness(Map<String, Object> map) throws Exception {
        House365RestObject<ProjectEntity> restObject = new House365RestObject<>();
        String contractCode = ((String[]) map.get(Constant.PROJECT_CONTRACT_CODE))[0];
        QueryParams<ProjectEntity> queryParams = new QueryParams<>();
        Map<String, Object> paraMap = new HashMap<>(10);
        paraMap.put("EQ_contractCode", contractCode);
        queryParams.setSearchParams(paraMap);
        queryParams.setLimit(1);
        List<ProjectEntity> projects = projectService.queryByPage(queryParams);
        ProjectEntity entity = null;
        if (projects.size() > 0) {
            entity = new ProjectEntity();
            BeanUtils.copyProperties(entity, map);
            int id = projects.get(0).getId();
            entity.setId(id);

            //记录项目更新日志
            ProjectEntity oldEntity = projectService.getById(id);
            projectService.update(entity);
            ProjectEntity newEntity = projectService.getById(id);
            logUtils.recordOperateLog(oldEntity, newEntity, id, 0, "updateProjectInfo接口");
            //更新客户项目表中项目名称
            if (null != entity.getId()) {
                customerProjectService.updateName(entity.getId(), Strings.isNullOrEmpty(
                        entity.getProjectName()) ? "" : entity.getProjectName());
            }
        } else {
            throw new RuntimeException("项目不存在，合同号为" + contractCode);
        }
        return restObject;
    }

    /**
     * 业务层统校验自己所需参数是否存在 所有参数都要存在
     *
     * @author hqc
     */
    protected void checkInterfaceParameter(
            Map<String, Object> map, String[] checkParams
    ) throws IllegalServiceParameterException {
        // 方法所需参数
        for (String str : checkParams) {
            // 如果不存在跳出 同时抛出相应异常
            if (!map.containsKey(str)) {
                throw new IllegalServiceParameterException("业务入口参数异常：" + str + "参数为空!");
            }
        }
    }

    @Override
    public boolean isControlService() {
        return false;
    }

    @Override
    public boolean isLogService() {
        return false;
    }

    @Override
    public boolean isMonitorService() {
        return false;
    }

    @Override
    public Object rollback() {
        return null;
    }

    @Override
    public void commit() {
    }

}
