package com.yh.saas.plugin.yiliangyiyun.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.winsea.svc.base.security.util.AuthSecurityUtils;
import com.yh.saas.common.support.util.IdGenerator;
import com.yh.saas.common.support.util.StringUtils;
import com.yh.saas.plugin.yiliangyiyun.constant.StatusEnum;
import com.yh.saas.plugin.yiliangyiyun.entity.*;
import com.yh.saas.plugin.yiliangyiyun.exception.ServiceException;
import com.yh.saas.plugin.yiliangyiyun.mapper.SettledCompanyInfoMapper;
import com.yh.saas.plugin.yiliangyiyun.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yh.saas.plugin.yiliangyiyun.util.GeTuiUtils;
import com.yh.saas.plugin.yiliangyiyun.util.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 入驻公司信息 服务实现类
 * </p>
 *
 * @author Gongdc
 * @since 2021-08-28
 */
@Service
public class SettledCompanyInfoServiceImpl extends ServiceImpl<SettledCompanyInfoMapper, SettledCompanyInfo> implements ISettledCompanyInfoService {


    @Autowired
    private ISettledCompanyContactsService settledCompanyContactsService;
    @Autowired
    private ISettledCompanyErrorService settledCompanyErrorService;
    @Autowired
    private GeTuiUtils geTuiUtils;
    @Autowired
    private ICommonUserService commonUserService;
    @Autowired
    private ICollectionCompanyService collectionCompanyService;
    @Autowired
    private WebSocket webSocket;

