package com.house365.ws.interfaces.rest;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import com.house365.beans.entity.CustomerProjectEntity;
import com.house365.beans.entity.ProjectEntity;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.ServiceRunException;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.ws.dao.mapper.CustomerProjectMapper;
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/10/25.
 */
@Service("updateCustomerStatus")
public class UpdateCustomerStatusImpl implements IUpdateCustomerStatus {

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

    @Autowired
    private CustomerProjectMapper projectMapper;

    @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)) {
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, Map<String, Map>> webMap = objectMapper.readValue(data, Map.class);
                List<Map<String, Object>> dataList = (List<Map<String, Object>>) webMap.get("list");
                if (CollectionUtils.isNotEmpty(dataList)) {
                    if (dataList.size() > 1000) {
                        response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                        response.setMsg("请求参数list不能超过1000条");
                        return JSONObject.fromObject(response).toString();
                    } else {
                        for (Map<String, Object> m : dataList) {
                            String phone = m.get("phone").toString();
                            String contractNo = m.get("contractNo").toString();
                            String status = m.get("status").toString();
                            if (StringUtils.isBlank(phone) || StringUtils.isBlank(contractNo) || StringUtils.isBlank(status)) {
                                response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                                response.setMsg("请求参数不能为空");
                                return JSONObject.fromObject(response).toString();
                            }
                            Map<String, Object> searchMap = new HashMap<>(10);
                            searchMap.put("customerPhone", phone);
                            searchMap.put("contract", contractNo);
                            List<CustomerProjectEntity> list = projectMapper.queryByConditions(searchMap);
                            if (CollectionUtils.isNotEmpty(list)) {
                                int id = list.get(0).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);
                            }
                        }
                    }
                }

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

    }
}
