package com.xhpc.user.service.impl;

import com.xhpc.common.core.domain.R;
import com.xhpc.common.core.utils.SecurityUtils;
import com.xhpc.common.core.web.domain.AjaxResult;
import com.xhpc.common.core.web.service.BaseService;
import com.xhpc.common.security.service.TokenService;
import com.xhpc.common.util.UserTypeUtil;
import com.xhpc.system.api.domain.SysUser;
import com.xhpc.system.api.model.LoginUser;
import com.xhpc.user.domain.XhpcCommunity;
import com.xhpc.user.domain.XhpcCommunityPersonnel;
import com.xhpc.user.mapper.XhpcCommunityMapper;
import com.xhpc.user.service.IMechanismService;
import com.xhpc.user.service.IXhpcCommunityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author yuyang
 * @date 2021/12/20 9:59
 */
@Service
public class XhpcCommunityServiceImpl extends BaseService implements IXhpcCommunityService {

    @Resource
    XhpcCommunityMapper xhpcCommunityMapper;
    @Resource
    IMechanismService mechanismService;
    @Resource
    TokenService tokenService;

    private static final Logger logger = LoggerFactory.getLogger(XhpcCommunityServiceImpl.class);


    /**
     * 社区组树列表
     *
     * @param name         桩名称
     * @return
     */
    @Override
    public List<Map<String, Object>> userList(HttpServletRequest request, String name){
        Long userId = SecurityUtils.getUserId();
        List<Map<String, Object>> list =new ArrayList<>();
        LoginUser loginUser = tokenService.getLoginUser(request);
        if(userId !=null){
            String userType = loginUser.getSysUser().getUserType();
            if(UserTypeUtil.SYS_USER_TYPE_ZERO.equals(userType)){
                list = xhpcCommunityMapper.tree(name, loginUser.getTenantId());
            }
        }

        Iterator<Map<String, Object>> iterator = list.iterator();
        while (iterator.hasNext()){
            Map<String, Object> commMap = iterator.next();
            List<Map<String, Object>> userMapList = xhpcCommunityMapper.communityPersonnelTree(commMap.get("id").toString().replaceAll("COMM_", ""));
            if (userMapList.size() < 1){
                iterator.remove();
            } else {
                commMap.put("children", userMapList);
            }
        }
        return list;
    }


    @Override
    public List<Map<String, Object>> list(HttpServletRequest request, String name) {
        Long userId = SecurityUtils.getUserId();
        List<Map<String, Object>> list =new ArrayList<>();
        LoginUser loginUser = tokenService.getLoginUser(request);
        if(userId !=null){
            startPage();
            String userType = loginUser.getSysUser().getUserType();
            if(UserTypeUtil.SYS_USER_TYPE_ZERO.equals(userType)){
                list = xhpcCommunityMapper.list(name,loginUser.getTenantId());
            }
        }
        return list;
    }

