package com.gree.mall.manager.logic.admin;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.admin.reqDto.AdminCompanyWechatReqBean;
import com.gree.mall.manager.bean.admin.reqDto.AdminUserAddReqBean;
import com.gree.mall.manager.bean.admin.respDto.AdminCompanyWechatRespPageBean;
import com.gree.mall.manager.commonmapper.AdminMapper;
import com.gree.mall.manager.config.wx.WxConfiguration;
import com.gree.mall.manager.enums.RoleTypeEnum;
import com.gree.mall.manager.enums.admin.AdminWebsitTypeEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.AdminCompanyWechatService;
import com.gree.mall.manager.plus.service.AdminRoleService;
import com.gree.mall.manager.plus.service.BuyCompanyInfoService;
import com.gree.mall.manager.plus.service.BuyServiceRecordService;
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 org.springframework.transaction.annotation.Transactional;

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

@Slf4j
@Service
public class AdminCompanyWechatLogic {

    @Autowired
    AdminRoleService adminRoleService;
    @Autowired
    private AdminCompanyWechatService adminCompanyWechatService;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    BuyCompanyInfoService buyCompanyInfoService;
    @Autowired
    BuyServiceRecordService buyServiceRecordService;
    @Autowired
    WxConfiguration wxConfiguration;
    @Autowired
    private AdminUserLogic adminUserLogic;
    @Autowired
    AdminWebsitLogic adminWebsitLogic;
    @Autowired
    AdminCompanyWechatTemplateLogic adminCompanyWechatTemplateLogic;
    @Autowired
    AdminCompanyWechatOtherLogic adminCompanyWechatOtherLogic;
    @Autowired
    CommonLogic commonLogic;


