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.universal.dto.SendMsgDTO;
import com.xxfc.platform.universal.feign.MQSenderFeign;
import com.github.wxiaoqi.security.admin.dto.CompanyInfoFindDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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
    ConfigFeign  configFeign;

    @Autowired
    BranchCompanyBiz branchCompanyBiz;

    @Autowired
    GroupBiz groupBiz;

    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 {
            insertSelective(companyInfo);
            id=companyInfo.getId();
            //初始化商家账号
            addUser(id);
            //初始化店铺
            BranchCompany branchCompany = getBranchCompanyInfo();
            branchCompany.setCompanyId(id);
            branchCompany.setInviterAccount(companyInfoApply.getInviterAccount());
            branchCompany.setCode(CODE+ReferralCodeUtil.encode(companyInfoApply.getId().intValue()));
            branchCompanyBiz.addOrUpd(branchCompany);
        }
        sendQueue(companyInfo);
        return  id;
    }



    //初始化店铺信息
    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 {
            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);
    }

}