    @Override
    public AjaxResult addCommunity(HttpServletRequest request,XhpcCommunity xhpcCommunity) {

        R r= judgeXhpcCommunity(xhpcCommunity);
        if(r.getCode() !=200){
            return AjaxResult.error(r.getMsg());
        }
        //名称重复不能入库
        Map<String, Object> communityById = xhpcCommunityMapper.getCommunityById(null, xhpcCommunity.getName(), null);
        if(communityById !=null){
            return AjaxResult.error("社区组名称重复");
        }

        String chargingStationIds = xhpcCommunity.getChargingStationIds();
        if("".equals(chargingStationIds) || chargingStationIds ==null){
            xhpcCommunity.setStatus(0);
        }else{
            xhpcCommunity.setStatus(1);
        }
        Long userId = SecurityUtils.getUserId();
        if(userId !=null){
            LoginUser loginUser = tokenService.getLoginUser(request);
            SysUser sysUser = loginUser.getSysUser();
            if(UserTypeUtil.SYS_USER_TYPE_ONE.equals(sysUser.getUserType()) || UserTypeUtil.SYS_USER_TYPE_THREE.equals(sysUser.getUserType())){
                xhpcCommunity.setType(2);
                xhpcCommunity.setOperatorId(sysUser.getOperatorId());
            }else{
                xhpcCommunity.setType(1);
            }
        }else{
            return AjaxResult.error("请重新登录");
        }
        xhpcCommunityMapper.addCommunity(xhpcCommunity);
        if(!"".equals(chargingStationIds) && chargingStationIds !=null){
            mechanismService.addMechanism(Arrays.asList(chargingStationIds.split(",")),xhpcCommunity.getCommunityId(),0);
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult deleteCommunity(XhpcCommunity xhpcCommunity) {
        if(xhpcCommunity !=null && xhpcCommunity.getCommunityId() !=null){
            int i = xhpcCommunityMapper.countCommunityPersonnel(xhpcCommunity.getCommunityId());
            if(i==0){
                xhpcCommunityMapper.deleteCommunity(xhpcCommunity.getCommunityId());
                return AjaxResult.success();
            }else{
                return AjaxResult.error("该社区组下有用户不能删除");
            }
        }else{
            return AjaxResult.error("请传社区组id");
        }
    }

    @Override
    public AjaxResult updateCommunity(XhpcCommunity xhpcCommunity) {

        R r = judgeXhpcCommunity(xhpcCommunity);
        if(r.getCode()!=200){
            return AjaxResult.error(r.getMsg());
        }
        //名称重复不能入库
        Map<String, Object> communityById = xhpcCommunityMapper.getCommunityById(xhpcCommunity.getCommunityId(), xhpcCommunity.getName(), 2);
        if(communityById !=null){
            return AjaxResult.error("社区名称重复");
        }

        String chargingStationIds = xhpcCommunity.getChargingStationIds();
        if("".equals(chargingStationIds) || chargingStationIds ==null){
            xhpcCommunity.setStatus(0);
        }else{
            xhpcCommunity.setStatus(1);
        }
        xhpcCommunityMapper.updateCommunity(xhpcCommunity);
        mechanismService.updateMechanism(xhpcCommunity.getCommunityId(),0);
        if(!"".equals(chargingStationIds) && chargingStationIds !=null){
            mechanismService.addMechanism(Arrays.asList(chargingStationIds.split(",")),xhpcCommunity.getCommunityId(),0);
        }
        return AjaxResult.success();
    }

    @Override
    public Map<String, Object> getCommunityById(XhpcCommunity xhpcCommunity) {

        return xhpcCommunityMapper.getCommunityById(xhpcCommunity.getCommunityId(),null,1);
    }

    @Override
    public List<Map<String, Object>> communityPersonnelList(Long communityId, String account, String phone, Integer status) {
        return xhpcCommunityMapper.communityPersonnelList(communityId, account, phone, status);
    }

    @Override
    @Transactional
    public AjaxResult addCommunityPersonnel(HttpServletRequest request,XhpcCommunityPersonnel xhpcCommunityPersonnel) {
        R r =  judgeXhpcCommunityPersonnel(xhpcCommunityPersonnel);
        if(r.getCode()!=200){
            return AjaxResult.error(r.getMsg());
        }
        String phone = xhpcCommunityPersonnel.getPhone();
        String account = xhpcCommunityPersonnel.getAccount();
        Map<String, Object> communityPersonnelById = xhpcCommunityMapper.getCommunityPersonnelById(null, phone, account, 3);
        if(communityPersonnelById !=null){
            if(phone.equals(communityPersonnelById.get("phone").toString())){
                return AjaxResult.error("手机号重复");
            }
            if(account.equals(communityPersonnelById.get("account").toString())){
                return AjaxResult.error("账号重复");
            }
        }
        BigDecimal rechargeMoney = xhpcCommunityPersonnel.getRechargeMoney();
        if(new BigDecimal(0).compareTo(rechargeMoney)==-1){
            //增加社区用户的剩余金额
            xhpcCommunityPersonnel.setSurplusMoney(rechargeMoney);
        }
        Long userId = SecurityUtils.getUserId();
        if(userId !=null){
            LoginUser loginUser = tokenService.getLoginUser(request);
            SysUser sysUser = loginUser.getSysUser();
            if(UserTypeUtil.SYS_USER_TYPE_ONE.equals(sysUser.getUserType()) || UserTypeUtil.SYS_USER_TYPE_THREE.equals(sysUser.getUserType())){
                xhpcCommunityPersonnel.setCreateType(2);
                xhpcCommunityPersonnel.setCreateId(sysUser.getOperatorId());
            }else{
                xhpcCommunityPersonnel.setCreateType(1);
            }
        }else{
            return AjaxResult.error("请重新登录");
        }
        xhpcCommunityMapper.addCommunityPersonnel(xhpcCommunityPersonnel);
        //增加一条充值记录
        if(new BigDecimal(0).compareTo(rechargeMoney)==-1){
            mechanismService.addRechargeOrder(xhpcCommunityPersonnel.getCommunityPersonnelId(),UserTypeUtil.COMMUNIT_TYPE,rechargeMoney,rechargeMoney,UserTypeUtil.RECHARGE_PT);
        }
        return AjaxResult.success();
    }

    @Override
    public Map<String, Object> getCommunityPersonnelById(XhpcCommunityPersonnel xhpcCommunityPersonnel) {
        return xhpcCommunityMapper.getCommunityPersonnelById(xhpcCommunityPersonnel.getCommunityPersonnelId(), null, null, 1);
    }

    @Override
    public AjaxResult updateCommunityPersonnel(XhpcCommunityPersonnel xhpcCommunityPersonnel) {
        R r = judgeXhpcCommunityPersonnel(xhpcCommunityPersonnel);
        if(r.getCode()!=200){
            return AjaxResult.error(r.getMsg());
        }
        Long communityPersonnelId = xhpcCommunityPersonnel.getCommunityPersonnelId();
        String phone = xhpcCommunityPersonnel.getPhone();
        String account = xhpcCommunityPersonnel.getAccount();
        BigDecimal rechargeMoney = xhpcCommunityPersonnel.getRechargeMoney();
        BigDecimal surplusMoney = xhpcCommunityPersonnel.getSurplusMoney();
        if( rechargeMoney!=null){
            return AjaxResult.error("充值金额不能填写");
        }
        if( surplusMoney!=null){
            return AjaxResult.error("剩余金额不能填写");
        }
        Map<String, Object> communityPersonnelById = xhpcCommunityMapper.getCommunityPersonnelById(communityPersonnelId, phone, account, 2);
        if(communityPersonnelById !=null){
            if(phone.equals(communityPersonnelById.get("phone").toString())){
                return AjaxResult.error("手机号重复");
            }
            if(account.equals(communityPersonnelById.get("account").toString())){
                return AjaxResult.error("账号重复");
            }
        }
        xhpcCommunityMapper.updateCommunityPersonnel(xhpcCommunityPersonnel);
        return AjaxResult.success();
    }

    @Override
    public void deleteCommunityPersonnel(XhpcCommunityPersonnel xhpcCommunityPersonnel) {
        xhpcCommunityMapper.deleteCommunityPersonnel(xhpcCommunityPersonnel.getCommunityPersonnelId());
    }

    @Override
    public void updateCommunityPersonnelStatus(XhpcCommunityPersonnel xhpcCommunityPersonnel) {
        xhpcCommunityMapper.updateCommunityPersonnelStatus(xhpcCommunityPersonnel.getCommunityPersonnelId(),xhpcCommunityPersonnel.getStatus());
    }

    @Override
    @Transactional
    public AjaxResult addRecharge(XhpcCommunityPersonnel xhpcCommunityPersonnel) {

        //充值金额
        BigDecimal rechargeMoney = xhpcCommunityPersonnel.getRechargeMoney();
        logger.info("<<<<<<<<<<<<<<<<<<<<<<<<rechargeMoney>>>>>>>>>>>>>>>>>"+rechargeMoney);
        Long communityPersonnelId = xhpcCommunityPersonnel.getCommunityPersonnelId();
        if(rechargeMoney !=null &&new BigDecimal(0).compareTo(rechargeMoney)==-1){
            //增加社区用户的剩余金额
            Map<String, Object> communityPersonnelById = xhpcCommunityMapper.getCommunityPersonnelById(communityPersonnelId, null, null, 1);
            if(communityPersonnelById !=null){
                BigDecimal surplusMoney = new BigDecimal(communityPersonnelById.get("surplusMoney").toString());
                //原本充值金额
                BigDecimal rechargeMoney1 = new BigDecimal(communityPersonnelById.get("rechargeMoney").toString());
                logger.info("<<<<<<<<<<<<<<<<<<<<<<<<surplusMoney>>>>>>>>>>>>>>>>>"+surplusMoney);
                logger.info("<<<<<<<<<<<<<<<<<<<<<<<<rechargeMoney1>>>>>>>>>>>>>>>>>"+rechargeMoney1);
                XhpcCommunityPersonnel xhpcCommunityPersonnel1=new XhpcCommunityPersonnel();
                xhpcCommunityPersonnel1.setCommunityPersonnelId(communityPersonnelId);
                BigDecimal remainingSum = surplusMoney.add(rechargeMoney);
                xhpcCommunityPersonnel1.setSurplusMoney(remainingSum);
                xhpcCommunityPersonnel1.setRechargeMoney(rechargeMoney1.add(rechargeMoney));
                xhpcCommunityMapper.updateCommunityPersonnel(xhpcCommunityPersonnel1);

                Long rechargeOrderId=null;
                if(UserTypeUtil.RECHARGE_PT.equals(xhpcCommunityPersonnel.getRechargeType())){
                    //增加充值记录
                     rechargeOrderId = mechanismService.addRechargeOrder(communityPersonnelId, UserTypeUtil.COMMUNIT_TYPE, rechargeMoney, remainingSum, xhpcCommunityPersonnel.getRechargeType());
                }else{
                    rechargeOrderId=xhpcCommunityPersonnel.getMoneyOrderId();
                }
                //增加用户流水
                mechanismService.insertUserAccount(communityPersonnelId,rechargeMoney,remainingSum,null,rechargeOrderId,null,UserTypeUtil.INSERT_BALANCE,xhpcCommunityPersonnel1.getTenantId(),UserTypeUtil.COMMUNIT_TYPE);
                return AjaxResult.success();
            }
        }
        return AjaxResult.error("充值金额必需大于0");
    }

    /**
     * 根据用户id获取社区组
     *
     * @param userId
     * @param tenantId
     */
    @Override
    public Map<String, Object> getCommunityPersonnelUserId(Long userId, String tenantId,Long chargingStationId) {
        return xhpcCommunityMapper.getCommunityPersonnelUserId(userId, tenantId,chargingStationId);
    }

    public R judgeXhpcCommunity(XhpcCommunity xhpcCommunity){

        if(xhpcCommunity.getName()==null || "".equals(xhpcCommunity.getName())){
            return R.fail("名称必填");
        }
        if(xhpcCommunity.getContactName()==null || "".equals(xhpcCommunity.getContactName())){
            return R.fail("联系人必填");
        }
        if(xhpcCommunity.getContactPhone()==null || "".equals(xhpcCommunity.getContactPhone())){
            return R.fail("联系人电话必填");
        }
        if(xhpcCommunity.getAddress()==null || "".equals(xhpcCommunity.getAddress())){
            return R.fail("地址必填");
        }
        return R.ok();
    }

    public R judgeXhpcCommunityPersonnel(XhpcCommunityPersonnel xhpcCommunityPersonnel){

        if(xhpcCommunityPersonnel.getName()==null || "".equals(xhpcCommunityPersonnel.getName())){
            return R.fail("名称必填");
        }
        if(xhpcCommunityPersonnel.getAccount()==null || "".equals(xhpcCommunityPersonnel.getAccount()) || !"S".equals(xhpcCommunityPersonnel.getAccount().substring(0,1))){
            return R.fail("账号必填且S开头11位");
        }
        if(xhpcCommunityPersonnel.getPhone()==null || "".equals(xhpcCommunityPersonnel.getPhone()) || xhpcCommunityPersonnel.getPhone().length()!=11){
            return R.fail("绑定手机号必填");
        }

        return R.ok();
    }


}
