package com.dgtly.system.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.dgtly.common.core.domain.Ztree;
import com.dgtly.common.utils.DateUtils;
import com.dgtly.common.utils.StringUtils;
import com.dgtly.common.utils.UserIdentityUtil;
import com.dgtly.system.domain.*;
import com.dgtly.system.mapper.*;
import com.dgtly.system.service.ISysDictDataService;
import com.dgtly.system.util.MailUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.dgtly.system.service.ISysUserOrderAuthorService;
import com.dgtly.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;

/**
 * 权限Service业务层处理
 *
 * @author dgtly
 * @date 2022-03-22
 */
@Slf4j
@Service
@Component
public class SysUserOrderAuthorServiceImpl implements ISysUserOrderAuthorService
{
    @Autowired
    private SysUserOrderAuthorMapper sysUserOrderAuthorMapper;

    @Autowired
    private SysUserAuthorRelMapper userAuthorRelMapper;

    @Autowired
    private SysUserExtMapper userExtMapper;
    @Autowired
    private ISysDictDataService sysDictDataService;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysUserQuitMapper userQuitMapper;
    @Autowired
    private AssRelcustomerinfoMapper relcustomerinfoMapper;
    @Autowired
    private MailUtils mailUtils;
    @Autowired
    private MetaHanaDeliverOrderMapper metaHanaDeliverOrderMapper;
    @Autowired
    private DeliverQuantityConfirmMapper deliverQuantityConfirmMapper;
    @Autowired
    private SysBatchSignForMapper sysBatchSignForMapper;

    @Autowired
    private SysDictDataMapper sysDictDataMapper;


    @Autowired
    private CustomerMapper customersMapper;
    @Value(value = "${spring.mail.username}")
    private String myEmailAccount;
    @Value(value = "${spring.mail.password}")
    public  String myEmailPassword;
    @Value(value = "${spring.mail.host}")
    public  String myEmailSMTPHost;

    /**
     * 查询权限
     *
     * @param authorId 权限ID
     * @return 权限
     */
    @Override
    public SysUserOrderAuthor selectSysUserOrderAuthorById(Long authorId)
    {
        return sysUserOrderAuthorMapper.selectSysUserOrderAuthorById(authorId);
    }

    /**
     * 查询权限列表
     *
     * @param sysUserOrderAuthor 权限
     * @return 权限
     */
    @Override
    public List<SysUserOrderAuthor> selectSysUserOrderAuthorList(SysUserOrderAuthor sysUserOrderAuthor)
    {
        return sysUserOrderAuthorMapper.selectSysUserOrderAuthorList(sysUserOrderAuthor);
    }

    /**
     * 新增权限
     *
     * @param sysUserOrderAuthor 权限
     * @return 结果
     */
    @Override
    public int insertSysUserOrderAuthor(SysUserOrderAuthor sysUserOrderAuthor)
    {
        sysUserOrderAuthor.setCreateTime(DateUtils.getNowDate());
        return sysUserOrderAuthorMapper.insertSysUserOrderAuthor(sysUserOrderAuthor);
    }

    /**
     * 修改权限
     *
     * @param sysUserOrderAuthor 权限
     * @return 结果
     */
    @Override
    public int updateSysUserOrderAuthor(SysUserOrderAuthor sysUserOrderAuthor)
    {
        sysUserOrderAuthor.setUpdateTime(DateUtils.getNowDate());
        return sysUserOrderAuthorMapper.updateSysUserOrderAuthor(sysUserOrderAuthor);
    }

    /**
     * 删除权限对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteSysUserOrderAuthorByIds(String ids)
    {
        return sysUserOrderAuthorMapper.deleteSysUserOrderAuthorByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除权限信息
     *
     * @param authorId 权限ID
     * @return 结果
     */
    @Override
    public int deleteSysUserOrderAuthorById(Long authorId)
    {
        return sysUserOrderAuthorMapper.deleteSysUserOrderAuthorById(authorId);
    }

    @Override
    @Transactional
    public int insertRel(SysUserAuthorRel role)
    {
        /*1、查询所有一级节点*/
        String identity = "";
        SysUserExt sysUserExt = new SysUserExt();
        sysUserExt.setUserId(role.getUserId());
        for (Long authorId : role.getAuthorIds()){
            SysUserOrderAuthor sysUserOrderAuthor = sysUserOrderAuthorMapper.selectSysUserOrderAuthorById(authorId);
            if (sysUserOrderAuthor.getParentId()==1L){
                if(UserIdentityUtil.UI_DIY_NAME.equals(sysUserOrderAuthor.getAuthorName())){
                    identity+=UserIdentityUtil.UI_DIY+",";
                }else if(UserIdentityUtil.UI_CW_NAME.equals(sysUserOrderAuthor.getAuthorName())){
                    identity+=UserIdentityUtil.UI_CW+",";
                }else if(UserIdentityUtil.UI_YSL_NAME.equals(sysUserOrderAuthor.getAuthorName())){
                    identity+=UserIdentityUtil.UI_YSL+",";
                }else if(UserIdentityUtil.UI_FC_NAME.equals(sysUserOrderAuthor.getAuthorName())){
                    identity+=UserIdentityUtil.UI_FC+",";
                }else if(UserIdentityUtil.UI_XLS_NAME.equals(sysUserOrderAuthor.getAuthorName())){
                    identity+=UserIdentityUtil.UI_XLS+",";
                }else if(UserIdentityUtil.UI_SAF_NAME.equals(sysUserOrderAuthor.getAuthorName())){
                    identity+=UserIdentityUtil.UI_SAF+",";
                }else if(UserIdentityUtil.UI_GZ_NAME.equals(sysUserOrderAuthor.getAuthorName())){
                    identity+=UserIdentityUtil.UI_GZ+",";
                }else if(UserIdentityUtil.UI_JZ_NAME.equals(sysUserOrderAuthor.getAuthorName())){
                    identity+=UserIdentityUtil.UI_JZ+",";
                }
            }
        }
        if (!"".equals(identity)) {
            sysUserExt.setIdentity(identity.substring(0, identity.length() - 1));
        }
        /*判断节点对应身份进行人员身份修改*/
        userAuthorRelMapper.deleteSysUserAuthorRelById(role.getUserId());
        int rows = 1;
        // 新增角色与部门（数据权限）管理
        List<SysUserAuthorRel> list = new ArrayList<SysUserAuthorRel>();
        for (Long authorId : role.getAuthorIds())
        {
            SysUserAuthorRel rd = new SysUserAuthorRel();
            rd.setUserId(role.getUserId());
            rd.setAuthorId(authorId);
            list.add(rd);
        }
        if (list.size() > 0)
        {
            rows = userAuthorRelMapper.batchRel(list);
            if (!"".equals(identity)) {
                rows = userExtMapper.updateSysUserExt(sysUserExt);
            }
        }
        return rows;
    }

