package com.xhpc.card.service.impl;

import com.xhpc.card.domain.*;
import com.xhpc.card.mapper.*;
import com.xhpc.card.pojo.*;
import com.xhpc.card.service.IXhpcCardService;
import com.xhpc.card.utils.MyPagingUtil;
import com.xhpc.common.api.CardHistoryOrderService;
import com.xhpc.common.core.domain.R;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yuyang
 * @date 2022/1/20 13:44
 */
@Service
public class XhpcCardServiceImpl implements IXhpcCardService {

    @Resource
    private XhpcCardMapper xhpcCardMapper;
    @Resource
    private CardHistoryOrderService cardHistoryOrderService;
    @Resource
    private TIccardDeviceMapper tIccardDeviceMapper;
    @Resource
    private TIccardUsersMapper tIccardUsersMapper;
    @Resource
    private TIccardInfoMapper tIccardInfoMapper;
    @Resource
    private XhpcOperatorMapper xhpcOperatorMapper;
    @Resource
    private XhpcAppUserMapper xhpcAppUserMapper;
    @Resource
    private XhpcCommunityPersonnelMapper xhpcCommunityPersonnelMapper;
    @Resource
    private XhpcCustomersPersonnelMapper xhpcCustomersPersonnelMapper;


    ///**
    // * 卡启动充电判断
    // *
    // * @param cardno
    // * @param serialNumber
    // * @return
    // */
    //@Override
    //public R cardStartup(String cardno, String serialNumber) {
    //
    //    IccardInfo iccardInfo = xhpcCardMapper.getIccardInfoCardno(cardno);
    //    if(iccardInfo !=null){
    //        if(iccardInfo.getCardtype()==0){
    //            return R.fail(Constants.OFFLINE_CARD);
    //        }
    //        if(iccardInfo.getStatus()==0){
    //            return R.fail(Constants.ZERO_CARD);
    //        }
    //        if(iccardInfo.getStatus()==2){
    //            return R.fail(Constants.TWO_CARD);
    //        }
    //        if(iccardInfo.getStatus()==3){
    //            return R.fail(Constants.THREE_CARD);
    //        }
    //        if(iccardInfo.getStatus()==4){
    //            return R.fail(Constants.FOUR_CARD);
    //        }
    //    }else{
    //        return R.fail(Constants.LNVALID_CARD);
    //    }
    //    //查询卡号对应的用户
    //    XhpcIcCardInfo xhpcIcCardInfo = xhpcCardMapper.getXhpcIcCardInfo(iccardInfo.getId().toString());
    //    if (xhpcIcCardInfo == null) {
    //        return R.fail(Constants.LNVALID_USER);
    //    }
    //    Long userId = xhpcIcCardInfo.getUserId();
    //    Integer userType = xhpcIcCardInfo.getUserType();
    //    String tenantId = xhpcIcCardInfo.getTenantId();
    //    Integer type = 1;
    //    String grantOperator = xhpcIcCardInfo.getGrantOperatorId();
    //    return cardHistoryOrderService.cardStartup(userId, serialNumber, userType, tenantId, type, grantOperator);
    //}

    @Override
    public R cardStartup(String cardno, String serialNumber,String rateModelId) {

        IccardInfo iccardInfo = xhpcCardMapper.getIccardInfoCardno(cardno);
        if(iccardInfo !=null){
            if(iccardInfo.getCardtype()==0){
                return R.fail(Constants.OFFLINE_CARD);
            }
            if(iccardInfo.getStatus()==0){
                return R.fail(Constants.ZERO_CARD);
            }
            if(iccardInfo.getStatus()==2){
                return R.fail(Constants.TWO_CARD);
            }
            if(iccardInfo.getStatus()==3){
                return R.fail(Constants.THREE_CARD);
            }
            if(iccardInfo.getStatus()==4){
                return R.fail(Constants.FOUR_CARD);
            }
        }else{
            return R.fail(Constants.LNVALID_CARD);
        }
        if("".equals(rateModelId) || rateModelId==null){
            return R.fail(Constants.LNVALID_RATE_MODE);
        }
        //查询卡号对应的用户
        XhpcIcCardInfo xhpcIcCardInfo = xhpcCardMapper.getXhpcIcCardInfo(iccardInfo.getId().toString());
        if(xhpcIcCardInfo ==null){
            return R.fail(Constants.LNVALID_USER);
        }
        Long userId=xhpcIcCardInfo.getUserId();
        Integer userType=xhpcIcCardInfo.getUserType();
        String tenantId=xhpcIcCardInfo.getTenantId();
        Integer type =1;//改成卡授权的类型
        String grantOperator=xhpcIcCardInfo.getGrantOperatorId();//改成卡授权的运营商
        return cardHistoryOrderService.cardStartup(userId, serialNumber, userType,tenantId,type,grantOperator,rateModelId);
    }

