package com.xkrs.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.xkrs.common.encapsulation.PromptMessageEnum;
import com.xkrs.dao.*;
import com.xkrs.model.entity.*;
import com.xkrs.model.qo.BankCardQo;
import com.xkrs.model.qo.BusinessQo;
import com.xkrs.service.MerchantSettlementService;
import com.xkrs.utils.*;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.crypto.keygen.KeyGenerators;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import static com.xkrs.common.encapsulation.OutputEncapsulation.outputEncapsulationObject;
import static com.xkrs.utils.DateTimeUtil.dateTimeToString;
import static com.xkrs.utils.DateTimeUtil.getNowTime;
import static com.xkrs.utils.EncryptDecryptUtil.encry256;

/**
 * @Author: XinYi Song
 * @Date: 2021/12/14 9:52
 * 商家模块
 */
@Service
public class MerchantSettlementServiceImpl implements MerchantSettlementService {

    @Resource
    private BusinessDao businessDao;

    @Resource
    private BankCardDao bankCardDao;

    @Resource
    private Query query;

    @Resource
    private SysUserDao sysUserDao;

    @Resource
    private RelUserRoleDao relUserRoleDao;

    @Resource
    private RelRoleAuthorityDao relRoleAuthorityDao;

    /**
     * 商家入驻
     * @param businessQo
     * @param
     * @param
     * @param bankCardQos
     * @param
     * @return
     */
    @Override
    public String merchantSettlement(BusinessQo businessQo, List<Object> bankCardQos) throws IOException {
        Locale locale = LocaleContextHolder.getLocale();
        BusinessEntity byBusinessName = businessDao.findByBusinessName(businessQo.getBusinessName());
        if(byBusinessName != null){
            return outputEncapsulationObject(PromptMessageEnum.FILE_EXISTS,"您已入驻，请勿重复入驻或提交！",locale);
        }
        BusinessEntity byBusinessPhone = businessDao.findByBusinessPhone(businessQo.getBusinessPhone());
        if(byBusinessPhone != null){
            return outputEncapsulationObject(PromptMessageEnum.FILE_EXISTS,"该手机号已用于入驻，请勿重复使用！",locale);
        }
        for(Object bankCardQo : bankCardQos){
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(bankCardQo));
            BankCardQo bankCardQo1 = jsonObject.toJavaObject(BankCardQo.class);
            Map<String, Object> stringObjectMap = VerifyBankCardUtil.checkBankCar(bankCardQo1.getBankCardNumber());
            if(!((Boolean) stringObjectMap.get("card")) || "findNotName".equals(stringObjectMap.get("cardName").toString())){
                return outputEncapsulationObject(PromptMessageEnum.DATA_WRONG,"银行卡信息有误，请检查重新填写！",locale);
            }
            BankCardEntity bankCardEntity = new BankCardEntity();
            bankCardEntity.setBankCardNumber(bankCardQo1.getBankCardNumber());
            bankCardEntity.setAccountBank(bankCardQo1.getAccountBank());
            bankCardEntity.setBankName(stringObjectMap.get("cardName").toString());
//            bankCardEntity.setBusinessId(businessId);
            bankCardEntity.setBusinessPhone(businessQo.getBusinessPhone());
            bankCardDao.save(bankCardEntity);
        }
        BusinessEntity businessEntity = new BusinessEntity();
        businessEntity.setBusinessName(businessQo.getBusinessName());
        businessEntity.setBusinessPro(businessQo.getBusinessPro());
        businessEntity.setBusinessCity(businessQo.getBusinessCity());
        businessEntity.setBusinessCountry(businessQo.getBusinessCountry());
        businessEntity.setBusinessAddress(businessQo.getBusinessAddress());
        businessEntity.setBusinessPhone(businessQo.getBusinessPhone());
        businessEntity.setBusinessPhoto(businessQo.getBusinessPhoto());
        businessEntity.setBusinessLicense(businessQo.getBusinessLicense());
        businessEntity.setBusinessDiscount(businessQo.getBusinessDiscount());
        businessEntity.setHeadIdentifier(businessQo.getHeadIdentifier());
        businessEntity.setBusinessType("0");
        businessEntity.setSettleInTime(DateTimeUtil.dateTimeToString(LocalDateTime.now()));
        businessDao.save(businessEntity);
        return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"提交成功！等待总部审核！",locale);
    }

    /**
     * 通过状态查询商家入驻的信息
     * @param type
     * @return
     */
    @Override
    public String findAllByBusinessType(String type) {
        Locale locale = LocaleContextHolder.getLocale();
        List<BusinessEntity> allByBusinessType = businessDao.findAllByBusinessType(type);
        if(allByBusinessType == null || allByBusinessType.size() == 0){
            return outputEncapsulationObject(PromptMessageEnum.DATA_NONE,"暂时没有您所需要的商家的信息！",locale);
        }
        return outputEncapsulationObject(PromptMessageEnum.SUCCESS,allByBusinessType,locale);
    }

    /**
     * 根据省市区查询审核通过的商家的信息
     * @param countyName
     * @param keepType
     * @return
     */
    @Override
    public String findAllByCountyName(String countyName, String keepType) {
        return null;
    }

    /**
     * 根据商家用户id查询入驻信息
     * @param businessId
     * @return
     */
    @Override
    public String findBusinessById(Integer businessId) {
        Locale locale = LocaleContextHolder.getLocale();
        BusinessEntity byBusinessId = businessDao.findByBusinessIdAndBusinessType(businessId,"1");
        if(byBusinessId == null){
            return outputEncapsulationObject(PromptMessageEnum.DATA_NONE,"你还未入驻，请先入驻！",locale);
        }
        return outputEncapsulationObject(PromptMessageEnum.SUCCESS,byBusinessId,locale);
    }

    /**
     * 市区查询商家的信息
     * @param businessCity
     * @param businessCountry
     * @param businessName
     * @return
     */
    @Override
    public String selectAllBusiness(String businessCity, String businessCountry, String businessName) {
        Locale locale = LocaleContextHolder.getLocale();
        List<BusinessEntity> businessEntities = query.selectAllBusiness(businessCity, businessCountry, businessName);
        if(businessEntities == null || businessEntities.size() == 0){
            return outputEncapsulationObject(PromptMessageEnum.DATA_NONE,"暂时没有任何商家的信息！",locale);
        }
        return outputEncapsulationObject(PromptMessageEnum.SUCCESS,businessEntities,locale);
    }

    /**
     * 对商家入驻进行审核（1审核通过  2审核不通过）
     * @param id
     * @param
     * @return
     */
    @Transactional(rollbackOn = Exception.class)
    @Override
    public String updatePassBusiness(Integer id,String username,String province,String city,String county) throws ClientException {
        Locale locale = LocaleContextHolder.getLocale();
        /*BusinessEntity businessEntity = businessDao.findById(id);
        if("1".equals(businessEntity.getBusinessType())){
            return outputEncapsulationObject(PromptMessageEnum.PROCESS_FAIL,"该商家已被审核并已通过审核！",locale);
        }*/
        String salt = KeyGenerators.string().generateKey();
        SysUserEntity sysUserEntity = new SysUserEntity();
        sysUserEntity.setUserName(username);
        sysUserEntity.setSalt(salt);
        sysUserEntity.setPassword(encry256("lyb123" + salt));
        sysUserEntity.setActiveFlag(0);
        sysUserEntity.setStatusCode(0);
        sysUserEntity.setAddTime(getNowTime());
        sysUserEntity.setProvince(province);
        sysUserEntity.setCity(city);
        sysUserEntity.setCounty(county);
        sysUserEntity.setDeleteFlag(0);
        int i = (int)(Math.random()*9+1)*100000;
        sysUserEntity.setIdentifier(String.valueOf(i));
        sysUserEntity.setIdentity("affiliate_merchant");

        sysUserDao.save(sysUserEntity);

        RelUserRoleEntity relUserRoleEntity = new RelUserRoleEntity();
        relUserRoleEntity.setUserId(sysUserEntity.getId().longValue());
        relUserRoleEntity.setRoleId(6);

        RelRoleAuthorityEntity relRoleAuthorityEntity = new RelRoleAuthorityEntity();
        relRoleAuthorityEntity.setRoleId(6);
        relRoleAuthorityEntity.setAuthorityId(6);
        relRoleAuthorityEntity.setUserId(sysUserEntity.getId());
        relUserRoleDao.save(relUserRoleEntity);

        relRoleAuthorityDao.save(relRoleAuthorityEntity);

        // 这一块整合手机号发送初始账号，密码，发送给对应得商家，并提醒及时修改初始账号密码
        SendSmsResponse lyb123 = AliYunSmsUtils.sendSmsToBusinessPass(username, username, "lyb123");

        // 修改商家入驻得状态（通过）
        businessDao.updatePassBusiness(id,dateTimeToString(LocalDateTime.now()),sysUserEntity.getId());

        return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"操作成功！",locale);
    }

    /**
     * 拒绝商家入驻的请求（审核不通过）
     * @param id
     * @param phone
     * @return
     */
    @Override
    public String updateNotPassBusiness(Integer id, String phone) throws ClientException {
        Locale locale = LocaleContextHolder.getLocale();
        SendSmsResponse sendSmsResponse = AliYunSmsUtils.sendSmsToBusinessNotPass(phone);
        businessDao.updateNotPassBusiness(id);
        return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"操作成功！",locale);
    }

    /**
     * 总部查看要审核的商家的信息
     * @param businessCity
     * @param businessCountry
     * @param businessName
     * @return
     */
    @Override
    public String selectDefaultBusiness(String businessCity, String businessCountry, String businessName) {
        Locale locale = LocaleContextHolder.getLocale();
        List<BusinessEntity> businessEntities = query.selectDefaultBusiness(businessCity, businessCountry, businessName);
        if(businessEntities == null || businessEntities.size() == 0){
            return outputEncapsulationObject(PromptMessageEnum.DATA_NONE,"暂时还没有要审核的商家的信息！",locale);
        }
        return outputEncapsulationObject(PromptMessageEnum.SUCCESS,businessEntities,locale);
    }
}