    /**
     * 查询权限树列表
     *
     * @return 所有权限信息
     */
    @Override
    public List<Ztree> selectSysUserOrderAuthorTree()
    {
        List<SysUserOrderAuthor> sysUserOrderAuthorList = sysUserOrderAuthorMapper.selectSysUserOrderAuthorList(new SysUserOrderAuthor());
        List<Ztree> ztrees = new ArrayList<Ztree>();
        for (SysUserOrderAuthor sysUserOrderAuthor : sysUserOrderAuthorList)
        {
            Ztree ztree = new Ztree();
            ztree.setId(sysUserOrderAuthor.getAuthorId());
            ztree.setpId(sysUserOrderAuthor.getParentId());
            ztree.setName(sysUserOrderAuthor.getAuthorName());
            ztree.setTitle(sysUserOrderAuthor.getAuthorName());
            ztrees.add(ztree);
        }
        return ztrees;
    }
    @Override
    public List<Ztree> userAuthorTreeData(Long userId) {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        List<SysUserOrderAuthor> menuList = sysUserOrderAuthorMapper.selectSysUserOrderAuthorList(new SysUserOrderAuthor());
        List<Long> user = sysUserOrderAuthorMapper.selectAuthorTree(userId);
        ztrees = initTree(menuList, user);

        getAuthorByLevel();//todo
        return ztrees;
    }
    @Override
    public List<Ztree> userAuthorTreeDataFmt(Long userId) {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        List<SysUserOrderAuthor> menuList = sysUserOrderAuthorMapper.selectSysUserOrderAuthorList(new SysUserOrderAuthor());
        List<Long> user = sysUserOrderAuthorMapper.selectAuthorTree(userId);
        ztrees = initTree(menuList, user);
        ztrees = buildTree(ztrees, 0L);
        return ztrees;
    }

    //把一个List转成树
    static List<Ztree> buildTree(List<Ztree> list,Long pid){
        List<Ztree> tree=new ArrayList<>();
        for(Ztree node:list){
            if(Objects.equals(node.getpId(),pid)){
                tree.add(findChild(node,list));
            }
        }
        return tree;
    }

    static Ztree findChild(Ztree node, List<Ztree> list){
        for(Ztree n:list){
            if(Objects.equals(n.getpId(),node.getId())){
                if(node.getChildren() == null){
                    node.setChildren(new ArrayList<Ztree>());
                }
                node.getChildren().add(findChild(n,list));
            }
        }
        return node;
    }

