package com.sptg.estate.biz.service.impl;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import com.sptg.common.core.constant.OperationConstant;
import com.sptg.estate.api.dto.MemberDto;
import com.sptg.estate.api.entity.*;
import com.sptg.estate.biz.event.ApplyUserAddEvent;
import com.sptg.estate.biz.mapper.MemberMapper;
import com.sptg.estate.biz.service.*;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * title: MemberServiceImpl
 * package: com.sptg.estate.biz.security.impl
 * description: 会员  服务层实现类
 *
 *               
 *                
 */
@Service
@AllArgsConstructor
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberServiceInterface {

    private final UserServiceInterface userServiceInterface;

    private final MemberAndUserInterface memberAndUserInterface;

    private final VideoCallAccountServiceInterface videoCallAccountServiceInterface;

    private final RoomServiceInterface roomServiceInterface;

//    private final ApplyUserInterface applyUserInterface;
    @Autowired
    private ApplicationContext applicationContext;


    @Override
    public ResultBean<Member> getMemberByOpenid(MemberDto memberDto) {
        //构建查询条件
        Wrapper<Member> wrapper = new EntityWrapper<>();
        //openid
        wrapper.eq("s_openid", memberDto.getOpenid());
        //openid
        wrapper.eq("l_id", memberDto.getId());
        //机构id
        wrapper.eq("l_org_id",memberDto.getOrgId());
        //数据状态   数据状态：{ -1：已删除，0：正常 }
        wrapper.eq("i_status", OperationConstant.ZERO);
        return new ResultBean<>(ResultEnum.SUCCESS,this.selectOne(wrapper));
    }

    @Override
    public ResultBean<Member> getMemberById(MemberDto memberDto) {
        //构建查询条件
        Wrapper<Member> wrapper = new EntityWrapper<>();
        wrapper.eq("l_id", memberDto.getId());
        //机构id
        wrapper.eq("l_org_id",memberDto.getOrgId());
        //数据状态   数据状态：{ -1：已删除，0：正常 }
        wrapper.eq("i_status", OperationConstant.ZERO);
        return new ResultBean<>(ResultEnum.SUCCESS,this.selectOne(wrapper));
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public ResultBean<Boolean> memberRegister(Member member) {
        //匹配user
        List<User> userList = this.userServiceInterface.getUserByTelAndName(member);
        //匹配到user---member为已认证
        if(userList.size()>0){
            //认证状态：{ 0：未认证，1：待审审核，2：已认证 }
            member.setState(OperationConstant.TWO);
        }else{
            member.setState(OperationConstant.ZERO);
        }
        member.setCreateDate(new Date());
        if (StringUtils.isEmpty(member.getName())){
            member.setName(member.getTel());
        }
        member.setEnable(OperationConstant.ONE);
        boolean insertResult = this.insert(member);
        if(insertResult && userList.size()>0){
            List<MemberAndUser> memberAndUserList = new ArrayList<>(userList.size());
            List<ApplyUser> applyUserList = new ArrayList<>(userList.size());
            for(User user:userList){
                MemberAndUser memberAndUser = new MemberAndUser();
                memberAndUser.setMemberId(member.getId());
                memberAndUser.setUserId(user.getId());
                memberAndUser.setRoomId(user.getRoomId());
                memberAndUserList.add(memberAndUser);
                //更改住户的APP会员激活状态
                user.setIsMember(OperationConstant.ONE);
                this.userServiceInterface.updateById(user);

                applyUserList.add(applyUserFromMemberUser(member, user));
            }
            if(memberAndUserList.size()>0){
                //保存会员和user的关系
                this.memberAndUserInterface.addMemberAndUsers(memberAndUserList);
                //  生成视频对讲账号
                VideoCallAccount account = new VideoCallAccount();
                account.setMember(member);
                account.setUserList(userList);
                this.videoCallAccountServiceInterface.createAccountByUser(account);
                //自动生成会员申请审核记录（自动通过）
//                this.applyUserInterface.addApplyUsers(applyUserList);
                ApplyUserAddEvent event = new ApplyUserAddEvent(this, applyUserList);
                applicationContext.publishEvent(event);
            }
        }
        return new ResultBean<>(ResultEnum.SUCCESS,insertResult);
    }

    public ApplyUser applyUserFromMemberUser(Member member, User user){
        Room room = this.roomServiceInterface.findRoomById(user.getRoomId());
        Assert.notNull(room,"房间Id不存在");
        ApplyUser applyUser = new ApplyUser();
        applyUser.setCheckState(1);//0-待审核 1-审核通过 2-审核不通过
        applyUser.setRecordType(1);//申请的记录类型 0--认证类型 1--新增类型 2--编辑类型(通过user编辑生成的) 3--编辑类型(通过applyUser编辑生成)
        applyUser.setCheckDate(new Date());
        applyUser.setCheckOpinion("APP注册关联住户生成系统自动审批通过记录！");
        applyUser.setCreateType(3);//申请来源0-小程序添加 1-后台添加  2-后台导入 3-app添加
        applyUser.setEstatePosition(room.getEstatePosition());
        applyUser.setOrgPosition(room.getOrgPosition());
        applyUser.setFaceCode(user.getFaceCode());
        applyUser.setIdCard(user.getIdCard());
        applyUser.setImageUri(user.getImageUri());
        applyUser.setMemberId(member.getId());
        applyUser.setUserId(user.getId());
        applyUser.setOperatorType(2);//审核人类型：1-业主，2-后台
        applyUser.setName(user.getName());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            applyUser.setCreateDate(simpleDateFormat.parse(new Date().toString()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        applyUser.setBuildingId(room.getBuildingId());
        applyUser.setBuildingName(room.getBuildingName());
        applyUser.setRoomId(room.getId());
        applyUser.setRoomName(room.getName());
        applyUser.setType(user.getType());
        applyUser.setNationality(user.getNationality());
        applyUser.setPassportImgUri(user.getPassportImgUri());
        applyUser.setEntryImgUri(user.getEntryImgUri());
        applyUser.setTel(user.getTel());

        applyUser.setSex(user.getSex());
        applyUser.setUnitId(user.getUnitId());
        applyUser.setUnitName(user.getUnitName());
        applyUser.setResidentialId(user.getResidentialId());
        applyUser.setResidentialName(user.getResidentialName());
        applyUser.setOperatorName(user.getName());
        return applyUser;
    }

    @Override
    public ResultBean<Boolean> checkMemberTel(Member member) {
        //构建查询条件
        Wrapper<Member> wrapper = new EntityWrapper<>();
        //机构id
        wrapper.eq("l_org_id",member.getOrgId());
        //机构id
        wrapper.eq("s_tel",member.getTel());
        //数据状态
        wrapper.eq("i_status", OperationConstant.ZERO);
        //名字
        if(StringUtils.isNotBlank(member.getName())){
            wrapper.eq("s_name",member.getName());
        }
        //统计
        int count = this.selectCount(wrapper);
        if(count>0){
            return new ResultBean<>(ResultEnum.SUCCESS,true);
        }
        return new ResultBean<>(ResultEnum.SUCCESS,false);
    }

    @Override
    public ResultBean<Boolean> updateMemberOpenId(Member member) {
        //构建查询条件
        Wrapper<Member> wrapper = new EntityWrapper<>();
        //机构id
        wrapper.eq("l_org_id",member.getOrgId());
        //机构id
        wrapper.eq("s_tel",member.getTel());
        //数据状态
        wrapper.eq("i_status", OperationConstant.ZERO);
        //名字
        wrapper.eq("s_name",member.getName());
        Member update = new Member();
        //需要修改的字段
        update.setOpenid(member.getOpenid());
        return new ResultBean<>(ResultEnum.SUCCESS,this.update(update,wrapper));
    }

    @Override
    public int getMemberAccount(MemberDto memberDto) {
        Wrapper<Member> wrapper = new EntityWrapper<>();
        wrapper.like("s_org_position", memberDto.getOrgPosition(), SqlLike.RIGHT);
        //当月新增
        if (OperationConstant.TWO == memberDto.getIsAllType()) {
            wrapper.and("DATE_FORMAT(t_create_date,'%Y%m')=DATE_FORMAT(NOW(),'%Y%m')");
        }
        //过滤删除
        wrapper.notIn("i_status", OperationConstant.MINUS_ONE);
        return this.selectCount(wrapper);
    }

    @Override
    public ResultBean<Map<String, Object>> getMemberTypeCount(MemberDto memberDto) {
        EntityWrapper<Member> wrapper=new EntityWrapper<>();
        //0-小程序添加 1-后台添加  2-后台导入 3-app添加 人数
        String sqlSelect="sum(case  when i_create_type=0 then 1 ELSE 0 end) wxAppletCount," +
                "sum(case  when i_create_type=1 then 1 ELSE 0 end) backgroundCount," +
                "sum(case  when i_create_type=2 then 1 ELSE 0 end) backgroundImportCount," +
                "sum(case  when i_create_type=3 then 1 ELSE 0 end) appCount";
        wrapper.setSqlSelect(sqlSelect);
        //根据机构
        wrapper.like("s_org_position", memberDto.getOrgPosition(), SqlLike.RIGHT);
        wrapper.eq("i_status",OperationConstant.ZERO);
        return new ResultBean<>(ResultEnum.SUCCESS,this.selectMap(wrapper));
    }

    @Override
    public ResultBean<Boolean> updateMemberPassword(Member member) {
        //构建查询条件
        Wrapper<Member> wrapper = new EntityWrapper<>();
        //机构id
        wrapper.eq("l_org_id",member.getOrgId());
        //机构id
        wrapper.eq("s_tel",member.getTel());
        //数据状态
        wrapper.eq("i_status", OperationConstant.ZERO);
        Member update = new Member();
        //重置密码
        update.setPassword(member.getPassword());
        return new ResultBean<>(ResultEnum.SUCCESS,this.update(update,wrapper));
    }

    @Override
    public Member findMemberByTel(Member member) {
        //构建查询条件
        Wrapper<Member> wrapper = new EntityWrapper<>();
        //电话
        wrapper.eq("s_tel",member.getTel());
        //机构id
        wrapper.eq("l_org_id",member.getOrgId());
        // 数据状态   数据状态：{ -1：已删除，0：正常 }
        wrapper.eq("i_status", OperationConstant.ZERO);
        Member m = this.selectOne(wrapper);
        //查询会员的视频呼叫账号
        if(m!=null && m.getState()==2){
            VideoCallAccount v = this.videoCallAccountServiceInterface.selectByCustomerId(m.getId());
            m.setVideoCallAccount(v);
        }
        return m;
    }

    @Override
    public Page<Member> showMemberList(MemberDto memberDto) {
        //排序字段 时间降序
        memberDto.getPage().setOrderByField("t_create_date");
        memberDto.getPage().setAsc(false);
        //构建查询条件
        Wrapper<Member> wrapper = new EntityWrapper<>();
        //根据名字查询
        if(StringUtils.isNotBlank(memberDto.getName())){
            wrapper.like("s_name",memberDto.getName());
        }
        if(StringUtils.isNotBlank(memberDto.getTel())){
            wrapper.like("s_tel", memberDto.getTel());
        }
        if(memberDto.getState()!=null){
            wrapper.eq("i_state", memberDto.getState());
        }
        //排除删除的数据
        wrapper.notIn("i_status", OperationConstant.MINUS_ONE);
        //机构
        wrapper.like("s_org_position",memberDto.getOrgPosition());
        //排序
        if (StringUtils.isNotBlank(memberDto.getSortField()) && StringUtils.isNotBlank(memberDto.getSortOrder())){
            wrapper.orderBy(memberDto.getSortField(),memberDto.getSortOrder().equals("asc"));
        }
        return this.selectPage(memberDto.getPage(), wrapper);
    }

    @Override
    public ResultBean<Member> memberRegisterNew(Member member) {
        //匹配user
        List<User> userList = this.userServiceInterface.getUserByTelAndName(member);
        //匹配到user---member为已认证
        if(userList.size()>0){
            //认证状态：{ 0：未认证，1：待审审核，2：已认证 }
            member.setState(OperationConstant.TWO);
        }else{
            member.setState(OperationConstant.ZERO);
        }
        //1：启用      2：禁用
        member.setEnable(OperationConstant.ONE);
        Boolean insertResult = this.insert(member);
        if(insertResult && userList.size()>0){
            List<MemberAndUser> list = new ArrayList<>(userList.size());
            for(User user:userList){
                MemberAndUser memberAndUser = new MemberAndUser();
                memberAndUser.setMemberId(member.getId());
                memberAndUser.setUserId(user.getId());
                memberAndUser.setRoomId(user.getRoomId());
                list.add(memberAndUser);
            }
            if(list.size()>0){
                //保存会员和user的关系
                ResultBean<Boolean> resultBean = this.memberAndUserInterface.addMemberAndUsers(list);
                //  生成视频对讲账号
                VideoCallAccount account = new VideoCallAccount();
                account.setMember(member);
                account.setUserList(userList);
                this.videoCallAccountServiceInterface.createAccountByUser(account);
            }
        }
        return new ResultBean<>(ResultEnum.SUCCESS,member);
    }

    @Override
    public List<Member> findMemberByNameAndTel(String name, String tel) {
        //构建查询条件
        Wrapper<Member> wrapper = new EntityWrapper<>();
        //姓名
        wrapper.eq("s_name",name);
        //电话
        wrapper.eq("s_tel",tel);
        //数据状态   数据状态：{ -1：已删除，0：正常 }
        wrapper.eq("i_status", OperationConstant.ZERO);
        return this.selectList(wrapper);
    }

    @Override
    public ResultBean<Boolean> changeTel(Member member) {
        return new ResultBean<>(ResultEnum.SUCCESS,this.updateById(member));
    }

    @Override
    public ResultBean<Boolean> updateMember(Member member) {
        return new ResultBean<>(ResultEnum.SUCCESS,this.updateAllColumnById(member));
    }

    @Override
    public ResultBean<Boolean> activation(MemberDto memberDto) {
        memberDto.setState(OperationConstant.ZERO);
        memberDto.setStatus(OperationConstant.ZERO);
        memberDto.setEnable(OperationConstant.ONE);
        memberDto.setCreateDate(new Date());
        return new ResultBean<>(ResultEnum.SUCCESS,this.insert(memberDto));
    }

    @Override
    public Member getMember(Member member){
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("i_status",OperationConstant.ZERO);
        if (StringUtils.isNotEmpty(member.getTel())){
            wrapper.eq("s_tel",member.getTel());
        }
        if(StringUtils.isNotEmpty(member.getName())){
            wrapper.eq("s_name",member.getName());
        }
        return this.selectOne(wrapper);
    }
}
