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.XhpcCustomers;
import com.xhpc.user.domain.XhpcCustomersPersonnel;
import com.xhpc.user.mapper.XhpcCustomersMapper;
import com.xhpc.user.service.IMechanismService;
import com.xhpc.user.service.IXhpcCustomersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @author yuyang
 * @date 2021/12/23 15:53
 */
@Service
public class XhpcCustomersServiceImpl extends BaseService implements IXhpcCustomersService {

    @Autowired
    private XhpcCustomersMapper xhpcCustomersMapper;
    @Autowired
    private IMechanismService mechanismService;
    @Autowired
    private TokenService tokenService;

    @Override
    public List<Map<String, Object>> userList(HttpServletRequest request,String name){
        List<Map<String, Object>> list = new ArrayList<>();
        LoginUser loginUser = tokenService.getLoginUser(request);
        String userType = loginUser.getSysUser().getUserType();
        if(UserTypeUtil.SYS_USER_TYPE_ZERO.equals(userType)){
            list = xhpcCustomersMapper.tree(name,null,loginUser.getTenantId());
        }else{
            list = xhpcCustomersMapper.tree(name,loginUser.getSysUser().getOperatorId(),loginUser.getTenantId());
        }

        Iterator<Map<String, Object>> iterator = list.iterator();
        while (iterator.hasNext()){
            Map<String, Object> cusMap = iterator.next();
            List<Map<String, Object>> userList = xhpcCustomersMapper.customersPersonnelTree(cusMap.get("id").toString().replaceAll("CUS_", ""));
            if (userList.size() < 1){
                iterator.remove();
            } else {
                cusMap.put("children", userList);
            }
        }
        return list;
    }


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

