package com.house365.ws.interfaces.rest;

import com.beust.jcommander.internal.Lists;
import com.google.common.base.Strings;
import com.house365.beans.entity.CustomerProjectEntity;
import com.house365.beans.entity.UserEntity;
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.House365RestResponse;
import com.house365.web.util.StringUtils;
import com.house365.ws.beans.response.CustomerProjectResponse;
import com.house365.ws.dao.mapper.CustomerProjectMapper;
import com.house365.ws.interfaces.server.ICustomerProject;
import com.house365.ws.service.interfaces.ICustomerProjectService;
import com.house365.ws.system.ReturnAppResult;
import com.house365.ws.system.ReturnResult;
import com.house365.ws.util.Constant;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.house365.ws.util.Constant.MANAGER;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Date: 16/9/18</p>
 *
 * @author XN
 * @version 1.0
 */
@Service("updateCustomerProjectStatus")
public class UpdateCustomerProjectStatusImpl implements IUpdateCustomerProjectStatus {

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

    @Autowired
    private ICustomerProjectService customerProjectService;

    @Autowired
    private ICustomerProject customerProject;

    @Autowired
    private CustomerProjectMapper projectMapper;

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

    @Override
    public void commit() {

    }

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<UserEntity> response = new House365RestResponse<>();
        // 业务校验统一入口
        try {
            checkInterfaceParameter(map, Constant.ChangeCustomerProjectStatusParams);
            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 {
            String msg = doBusiness(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage() + ":" + msg);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        return JSONObject.fromObject(response).toString();
    }

    /**
     * 业务层统逻辑处理
     */
    private String doBusiness(Map<String, Object> map) throws Exception {
        // 返回Json对象
        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        String contract = getMapValueByKey(Constant.PROJECT_CONTRACT, map, "");
        String status = getMapValueByKey(Constant.CUSTOMER_STATUS, map, "");
        String occurTime = getMapValueByKey(Constant.OCCURTIME, map, "");

        if (Strings.isNullOrEmpty(phone) || Strings.isNullOrEmpty(contract) || Strings.isNullOrEmpty(
                status) || !StringUtils.isNumeric(status) || Strings.isNullOrEmpty(occurTime)) {
            throw new Exception("参数无效");
        }

        String statusName = Constant.CustomerStatusEnum.getMsgByStatus(Integer.parseInt(status));
        if (Strings.isNullOrEmpty(statusName)) {
            throw new Exception("状态参数无效");
        }

        List<String> phones = new ArrayList<>();
        if (phone.contains(",")) {
            phones.addAll(Lists.newArrayList(phone.split(",")));
        } else {
            phones.add(phone);
        }

        Map<String, Object> queryMap = new HashMap<>(10);
        queryMap.put("IN_customerPhones", phones);
        queryMap.put("EQ_contract", contract);
        queryMap.put("EQ_isRepeat", 0);

        QueryParams queryParams = new QueryParams();
        queryParams.setSearchParams(queryMap);
        List<CustomerProjectEntity> list = customerProjectService.queryAll(queryParams);

        String msg = "";

        int i = 0;
        if (CollectionUtils.isNotEmpty(list)) {
            for (CustomerProjectEntity cpe : list) {
                try {
                    CustomerProjectResponse cpr = customerProject.changeStatusNew(cpe.getId(), MANAGER, Integer.valueOf(status), "经管系统接口调用", occurTime);
                    if (ReturnResult.SUCCESS.getResultCode().equals(cpr.getResultCode())) {
                        i++;
                    }
                    //同步更新经管客户状态
                    int id = cpe.getId();
                    Map<String, Object> updateMap = new HashMap<>(10);
                    updateMap.put("jgStatus", Integer.valueOf(status));
                    updateMap.put("id", id);
                    updateMap.put("updateTime", new Date());
                    projectMapper.updateCustomerStatus(updateMap);
                } catch (Exception e) {
                    LOGGER.error(e.getMessage(), e);
                    continue;
                }
            }
        }
        msg = "成功更新" + i + "个客户项目状态，共" + phones.size() + "个";
        return msg;
    }

    /**
     * 获取map中的值
     *
     * @param key          key
     * @param map          map
     * @param 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;
    }

    /**
     * 业务层统校验自己所需参数是否存在
     * 所有参数都要存在
     *
     * @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;
    }
}
