package com.github.wxiaoqi.security.admin.biz;


import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.wxiaoqi.security.admin.entity.*;
import com.github.wxiaoqi.security.admin.mapper.CompanyInfoMapper;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.ReferralCodeUtil;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.xxfc.platform.app.entity.Cofig;
import com.xxfc.platform.app.feign.ConfigFeign;
import com.xxfc.platform.im.dto.AppUserV2DTO;
import com.xxfc.platform.im.feign.ImFeign;
import com.xxfc.platform.universal.dto.SendMsgDTO;
import com.xxfc.platform.universal.dto.UploadImgDTO;
import com.xxfc.platform.universal.feign.MQSenderFeign;
import com.github.wxiaoqi.security.admin.dto.CompanyInfoFindDTO;
import com.xxfc.platform.universal.feign.ThirdFeign;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

import static com.github.wxiaoqi.security.common.config.rabbit.RabbitConstant.*;


@Service
@Slf4j
public class CompanyInfoBiz extends BaseBiz<CompanyInfoMapper, CompanyInfo>{



    @Autowired
    MQSenderFeign mqSenderFeign;

    @Autowired
    AppUserLoginBiz appUserBiz;

    @Autowired
    UserBiz userBiz;

    @Autowired
    AppUserDetailBiz appUserDetailBiz;


    @Autowired
    ConfigFeign  configFeign;

    @Autowired
    BranchCompanyBiz branchCompanyBiz;

    @Autowired
    GroupBiz groupBiz;

    @Autowired
    AppUserRelationBiz userRelationBiz;

    @Autowired
    CompanyWalletBiz companyWalletBiz;

    @Autowired
    ThirdFeign thirdFeign;

    @Autowired
    ImFeign imFeign;

    public   static  final  String CODE="SHOP-";





