package com.sqx.modules.resumes.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.entity.Msg;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.service.MsgService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.firstLogin.entity.HrEntity;
import com.sqx.modules.firstLogin.service.HrService;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.message.service.MessageService;
import com.sqx.modules.resumes.dao.CompanyDao;
import com.sqx.modules.resumes.entity.Company;
import com.sqx.modules.resumes.entity.CompanyUser;
import com.sqx.modules.resumes.entity.PostPush;
import com.sqx.modules.resumes.service.CompanyService;
import com.sqx.modules.resumes.service.CompanyUserService;
import com.sqx.modules.resumes.service.PostPushService;
import com.sqx.modules.utils.SenInfoCheckUtil;
import com.sqx.modules.utils.excel.ExcelData;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 企业
 */
@Service
public class CompanyServiceImpl extends ServiceImpl<CompanyDao, Company> implements CompanyService {

    @Autowired
    private UserService userService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private MsgService msgService;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private PostPushService postPushService;
    @Autowired
    private HrService hrService;
    @Autowired
    private CompanyUserService companyUserService;


//    @Override
//    public Result insertCompany(Company company) {
//        Company oldCompany = selectCompanyByUserId(company.getUserId());
//        if (oldCompany != null) {
//            return Result.error("当前用户已经有企业了！");
//        }
//        String format = DateUtils.format(new Date());
//        company.setCreateTime(format);
//        company.setUpdateTime(format);
//        company.setStatus(1);
//        baseMapper.insert(company);
//        MessageInfo messageInfo = new MessageInfo();
//        messageInfo.setState("20");
//        messageInfo.setIsSee("0");
//        messageInfo.setContent(String.valueOf(company.getUserId()));
//        messageService.save(messageInfo);
//        return Result.success();
//    }
    @Override
    public Result insertCompany(Company company,Long userId) {
        QueryWrapper<Company> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("company_all_name",company.getCompanyAllName()).eq("status",2).eq("is_use",1);
        Company companyOne= baseMapper.selectOne(queryWrapper);
        if (companyOne != null){
            company.setIsUse(0);
            company.setStatus(1);
            company.setUpdateTime(String.valueOf(LocalDateTime.now()));
            baseMapper.insert(company);
            CompanyUser companyUser = new CompanyUser();
            companyUser.setCompanyId(companyOne.getCompanyId());
            companyUser.setUserId(userId);
            companyUser.setCreateTime(String.valueOf(LocalDateTime.now()));
            companyUser.setIsUse(0);
            companyUserService.save(companyUser);
        }else {
                QueryWrapper<Company> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("company_all_name",company.getCompanyAllName()).eq("status",1).eq("is_use",1);
                Company company1 =baseMapper.selectOne(queryWrapper1);
                if (company1 != null){
                    return Result.error("该企业正在审核中，请等待审核完成");
                }else {
                    company.setStatus(1);
                    company.setIsUse(1);
                    company.setCompanyCreateTime(String.valueOf(LocalDateTime.now()));
                    company.setUpdateTime(String.valueOf(LocalDateTime.now()));
                    baseMapper.insert(company);
                    CompanyUser companyUser = new CompanyUser();
                    companyUser.setCompanyId(company.getCompanyId());
                    companyUser.setUserId(userId);
                    companyUser.setCreateTime(String.valueOf(LocalDateTime.now()));
                    companyUser.setIsUse(0);
                    companyUserService.save(companyUser);
                    return Result.success().put("data",company.getCompanyId());
                }
        }
        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setState("20");
        messageInfo.setIsSee("0");
        messageInfo.setContent(String.valueOf(company.getUserId()));
        messageService.save(messageInfo);
        return Result.success();
    }

    @Override
    public Result updateCompany(Company company) {
        company.setUpdateTime(DateUtils.format(new Date()));
        baseMapper.updateById(company);
        if (company.getStatus()!=2){
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setState("20");
            messageInfo.setIsSee("0");
            messageInfo.setContent(String.valueOf(company.getUserId()));
            messageService.save(messageInfo);
        }
        return Result.success();
    }

