package com.slodon.b2b2c.model.seller;

import cn.hutool.json.JSONObject;
import com.gexin.fastjson.JSON;
import com.slodon.b2b2c.core.constant.BizTypeConst;
import com.slodon.b2b2c.core.constant.SMSConst;
import com.slodon.b2b2c.core.constant.VendorConst;
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.sms.SmsResponse;
import com.slodon.b2b2c.core.util.AssertUtil;
import com.slodon.b2b2c.core.util.Md5;
import com.slodon.b2b2c.core.util.StringUtil;
import com.slodon.b2b2c.dao.read.seller.StoreReadMapper;
import com.slodon.b2b2c.dao.read.seller.VendorReadMapper;
import com.slodon.b2b2c.dao.read.seller.VendorRolesReadMapper;
import com.slodon.b2b2c.dao.write.seller.VendorWriteMapper;
import com.slodon.b2b2c.seller.dto.VendorAddDTO;
import com.slodon.b2b2c.seller.dto.VendorRegisterDTO;
import com.slodon.b2b2c.seller.example.VendorExample;
import com.slodon.b2b2c.seller.example.VendorRolesExample;
import com.slodon.b2b2c.seller.pojo.Store;
import com.slodon.b2b2c.seller.pojo.Vendor;
import com.slodon.b2b2c.seller.pojo.VendorRoles;
import com.slodon.b2b2c.sms.DySmsSender;
import com.slodon.b2b2c.sms.base.SmsSender;
import com.slodon.smartid.client.utils.SmartId;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class VendorModel {

    @Resource
    private VendorReadMapper vendorReadMapper;
    @Resource
    private VendorWriteMapper vendorWriteMapper;
    @Resource
    private VendorRolesReadMapper vendorRolesReadMapper;
    @Resource
    private StoreReadMapper storeReadMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private StoreModel storeModel;

    /**
     * 新增商家表
     *
     * @param vendor 商户信息
     * @return Integer
     */
    public Integer saveVendor(Vendor vendor) {
        int count = vendorWriteMapper.insert(vendor);
        if (count == 0) {
            throw new MallException("添加商家表失败，请重试");
        }
        return count;
    }

    /**
     * 添加子账号
     *
     * @param vendorAddDTO 前端传来的参数
     * @param storeId      店铺id
     * @param ip           IP地址
     * @return
     */
    public void saveVendor(VendorAddDTO vendorAddDTO, Long storeId, String ip) {
        //账号名称查重
        VendorExample example = new VendorExample();
        example.setVendorName(vendorAddDTO.getVendorName());
        example.setIsAllowLoginNotEquals(VendorConst.LOGOUT_ALLOW_LOGIN);
        int count = vendorReadMapper.countByExample(example);
        AssertUtil.isTrue(count > 0, "账号名称已存在！");
        //账号手机号查重
        example.setVendorName(null);
        example.setVendorMobile(vendorAddDTO.getVendorMobile());
        count = vendorReadMapper.countByExample(example);
        AssertUtil.isTrue(count > 0, "该手机号已被其他账号绑定，请重新填写");
        //账号邮箱查重
        example.setVendorMobile(null);
        example.setVendorEmail(vendorAddDTO.getVendorEmail());
        count = vendorReadMapper.countByExample(example);
        AssertUtil.isTrue(count > 0, "该邮箱已被其他账号绑定，请重新填写");

        JSONObject jsonObject=storeModel.getStoreUrlsObject(storeId,vendorAddDTO.getVendorName());

        //添加vendor
        Vendor vendor = new Vendor();
        BeanUtils.copyProperties(vendorAddDTO, vendor);
        vendor.setVendorId(SmartId.nextId(BizTypeConst.VENDOR));
        vendor.setStoreId(storeId);
        vendor.setVendorPassword(Md5.getMd5String(vendorAddDTO.getVendorPassword()));
        vendor.setIsStoreAdmin(VendorConst.IS_STORE_ADMIN_0);
        vendor.setRegisterTime(new Date());
        vendor.setLatestLoginTime(new Date());
        vendor.setIsAllowLogin(VendorConst.IS_ALLOW_LOGIN);
        vendor.setLatestLoginIp(ip);
        vendor.setStoreUrlBy9710(jsonObject.getStr("storeUrlBy9710"));
        vendor.setStoreUrlBy9810(jsonObject.getStr("storeUrlBy9810"));
        this.saveVendor(vendor);
    }

    /**
     * 注册商家账号
     *
     * @param vendorRegisterDTO 前端传来的参数
     */
    @Transactional(rollbackFor = Exception.class)
    public void registerVendor(VendorRegisterDTO vendorRegisterDTO) throws Exception {
        //商户账号重复判断
        VendorExample example = new VendorExample();
        example.setVendorName(vendorRegisterDTO.getVendorName().trim());
        example.setIsAllowLoginNotEquals(VendorConst.LOGOUT_ALLOW_LOGIN);
        List<Vendor> vendors = vendorReadMapper.listByExample(example);
        AssertUtil.isTrue(!CollectionUtils.isEmpty(vendors), "商户账号名称已存在，请重新输入");

        //判断手机号是否存在
        VendorExample vendorExample = new VendorExample();
        vendorExample.setVendorMobile(vendorRegisterDTO.getVendorMobile());
        vendorExample.setIsAllowLoginNotEquals(VendorConst.LOGOUT_ALLOW_LOGIN);
        List<Vendor> vendorList = vendorReadMapper.listByExample(vendorExample);

        AssertUtil.isTrue(!CollectionUtils.isEmpty(vendorList), "此手机号已绑定商家账号");

        Vendor vendor = new Vendor();
        PropertyUtils.copyProperties(vendor, vendorRegisterDTO);
        //数据合格，插入vendor表
        vendor.setVendorName(vendorRegisterDTO.getVendorName().trim());
        vendor.setVendorPassword(Md5.getMd5String(vendorRegisterDTO.getVendorPassword()));

        //注册的商家，暂时无店铺，店铺id设置为0
        vendor.setStoreId(0L);

        //查询内置商家角色
        VendorRolesExample rolesExample = new VendorRolesExample();
        rolesExample.setIsInner(1);
        rolesExample.setOrderBy("roles_id asc");
        List<VendorRoles> vendorRoles = vendorRolesReadMapper.listByExample(rolesExample);
        if (CollectionUtils.isEmpty(vendorRoles)) {
            vendor.setRolesId(0);
        } else {
            vendor.setRolesId(vendorRoles.get(0).getRolesId());
        }

        //注册时默认超级管理员
        vendor.setIsStoreAdmin(VendorConst.IS_STORE_ADMIN_1);
        vendor.setRegisterTime(new Date());
        vendor.setLatestLoginTime(new Date());
        vendor.setLatestLoginIp(vendorRegisterDTO.getIp());
        vendor.setVendorId(SmartId.nextId(BizTypeConst.VENDOR));
        this.saveVendor(vendor);
    }

    /**
     * 根据vendorId删除商家表
     *
     * @param vendorId 商户id
     */
    public void deleteVendor(Long vendorId) {
        if (StringUtils.isEmpty(vendorId)) {
            throw new MallException("请选择要删除的数据");
        }
        int count = vendorWriteMapper.deleteByPrimaryKey(vendorId);
        if (count == 0) {
            log.error("根据vendorId：" + vendorId + "删除商家表失败");
            throw new MallException("删除商家表失败,请重试");
        }
    }

    /**
     * 根据vendorId更新商家表
     *
     * @param vendor 商户信息
     */
    public void updateVendor(Vendor vendor) {
        //账号名称查重
        if (!StringUtils.isEmpty(vendor.getVendorName())) {
            VendorExample example = new VendorExample();
            example.setVendorName(vendor.getVendorName());
            example.setVendorIdNotEquals(vendor.getVendorId());
            example.setIsAllowLoginNotEquals(VendorConst.LOGOUT_ALLOW_LOGIN);
            int count = vendorReadMapper.countByExample(example);
            AssertUtil.isTrue(count > 0, "账号名称已存在");
        }
        //账号手机号查重
        if (!StringUtils.isEmpty(vendor.getVendorMobile())) {
            VendorExample example = new VendorExample();
            example.setVendorMobile(vendor.getVendorMobile());
            example.setVendorIdNotEquals(vendor.getVendorId());
            example.setIsAllowLoginNotEquals(VendorConst.LOGOUT_ALLOW_LOGIN);
            int count = vendorReadMapper.countByExample(example);
            AssertUtil.isTrue(count > 0, "该手机号已被其他账号绑定，请重新填写");
        }
        //账号邮箱查重
        if (!StringUtils.isEmpty(vendor.getVendorEmail())) {
            VendorExample example = new VendorExample();
            example.setVendorEmail(vendor.getVendorEmail());
            example.setVendorIdNotEquals(vendor.getVendorId());
            example.setIsAllowLoginNotEquals(VendorConst.LOGOUT_ALLOW_LOGIN);
            int count = vendorReadMapper.countByExample(example);
            AssertUtil.isTrue(count > 0, "该邮箱已被其他账号绑定，请重新填写");
        }
        int count = vendorWriteMapper.updateByPrimaryKeySelective(vendor);
        if (count == 0) {
            log.error("根据vendorId：" + vendor.getVendorId() + "更新商家表失败");
            throw new MallException("更新商家表失败,请重试");
        }
    }

    /**
     * 根据vendorId获取商家表详情
     *
     * @param vendorId 商户id
     * @return 商户信息
     */
    public Vendor getVendorByVendorId(Long vendorId) {
        Vendor vendor = vendorReadMapper.getByPrimaryKey(vendorId);
        AssertUtil.notNull(vendor, "获取商户信息为空，请重试");
        if (!StringUtil.isNullOrZero(vendor.getStoreId())) {
            //查询店铺信息
            Store store = storeReadMapper.getByPrimaryKey(vendor.getStoreId());
            AssertUtil.notNull(store, "获取店铺信息为空，请重试");
            vendor.setStore(store);
        }
        return vendor;
    }

    /**
     * 根据条件获取商家表列表
     *
     * @param example 查询条件信息
     * @param pager   分页信息
     * @return
     */
    public List<Vendor> getVendorList(VendorExample example, PagerInfo pager) {
        List<Vendor> vendorList;
        if (pager != null) {
            pager.setRowsCount(vendorReadMapper.countByExample(example));
            vendorList = vendorReadMapper.listPageByExample(example, pager.getStart(), pager.getPageSize());
        } else {
            vendorList = vendorReadMapper.listByExample(example);
        }
        return vendorList;
    }

    /**
     * 获取店铺主账号id
     *
     * @param vendor 店铺管理员
     * @return 店铺主账号id
     */
    public Long getStoreMainVendorId(Vendor vendor) {
        if (vendor.getIsStoreAdmin().equals(VendorConst.IS_STORE_ADMIN_1)) {
            //该管理员为主账号
            return vendor.getVendorId();
        }
        VendorExample vendorExample = new VendorExample();
        vendorExample.setStoreId(vendor.getStoreId());
        vendorExample.setIsStoreAdmin(VendorConst.IS_STORE_ADMIN_1);
        List<Vendor> vendors = vendorReadMapper.listByExample(vendorExample);
        return vendors.get(0).getVendorId();
    }


    /**
     * 发送商家入驻成功短信
     *
     * @param vendorRegisterDTO
     */
    public void sendVendorRegisterOkSms(VendorRegisterDTO vendorRegisterDTO) {
        log.info("*********** 开始发送商家入驻成功短信::sendVendorRegisterOkSms **********");
        log.info("**** 商家信息如下:{} ****", JSON.toJSONString(vendorRegisterDTO));
        if (StringUtil.isEmpty(vendorRegisterDTO.getVendorMobile())) {
            return;
        }
        SmsSender smsSender = new DySmsSender(stringRedisTemplate);
        SmsRequest smsRequest = new SmsRequest();
        smsRequest.setSmsType(SMSConst.NOTIFICATION_SMS);
        smsRequest.setMobile(vendorRegisterDTO.getVendorMobile());
        String templateCode = stringRedisTemplate.opsForValue().get("notification_sms_ali_register_success_sms_template");
        if (!StringUtil.isEmpty(templateCode)) {
            smsRequest.setTemplateId(templateCode);
            smsSender.sendSms(smsRequest);
        }
    }
}