package com.uas.platform.b2b.erp.service.impl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.uas.message.mail.service.MailService;
import com.uas.platform.b2b.dao.CommonDao;
import com.uas.platform.b2b.dao.InvitationRecordDao;
import com.uas.platform.b2b.dao.VendorDao;
import com.uas.platform.b2b.erp.model.ErpInviteRecord;
import com.uas.platform.b2b.erp.model.InquiryVendorInfo;
import com.uas.platform.b2b.erp.service.VendorService;
import com.uas.platform.b2b.erp.support.ErpBufferedLogger;
import com.uas.platform.b2b.model.InvitationRecord;
import com.uas.platform.b2b.model.Vendor;
import com.uas.platform.b2b.support.MessageConf;
import com.uas.platform.b2b.support.SendMsgUtils;
import com.uas.platform.b2b.support.SysConf;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.b2b.temporary.model.PartnershipRecord;
import com.uas.platform.core.logging.BufferedLoggerManager;
import com.uas.platform.core.model.Constant;
import com.uas.platform.core.model.Status;
import com.uas.platform.core.util.serializer.FlexJsonUtils;
import com.uas.sso.entity.PartnershipRecordView;
import com.uas.sso.util.AccountUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by hejq on 2017-09-29.
 */
@Service
public class VendorServiceImpl implements VendorService{

    @Autowired
    private InvitationRecordDao invitationRecordDao;

    @Autowired
    private MailService mailService;

    @Autowired
    private MessageConf messageConf;

    @Autowired
    private VendorDao vendorDao;

    @Autowired
    private SysConf sysConf;

    @Autowired
    private CommonDao commonDao;

    /**
     * 短信接口
     */
    final String messageUrl = "http://message.ubtob.com/sms/send";

    /**
     * 日期格式
     */
    final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 电话号码匹配格式
     */
    static final String TEL_REGEXP = "^((\\(\\d{3}\\))|(\\d{3}\\-))?(13|15|18|17)\\d{9}$";

    /**
     * 匹配中文正则式
     */
    private static final String CHINESE_REGEXP = "^[\u4e00-\u9fa5]*$";

    /**
     * 匹配英文正则式
     */
    private static final String ENGLISH_REGEXP = "^[A-Za-z]+$";

    private final static ErpBufferedLogger logger = BufferedLoggerManager.getLogger(ErpBufferedLogger.class);

