package com.jeequan.jeepay.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.SysUser;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.db.entity.*;
import com.jeequan.jeepay.service.mapper.MchStoreMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 商户门店表 服务实现类
 * </p>
 *
 * @author [mybatis plus generator]
 * @since 2021-12-28
 */
@Slf4j
@Service
public class MchStoreService extends ServiceImpl<MchStoreMapper, MchStore> {

    @Autowired
    private PayOrderService payOrderService;
    @Autowired
    private MchStoreDeviceService mchStoreDeviceService;
    @Autowired
    private MchQrcodeCardService mchQrcodeCardService;
    @Autowired
    private SysUserMchStoreRelaService mchStoreRelaService;
    @Autowired
    private MchQrcodeCardService qrcodeCardService;
    @Autowired
    private MchStoreMapper mchStoreMapper;

    /**
     * 获取到默认门店
     **/
    public MchStore queryDefaultStore(String mchNo) {
        return this.getOne(Wrappers.lambdaQuery(MchStore.class).eq(MchStore::getMchNo, mchNo).eq(MchStore::getDefaultFlag, CS.YES), false);
    }

    /**
     * 修改当前商户下所有门店为非默认
     **/
    public void updateAllDefaultFlag(String mchNo) {
        Assert.hasLength(mchNo, "用户号不能为空");
        lambdaUpdate().eq(MchStore::getMchNo, mchNo)
                .set(MchStore::getDefaultFlag, CS.NO)
                .update();
    }


    /**
     * 删除门店
     **/
    @Transactional
    public void deleteStore(String recordId, boolean isMchDelete) {

        // 校验当前门店
        MchStore mchStore = getById(recordId);
        if (mchStore == null) {
            throw new BizException("门店不存在");
        }
        if (!isMchDelete) {
            if (mchStore.getDefaultFlag() == CS.YES) {
                throw new BizException("默认门店不可删除");
            }
            // 商户门店数不可为空
            long storeCount = lambdaQuery().eq(MchStore::getMchNo, mchStore.getMchNo()).count();
            if (storeCount <= 1) {
                throw new BizException("不可删除商户最后一个门店");
            }
        }

        // 判断门店是否已配置关联
        long payOrderCount = payOrderService.count(Wrappers.lambdaQuery(PayOrder.class).eq(PayOrder::getStoreId, recordId));
        if (payOrderCount > 0) {
            throw new BizException("当前门店已经存在交易，暂不支持删除操作");
        }

        // 门店设备配置
        List<MchStoreDevice> storeDeviceList = mchStoreDeviceService.list(MchStoreDevice.gw().eq(MchStoreDevice::getStoreId, recordId));

        // 商户码牌
        List<MchQrcodeCard> qrcodeCardList = mchQrcodeCardService.list(MchQrcodeCard.gw().eq(MchQrcodeCard::getStoreId, recordId));

        if (!storeDeviceList.isEmpty()) {
            boolean updateDevice = mchStoreDeviceService.update(
                    Wrappers.lambdaUpdate(MchStoreDevice.class)
                            .eq(MchStoreDevice::getStoreId, recordId)
                            .set(MchStoreDevice::getBindState, CS.NO)
                            .set(MchStoreDevice::getStoreId, "")
            );
            if (!updateDevice) {
                log.info("解绑门店设备配置失败");
                throw new BizException("解绑门店设备配置失败，请联系管理员。");
            }
        }
        if (!qrcodeCardList.isEmpty()) {
            // 更新门店码牌配置
            boolean updateCard = mchQrcodeCardService.update(
                    Wrappers.lambdaUpdate(MchQrcodeCard.class)
                            .eq(MchQrcodeCard::getStoreId, recordId)
                            .set(MchQrcodeCard::getBindState, CS.NO)
                            .set(MchQrcodeCard::getMchNo, mchStore.getMchNo()));
            if (!updateCard) {
                log.info("更新门店码牌配置失败");
                throw new BizException("更新门店码牌配置失败，请联系管理员。");
            }
        }

        // 删除门店
        int result = baseMapper.deleteById(recordId);
        if (result == 0) {
            throw new BizException("删除门店信息失败，请联系管理员。");
        }
    }