    @Override
    public R<ListOfAuthorizedDevices> queryDeviceList(Long currentPage, Long items) {
        //计算分页索引
        currentPage = MyPagingUtil.calculateStartIndex(currentPage, items);
        ListOfAuthorizedDevices listOfAuthorizedDevices = new ListOfAuthorizedDevices();
        listOfAuthorizedDevices.setData(new ArrayList<>());
        listOfAuthorizedDevices.setTotalItems(0);
        List<TIccardDevice> tIccardDeviceList = tIccardDeviceMapper.selectAllByPage(currentPage, items);
        if (tIccardDeviceList.isEmpty()) {
            return R.ok(listOfAuthorizedDevices);
        }
        for (TIccardDevice tIccardDevice : tIccardDeviceList) {
            ListOfAuthorizedDevices.DataDTO dataDTO = new ListOfAuthorizedDevices.DataDTO();
            dataDTO.setDeviceId(tIccardDevice.getId());
            dataDTO.setDeviceName(tIccardDevice.getDevname());
            dataDTO.setDeviceType(tIccardDevice.getDevtype());
            dataDTO.setDeviceNumber(tIccardDevice.getSerialnumber());
            Integer corpindex = tIccardDevice.getCorpindex();
            if (corpindex != null) {
                TIccardUsers tIccardUser = tIccardUsersMapper.selectByPrimaryKey(tIccardDevice.getCorpindex());
                dataDTO.setGrantOperator(tIccardUser.getUsername());
            }
            dataDTO.setType(tIccardDevice.getType());
            listOfAuthorizedDevices.getData().add(dataDTO);
        }
        List<TIccardDevice> tIccardDeviceList1 = tIccardDeviceMapper.selectAll();
        listOfAuthorizedDevices.setTotalItems(tIccardDeviceList1.size());
        return R.ok(listOfAuthorizedDevices);
    }

    @Override
    public R<Object> deleteDevice(Integer deviceId) {

        if (deviceId == null) {
            return R.fail("deviceId为null");
        }
        TIccardDevice tIccardDevice = tIccardDeviceMapper.selectDeletedStatusByDeviceId(deviceId);
        if (tIccardDevice != null) {
            return R.fail(404, "指定资源不存在");
        }
        tIccardDeviceMapper.updateCardDeviceStatusIsDel(deviceId);
        return R.ok();
    }

    @Override
    public R<CardList> queryCardListBy(QueryConditions queryConditions) {
        //todo 最后再做
        //计算分页索引
        long startIndex = MyPagingUtil.calculateStartIndex(queryConditions.getCurrentPage(), queryConditions.getItems());
        queryConditions.setCurrentPage(startIndex);
        CardList cardList = new CardList();
        cardList.setTotalItems(0);
        cardList.setData(new ArrayList<>());
        List<TIccardInfo> tIccardInfoList2 = tIccardInfoMapper.selectAllBy(queryConditions);
        List<TIccardInfo> tIccardInfoList = tIccardInfoMapper.selectAll();
        if (tIccardInfoList.isEmpty()) {
            return R.ok(cardList);
        }
        //1.遍历卡记录
        for (TIccardInfo tIccardInfo : tIccardInfoList) {
            //2.封装通用数据
            CardList.DataDTO dataDTO = new CardList.DataDTO();
            dataDTO.setCardSerialNumber(tIccardInfo.getCardid());
            dataDTO.setCardPhysicalNumber(tIccardInfo.getCardno());
            //获取授权商id
            String corpno = tIccardInfo.getCorpno();
            XhpcOperator xhpcOperator = xhpcOperatorMapper.selectByPrimaryKey(Long.valueOf(corpno));
            dataDTO.setGrantOperator(xhpcOperator.getName());
            dataDTO.setClassification(tIccardInfo.getCardtype());
            //3.判断是否是离线卡，离线卡处理逻辑
            if (dataDTO.getClassification() == 0) {
                dataDTO.setCardType(1);
                //获取卡用户索引，为null表示没有该卡没有绑用户
                Integer userIndex = tIccardInfo.getUserindex();
                if (userIndex == null) {
                    dataDTO.setCardStatus(1);
                } else {
                    dataDTO.setCardStatus(0);
                    dataDTO.setUserType(10);
                    TIccardUsers tIccardUsers = tIccardUsersMapper.selectByPrimaryKey(userIndex);
                    dataDTO.setUserAccount(tIccardUsers.getPhone());
                }
            } else {
                //联网卡处理逻辑
                dataDTO.setCardStatus(0);
                Integer isPlatform = tIccardInfo.getIsPlatform();
                dataDTO.setCardType(isPlatform);
            }
            cardList.getData().add(dataDTO);
        }
        return R.ok(cardList);
    }

