package com.house365.ws.interfaces.rest;

import com.google.common.base.Strings;
import com.house365.beans.entity.ProjectEntity;
import com.house365.beans.entity.ProjectLogEntity;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.ServiceRunException;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.ws.dao.mapper.ProjectLogMapper;
import com.house365.ws.dao.mapper.ProjectMapper;
import com.house365.ws.system.ReturnAppResult;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @author Created by Administrator on 2019/8/13.
 */
@Service("updateProjectCode")
public class UpdateProjectCode implements IUpdateProjectCode {

    private Logger logger = LoggerFactory.getLogger(UpdateProjectCode.class);

    @Autowired
    private ProjectMapper mapper;
    @Autowired
    private ProjectLogMapper logMapper;

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<ProjectEntity> response = new House365RestResponse<>();
        try {
            // 业务层统一处理
            String data = getMapValueByKey("data", map, "");
            logger.info("修改合同号接口参数： + " + data);
            if (!Strings.isNullOrEmpty(data)) {
                JSONObject object = JSONObject.fromObject(data);
                String contractCode = getJsonValueByKey("contractCode", object, "");
                String newContractCode = getJsonValueByKey("newContractCode", object, "");
                if (StringUtils.isBlank(contractCode) || StringUtils.isBlank(newContractCode)) {
                    response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                    response.setMsg("合同号参数不能为空");
                    return JSONObject.fromObject(response).toString();
                }
                Map<String, Object> searchMap = new HashMap<>(10);
                searchMap.put("contractCode", contractCode);
                List<ProjectEntity> list = mapper.queryByConditions(searchMap);
                if (CollectionUtils.isNotEmpty(list)) {
                    searchMap.put("contractCode", newContractCode);
                    List<ProjectEntity> newList = mapper.queryByConditions(searchMap);
                    if (CollectionUtils.isNotEmpty(newList)) {
                        response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                        response.setMsg("新的合同号在系统中已经存在");
                        return JSONObject.fromObject(response).toString();
                    }
                    int id = list.get(0).getId();
                    Map<String, Object> updateMap = new HashMap<>(10);
                    updateMap.put("id", id);
                    updateMap.put("contractCode", newContractCode);
                    mapper.updateCode(updateMap);
                    //记录项目操作日志
                    ProjectLogEntity logEntity = new ProjectLogEntity();
                    logEntity.setRelateId(id);
                    logEntity.setType(2);
                    logEntity.setModifyColumn("contractCode");
                    logEntity.setModifyName("合同号");
                    logEntity.setOldValue(contractCode);
                    logEntity.setNewValue(newContractCode);
                    logEntity.setCreateUserId(0);
                    logEntity.setCreateUserName("合同系统");
                    logEntity.setCreateTime(new Date());
                    logMapper.save(logEntity);
                } else {
                    response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                    response.setMsg("根据该合同号查不到数据");
                    return JSONObject.fromObject(response).toString();
                }
            } else {
                response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                response.setMsg("接口参数不全");
                return JSONObject.fromObject(response).toString();
            }
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (Exception e) {
            logger.error("同步修改合同编号接口失败", e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        return JSONObject.fromObject(response).toString();
    }

    private String getJsonValueByKey(String key, JSONObject obj, String defaultValue) {
        String value = "";
        if (obj.containsKey(key) && obj.get(key) != null && !Strings.isNullOrEmpty(String.valueOf(obj.get(key)))) {
            value = String.valueOf(obj.get(key));
        }

        if (Strings.isNullOrEmpty(value)) {
            value = defaultValue;
        }
        return value;
    }

    private String getMapValueByKey(String key, Map<String, Object> map, String defaultValue) {
        String value = "";
        if (map.containsKey(key) && map.get(key) != null && !Strings.isNullOrEmpty(((String[]) map.get(key))[0])) {
            value = ((String[]) map.get(key))[0];
        }

        if (Strings.isNullOrEmpty(value)) {
            value = defaultValue;
        }
        return value;
    }

    @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() {

    }
}