    public Long addOrUpd(CompanyInfoApply companyInfoApply){
        Long id = companyInfoApply.getBranchId() == null ? 0L :companyInfoApply.getBranchId();
        List<CompanyInfo> list=getListByExample(id,companyInfoApply.getName());
        if (list.size() > 0){
            throw  new BaseException("公司名称不能重复", ResultCode.FAILED_CODE);
        }
        CompanyInfo companyInfo=JSONUtil.toBean(companyInfoApply.getDetailJson(),CompanyInfo.class);
        if (id  > 0L ){
            companyInfo.setId(id);
            updateSelectiveById(companyInfo);
        }else {
            setHeadLog(companyInfo);
            insertSelective(companyInfo);
            id=companyInfo.getId();
            //初始化商家账号
            addUser(id);
            //初始化店铺
            setInviterAccount(companyInfoApply);
            //修改app用户资料
            setHeadImg(companyInfo);
            BranchCompany branchCompany = getBranchCompanyInfo();
            BeanUtils.copyProperties(companyInfo,branchCompany);
            branchCompany.setCompanyId(id);
            branchCompany.setInviterAccount(companyInfoApply.getInviterAccount());
            branchCompany.setCode(CODE+ReferralCodeUtil.encode(companyInfoApply.getId().intValue()));
            branchCompany.setLeader(companyInfoApply.getContact());
            branchCompany.setLeaderContactInfo(companyInfoApply.getMobile());
            branchCompanyBiz.addOrUpd(branchCompany);
            CompanyWallet companyWallet = new CompanyWallet();
            companyWallet.setCompanyId(branchCompany.getId());
            companyWalletBiz.insertSelective(companyWallet);
        }
        sendQueue(companyInfo);
        return  id;
    }
    public  void  setHeadImg(CompanyInfo companyInfo){
        UploadImgDTO uploadImgDTO = new UploadImgDTO();
        uploadImgDTO.setUserId(companyInfo.getAppUserId());
        uploadImgDTO.setPrefix(companyInfo.getHeadLogo());
        try {
            ObjectRestResponse<String> restResponse = thirdFeign.uploadHead(uploadImgDTO);
            AppUserDetail userDetail = new AppUserDetail();

            if (org.apache.commons.lang.StringUtils.isNotBlank(restResponse.getData())){
                userDetail.setHeadimgurl(restResponse.getData());
            }
            if (org.apache.commons.lang.StringUtils.isNotBlank(companyInfo.getName())){
                AppUserLogin userLogin = appUserBiz.selectById(companyInfo.getAppUserId());
                if (userLogin != null ){
                    AppUserV2DTO appUserV2DTO = new AppUserV2DTO();
                    appUserV2DTO.setNickname(companyInfo.getName());
                    appUserV2DTO.setPhone(userLogin.getUsername());
                    imFeign.updateV2(appUserV2DTO);
                }
            }
            userDetail.setNickname(companyInfo.getName());
            appUserDetailBiz.updateSelectiveById(userDetail);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public  void  setHeadLog(CompanyInfo companyInfo){
        String headLog = companyInfo.getHeadLogo();
        if (StringUtils.isBlank(headLog)){
            Long id = companyInfo.getId() == null ? 0L : companyInfo.getId();
            if ( id > 0){
                CompanyInfo companyInfo1=selectById(id);
                headLog=companyInfo1 == null ? null : companyInfo1.getHeadLogo();
            }
            headLog = StringUtils.isBlank(headLog) ? "https://chwplatform.upyuns.com/image/app/shop_logo_default.png" : headLog;
        }
        companyInfo.setHeadLogo(headLog);
    }

    //app上级用户为店铺推荐人
    public  void  setInviterAccount(CompanyInfoApply companyInfoApply){
        Integer inviterAccount = companyInfoApply.getInviterAccount() == null ? 0 : companyInfoApply.getInviterAccount();
        if (inviterAccount == 0){
            Integer appUserId = companyInfoApply.getAppUserId() == null ? 0 : companyInfoApply.getAppUserId();
            if (appUserId > 0){
                AppUserRelation appUserRelation = userRelationBiz.getRelationByUserId(appUserId);
                if (appUserRelation != null ){
                    companyInfoApply.setInviterAccount(appUserRelation.getParentId());
                }

            }
        }
    }



    //初始化店铺信息
    public BranchCompany getBranchCompanyInfo(){
        try {
            List<Cofig> list=configFeign.getAllByType(ConfigFeign.TYPE_BRANCH_COMPANY+"").getData();
            if (list!=null && list.size()>0){
                String params=list.get(0).getParams();
                return  JSONUtil.toBean(params, BranchCompany.class);
            }
        }catch (Exception e){
            log.error(e.getMessage(), e);;
        }
        return  null;
    }


    public  void   saveOrUpd(CompanyInfo companyInfo){
        Long id = companyInfo.getId() == null ? 0L :companyInfo.getId();
        if (id  > 0L ){
            updateSelectiveById(companyInfo);
        }else {
            setHeadLog(companyInfo);
            insertSelective(companyInfo);
        }
        sendQueue(companyInfo);
    }


    private void sendQueue(CompanyInfo companyInfo) {
        try {

            SendMsgDTO sendMsgDTO = new SendMsgDTO() {{
                setExchange(ADMIN_TOPIC);
            }};
            sendMsgDTO.setJson(JSONUtil.toJsonStr(companyInfo));
            sendMsgDTO.setRoutKey(KEY_CORPORATION_UPD);
            mqSenderFeign.postSendMessage(sendMsgDTO);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
    public List<CompanyInfo>  getListByExample(Long id,String name){
        Example example=new Example(CompanyInfo.class);
        example.createCriteria().andEqualTo("name",name).andNotEqualTo("id",id);
        return  selectByExample(example);
    }


    public List<CompanyInfo> getList(CompanyInfoFindDTO companyInfoFindDTO){
        Example example=new Example(CompanyInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("isDel",0);
        if (StringUtils.isNotBlank(companyInfoFindDTO.getName()) ){
            criteria.andLike("name","%" + companyInfoFindDTO.getName() + "%");
        }
        if (companyInfoFindDTO.getIds() != null && companyInfoFindDTO.getIds().size() > 0){
            criteria.andIn("id",companyInfoFindDTO.getIds());
        }
        if (companyInfoFindDTO.getDataCorporationIds() != null && companyInfoFindDTO.getDataCorporationIds().size() > 0){
            criteria.andIn("id",companyInfoFindDTO.getDataCorporationIds());
        }
        example.setOrderByClause("crt_time desc ");

        return  selectByExample(example);
    }

    public ObjectRestResponse selectList(CompanyInfoFindDTO companyInfoFindDTO){
        PageHelper.startPage(companyInfoFindDTO.getPage(), companyInfoFindDTO.getLimit());
        PageInfo<CompanyInfo> pageInfo = new PageInfo<>(getList(companyInfoFindDTO));
        return ObjectRestResponse.succ(PageDataVO.pageInfo(pageInfo));
    }

    public  void  addUser(Long branchId){
        CompanyInfo companyInfo = selectById(branchId);
        Integer appUserId=companyInfo.getAppUserId() == null ? 0 : companyInfo.getAppUserId();
        AppUserLogin appUser = appUserBiz.selectById(appUserId);
        if (appUser == null || StringUtils.isBlank(appUser.getUsername())){
            throw  new BaseException("app用户不存在",ResultCode.FAILED_CODE);
        }
        String username=appUser.getUsername();
        User user = userBiz.getUserByUsername(username);
        if (user != null ){
            throw  new BaseException("商家用户已存在相同手机号"+username,ResultCode.FAILED_CODE);
        }
        String password=username.substring(5);
        user =new User();
        user.setUsername(username);
        user.setMobilePhone(username);
        user.setName(companyInfo.getName());
        user.setPassword(password);
        user.setStatus(1);
        user.setCorporationId(branchId);
        user.setDataAll(2);
        user.setDataCorporation(branchId+"");
        user.setAppUserId(appUserId);
        userBiz.insertSelective(user);
        List<Integer> members=new ArrayList<>();
        members.add(6);
        groupBiz.modifyUserGroups(user.getId(),members);
    }

    public CompanyInfo getInfoByCompanyId(Integer companyId){
        return  mapper.getInfoByCompanyId(companyId);
    }

}
