package com.mortals.xhx.module.platform.web;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.common.IBaseEnum;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.util.AESUtil;
import com.mortals.framework.util.MD5Util;
import com.mortals.framework.util.SecurityUtil;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.common.code.*;
import com.mortals.xhx.common.key.Constant;
import com.mortals.xhx.module.platform.model.PlatformListenerEntity;
import com.mortals.xhx.module.platform.model.PlatformListenerQuery;
import com.mortals.xhx.module.platform.model.PlatformQuery;
import com.mortals.xhx.module.platform.service.PlatformListenerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.mortals.framework.web.BaseCRUDJsonMappingController;
import com.mortals.xhx.module.platform.model.PlatformEntity;
import com.mortals.xhx.module.platform.service.PlatformService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>Title: 平台用户</p>
 * <p>Description: PlatformController  </p>
 * <p>Copyright: Copyright &reg;  </p>
 * <p>Company: </p>
 *
 * @author zxfei
 * @version 1.0.0
 */
@RestController
@RequestMapping("platform")
public class PlatformController extends BaseCRUDJsonBodyMappingController<PlatformService, PlatformEntity, Long> {

    @Autowired
    private ParamService paramService;
    @Autowired
    private PlatformListenerService listenerService;

    public PlatformController() {
        super.setFormClass(PlatformForm.class);
        super.setModuleDesc("平台用户");
    }

    @Override
    protected void init(Map<String, Object> model, Context context) {
        this.addDict(model, "status", IBaseEnum.getEnumMap(PlatformModelStatus.class));
        this.addDict(model, "type", IBaseEnum.getEnumMap(PlatformTypeEnum.class));
        this.addDict(model, "listenerType", paramService.getParamByFirstOrganize(Constant.Param_listener));
    }

    @Override
    protected int doListAfter(PlatformEntity query, Map<String, Object> model, Context context) throws AppException {

        model.put("result",model.get("data"));

        return super.doListAfter(query, model, context);
    }

    @Override
    protected void addAfter(Map<String, Object> model) throws AppException {
        PlatformEntity entity = (PlatformEntity) model.get("entity");
        //生成secuID
        entity.setSecretKey(RandomUtil.randomString(64));
        entity.setStatus(YesNoEnum.YES.getValue());

        model.put("entity", entity);
        super.addAfter(model);
    }

    @Override
    protected void saveBefore(PlatformEntity entity, Map<String, Object> model, Context context) throws AppException {
        if (entity.newEntity()) {
            //新增
            PlatformEntity platformEntity = this.service.selectOne(new PlatformQuery().platformSn(entity.getPlatformSn()), context);

            if (!ObjectUtils.isEmpty(platformEntity)) {
                throw new AppException("业务平台标识已存在！");
            }
        } else {
            //修改
            PlatformEntity platformEntity = this.service.selectOne(new PlatformQuery().platformSn(entity.getPlatformSn()), context);
            if (!ObjectUtils.isEmpty(platformEntity) && entity.getId() != platformEntity.getId()) {
                throw new AppException("业务平台标识已存在！");
            }
        }
    }

    @Override
    protected int saveAfter(PlatformEntity entity, Map<String, Object> model, Context context) throws AppException {

        Map<String, String> map = paramService.getParamByFirstOrganize(Constant.Param_listener);

        if (entity.newEntity()) {
            Long id = (Long) model.get("id");
            List<PlatformListenerEntity> collect = entity.getListener().stream().map(item -> {
                PlatformListenerEntity listenerEntity = new PlatformListenerEntity();
                String value = map.get(item);
                listenerEntity.setPlatformId(id);
                listenerEntity.setPlatformSn(entity.getPlatformSn());
                listenerEntity.setTypeCode(item);
                listenerEntity.setTypeName(value);
                listenerEntity.setCreateTime(new Date());
                listenerEntity.setCreateUserName(context.getUser().getLoginName());
                listenerEntity.setCreateUser(context.getUser().getRealName());
                return listenerEntity;
            }).collect(Collectors.toList());
            listenerService.save(collect);
        } else {
            Long[] ids = listenerService.find(new PlatformListenerQuery().platformId(entity.getId())).stream().map(item -> item.getId()).toArray(Long[]::new);
            listenerService.remove(ids, context);

            List<PlatformListenerEntity> collect = entity.getListener().stream().map(item -> {
                PlatformListenerEntity listenerEntity = new PlatformListenerEntity();
                String value = map.get(item);
                listenerEntity.setPlatformId(entity.getId());
                listenerEntity.setPlatformSn(entity.getPlatformSn());
                listenerEntity.setTypeCode(item);
                listenerEntity.setTypeName(value);
                listenerEntity.setCreateTime(new Date());
                listenerEntity.setCreateUserName(context.getUser().getLoginName());
                listenerEntity.setCreateUser(context.getUser().getRealName());
                return listenerEntity;
            }).collect(Collectors.toList());
            listenerService.save(collect);
        }

        //新增

        List<String> listener = entity.getListener();

        //保存监听器
        //  List<PlatformListenerEntity> platformListenerEntities = listenerService.find(new PlatformListenerQuery().platformId(model.get("id").toString()));


        return super.saveAfter(entity, model, context);
    }

}