package com.slodon.b2b2c.model.seller;

import cn.hutool.core.collection.CollectionUtil;
import com.gexin.fastjson.JSON;
import com.slodon.b2b2c.core.constant.*;
import com.slodon.b2b2c.core.exception.MallException;
import com.slodon.b2b2c.core.response.PagerInfo;
import com.slodon.b2b2c.core.sms.SmsRequest;
import com.slodon.b2b2c.core.uid.GoodsIdGenerator;
import com.slodon.b2b2c.core.util.AssertUtil;
import com.slodon.b2b2c.core.util.StringUtil;
import com.slodon.b2b2c.dao.read.goods.GoodsCategoryReadMapper;
import com.slodon.b2b2c.dao.read.seller.StoreApplyReadMapper;
import com.slodon.b2b2c.dao.read.seller.StoreCertificateReadMapper;
import com.slodon.b2b2c.dao.read.seller.StoreGradeReadMapper;
import com.slodon.b2b2c.dao.read.seller.StoreNameReadMapper;
import com.slodon.b2b2c.dao.write.seller.StoreApplyWriteMapper;
import com.slodon.b2b2c.dao.write.seller.StoreBindCategoryWriteMapper;
import com.slodon.b2b2c.dao.write.seller.StoreCertificateWriteMapper;
import com.slodon.b2b2c.dao.write.seller.StoreNameWriteMapper;
import com.slodon.b2b2c.enums.WebSiteConstant;
import com.slodon.b2b2c.goods.example.GoodsCategoryExample;
import com.slodon.b2b2c.goods.pojo.GoodsCategory;
import com.slodon.b2b2c.seller.dto.StoreApplyDTO;
import com.slodon.b2b2c.seller.dto.StoreSiteCategoryInfoDTO;
import com.slodon.b2b2c.seller.example.StoreApplyExample;
import com.slodon.b2b2c.seller.example.StoreBindCategoryExample;
import com.slodon.b2b2c.seller.example.StoreCertificateExample;
import com.slodon.b2b2c.seller.example.StoreNameExample;
import com.slodon.b2b2c.seller.pojo.*;
import com.slodon.b2b2c.sms.DySmsSender;
import com.slodon.b2b2c.sms.base.SmsSender;
import com.slodon.b2b2c.system.pojo.Admin;
import com.slodon.smartid.client.utils.SmartId;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class StoreApplyModel {

    @Resource
    private StoreApplyReadMapper storeApplyReadMapper;
    @Resource
    private StoreNameReadMapper storeNameReadMapper;
    @Resource
    private StoreNameWriteMapper storeNameWriteMapper;
    @Resource
    private StoreApplyWriteMapper storeApplyWriteMapper;
    @Resource
    private StoreGradeReadMapper storeGradeReadMapper;
    @Resource
    private StoreCertificateReadMapper storeCertificateReadMapper;
    @Resource
    private StoreCertificateWriteMapper storeCertificateWriteMapper;
    @Resource
    private StoreBindCategoryWriteMapper storeBindCategoryWriteMapper;
    @Resource
    private GoodsCategoryReadMapper goodsCategoryReadMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private VendorModel vendorModel;

    /**
     * 新增商家申请表
     *
     * @param storeApply
     * @return
     */
    public Integer saveStoreApply(StoreApply storeApply) {
        int count = storeApplyWriteMapper.insert(storeApply);
        if (count == 0) {
            throw new MallException("添加商家申请表失败，请重试");
        }
        return count;
    }

    /**
     * 保存商家申请信息
     *
     * @param storeApplyDTO 商户申请信息
     * @param vendor        商户账号
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveStoreApplyInfo(StoreApplyDTO storeApplyDTO, Vendor vendor) throws Exception {
        //重复判断：企业入驻时公司名称不能重复
        String companyName = null;
        if (storeApplyDTO.getEnterType() == StoreConst.APPLY_TYPE_COMPANY) {
            companyName = storeApplyDTO.getCompanyName().trim();

            StoreCertificateExample example = new StoreCertificateExample();
            example.setCompanyName(companyName);
            int count = storeCertificateReadMapper.countByExample(example);
            AssertUtil.isTrue(count > 0, "公司名称已存在");
        }

        Long storeId = SmartId.nextId(BizTypeConst.STORE);
        if (CollectionUtil.isEmpty(storeApplyDTO.getSiteInfoList())){
            throw new MallException("请选择经营信息");
        }

        for (StoreSiteCategoryInfoDTO siteCategoryInfoDTO : storeApplyDTO.getSiteInfoList()) {
            //重复判断：店铺名称不能重复
            String storeName = siteCategoryInfoDTO.getStoreName().trim();
            if (WebSiteConstant.MEMBER_OVERSEA.equals(siteCategoryInfoDTO.getWebSite())) {
                StoreApplyExample example = new StoreApplyExample();
                example.setState(StoreConst.STATE_4_STORE_OPEN);
                example.setStoreName(storeName);
                int count = storeApplyReadMapper.countByExample(example);
                AssertUtil.isTrue(count > 0, "店铺名称已存在");
                //插入store_apply表
                StoreApply storeApply = new StoreApply();
                storeApply.setVendorId(vendor.getVendorId());
                storeApply.setVendorName(vendor.getVendorName());
                storeApply.setStoreName(storeName);
                storeApply.setState(StoreConst.STATE_1_SEND_APPLY);
//                storeApply.setApplyYear(storeApplyDTO.getApplyYear());
//                storeApply.setStoreGradeId(storeApplyDTO.getStoreGradeId());
                storeApply.setApplyYear(NumConstant.ONE);
                storeApply.setStoreGradeId(StoreConst.STORE_CRADE_1);
                storeApply.setSubmitTime(new Date());
                storeApply.setStoreId(storeId);
                storeApply.setStoreType(StoreConst.NO_OWN_STORE);
//                storeApply.setSiteInfoJson(JSON.toJSONString(storeApplyDTO.getSiteInfoList()));
                //根据gradeId查询收费标准
                StoreGrade storeGrade = storeGradeReadMapper.getByPrimaryKey(StoreConst.STORE_CRADE_1);
//                 storeApply.setPayAmount(new BigDecimal(storeGrade.getPrice()).multiply(new BigDecimal(storeApplyDTO.getApplyYear())));
                count = storeApplyWriteMapper.insert(storeApply);
                if (count == 0) {
                    throw new MallException("店铺申请表添加失败，请重试");
                }
            } else {
                StoreNameExample example = new StoreNameExample();
                example.setStoreName(storeName);
                example.setWebSite(siteCategoryInfoDTO.getWebSite());
                int count = storeNameReadMapper.countByExample(example);
                AssertUtil.isTrue(count > 0, "店铺名称已存在");
                StoreName name = new StoreName();
                name.setStoreName(storeName);
                name.setWebSite(siteCategoryInfoDTO.getWebSite());
                name.setStoreId(storeId);
                name.setCreateId(vendor.getVendorId());
                name.setCreateTime(new Date());
                name.setUpdateId(vendor.getVendorId());
                name.setUpdateTime(new Date());
                count = storeNameWriteMapper.insert(name);
                if (count == 0) {
                    throw new MallException("店铺名称表添加失败，请重试");
                }
            }
        }

        //插入store_certificate表
        StoreCertificate storeCertificate = new StoreCertificate();
        PropertyUtils.copyProperties(storeCertificate, storeApplyDTO);

        storeCertificate.setVendorId(vendor.getVendorId());
        storeCertificate.setVendorName(vendor.getVendorName());
        storeCertificate.setCompanyName(companyName);

        int count = storeCertificateWriteMapper.insert(storeCertificate);
        if (count == 0) {
            throw new MallException("店铺资质表添加失败，请重试");
        }

        GoodsCategoryExample goodsCategoryExample = new GoodsCategoryExample();
        List<GoodsCategory> goodsCategoryList = goodsCategoryReadMapper.listByExample(goodsCategoryExample);

        for (StoreSiteCategoryInfoDTO siteCategoryInfoDTO : storeApplyDTO.getSiteInfoList()) {
            //插入store_bind_category表
            StoreBindCategory storeBindCategory = new StoreBindCategory();
            storeBindCategory.setStoreId(0L);
            storeBindCategory.setWebSite(siteCategoryInfoDTO.getWebSite());
            storeBindCategory.setCreateVendorId(vendor.getVendorId());
            storeBindCategory.setCreateTime(new Date());
            storeBindCategory.setState(StoreConst.STORE_CATEGORY_STATE_SEND);

            String[] split = siteCategoryInfoDTO.getGoodsCategoryIds().split(",");
            for (String goodsCategoryId : split) {
                String[] split1 = goodsCategoryId.split("-");
                storeBindCategory.setGoodsCategoryId1(Integer.parseInt(split1[0]));
                storeBindCategory.setGoodsCategoryId2(Integer.parseInt(split1[1]));
                storeBindCategory.setGoodsCategoryId3(Integer.parseInt(split1[2]));
                //根据一级分类id查询一级分类名称
                GoodsCategory goodsCategory1 = goodsCategoryList.stream()
                        .filter(goodsCategory -> goodsCategory.getCategoryId().equals(Integer.valueOf(split1[0])))
                        .findFirst()
                        .orElseThrow(() -> new MallException("未找到对应的一级商品分类"));
                //根据二级分类id查询二级分类名称
                GoodsCategory goodsCategory2 = goodsCategoryList.stream()
                        .filter(goodsCategory -> goodsCategory.getCategoryId().equals(Integer.valueOf(split1[1])))
                        .findFirst()
                        .orElseThrow(() -> new MallException("未找到对应的二级商品分类"));
                //根据三级分类id查询三级分类名称
                GoodsCategory goodsCategory3 = goodsCategoryList.stream()
                        .filter(goodsCategory -> goodsCategory.getCategoryId().equals(Integer.valueOf(split1[2])))
                        .findFirst()
                        .orElseThrow(() -> new MallException("未找到对应的三级商品分类"));
                //拼接类目组合名称
                String goodsCateName = goodsCategory1.getCategoryName() + ">" + goodsCategory2.getCategoryName() + ">" + goodsCategory3.getCategoryName();
                storeBindCategory.setGoodsCateName(goodsCateName);
                storeBindCategory.setScaling(goodsCategory3.getScaling());
                count = storeBindCategoryWriteMapper.insert(storeBindCategory);
                if (count == 0) {
                    throw new MallException("店铺可用商品分类表添加失败，请重试");
                }

            }
        }

    }

    /**
     * 根据applyId删除商家申请表
     *
     * @param applyId applyId
     * @return
     */
    public Integer deleteStoreApply(Integer applyId) {
        if (StringUtils.isEmpty(applyId)) {
            throw new MallException("请选择要删除的数据");
        }
        int count = storeApplyWriteMapper.deleteByPrimaryKey(applyId);
        if (count == 0) {
            log.error("根据applyId：" + applyId + "删除商家申请表失败");
            throw new MallException("删除商家申请表失败,请重试");
        }
        return count;
    }

    /**
     * 根据applyId更新商家申请表
     *
     * @param storeApply
     * @return
     */
    public Integer updateStoreApply(StoreApply storeApply) {
        if (StringUtils.isEmpty(storeApply.getApplyId())) {
            throw new MallException("请选择要修改的数据");
        }
        int count = storeApplyWriteMapper.updateByPrimaryKeySelective(storeApply);
        if (count == 0) {
            log.error("根据applyId：" + storeApply.getApplyId() + "更新商家申请表失败");
            throw new MallException("更新商家申请表失败,请重试");
        }
        return count;
    }

    /**
     * 根据applyId更新商家申请表
     *
     * @param storeApplyDTO 修改的申请信息
     * @param vendor        商户账号
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateStoreApplyInfo(StoreApplyDTO storeApplyDTO, Vendor vendor) throws Exception {
        //重复判断：企业入驻时公司名称不能重复
        String companyName = null;
        if (storeApplyDTO.getEnterType() == StoreConst.APPLY_TYPE_COMPANY) {
            companyName = storeApplyDTO.getCompanyName().trim();
            if (!StringUtils.isEmpty(companyName)) {
                StoreCertificateExample example = new StoreCertificateExample();
                example.setCompanyName(companyName);
                example.setVendorIdNotEquals(vendor.getVendorId());
                int count = storeCertificateReadMapper.countByExample(example);
                AssertUtil.isTrue(count > 0, "公司名称已存在");
            }
        }

        if (CollectionUtil.isEmpty(storeApplyDTO.getSiteInfoList())){
            throw new MallException("请选择经营信息");
        }

        for (StoreSiteCategoryInfoDTO siteCategoryInfoDTO : storeApplyDTO.getSiteInfoList()) {
            //重复判断：店铺名称不能重复
            String storeName = siteCategoryInfoDTO.getStoreName().trim();
            if (!StringUtils.isEmpty(storeName)) {
                if (WebSiteConstant.MEMBER_OVERSEA.equals(siteCategoryInfoDTO.getWebSite())) {
                    StoreApplyExample example = new StoreApplyExample();
                    example.setStoreName(storeName);
                    example.setVendorIdNotEquals(vendor.getVendorId());
                    int count = storeApplyReadMapper.countByExample(example);
                    AssertUtil.isTrue(count > 0, "店铺名称已存在");
                    //更新store_apply表
                    StoreApply storeApply = storeApplyReadMapper.getByPrimaryKey(storeApplyDTO.getApplyId());
                    PropertyUtils.copyProperties(storeApply, storeApplyDTO);
                    storeApply.setStoreName(storeName);
                    storeApply.setState(StoreConst.STATE_1_SEND_APPLY);
                    storeApply.setSubmitTime(new Date());
                    count = storeApplyWriteMapper.updateByPrimaryKeySelective(storeApply);
                    if (count == 0) {
                        log.error("根据applyId：" + storeApply.getApplyId() + "更新商家申请表失败");
                        throw new MallException("更新商家申请表失败,请重试");
                    }
                } else {
                    int count;
                    if (siteCategoryInfoDTO.getId() != null) {
                        StoreNameExample example = new StoreNameExample();
                        example.setIdNotEquals(siteCategoryInfoDTO.getId());
                        example.setStoreName(storeName);
                        example.setWebSite(siteCategoryInfoDTO.getWebSite());
                        count = storeNameReadMapper.countByExample(example);
                        AssertUtil.isTrue(count > 0, "店铺名称已存在");
                        StoreName name = storeNameReadMapper.getByPrimaryKey(siteCategoryInfoDTO.getId());
                        PropertyUtils.copyProperties(name, siteCategoryInfoDTO);
                        name.setStoreName(storeName);
                        name.setUpdateId(vendor.getVendorId());
                        name.setUpdateTime(new Date());
                        count = storeNameWriteMapper.updateByPrimaryKeySelective(name);
                        if (count == 0) {
                            log.error("根据id：" + name.getId() + "更新店铺名称表失败");
                            throw new MallException("更新店铺名称表失败,请重试");
                        }
                    } else {
                        StoreName name = new StoreName();
                        PropertyUtils.copyProperties(name, siteCategoryInfoDTO);
                        StoreApply storeApply = storeApplyReadMapper.getByPrimaryKey(storeApplyDTO.getApplyId());
                        name.setStoreId(storeApply.getStoreId());
                        name.setStoreName(storeName);
                        name.setCreateId(vendor.getVendorId());
                        name.setCreateTime(new Date());
                        count = storeNameWriteMapper.insert(name);
                        if (count == 0) {
                            log.error("添加店铺名称表失败");
                            throw new MallException("添加店铺名称表失败,请重试");
                        }
                    }

                }

            }
        }
        StoreCertificate storeCertificate = storeCertificateReadMapper.getByPrimaryKey(storeApplyDTO.getCertificateId());
        PropertyUtils.copyProperties(storeCertificate, storeApplyDTO);


        //更新store_certificate表
        storeCertificate.setCompanyName(companyName);
        int count = storeCertificateWriteMapper.updateByPrimaryKeySelective(storeCertificate);
        if (count == 0) {
            log.error("根据certificateId：" + storeCertificate.getCertificateId() + "更新商家资质表失败");
            throw new MallException("更新商家资质表失败,请重试");
        }

        //更新store_bind_category表
        StoreBindCategoryExample storeBindCategoryExample = new StoreBindCategoryExample();
        storeBindCategoryExample.setCreateVendorId(vendor.getVendorId());
        storeBindCategoryWriteMapper.deleteByExample(storeBindCategoryExample);

        GoodsCategoryExample goodsCategoryExample = new GoodsCategoryExample();
        List<GoodsCategory> goodsCategoryList = goodsCategoryReadMapper.listByExample(goodsCategoryExample);

        for (StoreSiteCategoryInfoDTO siteCategoryInfoDTO : storeApplyDTO.getSiteInfoList()) {
            StoreBindCategory storeBindCategory = new StoreBindCategory();
            storeBindCategory.setStoreId(0L);
            storeBindCategory.setWebSite(siteCategoryInfoDTO.getWebSite());
            storeBindCategory.setCreateVendorId(vendor.getVendorId());
            storeBindCategory.setCreateTime(new Date());
            storeBindCategory.setState(StoreConst.STORE_CATEGORY_STATE_SEND);

            String[] split = siteCategoryInfoDTO.getGoodsCategoryIds().split(",");
            for (String goodsCategoryId : split) {
                String[] split1 = goodsCategoryId.split("-");
                storeBindCategory.setGoodsCategoryId1(Integer.parseInt(split1[0]));
                storeBindCategory.setGoodsCategoryId2(Integer.parseInt(split1[1]));
                storeBindCategory.setGoodsCategoryId3(Integer.parseInt(split1[2]));
                //根据一级分类id查询一级分类名称
                GoodsCategory goodsCategory1 = goodsCategoryList.stream()
                        .filter(goodsCategory -> goodsCategory.getCategoryId().equals(Integer.valueOf(split1[0])))
                        .findFirst()
                        .orElseThrow(() -> new MallException("未找到对应的一级商品分类"));
                //根据二级分类id查询二级分类名称
                GoodsCategory goodsCategory2 = goodsCategoryList.stream()
                        .filter(goodsCategory -> goodsCategory.getCategoryId().equals(Integer.valueOf(split1[1])))
                        .findFirst()
                        .orElseThrow(() -> new MallException("未找到对应的二级商品分类"));
                //根据三级分类id查询三级分类名称
                GoodsCategory goodsCategory3 = goodsCategoryList.stream()
                        .filter(goodsCategory -> goodsCategory.getCategoryId().equals(Integer.valueOf(split1[2])))
                        .findFirst()
                        .orElseThrow(() -> new MallException("未找到对应的三级商品分类"));
                //拼接类目组合名称
                String goodsCateName = goodsCategory1.getCategoryName() + ">" + goodsCategory2.getCategoryName() + ">" + goodsCategory3.getCategoryName();
                storeBindCategory.setGoodsCateName(goodsCateName);
                storeBindCategory.setScaling(goodsCategory3.getScaling());
                count = storeBindCategoryWriteMapper.insert(storeBindCategory);
                if (count == 0) {
                    throw new MallException("店铺可用商品分类表添加失败，请重试");
                }
            }
        }
    }

    /**
     * 根据applyId审核商户入驻请求
     *
     * @param applyId        申请id
     * @param isPass         是否通过[true==通过,false==驳回]
     * @param refuseReason   审核原因
     * @param remark         备注
     * @param scalingBindIds 分佣比例集合：bindId1-scaling1,bindId2-scaling2,...
     * @param admin          审核管理员
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public StoreApply audit(Integer applyId, Boolean isPass, String refuseReason, String remark, String scalingBindIds, Admin admin) {
        //通过applyId查询数据库中的请求
        StoreApply storeApply = storeApplyReadMapper.getByPrimaryKey(applyId);
        if (storeApply == null) {
            //数据库里不存在该商家的申请
            throw new MallException("您无权进行此操作");
        }

        //审核前的状态
        Integer oldState = storeApply.getState();
        if (oldState != StoreConst.STATE_1_SEND_APPLY) {
            throw new MallException("该申请不在审核状态");
        }

        //计算审核后的状态
        int newState;
        if (isPass) {
            newState = StoreConst.STATE_2_DONE_APPLY;
            //生成支付单号，计算支付金额
//            storeApply.setPaySn(GoodsIdGenerator.getPaySn());
//            //根据gradeId查询收费标准
//            StoreGrade storeGrade = storeGradeReadMapper.getByPrimaryKey(storeApply.getStoreGradeId());
//            storeApply.setPayAmount(new BigDecimal(storeGrade.getPrice()).multiply(new BigDecimal(storeApply.getApplyYear())));
//            storeApply.setPaymentCode(OrderPaymentConst.PAYMENT_CODE_ONLINE);
//            storeApply.setPaymentName(OrderPaymentConst.PAYMENT_NAME_ONLINE);
        } else {
            newState = StoreConst.STATE_3_FAIL_APPLY;
        }
        storeApply.setState(newState);
        storeApply.setApplyTime(new Date());
        //处理审核意见
        storeApply.setRefuseReason(refuseReason == null ? "" : refuseReason);
        storeApply.setAuditInfo(remark == null ? "" : remark);
        //更新store_apply表
        int count;
        count = storeApplyWriteMapper.updateByPrimaryKeySelective(storeApply);
        if (count == 0) {
            throw new MallException("更新店铺申请失败");
        }

        if (isPass) {
            //2022-10-17 add if(!"".equals(scalingBindIds) && scalingBindIds!=null){}
            if (!"".equals(scalingBindIds) && scalingBindIds != null) {
                //审核成功，❶修改store_apply表;❷修改store_bind_category表，填写分佣比例;❸新增一个店铺，插入store表,;❹将storeId插入到vendor表
                //获取所有的分佣比例
                String[] scalings = scalingBindIds.split(",");
                //获取bindId对应的分佣比例
                for (String sca : scalings) {
                    String[] split = sca.split("-");
                    String bindId = split[0];
                    String scaling = split[1];
                    if (Double.valueOf(scaling).intValue() > 1 || Double.valueOf(scaling).intValue() < 0) {
                        throw new MallException("请填写0到1之间的数字");
                    }
                    //根据bingId插入scaling
                    StoreBindCategory storeBindCategory = new StoreBindCategory();
                    storeBindCategory.setBindId(Integer.parseInt(bindId));
                    storeBindCategory.setScaling(new BigDecimal(scaling));
                    storeBindCategory.setState(StoreConst.STORE_CATEGORY_STATE_PASS);
                    storeBindCategory.setAuditAdminId(admin.getAdminId());
                    storeBindCategory.setAuditTime(new Date());
                    count = storeBindCategoryWriteMapper.updateByPrimaryKeySelective(storeBindCategory);
                    if (count == 0) {
                        throw new MallException("添加分佣比例失败，请重试");
                    }
                }
            }

        }
        return storeApply;
    }


    /**
     * 发送商家店铺入驻审核通过短信
     *
     * @param storeApply
     */
    public void sendApplyStoreOkSms(StoreApply storeApply) {
        log.info("*********** 开始发送商家店铺审核通过短信::storeApply **********");
        log.info("**** 商家申请店铺信息如下:{} ****", JSON.toJSONString(storeApply));
        Vendor vendor = vendorModel.getVendorByVendorId(storeApply.getVendorId());
        if (StringUtil.isEmpty(vendor.getVendorMobile())) {
            return;
        }
        SmsSender smsSender = new DySmsSender(stringRedisTemplate);
        SmsRequest smsRequest = new SmsRequest();
        smsRequest.setSmsType(SMSConst.NOTIFICATION_SMS);
        smsRequest.setMobile(vendor.getVendorMobile());
        String templateCode = stringRedisTemplate.opsForValue().get("notification_sms_ali_store_apply_ok_sms_template");
        if (!StringUtil.isEmpty(templateCode)) {
            smsRequest.setTemplateId(templateCode);
            smsSender.sendSms(smsRequest);
        }
    }

    /**
     * 发送商家店铺入驻审核通过短信
     *
     * @param vendorMobiles
     */
    public void sendApplyStoreOkSms(String vendorMobiles) {
        log.info("*********** 开始发送商家店铺审核通过短信::storeApply **********");
        log.info("**** 商家申请店铺信息如下:{} ****", vendorMobiles);
        if (StringUtil.isEmpty(vendorMobiles)) {
            return;
        }
        SmsSender smsSender = new DySmsSender(stringRedisTemplate);
        SmsRequest smsRequest = new SmsRequest();
        smsRequest.setSmsType(SMSConst.NOTIFICATION_SMS);
        smsRequest.setMobile(vendorMobiles);
        String templateCode = stringRedisTemplate.opsForValue().get("notification_sms_ali_store_apply_ok_sms_template");
        if (!StringUtil.isEmpty(templateCode)) {
            smsRequest.setTemplateId(templateCode);
            smsSender.sendSms(smsRequest);
        }
    }

    /**
     * 发送商家店铺入驻审核失败短信
     *
     * @param storeApply
     */
    public void sendApplyStoreFailedSms(StoreApply storeApply) {
        log.info("*********** 开始发送商家店铺审核拒绝短信::sendVendorRegisterOkSms **********");
        log.info("**** 商家申请店铺信息如下:{} ****", JSON.toJSONString(storeApply));
        Vendor vendor = vendorModel.getVendorByVendorId(storeApply.getVendorId());
        if (StringUtil.isEmpty(vendor.getVendorMobile())) {
            return;
        }
        SmsSender smsSender = new DySmsSender(stringRedisTemplate);
        SmsRequest smsRequest = new SmsRequest();
        smsRequest.setSmsType(SMSConst.NOTIFICATION_SMS);
        smsRequest.setMobile(vendor.getVendorMobile());
        String templateCode = stringRedisTemplate.opsForValue().get("notification_sms_ali_store_apply_fail_sms_template");
        if (!StringUtil.isEmpty(templateCode)) {
            smsRequest.setTemplateId(templateCode);
            smsSender.sendSms(smsRequest);
        }
    }

    /**
     * 发送商家店铺入驻审核失败短信
     *
     * @param vendorMobiles
     */
    public void sendApplyStoreFailedSms(String vendorMobiles) {
        log.info("*********** 开始发送商家店铺审核拒绝短信::sendVendorRegisterOkSms **********");
        log.info("**** 商家申请店铺信息如下:{} ****", vendorMobiles);
        if (StringUtil.isEmpty(vendorMobiles)) {
            return;
        }
        SmsSender smsSender = new DySmsSender(stringRedisTemplate);
        SmsRequest smsRequest = new SmsRequest();
        smsRequest.setSmsType(SMSConst.NOTIFICATION_SMS);
        smsRequest.setMobile(vendorMobiles);
        String templateCode = stringRedisTemplate.opsForValue().get("notification_sms_ali_store_apply_fail_sms_template");
        if (!StringUtil.isEmpty(templateCode)) {
            smsRequest.setTemplateId(templateCode);
            smsSender.sendSms(smsRequest);
        }
    }

    /**
     * 根据applyId审核商户入驻请求 批量
     *
     * @param applyId        申请id
     * @param isPass         是否通过[true==通过,false==驳回]
     * @param refuseReason   审核原因
     * @param remark         备注
     * @param scalingBindIds 分佣比例集合：bindId1-scaling1,bindId2-scaling2,...
     * @param admin          审核管理员
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public StoreApply auditNew(Integer applyId, Boolean isPass, String refuseReason, String remark, String scalingBindIds, Admin admin) {
        //通过applyId查询数据库中的请求
        StoreApply storeApply = storeApplyReadMapper.getByPrimaryKey(applyId);
        if (storeApply == null) {
            //数据库里不存在该商家的申请
            throw new MallException("您无权进行此操作");
        }

        //审核前的状态
        Integer oldState = storeApply.getState();
        if (oldState != StoreConst.STATE_1_SEND_APPLY) {
            throw new MallException("该申请不在审核状态");
        }

        //计算审核后的状态
        int newState;
        if (isPass) {
            newState = StoreConst.STATE_2_DONE_APPLY;
//            //生成支付单号，计算支付金额
//            storeApply.setPaySn(GoodsIdGenerator.getPaySn());
//            //根据gradeId查询收费标准
//            StoreGrade storeGrade = storeGradeReadMapper.getByPrimaryKey(storeApply.getStoreGradeId());
//            storeApply.setPayAmount(new BigDecimal(storeGrade.getPrice()).multiply(new BigDecimal(storeApply.getApplyYear())));
//            storeApply.setPaymentCode(OrderPaymentConst.PAYMENT_CODE_ONLINE);
//            storeApply.setPaymentName(OrderPaymentConst.PAYMENT_NAME_ONLINE);
        } else {
            newState = StoreConst.STATE_3_FAIL_APPLY;
        }
        storeApply.setState(newState);
        storeApply.setApplyTime(new Date());
        //处理审核意见
        storeApply.setRefuseReason(refuseReason == null ? "" : refuseReason);
        storeApply.setAuditInfo(remark == null ? "" : remark);
        //更新store_apply表
        int count;
        count = storeApplyWriteMapper.updateByPrimaryKeySelective(storeApply);
        if (count == 0) {
            throw new MallException("更新店铺申请失败");
        }

        if (isPass) {
            //2022-10-17 add if(!"".equals(scalingBindIds) && scalingBindIds!=null){}
            if (!"".equals(scalingBindIds) && scalingBindIds != null) {
                //审核成功，❶修改store_apply表;❷修改store_bind_category表，填写分佣比例;❸新增一个店铺，插入store表,;❹将storeId插入到vendor表
                //获取所有的分佣比例
                String[] scalings = scalingBindIds.split(",");
                //获取bindId对应的分佣比例
                for (String sca : scalings) {
                    String[] split = sca.split("-");
                    String bindId = split[0];
                    String scaling = split[1];
                    String createVendorId = split[2];
                    if (Double.valueOf(scaling).intValue() > 1 || Double.valueOf(scaling).intValue() < 0) {
                        throw new MallException("请填写0到1之间的数字");
                    }
                    if (Integer.valueOf(createVendorId).intValue() == storeApply.getVendorId()) {
                        //根据bingId插入scaling
                        StoreBindCategory storeBindCategory = new StoreBindCategory();
                        storeBindCategory.setBindId(Integer.parseInt(bindId));
                        storeBindCategory.setScaling(new BigDecimal(scaling));
                        storeBindCategory.setState(StoreConst.STORE_CATEGORY_STATE_PASS);
                        storeBindCategory.setAuditAdminId(admin.getAdminId());
                        storeBindCategory.setAuditTime(new Date());
                        count = storeBindCategoryWriteMapper.updateByPrimaryKeySelective(storeBindCategory);
                        if (count == 0) {
                            throw new MallException("添加分佣比例失败，请重试");
                        }
                    } else {

                    }

                }
            }

        }
        return storeApply;
    }

    /**
     * 根据applyId获取商家申请表详情
     *
     * @param applyId applyId
     * @return
     */
    public StoreApply getStoreApplyByApplyId(Integer applyId) {
        return storeApplyReadMapper.getByPrimaryKey(applyId);
    }

    /**
     * 根据条件获取商家申请表列表
     *
     * @param example 查询条件信息
     * @param pager   分页信息
     * @return
     */
    public List<StoreApply> getStoreApplyList(StoreApplyExample example, PagerInfo pager) {
        List<StoreApply> storeApplyList;
        if (pager != null) {
            pager.setRowsCount(storeApplyReadMapper.countByExample(example));
            storeApplyList = storeApplyReadMapper.listPageByExample(example, pager.getStart(), pager.getPageSize());
        } else {
            storeApplyList = storeApplyReadMapper.listByExample(example);
        }
        return storeApplyList;
    }

    /**
     * 根据条件获取商家申请表数量
     *
     * @param example 查询条件信息
     * @return
     */
    public Integer getStoreApplyCount(StoreApplyExample example) {
        return storeApplyReadMapper.countByExample(example);
    }

    /**
     * 获取店铺审核手机号
     *
     * @return
     */
    public List<String> getStoreApplyVendorMobile(List<String> ids) {
        return storeApplyReadMapper.getVendorMobileByStoreApply(ids);
    }

    public List<StoreApply> getStoreApplyCnList(StoreApplyExample example, PagerInfo pager) {
        pager.setRowsCount(storeApplyReadMapper.countCnByExample(example));
        return storeApplyReadMapper.listCnPageByExample(example, pager.getStart(), pager.getPageSize());
    }
}