    /**
     * 添加入住公司信息
     *
     * @param settledCompanyInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addSettledCompanyInfo(SettledCompanyInfo settledCompanyInfo) throws ServiceException {
        settledCompanyInfo.setId(IdGenerator.generateUUID());
        settledCompanyInfo.setStatusFlag(StatusEnum.TO_BE_REVIEWED.getFlag());
        settledCompanyInfo.setStatus(StatusEnum.TO_BE_REVIEWED.getName());
        settledCompanyInfo.setShowFlag("1");
        // 联系人处理
        List<SettledCompanyContacts> settledCompanyContactsList = settledCompanyInfo.getSettledCompanyContacts();
        if (!CollectionUtils.isEmpty(settledCompanyContactsList)) {
            settledCompanyContactsList.forEach(settledCompanyContacts -> {
                settledCompanyContacts.setId(IdGenerator.generateUUID());
                settledCompanyContacts.setInfoId(settledCompanyInfo.getId());
            });
            settledCompanyContactsService.insertBatch(settledCompanyContactsList);
        }
        this.insert(settledCompanyInfo);
        return settledCompanyInfo.getId();
    }


    /**
     * 编辑入住公司信息
     *
     * @param settledCompanyInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String editSettledCompanyInfo(SettledCompanyInfo settledCompanyInfo) throws ServiceException {
        // 更新公司信息
        this.updateById(settledCompanyInfo);
        // 联系人处理
        List<SettledCompanyContacts> settledCompanyContactsList = settledCompanyContactsService.selectList(new EntityWrapper<SettledCompanyContacts>()
                .eq("info_id", settledCompanyInfo.getId()));
        List<String> idList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(settledCompanyContactsList)) {
            idList = settledCompanyContactsList.stream().map(SettledCompanyContacts::getId).collect(Collectors.toList());
        }
        List<SettledCompanyContacts> settledCompanyContactsListNew = settledCompanyInfo.getSettledCompanyContacts();
        if (!CollectionUtils.isEmpty(settledCompanyContactsListNew)) {
            for (SettledCompanyContacts settledCompanyContacts : settledCompanyContactsListNew) {
                if (StringUtils.isEmpty(settledCompanyContacts.getId())) {
                    settledCompanyContacts.setId(IdGenerator.generateUUID());
                    settledCompanyContacts.setInfoId(settledCompanyInfo.getId());
                    settledCompanyContactsService.insert(settledCompanyContacts);
                } else {
                    settledCompanyContactsService.updateById(settledCompanyContacts);
                }
            }
            List<String> idListNew = settledCompanyContactsListNew.stream().map(SettledCompanyContacts::getId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(idList)) {
                idList.forEach(s -> {
                    if (!idListNew.contains(s)) {
                        settledCompanyContactsService.deleteById(s);
                    }
                });

            }
        } else {
            if (!CollectionUtils.isEmpty(idList)) {
                idList.forEach(s -> {
                    settledCompanyContactsService.deleteById(s);
                });

            }
        }
        return settledCompanyInfo.getId();
    }


    /**
     * 入驻公司列表
     *
     * @param settledCompanyInfo
     * @return
     */
    @Override
    public Page<SettledCompanyInfo> selectSettledCompanyInfo(SettledCompanyInfo settledCompanyInfo) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (settledCompanyInfo.getCurrentPage() - 1)
                * settledCompanyInfo.getPageSize());
        //公司id
        pageView.put("createPhone", settledCompanyInfo.getCreatePhone());
        pageView.put("pcFlag", settledCompanyInfo.getPcFlag());
        pageView.put("mainBusinessType", settledCompanyInfo.getMainBusinessType());
        pageView.put("searchKeyWord", settledCompanyInfo.getSearchKeyWord());
        pageView.put("province", settledCompanyInfo.getProvince());
        pageView.put("city", settledCompanyInfo.getCity());
        pageView.put("area", settledCompanyInfo.getArea());
        pageView.put("detailedAddress", settledCompanyInfo.getDetailedAddress());
        pageView.put("searchType", settledCompanyInfo.getSearchType());
        pageView.put("pageSize", settledCompanyInfo.getPageSize());
        pageView.put("currentPage", settledCompanyInfo.getCurrentPage());
        pageView.put("location", settledCompanyInfo.getLocation());
        // 查询总数
        Integer dataCount = baseMapper.getCountByCondition(pageView);
        List<SettledCompanyInfo> dataList = baseMapper.getListByCondition(pageView);
        if (!CollectionUtils.isEmpty(dataList)) {
            for (SettledCompanyInfo settledCompanyInfo1 : dataList) {
                CommonUser commonUser = commonUserService.selectOne(new EntityWrapper<CommonUser>().eq("phone", settledCompanyInfo1.getCreatePhone()));
                if (commonUser != null) {
                    //昵称
                    settledCompanyInfo1.setUserName(commonUser.getUserName());
                }
            }
        }
        Page<SettledCompanyInfo> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setTotal(dataCount == null ? 0 : dataCount);
        page.setCurrent(settledCompanyInfo.getCurrentPage());
        page.setSize(settledCompanyInfo.getPageSize());
        return page;
    }

    /**
     * 查看详情
     *
     * @param id
     * @return
     */
    @Override
    public SettledCompanyInfo getSettledCompanyInfo(String id) {
        //查看信息
        SettledCompanyInfo settledCompanyInfo = this.selectById(id);
        // 联系人
        List<SettledCompanyContacts> settledCompanyContactsList = settledCompanyContactsService.selectList(new EntityWrapper<SettledCompanyContacts>()
                .eq("info_id", settledCompanyInfo.getId()));
        // 举报
        List<SettledCompanyError> settledCompanyErrors = settledCompanyErrorService.selectList(new EntityWrapper<SettledCompanyError>()
                .eq("info_id", settledCompanyInfo.getId()));
        // 收藏
        List<CollectionCompany> collectionCompanyList = collectionCompanyService.selectList(new EntityWrapper<CollectionCompany>()
                .eq("info_id", settledCompanyInfo.getId()));
        settledCompanyInfo.setSettledCompanyContacts(settledCompanyContactsList);
        settledCompanyInfo.setSettledCompanyErrorList(settledCompanyErrors);
        settledCompanyInfo.setCollectionCompanyList(collectionCompanyList);
        return settledCompanyInfo;
    }


    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSettledCompanyInfo(String id) {
        //查询信息
        SettledCompanyInfo settledCompanyInfo = this.selectById(id);
        if (settledCompanyInfo != null) {
            //删除信息
            this.deleteById(settledCompanyInfo.getId());
            // 联系人
            boolean result = settledCompanyContactsService.delete(new EntityWrapper<SettledCompanyContacts>()
                    .eq("info_id", settledCompanyInfo.getId()));
            // 举报
            boolean res = settledCompanyErrorService.delete(new EntityWrapper<SettledCompanyError>()
                    .eq("info_id", settledCompanyInfo.getId()));
        }
    }


    /**
     * 审核
     *
     * @param settledCompanyInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String examine(SettledCompanyInfo settledCompanyInfo) {
        //查询
        SettledCompanyInfo settledCompanyInfo1 = this.selectById(settledCompanyInfo.getId());
        CommonUser commonUser = commonUserService.selectOne(new EntityWrapper<CommonUser>().eq("phone", settledCompanyInfo1.getCreatePhone()));
        if (settledCompanyInfo1 != null) {
            //通过
            if (settledCompanyInfo.getFlag() == 1) {
                settledCompanyInfo1.setStatusFlag(StatusEnum.ORDER_PASSED.getFlag());
                settledCompanyInfo1.setStatus(StatusEnum.ORDER_PASSED.getName());
                geTuiUtils.pushByCid("审核通知", "您的公司入住申请已审核通过", commonUser.getId());
                UnimallMessage messageDO = new UnimallMessage();
                messageDO.setAdminId(commonUser.getId());
                messageDO.setCustomer(commonUser.getUserName());
                messageDO.setOperation("审核通知");
                messageDO.setResult("您的公司入住申请已审核通过");
                messageDO.setGmtUpdate(new java.util.Date());
                messageDO.setGmtCreate(new Date());
                messageDO.setTaskId(IdGenerator.generateUUID());
                messageDO.setCompanyId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
                messageDO.setPath("XXXXX");
                webSocket.sendOneMessage(messageDO);
            }
            //驳回
            else {
                settledCompanyInfo1.setStatusFlag(StatusEnum.ORDER_REJECTED.getFlag());
                settledCompanyInfo1.setStatus(StatusEnum.ORDER_REJECTED.getName());
                geTuiUtils.pushByCid("驳回通知", "您的公司入住申请已被驳回", commonUser.getId());
                UnimallMessage messageDO = new UnimallMessage();
                messageDO.setAdminId(commonUser.getId());
                messageDO.setCustomer(commonUser.getUserName());
                messageDO.setOperation("驳回通知");
                messageDO.setResult("您的公司入住申请已被驳回");
                messageDO.setGmtUpdate(new java.util.Date());
                messageDO.setGmtCreate(new Date());
                messageDO.setTaskId(IdGenerator.generateUUID());
                messageDO.setCompanyId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
                messageDO.setPath("XXXXX");
                webSocket.sendOneMessage(messageDO);

            }
            //更改信息
            this.updateById(settledCompanyInfo1);
            return "OK";
        }
        return "NG";
    }


    /**
     * 显示隐藏
     *
     * @param id
     * @return
     */
    @Override
    public void showHidden(String id) {
        //查询销售计划信息
        SettledCompanyInfo settledCompanyInfo = this.selectById(id);
        if (settledCompanyInfo != null) {
            if ("2".equals(settledCompanyInfo.getShowFlag())) {
                settledCompanyInfo.setShowFlag("1");
            } else {
                settledCompanyInfo.setShowFlag("2");
            }
            this.updateById(settledCompanyInfo);
        }
    }


    /**
     * 收藏
     *
     * @param settledCompanyInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String collection(SettledCompanyInfo settledCompanyInfo) {
        CollectionCompany collectionCompany = new CollectionCompany();
        collectionCompany.setId(IdGenerator.generateUUID());
        collectionCompany.setInfoId(settledCompanyInfo.getId());
        collectionCompany.setCompName(settledCompanyInfo.getCompName());
        collectionCompany.setPhone(settledCompanyInfo.getLoginPhone());
        collectionCompanyService.insert(collectionCompany);
        return "OK";
    }

    /**
     * 取消收藏
     *
     * @param settledCompanyInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String collectionNot(SettledCompanyInfo settledCompanyInfo) {
        collectionCompanyService.delete(new EntityWrapper<CollectionCompany>()
                .eq("info_id", settledCompanyInfo.getId())
                .eq("phone", settledCompanyInfo.getLoginPhone()));
        return "OK";
    }


    /**
     * 我的收藏
     *
     * @param settledCompanyInfo
     * @return
     */
    @Override
    public Page<SettledCompanyInfo> myCollection(SettledCompanyInfo settledCompanyInfo) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (settledCompanyInfo.getCurrentPage() - 1)
                * settledCompanyInfo.getPageSize());
        //公司id
        pageView.put("loginPhone", settledCompanyInfo.getLoginPhone());
        pageView.put("pageSize", settledCompanyInfo.getPageSize());
        pageView.put("currentPage", settledCompanyInfo.getCurrentPage());
        // 查询总数
        Integer dataCount = baseMapper.getCountByMyCondition(pageView);
        List<SettledCompanyInfo> dataList = baseMapper.getListByMyCondition(pageView);
        Page<SettledCompanyInfo> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setTotal(dataCount == null ? 0 : dataCount);
        page.setCurrent(settledCompanyInfo.getCurrentPage());
        page.setSize(settledCompanyInfo.getPageSize());
        return page;
    }


    /**
     * 纠错举报
     *
     * @param settledCompanyError
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addSettledCompanyError(SettledCompanyError settledCompanyError) throws ServiceException {
        settledCompanyError.setInfoId(settledCompanyError.getId());
        settledCompanyError.setId(IdGenerator.generateUUID());
        settledCompanyErrorService.insert(settledCompanyError);
        return settledCompanyError.getId();
    }


    /**
     * 我的入驻公司
     *
     * @param settledCompanyInfo
     * @return
     */
    @Override
    public List<SettledCompanyInfo> companyList(SettledCompanyInfo settledCompanyInfo) {
        List<SettledCompanyInfo> settledCompanyInfoList = this.selectList(new EntityWrapper<SettledCompanyInfo>()
                .eq("create_phone", settledCompanyInfo.getLoginPhone())
                .eq("status_flag", "3"));
        return settledCompanyInfoList;
    }


}