    @Override
    public R<BindCardEcho> noBindCardInfo(Long cardId) {

        BindCardEcho bindCardEcho = new BindCardEcho();
        TIccardInfo tIccardInfo = tIccardInfoMapper.selectByPrimaryKey(Math.toIntExact(cardId));
        bindCardEcho.setCardId(tIccardInfo.getCardid());
        bindCardEcho.setCardNo(tIccardInfo.getCardno());
        bindCardEcho.setCardType(tIccardInfo.getCardtype());
        //如果该卡不是联网卡
        if (tIccardInfo.getCardtype() == 0) {
            return R.fail("该卡不是联网卡");
        }
        bindCardEcho.setCardClassification(tIccardInfo.getIsPlatform());
        //如果该卡的分类是平台卡的话
        if (bindCardEcho.getCardClassification() == 0) {
            //0 C端用户 2社区用户 3 B端用户
            int[] userTypeArray = {0, 2, 3};
            List<Integer> userType = Arrays.stream(userTypeArray).boxed().collect(Collectors.toList());
            bindCardEcho.setUserType(userType);

        } else {
            //如果是运营商的话
            //2社区用户 3 B端用户
            int[] userTypeArray = {2, 3};
            List<Integer> userType = Arrays.stream(userTypeArray).boxed().collect(Collectors.toList());
            bindCardEcho.setUserType(userType);
        }
        bindCardEcho.setCashPledge(Long.valueOf(tIccardInfo.getCashpledge()));
        bindCardEcho.setCardRecordId(tIccardInfo.getId());
        return R.ok(bindCardEcho);
    }