    public IPage<MchStore> listByPage(IPage<MchStore> iPage, MchStore mchStore, JSONObject paramJSON) {

        // 时间搜索
        Date[] searchDateRange = mchStore.buildQueryDateRange();
        mchStore.setFirstDate(searchDateRange[0]);
        mchStore.setLastDate(searchDateRange[1]);
        IPage<MchStore> mchStorePage = mchStoreMapper.listByPage(iPage, mchStore, paramJSON);
        if (!CollUtil.isEmpty(mchStorePage.getRecords())) {
            List<MchStore> recordsStoreList = mchStorePage.getRecords();
            for (MchStore storeItem : recordsStoreList) {
                //返回门店绑定的码牌数量
                if (StringUtils.isNotEmpty(storeItem.getStoreId())) {
                    List<MchQrcodeCard> mchQrcodeCardList = qrcodeCardService.list(MchQrcodeCard.gw().eq(MchQrcodeCard::getStoreId, storeItem.getStoreId()));
                    if (mchQrcodeCardList.isEmpty()){
                        storeItem.setDeviceNumber(0);
                    }else {
                        storeItem.setDeviceNumber(mchQrcodeCardList.size());
                    }
                }
                //手机号脱敏
                if (StringUtils.isNotEmpty(storeItem.getMchServicePhone())){
                    storeItem.setMchServicePhone(DesensitizedUtil.mobilePhone(storeItem.getMchServicePhone()));
                }
                if (StringUtils.isNotEmpty(storeItem.getContactPhone())){
                    storeItem.setContactPhone(DesensitizedUtil.mobilePhone(storeItem.getContactPhone()));
                }
                if (StringUtils.isNotEmpty(storeItem.getMchUserPhone())){
                    storeItem.setMchUserPhone(DesensitizedUtil.mobilePhone(storeItem.getMchUserPhone()));
                }
            }
        }
        return mchStorePage;
    }

    public IPage<MchStore> getBindStoreList(IPage<MchStore> iPage, MchStore mchStore, JSONObject paramJSON) {

        IPage<MchStore> storeList = listByPage(iPage, mchStore, paramJSON);
        // 待绑定门店的用户ID
        String userId = paramJSON.getString("userId");
        HashMap<String, String> userIdMap = new HashMap<>();
        Byte userType = paramJSON.getByte("userType");
        // 店长增加条件
        if (SysUser.UEST_TYPE_DIRECTOR == userType) {
            // 非本用户绑定的店长类型门店
            List<SysUserMchStoreRela> relaList = mchStoreRelaService.list(
                    Wrappers.lambdaQuery(SysUserMchStoreRela.class)
                            .ne(ObjectUtil.isNotEmpty(userId), SysUserMchStoreRela::getSysUserId, userId)
                            .eq(SysUserMchStoreRela::getUserType, SysUser.UEST_TYPE_DIRECTOR)
            );

            if (!ObjectUtils.isEmpty(relaList)) {
                relaList.forEach(item -> {
                    userIdMap.put(ObjectUtil.defaultIfBlank(item.getStoreId(), ""), ObjectUtil.defaultIfBlank(item.getStoreId(), ""));
                });

                // 门店是否有店长
                storeList.getRecords().forEach(item -> {
                    item.addExt("hasDirector", ObjectUtil.isNotEmpty(userIdMap.get(item.getStoreId())));
                });

                return storeList;
            }

        }

        return storeList;
    }

    /**
     * 根据新版商户号获取门店信息
     *
     * @param mchApplyId
     * @return
     */
    public MchStore getByMchApplyId(String mchApplyId) {
        return this.getOne(MchStore.gw().eq(MchStore::getMchApplyId, mchApplyId), false);
    }

    /**
     * 根据用户号获取门店id
     *
     * @param mchNo
     * @return
     */
    public List<String> listByMchNo(String mchNo) {
        LambdaQueryWrapper<MchStore> wrapper = Wrappers.lambdaQuery(MchStore.class)
                .eq(MchStore::getMchNo, mchNo).select(MchStore::getStoreId);
        return this.listObjs(wrapper, Object::toString);
    }
}