    @Override
    public AjaxResult addCustomers(HttpServletRequest request, XhpcCustomers xhpcCustomers) {
        R r = judgeXhpcCustomers(xhpcCustomers);
        if(r.getCode()!=200){
            return AjaxResult.error(r.getMsg());
        }
        //名称重复不能入库
        Map<String, Object> communityById = xhpcCustomersMapper.getCustomersById(null, xhpcCustomers.getName(), null);
        if(communityById !=null){
            return AjaxResult.error("大客户组名称重复");
        }
        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())){
                xhpcCustomers.setType(2);
                xhpcCustomers.setOperatorId(sysUser.getOperatorId());
            }else{
                xhpcCustomers.setType(1);
            }
        }else{
            return AjaxResult.error("请重新登录");
        }
        String chargingStationIds = xhpcCustomers.getChargingStationIds();
        if("".equals(chargingStationIds) || chargingStationIds ==null){
            xhpcCustomers.setStatus(0);
        }else{
            xhpcCustomers.setStatus(1);
        }
        xhpcCustomersMapper.addCustomers(xhpcCustomers);
        if(!"".equals(chargingStationIds) && chargingStationIds !=null){
            mechanismService.addMechanism(Arrays.asList(chargingStationIds.split(",")),xhpcCustomers.getCustomersId(),1);
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult deleteCustomers(XhpcCustomers xhpcCustomers) {
        if(xhpcCustomers !=null && xhpcCustomers.getCustomersId() !=null){
            int i = xhpcCustomersMapper.countCustomersPersonnel(xhpcCustomers.getCustomersId());
            if(i==0){
                 xhpcCustomersMapper.deleteCustomers(xhpcCustomers.getCustomersId());
                return AjaxResult.success();
            }else{
                return AjaxResult.error("该大客户组下有用户不能删除");
            }
        }else{
            return AjaxResult.error("请传大客户组id");
        }
    }

    @Override
    public Map<String, Object> getCustomersById(XhpcCustomers xhpcCustomers) {
        return xhpcCustomersMapper.getCustomersById(xhpcCustomers.getCustomersId(), null, 1);
    }

    @Override
    public AjaxResult updateCustomers(XhpcCustomers xhpcCustomers) {
        R r = judgeXhpcCustomers(xhpcCustomers);
        if(r.getCode()!=200){
            return AjaxResult.error(r.getMsg());
        }
        //名称重复不能入库
        Map<String, Object> customersById = xhpcCustomersMapper.getCustomersById(xhpcCustomers.getCustomersId(), xhpcCustomers.getName(), 2);
        if(customersById !=null){
            return AjaxResult.error("大客户组名称重复");
        }
        String chargingStationIds = xhpcCustomers.getChargingStationIds();
        if("".equals(chargingStationIds) || chargingStationIds ==null){
            xhpcCustomers.setStatus(0);
        }else{
            xhpcCustomers.setStatus(1);
        }
        xhpcCustomersMapper.updateCustomers(xhpcCustomers);
        mechanismService.updateMechanism(xhpcCustomers.getCustomersId(),1);
        if(!"".equals(chargingStationIds) && chargingStationIds !=null){
            mechanismService.addMechanism(Arrays.asList(chargingStationIds.split(",")),xhpcCustomers.getCustomersId(),1);
        }
        return AjaxResult.success();
    }

    @Override
    public List<Map<String, Object>> customersPersonnelList(Long customersId, String account, String phone, Integer status) {
        return xhpcCustomersMapper.customersPersonnelList(customersId, account, phone, status);
    }

    @Override
    public AjaxResult addCustomersPersonnel(HttpServletRequest request, XhpcCustomersPersonnel xhpcCustomersPersonnel) {
        R r = judgeXhpcCustomersPersonnel(xhpcCustomersPersonnel);
        if(r.getCode()!=200){
            return AjaxResult.error(r.getMsg());
        }
        String phone = xhpcCustomersPersonnel.getPhone();
        String account = xhpcCustomersPersonnel.getAccount();
        Map<String, Object> communityPersonnelById = xhpcCustomersMapper.getCustomersPersonnelById(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 = xhpcCustomersPersonnel.getRechargeMoney();
        if(rechargeMoney !=null){
            if(new BigDecimal(0).compareTo(rechargeMoney)==-1){
                //增加社区用户的剩余金额
                xhpcCustomersPersonnel.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())){
                xhpcCustomersPersonnel.setCreateType(2);
                xhpcCustomersPersonnel.setCreateId(sysUser.getOperatorId());
            }else{
                xhpcCustomersPersonnel.setCreateType(1);
            }
        }else{
            return AjaxResult.error("请重新登录");
        }
        xhpcCustomersPersonnel.setCreateTime(new Date());
        xhpcCustomersMapper.addCustomersPersonnel(xhpcCustomersPersonnel);
        if(rechargeMoney !=null){
            //增加一条充值记录
            if(new BigDecimal(0).compareTo(rechargeMoney)==-1){
                mechanismService.addRechargeOrder(xhpcCustomersPersonnel.getCustomersPersonnelId(),UserTypeUtil.CUSTOMERS_TYPE,rechargeMoney,rechargeMoney,UserTypeUtil.RECHARGE_PT);
            }
        }
        return AjaxResult.success();
    }

    @Override
    public Map<String, Object> getCustomersPersonnelById(XhpcCustomersPersonnel xhpcCustomersPersonnel) {
        return xhpcCustomersMapper.getCustomersPersonnelById(xhpcCustomersPersonnel.getCustomersPersonnelId(), null, null, 1);
    }

    @Override
    public AjaxResult updateCustomersPersonnel(XhpcCustomersPersonnel xhpcCustomersPersonnel) {
        R r =  judgeXhpcCustomersPersonnel(xhpcCustomersPersonnel);
        if(r.getCode()!=200){
            return AjaxResult.error(r.getMsg());
        }
        Long customersPersonnelId = xhpcCustomersPersonnel.getCustomersPersonnelId();
        String phone = xhpcCustomersPersonnel.getPhone();
        String account = xhpcCustomersPersonnel.getAccount();
        BigDecimal rechargeMoney = xhpcCustomersPersonnel.getRechargeMoney();
        BigDecimal surplusMoney = xhpcCustomersPersonnel.getSurplusMoney();
        if( rechargeMoney!=null){
            return AjaxResult.error("充值金额不能填写");
        }
        if( surplusMoney!=null){
            return AjaxResult.error("剩余金额不能填写");
        }
        Map<String, Object> customersPersonnelById = xhpcCustomersMapper.getCustomersPersonnelById(customersPersonnelId, phone, account, 2);
        if(customersPersonnelById !=null){
            if(phone.equals(customersPersonnelById.get("phone").toString())){
                return AjaxResult.error("手机号重复");
            }
            if(account.equals(customersPersonnelById.get("account").toString())){
                return AjaxResult.error("账号重复");
            }
        }
        xhpcCustomersMapper.updateCustomersPersonnel(xhpcCustomersPersonnel);
        return AjaxResult.success();
    }

    @Override
    public void deleteCustomersPersonnel(XhpcCustomersPersonnel xhpcCustomersPersonnel) {
        xhpcCustomersMapper.deleteCustomersPersonnel(xhpcCustomersPersonnel.getCustomersPersonnelId());
    }

    @Override
    public AjaxResult addRecharge(XhpcCustomersPersonnel xhpcCustomersPersonnel) {
        BigDecimal rechargeMoney = xhpcCustomersPersonnel.getRechargeMoney();
        Long customersPersonnelId = xhpcCustomersPersonnel.getCustomersPersonnelId();
        if(rechargeMoney !=null && new BigDecimal(0).compareTo(rechargeMoney)==-1){
            //增加社区用户的剩余金额
            Map<String, Object> communityPersonnelById = xhpcCustomersMapper.getCustomersPersonnelById(customersPersonnelId, null, null, 1);
            if(communityPersonnelById !=null){
                BigDecimal surplusMoney = new BigDecimal(communityPersonnelById.get("surplusMoney").toString());
                BigDecimal rechargeMoney1 = new BigDecimal(communityPersonnelById.get("rechargeMoney").toString());

                XhpcCustomersPersonnel xhpcCustomersPersonnel1=new XhpcCustomersPersonnel();
                xhpcCustomersPersonnel1.setCustomersPersonnelId(customersPersonnelId);
                BigDecimal remainingSum = surplusMoney.add(rechargeMoney);
                xhpcCustomersPersonnel1.setSurplusMoney(remainingSum);
                xhpcCustomersPersonnel1.setRechargeMoney(rechargeMoney1.add(rechargeMoney));
                xhpcCustomersMapper.updateCustomersPersonnel(xhpcCustomersPersonnel1);
                Long rechargeOrderId=null;
                if(UserTypeUtil.RECHARGE_PT.equals(xhpcCustomersPersonnel.getRechargeType())){
                    //增加充值记录
                     rechargeOrderId =mechanismService.addRechargeOrder(customersPersonnelId, UserTypeUtil.CUSTOMERS_TYPE,rechargeMoney,remainingSum,xhpcCustomersPersonnel.getRechargeType());
                }else{
                    rechargeOrderId= xhpcCustomersPersonnel.getMoneyOrderId();
                }
                //增加用户流水
                mechanismService.insertUserAccount(customersPersonnelId,rechargeMoney,remainingSum,null,rechargeOrderId,null,UserTypeUtil.INSERT_BALANCE,xhpcCustomersPersonnel1.getTenantId(),UserTypeUtil.CUSTOMERS_TYPE);
                return AjaxResult.success();
            }
        }
        return AjaxResult.error("充值金额大于0");
    }

    /**
     * 社区人员状态改变
     *
     * @param xhpcCustomersPersonnel
     */
    @Override
    public void updateCustomersPersonnelStatus(XhpcCustomersPersonnel xhpcCustomersPersonnel) {
        xhpcCustomersMapper.updateCustomersPersonnelStatus(xhpcCustomersPersonnel.getCustomersPersonnelId(),xhpcCustomersPersonnel.getStatus());
    }

    /**
     * 根据用户id获取大客户组
     *
     * @param userId
     * @param tenantId
     */
    @Override
    public Map<String, Object> getCustomersPersonnelUserId(Long userId, String tenantId, Long chargingStationId) {
        return xhpcCustomersMapper.getCustomersPersonnelUserId(userId, tenantId,chargingStationId);
    }

    @Override
    public Map<String, Object> getMotorcadeUserId(Long userId, String tenantId, Long chargingStationId) {
        return xhpcCustomersMapper.getMotorcadeUserId(userId, tenantId,chargingStationId);
    }
    public R judgeXhpcCustomers(XhpcCustomers xhpcCustomers){

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

    public R judgeXhpcCustomersPersonnel(XhpcCustomersPersonnel xhpcCustomersPersonnel){

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

}