    @Override
    public R<SearchCardResponse> searchCardUser(SearchCardUserQueryCondition queryCondition) {
        //计算分页索引
        long startIndex = MyPagingUtil.calculateStartIndex(queryCondition.getCurrentPage(), queryCondition.getItems());
        queryCondition.setCurrentPage(startIndex);
        SearchCardResponse searchCardResponse = new SearchCardResponse();
        searchCardResponse.setData(new ArrayList<>());
        searchCardResponse.setTotalItems(0L);
        //判断是平台还是运营商
        if (queryCondition.getCardClassification() == 0) {
            //(0 C端用户 2社区用户 3 B端用户)
            switch (queryCondition.getUserType()) {
                case 0:
                    List<XhpcAppUser> appUserList = xhpcAppUserMapper.selectByCondition(queryCondition);
                    Long allCount = xhpcAppUserMapper.selectCount(queryCondition);
                    searchCardResponse.setTotalItems(allCount);
                    for (XhpcAppUser xhpcAppUser : appUserList) {
                        SearchCardResponse.DataDTO dataDTO = new SearchCardResponse.DataDTO();
                        dataDTO.setUserAccount(xhpcAppUser.getPhone());
                        dataDTO.setUserType(0);
                        searchCardResponse.getData().add(dataDTO);
                    }
                    break;
                case 2:
                    List<XhpcCommunityPersonnel> xhpcCommunityPersonnelList = xhpcCommunityPersonnelMapper.selectByCondition(queryCondition);
                    Long allCount1 = xhpcCommunityPersonnelMapper.selectCount(queryCondition);
                    searchCardResponse.setTotalItems(allCount1);
                    for (XhpcCommunityPersonnel xhpcCommunityPersonnel : xhpcCommunityPersonnelList) {
                        SearchCardResponse.DataDTO dataDTO = new SearchCardResponse.DataDTO();
                        dataDTO.setUserAccount(xhpcCommunityPersonnel.getAccount());
                        dataDTO.setUserType(2);
                        searchCardResponse.getData().add(dataDTO);
                    }
                    break;
                case 3:
                    List<XhpcCustomersPersonnel> xhpcCustomersPersonnelList = xhpcCustomersPersonnelMapper.selectByCondition(queryCondition);
                    Long allCount2 = xhpcCustomersPersonnelMapper.selectCount(queryCondition);
                    searchCardResponse.setTotalItems(allCount2);
                    for (XhpcCustomersPersonnel xhpcCustomersPersonnel : xhpcCustomersPersonnelList) {
                        SearchCardResponse.DataDTO dataDTO = new SearchCardResponse.DataDTO();
                        dataDTO.setUserAccount(xhpcCustomersPersonnel.getAccount());
                        dataDTO.setUserType(3);
                        searchCardResponse.getData().add(dataDTO);
                    }
                    break;
                default:
                    return R.fail("没有此用户类型");
            }
        } else if (queryCondition.getCardClassification() == 1) {
            XhpcOperator operator = xhpcOperatorMapper.selectByName(queryCondition.getGrantOperatorName());
            if (operator == null) {
                return R.fail("没有此运营商,或未填入授权运营商参数");
            }
            Long operatorId = operator.getOperatorId();
            //2社区用户 3 B端用户)
            switch (queryCondition.getUserType()) {
                case 2:
                    List<XhpcCommunityPersonnel> xhpcCommunityPersonnelList = xhpcCommunityPersonnelMapper.selectByOperatorId(operatorId, queryCondition.getCurrentPage(), queryCondition.getItems());
                    Long allCount1 = xhpcCommunityPersonnelMapper.selectCountByOperatorId(operatorId);
                    searchCardResponse.setTotalItems(allCount1);
                    for (XhpcCommunityPersonnel xhpcCommunityPersonnel : xhpcCommunityPersonnelList) {
                        SearchCardResponse.DataDTO dataDTO = new SearchCardResponse.DataDTO();
                        dataDTO.setUserAccount(xhpcCommunityPersonnel.getAccount());
                        dataDTO.setUserType(2);
                        searchCardResponse.getData().add(dataDTO);
                    }
                    break;
                case 3:
                    List<XhpcCustomersPersonnel> xhpcCustomersPersonnelList = xhpcCustomersPersonnelMapper.selectByOperatorId(operatorId, queryCondition.getCurrentPage(), queryCondition.getItems());
                    Long allCount2 = xhpcCustomersPersonnelMapper.selectCountByOperatorId(operatorId);
                    searchCardResponse.setTotalItems(allCount2);
                    for (XhpcCustomersPersonnel xhpcCustomersPersonnel : xhpcCustomersPersonnelList) {
                        SearchCardResponse.DataDTO dataDTO = new SearchCardResponse.DataDTO();
                        dataDTO.setUserAccount(xhpcCustomersPersonnel.getAccount());
                        dataDTO.setUserType(3);
                        searchCardResponse.getData().add(dataDTO);
                    }
                    break;
                default:
                    return R.fail("没有此用户类型");
            }
        }
        return R.fail("没有此卡类型");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<Object> onlineCardBind(BindCardInfo bindCardInfo) {
        //check card type is online card
        if (bindCardInfo.getCardType() != 1) {
            R.fail("该卡不是联网卡");
        }
        //build an association
        XhpcIcCardInfo xhpcIcCardInfo = new XhpcIcCardInfo();
        xhpcIcCardInfo.setTIccardInfoId(String.valueOf(bindCardInfo.getCardRecordId()));
        xhpcIcCardInfo.setUseStatus(1L);
        xhpcIcCardInfo.setCreateTime(new Date());
        TIccardInfo tIccardInfo = tIccardInfoMapper.selectByPrimaryKey(bindCardInfo.getCardRecordId());
        xhpcIcCardInfo.setUserId(tIccardInfo.getUserindex());
        xhpcIcCardInfo.setUserAccount(bindCardInfo.getUserAccount());
        xhpcIcCardInfo.setUserType(Long.valueOf(bindCardInfo.getUserType()));
        xhpcCardMapper.insertSelective(xhpcIcCardInfo);
        return R.ok();
    }

}