    @Override
    public Result auditContent(String ids, String content, Integer status) {
        String value = commonInfoService.findOne(310).getValue();
        for (String id : ids.split(",")) {
            Company company = baseMapper.selectById(Long.parseLong(id));
            UserEntity userEntity = userService.selectUserById(company.getUserId());
            CompanyUser companyUser = companyUserService.getOne(new QueryWrapper<CompanyUser>().eq("company_id",company.getCompanyId()).eq("use_id",company.getUserId()));
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setContent(content);
            messageInfo.setTitle("企业审核通知");
            messageInfo.setState(String.valueOf(5));
            messageInfo.setUserName(userEntity.getUserName());
            messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
            messageInfo.setCreateAt(DateUtils.format(new Date()));
            messageInfo.setIsSee("0");
            List<String> msgList = new ArrayList<>();
            msgList.add("企业审核通知");
            if (company.getStatus().equals(1)) {
                if (status == 1) {
                    company.setStatus(2);
                    company.setAuditContent("通过");
                    userEntity.setUserType(2);
                    companyUser.setIsUse(1);
                    companyUserService.updateById(companyUser);
                    userService.updateById(userEntity);
                    msgList.add("审核通过");
                } else {
                    company.setStatus(3);
                    company.setAuditContent(content);
                    msgList.add("审核失败，请前往企业申请查看原因！");
                }

                baseMapper.updateById(company);
                msgList.add(DateUtils.format(new Date()));
                SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), value, msgList, 3, null);
                messageService.saveBody(messageInfo);
                if (StringUtils.isNotEmpty(userEntity.getClientid())) {
                    userService.pushToSingle(messageInfo.getTitle(), messageInfo.getContent(), userEntity.getClientid());
                }
            }
        }
        return Result.success();
    }

    public Result leaveCompany(Long userId){
        QueryWrapper<CompanyUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId).eq("is_use",1);
        CompanyUser companyUser =companyUserService.getOne(queryWrapper);
        companyUser.setIsUse(0);
        companyUserService.save(companyUser);
        return Result.success().put("data","退出当前公司成功");
    }
    @Override
    public Company selectCompanyByUserId(Long userId) {

        return baseMapper.selectOne(new QueryWrapper<Company>().eq("user_id", userId));
    }

    @Override
    public Result selectCompanyList(Integer page, Integer limit, String startTime, String endTime, String companyName, String companyPhone, String userName, Integer status) {
        Page<Company> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return Result.success().put("data", baseMapper.selectCompanyList(pages, startTime, endTime, companyName, companyPhone, userName, status));
    }

    @Override
    public Company selectCompanyByCompanyId(Long companyId) {
        Company company = baseMapper.selectById(companyId);
        QueryWrapper<CompanyUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_id", companyId).eq("is_use", 1);
        List<CompanyUser> companyUserList = companyUserService.getBaseMapper().selectList(queryWrapper);
        List<HrEntity> hrList = new ArrayList<>();
        List<UserEntity> userEntities = new ArrayList<>();
        if (companyUserList != null && !companyUserList.isEmpty()) {
            for (CompanyUser companyUser : companyUserList) {
                Long userId = companyUser.getUserId();
                HrEntity hr = hrService.getByUserId(String.valueOf(userId));
                UserEntity userEntity = userService.getById(userId);
                hrList.add(hr);
                userEntities.add(userEntity);
            }
            company.setHr(hrList);
            company.setUserEntities(userEntities);
        }
        return company;
    }

    @Override
    public Result selectCompanyListByMember(Integer page, Integer limit) {
        return Result.success().put("data", new PageUtils(baseMapper.selectCompanyListByMember(new Page<>(page, limit))));
    }

    @Override
    public Result giveCompany(String phone, String msg, String givePhone) {
        Msg byPhoneAndCode = msgService.findByPhoneAndCode(phone, msg);
        if (byPhoneAndCode == null) {
            return Result.error("验证码不正确！");
        }
        UserEntity user = userService.getOne(new QueryWrapper<UserEntity>().eq("phone", phone));
        Company company = selectCompanyByUserId(user.getUserId());
        if (company == null) {
            return Result.error("当前手机号没有绑定公司！");
        }
        UserEntity giveUser = userService.getOne(new QueryWrapper<UserEntity>().eq("phone", givePhone));
        if (giveUser == null) {
            return Result.error("转赠用户不存在，请检查手机号！");
        }
        Company one = baseMapper.selectOne(new QueryWrapper<Company>().eq("user_id", giveUser.getUserId()));
        if (one != null) {
            return Result.error("对方已绑定企业，请更换手机号");
        }
        company.setUserId(giveUser.getUserId());
        baseMapper.updateById(company);
        giveUser.setUserType(2);
        userService.updateById(giveUser);
        user.setUserType(1);
        userService.updateById(user);
        return Result.success();
    }

    @Override
    public ExcelData exportExcelCompanyList(String startTime, String endTime, String companyName, String companyPhone, String userName, Integer status) {
        List<Company> companyList = baseMapper.exportExcelCompanyList(startTime, endTime, companyName, companyPhone, userName, status);
        ExcelData data = new ExcelData();
        data.setName("企业列表");
        List<String> titles = new ArrayList<>();
        titles.add("编号");
        titles.add("企业名称");
        titles.add("企业税号");
        titles.add("企业地址");
        titles.add("企业经营范围");
        titles.add("企业法人");
        titles.add("注册资金");
        titles.add("企业注册时间");
        titles.add("企业logo");
        titles.add("公司规模");
        titles.add("企业资质");
        titles.add("企业证书");
        titles.add("绑定用户");
        titles.add("企业状态");
        titles.add("更新时间");
        titles.add("创建时间");
        titles.add("审核信息");
        titles.add("企业邮箱");
        titles.add("经度");
        titles.add("纬度");

        data.setTitles(titles);
        List<List<Object>> rows = new ArrayList<>();
        for (Company company : companyList) {
            List<Object> row = new ArrayList<>();
            row.add(company.getCompanyId());
            row.add(company.getCompanyName());
            row.add(company.getCompanyDutyParagraph());
            row.add(company.getCompanyAddress());
            row.add(company.getCompanyScope());
            row.add(company.getCompanyLegalPerson());
            row.add(company.getCompanyRegisteredFund());
            row.add(company.getCompanyCreateTime());
            row.add(company.getCompanyLogo());
            row.add(company.getCompanyPeople());
            row.add(company.getCompanyCertification());
            row.add(company.getCompanyCertificate());
            UserEntity userEntity = userService.getById(company.getUserId());
            if (userEntity!=null && StringUtils.isNotBlank(userEntity.getUserName())) {
                row.add(userEntity.getUserName());
            }else {
                row.add("用户已注销");
            }
            if (company.getStatus() == 1) {
                row.add("待审核");
            } else if (company.getStatus() == 2) {
                row.add("已通过");
            } else {
                row.add("已拒绝");
            }
            row.add(company.getUpdateTime());
            row.add(company.getCreateTime());
            row.add(company.getAuditContent());
            row.add(company.getEmail());
            row.add(company.getCompanyLng());
            row.add(company.getCompanyLat());
            rows.add(row);
        }
        data.setRows(rows);
        return data;
    }

    @Override
    public Result listCompany(Integer page, Integer limit, String companyName, String city, String companyScope, String companyPeople) {
        if(Objects.isNull(page) && Objects.isNull(limit)) {
            QueryWrapper<Company> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(Company::getStatus, 2)
                    .like(StringUtils.isNotBlank(companyName), Company::getCompanyName, companyName)
                    .like(StringUtils.isNotBlank(city), Company::getCity, city)
                    .like(StringUtils.isNotBlank(companyScope), Company::getCompanyScope, companyScope)
                    .eq(StringUtils.isNotBlank(companyPeople), Company::getCompanyPeople, companyPeople);
            List<Company> companyList = this.list(queryWrapper);

            return Result.success().put("data", companyList);
        } else {
            Page<Company> companyPage = new Page<>(page, limit);
            QueryWrapper<Company> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(Company::getStatus, 2)
                    .like(StringUtils.isNotBlank(companyName), Company::getCompanyName, companyName)
                    .like(StringUtils.isNotBlank(city), Company::getCity, city)
                    .like(StringUtils.isNotBlank(companyScope), Company::getCompanyScope, companyScope)
                    .eq(StringUtils.isNotBlank(companyPeople), Company::getCompanyPeople, companyPeople);
            IPage<Company> companyIPage = this.page(companyPage, queryWrapper);
            for (Company company : companyIPage.getRecords()) {
                List<PostPush> postPushList = postPushService.listPostPushByCompanyId(company.getCompanyId());
                company.setPostPushList(postPushList);
            }

            return Result.success().put("data", companyIPage);
        }
    }

    @Override
    public Result selectCompanyPostPushList(String key, PostPush postPush, Integer page, Integer limit, Double lat, Double lng) {
        QueryWrapper<Company> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status",1).eq("is_use",1).like("company_all_name",key);
        List<Company> companies = baseMapper.selectList(queryWrapper);
        for (Company company :companies){
            postPush.setCompanyId(company.getCompanyId());
            company.setPostPushList( postPushService.getPostPushList(page,limit,lng,lat,null,postPush,null,null));
        }
        return Result.success().put("data",companies);
    }

//    @Override
//    public Result selectCompanyPostPushList(String key, Integer page, Integer limit,PostPush postPush, Double lng, Double lat) {
//        QueryWrapper<Company> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("status",1).eq("is_use",1).like("company_all_name",key);
//        List<Company> companies = baseMapper.selectList(queryWrapper);
//        for (Company company :companies){
//            postPush.setCompanyId(company.getCompanyId());
//            company.setPostPushList((List<PostPush>) postPushService.getPostPushList(page,limit,lng,lat,null,postPush,null,null));
//        }
//        return Result.success().put("data",companies);
//    }

}