    /**
     * 商户列表
     */
    public IPage<AdminCompanyWechatRespPageBean> list(String userName, String nickName, String linkPhone, String email, Boolean status, Integer pageNum, Integer pageSize) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        return adminMapper.pageCompanyWechat(new Page(pageNum, pageSize), userName, nickName, linkPhone, email, status,adminUser.getCompanyWechatId());
    }


    /**
     * 新增商户
     */
    @Transactional
    public void addCompanyWechat(AdminCompanyWechatReqBean adminCompanyWechat) {
        if (Objects.isNull(adminCompanyWechat.getExpireTime())) {
//            throw new RemoteServiceException("过期时间不能为空");
            adminCompanyWechat.setExpireTime(DateUtil.offsetDay(DateUtil.date(), 6));
        }

        BuyCompanyInfo companyInfo = buyCompanyInfoService.lambdaQuery()
                .eq(BuyCompanyInfo::getCompanyName, StrUtil.trim(adminCompanyWechat.getNickName()))
                .one();

        if (Objects.isNull(companyInfo)) {
            companyInfo = new BuyCompanyInfo();
            companyInfo.setCompanyName(StrUtil.trim(adminCompanyWechat.getNickName()))
                    .setManager(adminCompanyWechat.getLinkName())
                    .setMobile(adminCompanyWechat.getLinkPhone())
                    .setAddress(adminCompanyWechat.getAddress())
                    .setEmail(adminCompanyWechat.getEmail())
                    .insert();
//            throw new RemoteServiceException("未找到购买方信息");
        }

        // 更新购买成功支付记录
        BuyServiceRecord serviceRecord = buyServiceRecordService.lambdaQuery()
                .eq(BuyServiceRecord::getCompanyName, companyInfo.getCompanyName())
                .eq(BuyServiceRecord::getIsPay, true)
                .orderByDesc(BuyServiceRecord::getCreateTime)
                .last("limit 1")
                .one();

        //目前默认用公众号，以公众号覆盖subAppId
        adminCompanyWechat.setSubAppId(adminCompanyWechat.getPubAppId());
        adminCompanyWechat.setSubSecret(adminCompanyWechat.getPubAppSecret());
        if(StringUtils.isBlank(adminCompanyWechat.getBillTitle())){
            adminCompanyWechat.setBillTitle(adminCompanyWechat.getCompanyName());
        }
        adminCompanyWechat.setBuyCompanyInfo(companyInfo.getId());
        adminCompanyWechat.setCompanyName(adminCompanyWechat.getNickName());
        adminCompanyWechat.insert();

        if (Objects.nonNull(serviceRecord)) {
            serviceRecord.setOpenTime(adminCompanyWechat.getCreateTime())
                    .setExpireTime(adminCompanyWechat.getExpireTime())
                    .updateById();
        }

        AdminUser adminUser = new AdminUser();
        adminUser.setNickName(adminCompanyWechat.getNickName());
        adminUser.setType(RoleTypeEnum.COMPANY.getCode());
        adminUser.setUserName(adminCompanyWechat.getUserName());
        adminUser.setPassword(adminCompanyWechat.getPassword());
        adminUser.setLinkName(adminCompanyWechat.getLinkName());
        adminUser.setLinkPhone(adminCompanyWechat.getLinkPhone());
        adminUser.setCompanyWechatId(adminCompanyWechat.getCompanyWechatId());
        adminUser.setCompanyName(adminCompanyWechat.getCompanyName());

        AdminRole adminRole = adminRoleService.lambdaQuery().eq(AdminRole::getName, "企业负责人").one();
        if(adminRole == null){
            throw new RemoteServiceException("请配置【企业负责人】角色来作为商户的默认角色");
        }
        AdminUserAddReqBean adminUserAddReqBean = new AdminUserAddReqBean();
        BeanUtils.copyProperties(adminUser, adminUserAddReqBean);
        adminUserAddReqBean.setRoleId(adminRole.getAdminRoleId());
        //生成商户部门挂在根目录下
        AdminWebsit adminWebsit = new AdminWebsit();
        adminWebsit.setWebsitId(IdWorker.getIdStr());
        adminWebsit.setName(adminCompanyWechat.getCompanyName());
        adminWebsit.setWebsitNumber(adminWebsit.getWebsitId());
        adminWebsit.setCompanyWechatId(adminCompanyWechat.getCompanyWechatId());
        adminWebsit.setCompanyWechatName(adminCompanyWechat.getCompanyName());
        adminWebsit.setAddress(adminCompanyWechat.getAddress());
        adminWebsit.setParentId("1");
        adminWebsit.setType(AdminWebsitTypeEnum.B.getKey());
        adminWebsit.insert();
        //生成网点部门挂在商户目录下
        AdminWebsit adminWebsit2 = new AdminWebsit();
        adminWebsit2.setWebsitId(IdWorker.getIdStr());
        adminWebsit2.setName(adminCompanyWechat.getCompanyName()+"-网点");
        adminWebsit2.setWebsitNumber(adminWebsit.getWebsitId());
        adminWebsit2.setCompanyWechatId(adminCompanyWechat.getCompanyWechatId());
        adminWebsit2.setCompanyWechatName(adminCompanyWechat.getCompanyName());
        adminWebsit2.setAddress(adminCompanyWechat.getAddress());
        adminWebsit2.setParentId(adminWebsit.getWebsitId());
        adminWebsit2.setType(AdminWebsitTypeEnum.C.getKey());
        adminWebsit2.setLng(adminCompanyWechat.getLng());
        adminWebsit2.setLat(adminCompanyWechat.getLat());
        adminWebsit2.insert();

        //添加企业用户
        List<String> websitIds = new ArrayList<>();
        websitIds.add(adminWebsit.getWebsitId());
        adminUserAddReqBean.setAdminWebsitId(websitIds);
        adminUserLogic.add(adminUserAddReqBean,true);
        //初始化模板
        adminCompanyWechatTemplateLogic.initCompanyWechatTemplate(adminCompanyWechat.getCompanyWechatId(), adminCompanyWechat.getCompanyName());
        //初始化其他配置
        adminCompanyWechatOtherLogic.init(adminCompanyWechat.getCompanyWechatId(), adminCompanyWechat.getCompanyName());
        //刷新微信和支付配置
        wxConfiguration.reloadWxConfig(Lists.newArrayList(adminCompanyWechat));
        log.info("初始化完成10");
    }

    /**
     * 编辑商户
     */
    @Transactional
    public void updateCompanyWechat(AdminCompanyWechat adminCompanyWechat) {
        if (StringUtils.isBlank(adminCompanyWechat.getCompanyWechatId())) {
            throw new RemoteServiceException("商户配置id不能为null");
        }
        if (Objects.nonNull(adminCompanyWechat.getExpireTime())) {
            AdminCompanyWechat companyWechat = adminCompanyWechatService.getById(adminCompanyWechat.getCompanyWechatId());
            if (companyWechat.getExpireTime().getTime() != adminCompanyWechat.getExpireTime().getTime()) {
                // 更新购买成功支付记录
//                BuyServiceRecord serviceRecord = buyServiceRecordService.lambdaQuery()
//                        .eq(BuyServiceRecord::getCompanyName, companyWechat.getCompanyName())
//                        .eq(BuyServiceRecord::getIsPay, true)
//                        .orderByDesc(BuyServiceRecord::getCreateTime)
//                        .last("limit 1")
//                        .one();
//
//                serviceRecord.setOpenTime(adminCompanyWechat.getCreateTime())
//                        .setExpireTime(adminCompanyWechat.getExpireTime())
//                        .updateById();
                log.info("编辑商户: 过期时间变更为" + DateUtil.formatDateTime(adminCompanyWechat.getExpireTime()));
            }
        }
        //目前默认用公众号，以公众号覆盖subAppId
        adminCompanyWechat.setSubAppId(adminCompanyWechat.getPubAppId());
        adminCompanyWechat.setSubSecret(adminCompanyWechat.getPubAppSecret());
        adminCompanyWechat.updateById();
        adminWebsitLogic.reloadJoinCode(adminCompanyWechat.getCompanyWechatId(),adminCompanyWechat.getJoinCode());
        //刷新
        AdminCompanyWechat adminCompanyWechat1 = adminCompanyWechatService.getById(adminCompanyWechat.getCompanyWechatId());
        wxConfiguration.reloadWxConfig(Lists.newArrayList(adminCompanyWechat1));
    }
}