    /**
     * 对象转树
     * @param sysUserOrderAuthorList
     * @return
     */
    public List<Ztree> initTree(List<SysUserOrderAuthor> sysUserOrderAuthorList, List<Long> roleMenuList)
    {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleMenuList);
        for (SysUserOrderAuthor menu : sysUserOrderAuthorList)
        {
            Ztree ztree = new Ztree();
            ztree.setId(menu.getAuthorId());
            ztree.setpId(menu.getParentId());
            ztree.setName(menu.getAuthorName());
            ztree.setTitle(menu.getAuthorName());
            ztree.setCode(menu.getCode());
            if (isCheck)
            {
                ztree.setChecked(roleMenuList.contains(menu.getAuthorId()));
            }
            ztree.setOpen(true);
            ztrees.add(ztree);
        }
        return ztrees;
    }

    public void userAuthorTask(){

    }

    public void getAuthorByLevel(){
        List<SysUserOrderAuthor> list = sysUserOrderAuthorMapper.selectSysUserOrderAuthorList(new SysUserOrderAuthor());
        List<Long> ids = new ArrayList<>();
        getParentAuthor(ids, list, 8L);
        System.out.println(ids);
    }

    public void getParentAuthor(List<Long> ids, List<SysUserOrderAuthor> list, Long id){
        for (SysUserOrderAuthor sysUserOrderAuthor : list) {
            Long itemId = sysUserOrderAuthor.getAuthorId();
            if(itemId.equals(0L)){
                ids.add(itemId);
            }else if(itemId.equals(id)){
                ids.add(itemId);
                getParentAuthor(ids, list , sysUserOrderAuthor.getParentId());
            }
        }
    }

    @Override
    public void initUserAuthor() {
        List<SysUserOrderAuthor> userOrderAuthorList = new ArrayList<>();
        List<SysUserAuthorRel> roleAuth = new ArrayList<>();
        //diy
        List<SysUserOrderAuthor> userOrderAuthorDiyList = sysUserOrderAuthorMapper.selectAuthorIdByCode("tuc_diy",null);
        if(userOrderAuthorDiyList !=null && userOrderAuthorDiyList.size()>0){
            List<Long> diyauthList=userOrderAuthorDiyList.stream().map(SysUserOrderAuthor::getAuthorId).collect(Collectors.toList());
            List<SysUserOrderAuthor> diyrole=sysUserOrderAuthorMapper.selectByParentId(diyauthList);
            if(diyrole !=null && diyrole.size()>0){
                userOrderAuthorDiyList.addAll(diyrole);
            }
        }

        //division
        //BMD-NVB2023T05
        List<SysUserOrderAuthor> userOrderAuthorBMDList = sysUserOrderAuthorMapper.selectAuthorIdByCode("tuc_diy","NVB2023T05");
        if(userOrderAuthorBMDList !=null && userOrderAuthorBMDList.size()>0){
        List<Long> BMdAuthList=userOrderAuthorBMDList.stream().map(SysUserOrderAuthor::getAuthorId).collect(Collectors.toList());
        List<SysUserOrderAuthor> BMdRole=sysUserOrderAuthorMapper.selectByParentId(BMdAuthList);
            if(BMdRole !=null && BMdRole.size()>0){
                userOrderAuthorBMDList.addAll(BMdRole);
            }
        }
        //12北-NVB2023T01
        List<SysUserOrderAuthor> userOrderAuthor12bList = sysUserOrderAuthorMapper.selectAuthorIdByCode("tuc_diy","NVB2023T01");
        if(userOrderAuthor12bList !=null && userOrderAuthor12bList.size()>0){
        List<Long> b12AuthList=userOrderAuthor12bList.stream().map(SysUserOrderAuthor::getAuthorId).collect(Collectors.toList());
        List<SysUserOrderAuthor> b12Role=sysUserOrderAuthorMapper.selectByParentId(b12AuthList);
            if(b12Role !=null && b12Role.size()>0){
                userOrderAuthor12bList.addAll(b12Role);
            }
        }
        //12南-NVB2023T02
        List<SysUserOrderAuthor> userOrderAuthor12nList = sysUserOrderAuthorMapper.selectAuthorIdByCode("tuc_diy","NVB2023T02");
        if(userOrderAuthor12nList !=null && userOrderAuthor12nList.size()>0){
        List<Long> n12AuthList=userOrderAuthor12nList.stream().map(SysUserOrderAuthor::getAuthorId).collect(Collectors.toList());
        List<SysUserOrderAuthor> n12Role=sysUserOrderAuthorMapper.selectByParentId(n12AuthList);
            if(n12Role !=null && n12Role.size()>0){
                userOrderAuthor12nList.addAll(n12Role);
            }
        }
        //12中-NVB2023T03
        List<SysUserOrderAuthor> userOrderAuthor12zList = sysUserOrderAuthorMapper.selectAuthorIdByCode("tuc_diy","NVB2023T03");
        if(userOrderAuthor12zList !=null && userOrderAuthor12zList.size()>0){
        List<Long> z12AuthList=userOrderAuthor12zList.stream().map(SysUserOrderAuthor::getAuthorId).collect(Collectors.toList());
        List<SysUserOrderAuthor> z12Role=sysUserOrderAuthorMapper.selectByParentId(z12AuthList);
            if(z12Role !=null && z12Role.size()>0){
                userOrderAuthor12zList.addAll(z12Role);
            }
        }
        //36城-NVB2023T04
        List<SysUserOrderAuthor> userOrderAuthor36List = sysUserOrderAuthorMapper.selectAuthorIdByCode("tuc_diy","NVB2023T04");
        if(userOrderAuthor36List !=null && userOrderAuthor36List.size()>0){
        List<Long> c36AuthList=userOrderAuthor36List.stream().map(SysUserOrderAuthor::getAuthorId).collect(Collectors.toList());
        List<SysUserOrderAuthor> c36Role=sysUserOrderAuthorMapper.selectByParentId(c36AuthList);
            if(c36Role !=null && c36Role.size()>0){
                userOrderAuthor36List.addAll(c36Role);
            }
        }
        //cw
       /* List<SysUserOrderAuthor> userOrderAuthorCwList = sysUserOrderAuthorMapper.selectAuthorIdByCode("tuc_cw");
        List<Long> cwauthList=userOrderAuthorCwList.stream().map(SysUserOrderAuthor::getAuthorId).collect(Collectors.toList());
        List<SysUserOrderAuthor> cwrole=sysUserOrderAuthorMapper.selectByParentId(cwauthList);
        userOrderAuthorCwList.addAll(cwrole);*/
       //ysl
        List<SysUserOrderAuthor> userOrderAuthorYSLList = sysUserOrderAuthorMapper.selectAuthorIdByCode("YSL",null);
        if(userOrderAuthorYSLList !=null && userOrderAuthorYSLList.size()>0){
        List<Long> yslauthList=userOrderAuthorYSLList.stream().map(SysUserOrderAuthor::getAuthorId).collect(Collectors.toList());
        List<SysUserOrderAuthor> yslrole=sysUserOrderAuthorMapper.selectByParentId(yslauthList);
            if(yslrole !=null && yslrole.size()>0){
                userOrderAuthorYSLList.addAll(yslrole);
            }
        }
        //xls
        List<SysUserOrderAuthor> userOrderAuthorXlsList = sysUserOrderAuthorMapper.selectAuthorIdByCode("XLS",null);
        if(userOrderAuthorXlsList !=null && userOrderAuthorXlsList.size()>0){
            List<Long> xlsAuthList=userOrderAuthorXlsList.stream().map(SysUserOrderAuthor::getAuthorId).collect(Collectors.toList());
            List<SysUserOrderAuthor> xlsRole=sysUserOrderAuthorMapper.selectByParentId(xlsAuthList);
            if(xlsRole !=null && xlsRole.size()>0){
                 userOrderAuthorXlsList.addAll(xlsRole);
            }
        }

        userExtMapper.selectUserExtList().forEach(sysUserExt -> {
            String sales = sysUserExt.getSalesLevel();
            if (sales != null) {
            int index = sales.indexOf("_");
            String intNumber = sales.substring(0, index);
           /* if (intNumber.equals("cw")) {
                userOrderAuthorList.clear();
                userOrderAuthorList.addAll(userOrderAuthorCwList);
            } else*/ if (intNumber.equals("diy")||intNumber.equals("company") || intNumber.equals("office") || intNumber.equals("emp")
                    || intNumber.equals("saledept") || intNumber.equals("suboffice")) {
                userOrderAuthorList.clear();
                roleAuth.clear();
                userOrderAuthorList.addAll(userOrderAuthorDiyList);
            } else if (intNumber.equals("ysl")) {
                userOrderAuthorList.clear();
                roleAuth.clear();
                userOrderAuthorList.addAll(userOrderAuthorYSLList);
            }else if (intNumber.equals("division")) {
                    userOrderAuthorList.clear();
                    roleAuth.clear();
                    if(("NVB2023T05").equals(sysUserExt.getOrgCode())){
                        userOrderAuthorList.addAll(userOrderAuthorBMDList);
                    }else if(("NVB2023T01").equals(sysUserExt.getOrgCode())){
                        userOrderAuthorList.addAll(userOrderAuthor12bList);
                    }else if(("NVB2023T02").equals(sysUserExt.getOrgCode())){
                        userOrderAuthorList.addAll(userOrderAuthor12nList);
                    }else if(("NVB2023T03").equals(sysUserExt.getOrgCode())){
                        userOrderAuthorList.addAll(userOrderAuthor12zList);
                    }else if(("NVB2023T04").equals(sysUserExt.getOrgCode())){
                        userOrderAuthorList.addAll(userOrderAuthor36List);
                    }

                }else if(intNumber.equals("customer")){
                    String isCustomerManager=sysUserExt.getIsCustomerManager();
                    if(isCustomerManager !=null && !("").equals(isCustomerManager)){
                        List<String> isManager =Arrays.asList(isCustomerManager.split(","));
                        //7新零售经销商
                        if(isManager.size()==1 && isManager.contains("7")){
                            userOrderAuthorList.clear();
                            roleAuth.clear();
                            userOrderAuthorList.addAll(userOrderAuthorXlsList);
                        }else if(isManager.contains("7") && isManager.size()>1 ){
                            userOrderAuthorList.clear();
                            roleAuth.clear();
                            userOrderAuthorList.addAll(userOrderAuthorXlsList);
                            userOrderAuthorList.addAll(userOrderAuthorDiyList);
                        }else {
                            userOrderAuthorList.clear();
                            roleAuth.clear();
                            userOrderAuthorList.addAll(userOrderAuthorDiyList);
                        }
                    }else{
                        userOrderAuthorList.clear();
                        roleAuth.clear();
                        userOrderAuthorList.addAll(userOrderAuthorDiyList);
                    }
                }
            if(userOrderAuthorList !=null && userOrderAuthorList.size()>0){
                userAuthorRelMapper.deleteSysUserAuthorRelById(sysUserExt.getUserId());
                SysUserAuthorRel role = new SysUserAuthorRel();
                role.setUserId(sysUserExt.getUserId());
                role.setAuthorId(userOrderAuthorList.get(0).getParentId());
                roleAuth.add(role);
                userOrderAuthorList.forEach(sysUserOrderAuthor -> {
                    SysUserAuthorRel userRel = new SysUserAuthorRel();
                    userRel.setUserId(sysUserExt.getUserId());
                    userRel.setAuthorId(sysUserOrderAuthor.getAuthorId());
                    roleAuth.add(userRel);
                });
               userAuthorRelMapper.batchRel(roleAuth);
            }
            }
        });

    }

    @Override
    public void quitUser() {
        List<SysUser> userList=userMapper.selectUser();
        Set<String> SapEmployeeIdList=userQuitMapper.selectAllUserSapEmployeeId();
         Set<String> employList=SapEmployeeIdList.stream().map(String::toUpperCase).collect(Collectors.toSet());
         for (SysUser sysUser :userList
                 ) {
             SysUserExt userExt = userExtMapper.selectSysUserExtById(sysUser.getUserId());
             if (userExt !=null && userExt.getSapEmployeeId() != null && userExt.getSapEmployeeId() !="") {
                 if(employList!=null && employList.size()>0){
                 if (employList.contains(userExt.getSapEmployeeId().toUpperCase())) {
                     sysUser.setQuit("2");
                     userMapper.updateUser(sysUser);
                 }
                 }
             }
         }

    }

    @Override
    public void updateCustomers() {
            List<AssRelcustomerinfo> list=relcustomerinfoMapper.selectCustomerNameAndCode();
            List<Customer> customersList=new ArrayList<>();
            if(list != null && list.size()>0){
                for (AssRelcustomerinfo info:list
                     ) {
                   Customer customers= customersMapper.selectCustomersByChainsCode(info.getMainkunnr());
                   if(customers==null){
                       Customer customer=new Customer();
                       customer.setChainsName(info.getMainname1());
                       customer.setChainsCode(info.getMainkunnr());
                       customersList.add(customer);
                   }
                }
                customersList.forEach(customers ->{
                    customersMapper.insertCustomers(customers);
                } );
            }
    }

    @Override
    public void sendmailUnionUser() {
        List<UserVO> userList = userMapper.sendmailUnionUser();
        if(userList.size()>0){
        // 1. 创建参数配置, 用于连接邮件服务器的参数配置
        Properties props = new Properties();                    // 参数配置
        props.setProperty("mail.transport.protocol", "smtp");   // 使用的协议（JavaMail规范要求）
        props.setProperty("mail.smtp.host", myEmailSMTPHost);   // 发件人的邮箱的 SMTP 服务器地址
        props.setProperty("mail.smtp.port", "25");
        props.setProperty("mail.smtp.auth", "true");            // 需要请求认证
        props.setProperty("mail.smtp.starttls.enable", "false");            // 需要请求认证
        props.setProperty("mail.smtp.ssl.enable", "false");            // 需要请求认证
        Set<String> sendEmailUser = getConfigValueSet("sendmailUnionUser");
        Session session = Session.getDefaultInstance(props);
        session.setDebug(true);

        for (String email : sendEmailUser
        ) {
            Mail mail = new Mail();
            try {
                mail.setFrom(myEmailAccount);
                mail.setTo(email);
                mail.setSubject("立邦随身邦用户账号重复");
                mail.setContent(getHtmlUserContextList(userList));
                //mailUtils.sendMailHtml(mailFromUsername, email, "用户账号重复通知", "您好，重复用户信息如下<br>" + userList);
                MimeMessage message = mailUtils.createMimeMessage(session, myEmailAccount, email, mail);

                // 4. 根据 Session 获取邮件传输对象
                Transport transport = session.getTransport();

                transport.connect(myEmailAccount, myEmailPassword);

                // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
                transport.sendMessage(message, message.getAllRecipients());

                // 7. 关闭连接
                transport.close();
            } catch (NoSuchProviderException e) {
                e.printStackTrace();
            } catch (MessagingException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        }
    }

    @Override
    public void sendMailHanaWarning(String HanaName) {
        // 1. 创建参数配置, 用于连接邮件服务器的参数配置
        Properties props = new Properties();                    // 参数配置
        props.setProperty("mail.transport.protocol", "smtp");   // 使用的协议（JavaMail规范要求）
        props.setProperty("mail.smtp.host", myEmailSMTPHost);   // 发件人的邮箱的 SMTP 服务器地址
        props.setProperty("mail.smtp.port", "25");
        props.setProperty("mail.smtp.auth", "true");            // 需要请求认证
        props.setProperty("mail.smtp.starttls.enable", "false");            // 需要请求认证
        props.setProperty("mail.smtp.ssl.enable", "false");            // 需要请求认证
        Set<String> sendEmailUser = getConfigValueSet("sendmailUnionUser");
        Session session = Session.getDefaultInstance(props);
        session.setDebug(true);

        for (String email : sendEmailUser
        ) {
            Mail mail = new Mail();
            try {
                mail.setFrom(myEmailAccount);
                mail.setTo(email);
                mail.setSubject("Hana数据拉取异常");
                mail.setContent(getHtmlHanaNameContextList(HanaName));
                MimeMessage message = mailUtils.createMimeMessage(session, myEmailAccount, email, mail);

                // 4. 根据 Session 获取邮件传输对象
                Transport transport = session.getTransport();

                transport.connect(myEmailAccount, myEmailPassword);

                // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
                transport.sendMessage(message, message.getAllRecipients());

                // 7. 关闭连接
                transport.close();
            } catch (NoSuchProviderException e) {
                e.printStackTrace();
            } catch (MessagingException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void unionCustomerUser() {
    /*    List<SysUser> userList = userMapper.selectAllUser();
        userList.forEach(user -> {
            user.setQuit("2");
            user.getSysUserExt().setIsCustomerManager(null);
            userMapper.updateUser(user);
            userExtMapper.updateSysUserExt(user.getSysUserExt());
        });*/
    }

    /**
     * 无tms工厂的交货单更新状态和订单
     */
    @Override
    public void tmsPlantByOrder() {
        List<String> selfDeliver = metaHanaDeliverOrderMapper.selectSelfDeliverNumber();
        List<String> plants = metaHanaDeliverOrderMapper.selectPlant();
        List<TmsLogisticsStatus> tmsStatusLog = sysBatchSignForMapper.selectByDelivery();
        Map<Object, List<TmsLogisticsStatus>> keytmsMap = new HashMap<>();
        Map<Object, List<TmsLogisticsStatus>> keytmsYes = new HashMap<>();
        if (tmsStatusLog != null && tmsStatusLog.size() > 0) {
            keytmsMap = tmsStatusLog.stream().collect(Collectors.groupingBy(TmsLogisticsStatus::getDeliveryNumber));
        }
        DeliverQuantityConfirm numbernull = new DeliverQuantityConfirm();
        List<DeliverQuantityConfirm> deliverNumber = deliverQuantityConfirmMapper.selectDeliverQuantityConfirmList(numbernull);
        List<String> OrderNumbers=metaHanaDeliverOrderMapper.selectDocNumberByVSBED12();
        List<String> deliverNumbers = new ArrayList<>();
        if (deliverNumber != null && deliverNumber.size() > 0) {
            deliverNumbers = deliverNumber.stream().map(DeliverQuantityConfirm::getCode).collect(Collectors.toList());
        }
        int count = metaHanaDeliverOrderMapper.selectCount();
        List<TmsLogisticsStatus> tmslistNo = new ArrayList<TmsLogisticsStatus>();
        List<TmsLogisticsStatus> tmslistYes = new ArrayList<TmsLogisticsStatus>();
        List<TmsLogisticsStatus> tmsStatus5list = new ArrayList<TmsLogisticsStatus>();
        List<DeliverQuantityConfirm> deliverlist = new ArrayList<DeliverQuantityConfirm>();
        int m = 10000;
        int y = 0;
        if (count % m != 0) {
            y = count / m + 1;
        }
        int n = 0;
        for (int x = 0; x <= y; x++) {
            if (x == 0) {
                n = 0;
            } else {
                n = n + 10000;
            }
            List<MetaHanaDeliverOrder> deliverOrderListstatusNo  = metaHanaDeliverOrderMapper.selectMetaDeliverOrderListByNo(n, m);
            if (deliverOrderListstatusNo != null && deliverOrderListstatusNo.size() > 0) {
                for (MetaHanaDeliverOrder deliver : deliverOrderListstatusNo
                ) {
                    if(selfDeliver !=null && selfDeliver.size()>0){
                        if(selfDeliver.contains(deliver.getDeliverNumber())){
                            continue;
                        }
                    }
                    if (plants != null && plants.size() > 0) {
                        if (plants.contains(deliver.getPlant())) {
                            continue;
                        }
                    }
                    if (("未复核").equals(deliver.getReviewStatus())) {
                        if(OrderNumbers !=null && OrderNumbers.size()>0){
                            if (OrderNumbers.contains(deliver.getDocNumber())) {
                                continue;
                            }
                        }
                        List<String> tms=new ArrayList<>();
                        if(tmslistNo !=null && tmslistNo.size()>0){
                             tms = tmslistNo.stream().map(TmsLogisticsStatus::getDeliveryNumber).collect(Collectors.toList());
                        }
                        if ((keytmsMap == null) || (!keytmsMap.containsKey(deliver.getDeliverNumber()) && !tms.contains(deliver.getDeliverNumber()))) {
                            TmsLogisticsStatus tmsLogisticsStatus = new TmsLogisticsStatus();
                            tmsLogisticsStatus.setCreateBy("未上TMS");
                            tmsLogisticsStatus.setCreateTime(new Date());
                            tmsLogisticsStatus.setUpdateBy("未上TMS");
                            tmsLogisticsStatus.setUpdateTime(new Date());
                            tmsLogisticsStatus.setIsDelete("0");
                            tmsLogisticsStatus.setOrderCreationTime("");
                            tmsLogisticsStatus.setDeliveryNumber(deliver.getDeliverNumber());
                            if (("").equals(deliver.getShipmentNumber()) || deliver.getShipmentNumber() == null || ("null").equals(deliver.getShipmentNumber())) {
                                tmsLogisticsStatus.setTmsShipmentNumber(deliver.getDeliverNumber());
                            } else {
                                tmsLogisticsStatus.setTmsShipmentNumber(deliver.getShipmentNumber());
                            }
                            tmsLogisticsStatus.setStatus("1");
                            tmsLogisticsStatus.setDriverName("未上TMS");
                            tmsLogisticsStatus.setCarNumber("未上TMS");
                            tmsLogisticsStatus.setDriverPhone("13888888888");
                            tmsLogisticsStatus.setCustomerCode(deliver.getCustomerCode());
                            tmsLogisticsStatus.setOrderNumber(deliver.getDocNumber());
                            tmsLogisticsStatus.setAssignTime(new Date());
                            tmsLogisticsStatus.setTransferOrder("n");
                            tmslistNo.add(tmsLogisticsStatus);
                            if (tmslistNo != null && tmslistNo.size() > 5000) {
                                sysBatchSignForMapper.saveTmsLogisticsStatus(tmslistNo);
                                tmslistNo.clear();
                                List<TmsLogisticsStatus> tmsNewLog = sysBatchSignForMapper.selectByDelivery();
                                if (tmsNewLog != null && tmsNewLog.size() > 0) {
                                    keytmsMap = tmsNewLog.stream().collect(Collectors.groupingBy(TmsLogisticsStatus::getDeliveryNumber));
                                }
                            }
                        }
                    }else if(("已复核").equals(deliver.getReviewStatus())){
                        List<String> tms=new ArrayList<>();
                        if(tmslistYes !=null && tmslistYes.size()>0){
                            tms = tmslistYes.stream().map(TmsLogisticsStatus::getDeliveryNumber).collect(Collectors.toList());
                            }
                            if ((keytmsMap == null ) || (!keytmsMap.containsKey(deliver.getDeliverNumber()) && !tms.contains(deliver.getDeliverNumber()))) {
                                TmsLogisticsStatus tmsLogisticsStatus = new TmsLogisticsStatus();
                                tmsLogisticsStatus.setCreateBy("未上TMS");
                                tmsLogisticsStatus.setCreateTime(new Date());
                                tmsLogisticsStatus.setUpdateBy("未上TMS");
                                tmsLogisticsStatus.setUpdateTime(new Date());
                                tmsLogisticsStatus.setIsDelete("0");
                                tmsLogisticsStatus.setOrderCreationTime("");
                                tmsLogisticsStatus.setDeliveryNumber(deliver.getDeliverNumber());
                                if (("").equals(deliver.getShipmentNumber()) || deliver.getShipmentNumber() == null || ("null").equals(deliver.getShipmentNumber())) {
                                    tmsLogisticsStatus.setTmsShipmentNumber(deliver.getDeliverNumber());
                                } else {
                                    tmsLogisticsStatus.setTmsShipmentNumber(deliver.getShipmentNumber());
                                }
                                tmsLogisticsStatus.setStatus("5");
                                tmsLogisticsStatus.setDriverName("未上TMS");
                                tmsLogisticsStatus.setCarNumber("未上TMS");
                                tmsLogisticsStatus.setDriverPhone("13888888888");
                                tmsLogisticsStatus.setCustomerCode(deliver.getCustomerCode());
                                tmsLogisticsStatus.setOrderNumber(deliver.getDocNumber());
                                tmsLogisticsStatus.setAssignTime(new Date());
                                tmsLogisticsStatus.setTransferOrder("n");
                                String time = deliver.getPostingDate();
                                Date date = new Date();
                                try {
                                    date = new SimpleDateFormat("yyyyMMdd").parse(time);
                                } catch (ParseException e) {
                                    //LOGGER.error("时间转换错误, string = {}", s, e);
                                }
                                tmsLogisticsStatus.setArrivalGoodsTime(date);
                                tmsLogisticsStatus.setGetGoodsTime(date);
                                tmsLogisticsStatus.setFactoryTime(date);
                                tmslistYes.add(tmsLogisticsStatus);
                                if (tmslistYes != null && tmslistYes.size() > 5000) {
                                    sysBatchSignForMapper.saveTmsLogisticsStatus(tmslistYes);
                                    tmslistYes.clear();
                                    List<TmsLogisticsStatus> tmsNewLog = sysBatchSignForMapper.selectByDelivery();
                                    if (tmsNewLog != null && tmsNewLog.size() > 0) {
                                        keytmsMap = tmsNewLog.stream().collect(Collectors.groupingBy(TmsLogisticsStatus::getDeliveryNumber));
                                    }
                                }
                            }
                            if((keytmsMap == null || !keytmsMap.containsKey(deliver.getDeliverNumber()))){
                            if(tmslistYes !=null && tmslistYes.size()>0){
                                keytmsYes = tmslistYes.stream().collect(Collectors.groupingBy(TmsLogisticsStatus::getDeliveryNumber));
                            }
                            }
                            if ((keytmsMap != null && keytmsMap.containsKey(deliver.getDeliverNumber())) || (keytmsYes !=null && keytmsYes.containsKey(deliver.getDeliverNumber()))) {
                                List<TmsLogisticsStatus> tmsStatusList =new ArrayList<>();
                                if(keytmsMap != null && keytmsMap.containsKey(deliver.getDeliverNumber())){
                                    tmsStatusList = keytmsMap.get(deliver.getDeliverNumber());
                                }else if(keytmsYes !=null && keytmsYes.containsKey(deliver.getDeliverNumber())){
                                    tmsStatusList = keytmsYes.get(deliver.getDeliverNumber());
                                }

                                if (tmsStatusList != null && tmsStatusList.size() > 0) {
                                    Optional<TmsLogisticsStatus> tmsStatus = tmsStatusList.stream().filter(org -> Objects.equals(org.getDeliveryNumber(), deliver.getDeliverNumber())).findFirst();
                                    if (!tmsStatus.get().getStatus().equals("5")) {
                                        tmsStatus.get().setStatus("5");
                                        String time = deliver.getPostingDate();
                                        Date date = new Date();
                                        try {
                                            date = new SimpleDateFormat("yyyyMMdd").parse(time);
                                        } catch (ParseException e) {
                                            //LOGGER.error("时间转换错误, string = {}", s, e);
                                        }
                                        tmsStatus.get().setArrivalGoodsTime(date);
                                        tmsStatus.get().setArrivalGoodsTime(date);
                                        tmsStatus.get().setGetGoodsTime(date);
                                        tmsStatus.get().setFactoryTime(date);
                                        tmsStatus.get().setUpdateTime(new Date());
                                        tmsStatus5list.add(tmsStatus.get());
                                        if (tmsStatus5list != null && tmsStatus5list.size() > 5000) {
                                            sysBatchSignForMapper.updateBatchTmsStatus(tmsStatus5list);
                                            tmsStatus5list.clear();
                                        }
                                    }
                                }
                                List<String> newdeliver = deliverlist.stream().map(DeliverQuantityConfirm::getCode).collect(Collectors.toList());
                                if ((deliverNumbers.size() == 0 && !newdeliver.contains(deliver.getCode())) || (!deliverNumbers.contains(deliver.getCode()) && !newdeliver.contains(deliver.getCode()))) {
                                    DeliverQuantityConfirm number = new DeliverQuantityConfirm();
                                    number.setCreateBy("未上TMS");
                                    number.setCreateTime(new Date());
                                    number.setUpdateBy("未上TMS");
                                    number.setUpdateTime(new Date());
                                    number.setIsDelete("0");
                                    number.setOrderNumber(deliver.getDocNumber());
                                    number.setOrderItem(deliver.getDocItem());
                                    number.setOrderCreationTime(deliver.getCreateDateDoc());
                                    number.setBelongTo(deliver.getCustomerCode());
                                    StringBuffer buffer = new StringBuffer();
                                    buffer.append(deliver.getDeliverNumber()).append(deliver.getDeliverItem());
                                    number.setCode(buffer.toString());
                                    if (("").equals(deliver.getShipmentNumber()) || deliver.getShipmentNumber() == null || ("null").equals(deliver.getShipmentNumber())) {
                                        number.setShipmentNumber(deliver.getDeliverNumber());
                                    } else {
                                        number.setShipmentNumber(deliver.getShipmentNumber());
                                    }
                                    number.setDeliveryNumber(deliver.getDeliverNumber());
                                    number.setDeliverItem(deliver.getDeliverItem());
                                    number.setShipToAddress(deliver.getShipToAddress());
                                    number.setMaterialCode(deliver.getMaterialCode());
                                    number.setMaterialName(deliver.getMaterialName());
                                    number.setSizeDim(deliver.getSizeDim());
                                    number.setDeliverQty(deliver.getDeliverQty());
                                    number.setDeliverWt(deliver.getDeliverWt());
                                    number.setConfirmQuantity(deliver.getDeliverQty());
                                    deliverlist.add(number);
                                    if (deliverlist != null && deliverlist.size() > 5000) {
                                        deliverQuantityConfirmMapper.saveDeliverNumber(deliverlist);
                                        deliverlist.clear();
                                        List<DeliverQuantityConfirm> delivernewNumber = deliverQuantityConfirmMapper.selectDeliverQuantityConfirmList(numbernull);
                                        if (delivernewNumber != null && delivernewNumber.size() > 0) {
                                            deliverNumbers = delivernewNumber.stream().map(DeliverQuantityConfirm::getCode).collect(Collectors.toList());
                                            }
                                        }
                                        }
                                    }
                                }
                            }
                        }
                    }
                if (tmslistNo != null && tmslistNo.size() > 0) {
                    sysBatchSignForMapper.saveTmsLogisticsStatus(tmslistNo);
                }
                if (tmslistYes != null && tmslistYes.size() > 0) {
                    sysBatchSignForMapper.saveTmsLogisticsStatus(tmslistYes);
                }
                if (tmsStatus5list != null && tmsStatus5list.size() > 0) {
                    sysBatchSignForMapper.updateBatchTmsStatus(tmsStatus5list);
                }
                if (deliverlist != null && deliverlist.size() > 0) {
                    deliverQuantityConfirmMapper.saveDeliverNumber(deliverlist);
                }

           // List<MetaHanaDeliverOrder> deliverOrderListstatusYes = metaHanaDeliverOrderMapper.selectMetaDeliverOrderListByYes(n,m);
           // if (deliverOrderListstatusYes != null && deliverOrderListstatusYes.size() > 0) {
             /*   List<TmsLogisticsStatus> tmslistYes = new ArrayList<TmsLogisticsStatus>();
                List<TmsLogisticsStatus> tmsStatus5list = new ArrayList<TmsLogisticsStatus>();
                List<DeliverQuantityConfirm> deliverlist = new ArrayList<DeliverQuantityConfirm>();*/
             /*   for (MetaHanaDeliverOrder deliver : deliverOrderListstatusYes
                ) {*/
    }

    /**
     * @description: 经销商自动上线
     * @param: []
     * @return: void
     * @author: njs
     * @date: 2023/2/23 13:17
     */
    @Override
    public void customersStart() {
        List<DataMasterCustomerVO> customerVOSOld = customersMapper.selectCustomerCodeByNotStart();
        //AND (CustomerTypeCode5 = 'SSB'
        // or (CustomerTypeCode1='D01' and IsBMDCustomer='否')
        // or (CustomerTypeCode1='D06'))
        List<DataMasterCustomerVO> customerVOS = new ArrayList<>();
        List<SysDictData>  sysDictData = sysDictDataMapper.selectDictDataByType("sys_system_bmd_name");
        log.info("获取非bmd的机构数量:{}", sysDictData.size());
        List<String> subOfficeName = sysDictData.stream().map(SysDictData::getDictLabel).collect(Collectors.toList());
        for (DataMasterCustomerVO customerVO : customerVOSOld){
            if (subOfficeName.contains(customerVO.getSalesGroupName()) || "SSB".equals(customerVO.getCustomerTypeCode5()) || ("D01".equals(customerVO.getCustomerTypeCode1()) && "否".equals(customerVO.getIsBMDCustomer())) || "D06".equals(customerVO.getCustomerTypeCode1())){
                customerVOS.add(customerVO);
            }
        }
        if(customerVOS !=null && customerVOS.size()>0){
            log.info("开始执行经销商自动上线");
            log.info("待上线经销商：{}", JSON.toJSON(customerVOS));
            List<CustomersVo> customers = new ArrayList<>();
            customerVOS.forEach(customer->{
                Calendar calendar = Calendar.getInstance();
                //昨日
                calendar.add(Calendar.DATE,-1);
                CustomersVo customersStart=new CustomersVo();
                customersStart.setCustomersCode(customer.getCustomerCode());
                customersStart.setCustomersName(customer.getCustomerName());
                customersStart.setOnlineTime(calendar.getTime());
                //all
                customersStart.setCustomerType(3);
                customers.add(customersStart);
            });
            customersMapper.insertCustomersStartBatch(customers);
        }
    }

    @Override
    public int insertCus(String customer) {
        Integer integer = deliverQuantityConfirmMapper.insertCus( customer);
        log.info("插入结果：{}", integer);
        return integer;
    }

    @Override
    public int selectCus(String customer) {
        return deliverQuantityConfirmMapper.selectCus( customer);
    }

    public Set<String> getConfigValueSet(String dictType){
            Set<String> res = new HashSet<>();
            List<SysDictData> dictDatas = sysDictDataService.selectSimpleDictDataByType(dictType);
            for(SysDictData d: dictDatas){
                res.add(d.getDictValue());
            }
            return res;
    }

    public String getHtmlHanaNameContextList(String hanaName) {

        String str = "";

            str += "<tr>" +
                    "   <td>" + hanaName
                    + "   </td>" +
                    "</tr>";


        String html = "<table border='1'  Cellspacing='0'>" +
                "    <tr>" +
                "        <th>Hana数据异常源名称</th>" +
                "    </tr>" +
                str +
                "</table>";

        return html;
    }

    public String getHtmlUserContextList(List<UserVO> userList) {

            String str = "";
            for (UserVO u : userList) {
                str += "<tr>" +
                        "   <td>" + u.getUserName()
                        + "   </td><td>" + u.getLoginName()
                        + "   </td><td>" + u.getPhonenumber()
                        + "   </td>" +
                        "</tr>";
            }

            String html = "<table border='1'  Cellspacing='0'>" +
                    "    <tr>" +
                    "        <th>用户昵称</th>" +
                    "        <th>用户登录名</th>" +
                    "        <th>用户手机号</th>" +
                    "    </tr>" +
                    str +
                    "</table>";

            return html;
        }
}