    @Override
    public void saveInvitation(List<InquiryVendorInfo> infos) {
        if(!CollectionUtils.isEmpty(infos)) {
            for(InquiryVendorInfo info :infos) {
                boolean tplstatus = false;
                boolean msgstatus = false;
                InvitationRecord record = invitationRecordDao.findByEnuuAndVendname(SystemSession.getUser().getEnterprise().getUu(), info.getVe_name());
                if(null == record || Status.NOT_UPLOAD.value() == record.getStatus()) {
                    record = info.covert();
                    //发送邮件前先进行判断，每天每个供应商只发送一封邮件(判断在erp已经做了，这边暂时不判断）
                    List<ErpInviteRecord> inviteRecords = getRecord(record.getVendname().trim());
                    if (CollectionUtils.isEmpty(inviteRecords)) {
                        // 发送邮件或短信成功才进行保存
                        if (record.getVenduseremail() != null && record.getVenduseremail().contains("@") && !record.getVenduseremail().matches(CHINESE_REGEXP)) {
                            Map<String, Object> model = new HashMap<String, Object>();
                            // 邮件信息
                            if (null != record.getVendusername()) {
                                model.put("vendorusername", record.getVendusername().trim());
                            }
                            model.put("vendorname", record.getVendname().trim());
                            model.put("custname", info.getEn_adminname() + "(" + info.getEn_name() + ")");
                            // 注册地址链接，为了测试正式分开，从系统配置中取
                            String url = sysConf.getRegisterUrl() + "?inviteuid=" + record.getBussinesscode()
                                    + "&inviteUserCode=" + SystemSession.getUser().getUserUU() + "&method=addVendor";
                            model.put("registerUrl", url);
                            try {
                                mailService.send(messageConf.getTplInvitationForERP(), record.getVenduseremail(), model);
                                record.setStatus(Status.DOWNLOADED.value());
                                tplstatus = true;
                                logger.log("erp邀请供应商注册", "邮件邀请：" + record.getVenduseremail(), 1);
                            } catch (Exception e) {
                                record.setStatus(Status.NOT_UPLOAD.value());
                                e.printStackTrace();
                            }
                        }
                        if (record.getVendusertel() != null && record.getVendusertel().matches(TEL_REGEXP)) {
                            try {
                                String[] args = {record.getVendusername(), record.getVendname(), info.getEn_adminname() + "(" + info.getEn_name()  + ")"}
;                               SendMsgUtils.sendMsg(record.getVendusertel(), messageConf.getMsgInvitationForERP(), args);
                                record.setStatus(Status.DOWNLOADED.value());
                                msgstatus = true;
                                logger.log("erp邀请供应商注册", "短信邀请：" + record.getVendusertel(), 1);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        if (tplstatus || msgstatus) {
                            invitationRecordDao.save(record);
                            //记录状态
                            addNewRecord(record.getVendusertel(), record.getVenduseremail(), sdf.format(new Date()), record.getVendname());
                        }
                        // 同步一个数据到账户中心（不是必须，不判断状态）
                        if (record.getId() == null) {// 新增时候才进行同步
                            try {
                                record.setUser(null);
                                record.setId(null);
                                record.setSamecount(null);
                                record.setVenduu(null);
                                record.setBussinesscode(SystemSession.getUser().getEnterprise().getEnBussinessCode());
                                AccountUtils.synchroInvitation(FlexJsonUtils.toJsonDeep(record));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 查询邀请是否已经发送
     *
     * @param name
     * @return
     */
    private List<ErpInviteRecord> getRecord(String name) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 判断是否是当天的单据
        String sql = "select * from invitation_tplrecord where ve_name = '" + name + "' and substr(ve_date, 1, 10) = '"
                + simpleDateFormat.format(new Date()) + "'";
        List<ErpInviteRecord> records = commonDao.query(sql, ErpInviteRecord.class);
        return records;
    }

    /**
     * 记录一个邮件发送状况，防止重复发送
     *
     * @param vendusertel
     * @param venduseremail
     * @param format
     */
    private void addNewRecord(String vendusertel, String venduseremail, String date, String name) {
        String sql = "insert into invitation_tplrecord values('" + venduseremail + "','" + vendusertel + "','success','" + date + "','" + name +"')";
        commonDao.getJdbcTemplate().update(sql);
    }

    @Override
    public List<InquiryVendorInfo> getInfo() {
        List<Vendor> vendors = vendorDao.findByMyEnUUAndErpstatus(SystemSession.getUser().getEnterprise().getUu(), Status.NOT_UPLOAD.value());
        List<InquiryVendorInfo> infos = new ArrayList<InquiryVendorInfo>();
        if(!CollectionUtils.isEmpty(vendors)) {
            for(Vendor vendor : vendors) {
                InquiryVendorInfo info = vendor.covert();
                infos.add(info);
            }
        }
        return infos;
    }

    @Override
    public void updateStatus(String ids) {
       updateDownStatus(ids);
    }

    /**
     * 更新平台供应商UU的下载状态
     *
     * @param ids
     */
    private void updateDownStatus(String ids) {
        String sql = "update purc$vendors set ve_erpstatus = 203 where ve_id in (" + ids +")";
        commonDao.getJdbcTemplate().update(sql);
    }

    /**
     * 添加合作伙伴
     *
     * @param vendor 供应商资料
     * @param appId  应用来源
     */
    @Override
    public void addPartnerShipRecord(Vendor vendor, String appId) {
        PartnershipRecord shipRecord = new PartnershipRecord(appId, vendor);
        PartnershipRecordView record = new PartnershipRecordView();
        BeanUtils.copyProperties(shipRecord, record, PartnershipRecordView.class);
        record.setCustUserCode(Long.valueOf(shipRecord.getCustUserCode()));
        record.setVendUserCode(Long.valueOf(shipRecord.getVendUserCode()));
        try {
            AccountUtils.synchronizeRecord(record);
            vendor.setSynchStatus(Constant.YES);
            vendorDao.save(vendor);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
