package com.house365.ws.interfaces.rest;

import com.google.common.base.Strings;
import com.house365.beans.entity.CmHouseEntity;
import com.house365.rest.context.CmConstant;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.IllegalServiceParameterException;
import com.house365.rest.exception.ServiceRunException;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.web.util.ThreadPoolManager;
import com.house365.ws.dao.interfaces.ICmHouseCommentDao;
import com.house365.ws.dao.interfaces.ICmHouseDao;
import com.house365.ws.system.ReturnAppResult;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Date: 2017/12/8</p>
 *
 * @author XN
 * @version 1.0
 */
@Component("updateHouseName")
public class UpdateHouseNameImpl implements IUpdateHouseNameInterface {
    private static final Logger LOGGER = LoggerFactory.getLogger("InterfaceLog");

    @Autowired
    private ICmHouseDao<CmHouseEntity> houseDao;

    @Autowired
    private ICmHouseCommentDao houseCommentDao;

    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    @Override
    public void updateHouseName(Map<String, Object> map) {
        //物业类型
        Integer channel = 0;
        //城市编号
        String cityKey = null;
        //楼盘Id
        Integer houseId = null;
        //name
        String houseName = null;

        if (map.get(CmConstant.CHANNEL) != null && ((String[]) map.get(CmConstant.CHANNEL)).length > 0) {
            String[] array = ((String[]) map.get(CmConstant.CHANNEL));
            if (checkNumOfArrayParameter(array)) {
                channel = Integer.parseInt(((String[]) map.get(CmConstant.CHANNEL))[0]);
            }
        }
        if (map.get(CmConstant.CITY_KEY) != null && ((String[]) map.get(CmConstant.CITY_KEY)).length > 0) {
            cityKey = ((String[]) map.get(CmConstant.CITY_KEY))[0];
        }
        if (map.get(CmConstant.HOUSEID) != null && ((String[]) map.get(CmConstant.HOUSEID)).length > 0) {
            String[] array = ((String[]) map.get(CmConstant.HOUSEID));
            if (checkNumOfArrayParameter(array)) {
                houseId = Integer.parseInt(((String[]) map.get(CmConstant.HOUSEID))[0]);
            }
        }
        if (map.get(CmConstant.HOUSENAME) != null && ((String[]) map.get(CmConstant.HOUSENAME)).length > 0) {
            houseName = ((String[]) map.get(CmConstant.HOUSENAME))[0];
        }

        if (!Strings.isNullOrEmpty(houseName)) {
            CmHouseEntity houseEntity = houseDao.getHouseByHouseId(houseId, cityKey, channel);
            if (!houseName.equalsIgnoreCase(houseEntity.getHouseName())) {
                houseEntity.setHouseName(houseName);
                houseDao.update(houseEntity);
                houseCommentDao.updateHouseName(houseEntity.getId(), houseName);
            }
        }
    }

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        final Map<String, Object> map = parameter.getArgs();
        House365RestResponse<Object> response = new House365RestResponse<Object>();

        // 业务校验统一入口
        try {
            checkInterfaceParameter(map);
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }
        // 业务层统一处理
        try {

            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg("SUCCESS");
            ThreadPoolManager.addExecuteTask(new Runnable() {
                @Override
                public void run() {
                    updateHouseName(map);
                }
            });

        } catch (Exception e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
        }

        return JSONObject.fromObject(response).toString();
    }

    /**
     * 业务层统校验自己所需参数是否存在
     *
     * @param map 请求参数封装成Map对象
     * @since [产品/模块版本](可选)
     */
    protected void checkInterfaceParameter(Map<String, Object> map) throws IllegalServiceParameterException {
        // 方法所需参数
        for (String str : CmConstant.UpdateHouseName) {
            // 如果不存在跳出 同时抛出相应异常
            if (!map.containsKey(str)) {
                LOGGER.error("业务入口参数异常：" + str + "参数为空!");
                throw new IllegalServiceParameterException("业务入口参数异常：" + str + "参数为空!");
            }
        }
    }

    private boolean checkNumOfArrayParameter(String[] parameter) {
        return (parameter.length > 0 && NumberUtils.isNumber(parameter[0]));
    }

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

    }
}
