package com.gree.mall.miniapp.logic.common;

import com.alibaba.fastjson.JSONObject;
import com.gree.mall.miniapp.logic.common.outside.WechatLogic;
import com.gree.mall.miniapp.plus.entity.AdminCompanyWechat;
import com.gree.mall.miniapp.plus.entity.AdminUser;
import com.gree.mall.miniapp.plus.entity.NoticeParam;
import com.gree.mall.miniapp.plus.entity.User;
import com.gree.mall.miniapp.plus.service.AdminCompanyWechatService;
import com.gree.mall.miniapp.plus.service.AdminUserService;
import com.gree.mall.miniapp.plus.service.NoticeParamService;
import com.gree.mall.miniapp.plus.service.UserService;
import com.gree.mall.miniapp.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.omg.CORBA.INTERNAL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信公众号通知
 */
@Slf4j
@Component
public class WxPubNoticeLogic {

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    WechatLogic wechatLogic;
    @Autowired
    NoticeParamService noticeParamService;
    @Autowired
    AdminCompanyWechatService adminCompanyWechatService;
    @Autowired
    UserService userService;
    @Autowired
    AdminUserService adminUserService;
    @Value("${spring.profiles.active}")
    private String env;



    static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");


    final Integer[] errMin = {1,2,5,10,20,40,80,160,320};
    final Integer errNum = errMin.length;

    public User getUserByMobile(String mobile,String companyWechatId){
        if(StringUtils.isBlank(mobile)){
            return null;
        }
        User user = userService.lambdaQuery()
                .ne(User::getMpOpenId,"")
                .eq(User::getMobile, mobile)
                .eq(User::getCompanyWechatId, companyWechatId).one();
        return user;
    }

    /**
     * 消息模板thing类型字段处理，只能20个字内
     * @param value
     * @return
     */
    public String getThing(String value){
        if(StringUtils.isBlank(value)){
            return "";
        }
        value = value.length() > 20 ? value.substring(0,18)+".." : value;
        return value;
    }

    public String getPhrase(String value){
        if(StringUtils.isBlank(value)){
            return "";
        }
        value = value.length() > 4 ? value.substring(0,4) : value;
        return value;
    }

    /**
     * 所有需要通知的商户账号
     * @param companyWechatId
     * @return
     */
    public List<AdminUser> getAdminUserList(String companyWechatId){
        List<AdminUser> list = adminUserService.lambdaQuery()
                .eq(AdminUser::getCompanyWechatId, companyWechatId)
                .eq(AdminUser::getPubNotice, true)
                .ne(AdminUser::getLinkPhone,"")
                .list();
        return list;
    }

    /**
     * 工单派工，改派通知 - 通知对象：师傅
     * @param orderBaseId 工单号
     * @param time 预约时间,预约时间为空则传派工时间
     * @param content 需求名称 例如：格力家用空调x3
     * @param address 派单地址
     */
//    public void addDispatch(String mobile,String companyWechatId,String orderBaseId,Date time,String content,String address){
//        try {
//            if (StringUtils.isBlank(mobile) || StringUtils.isBlank(companyWechatId)) {
//                return;
//            }
//            User user = getUserByMobile(mobile, companyWechatId);
//            if (user == null || StringUtils.isBlank(user.getMpOpenId())) {
//                return;
//            }
//            AdminCompanyWechat adminCompanyWechat = adminCompanyWechatService.getById(companyWechatId);
//            String templateId = adminCompanyWechat.getPubTemplateId1();
//
//            Map<String, String> map = new HashMap<>();
//            map.put("character_string2", mobile);
//            map.put("phone_number6", orderBaseId);
//            map.put("time7", sdf.format(time));
//            map.put("thing8", getThing(address));
//            map.put("thing9", getThing(content));
//
//            NoticeParam bean = new NoticeParam();
//            bean.setMobile(mobile);
//            bean.setMpOpenId(user.getMpOpenId());
//            bean.setTitle("工单派工，改派通知");
//            bean.setTemplateId(templateId);
//            bean.setContent(JSONObject.toJSONString(map));
//            bean.setPagePath("packageWorkorder/pages/orderDetail?id="+orderBaseId);//小程序跳转地址，没就空着
//            bean.setSubAppId(adminCompanyWechat.getSubAppId());
//            bean.setCompanyWechatId(adminCompanyWechat.getCompanyWechatId());
//            bean.setCompanyWechatName(adminCompanyWechat.getCompanyName());
//            bean.insert();
//        }catch(Exception e){
//            log.error("【添加工单派工，改派通知失败】",e);
//        }
//    }

    /**
     * 商城订单支付成功提醒发货-目标，商户所有接收通知的账号
     * @param companyWechatId 商户id
     * @param orderId 商城订单号
     * @param goodsName 商品名称
     * @param payment 订单金额
     * @param receName 收货人名称
     * @param address 收货人地址
     */
    public void addDeliver(String companyWechatId, String orderId, String goodsName, BigDecimal payment,String receName,String address){
        try {
            if (StringUtils.isBlank(companyWechatId)) {
                return;
            }
            List<AdminUser> adminUserList = getAdminUserList(companyWechatId);

            AdminCompanyWechat adminCompanyWechat = adminCompanyWechatService.getById(companyWechatId);
            String templateId = adminCompanyWechat.getPubTemplateId2();

            Map<String, String> map = new HashMap<>();
            map.put("character_string2", orderId);
            map.put("thing4", getThing(goodsName));
            map.put("amount8", payment.toString());
            map.put("thing16", getThing(receName));
            map.put("thing19", getThing(address));

            for (AdminUser adminUser : adminUserList) {
                User user = getUserByMobile(adminUser.getLinkPhone(), companyWechatId);
                if (user == null) {
                    continue;
                }
                NoticeParam bean = new NoticeParam();
                bean.setMobile(user.getMobile());
                bean.setMpOpenId(user.getMpOpenId());
                bean.setTitle("商城订单支付成功提醒发货");
                bean.setTemplateId(templateId);
                bean.setContent(JSONObject.toJSONString(map));
                bean.setPagePath("");//小程序跳转地址，没就空着
                bean.setSubAppId(adminCompanyWechat.getSubAppId());
                bean.setCompanyWechatId(adminCompanyWechat.getCompanyWechatId());
                bean.setCompanyWechatName(adminCompanyWechat.getCompanyName());
                bean.insert();
            }
        }catch(Exception e){
            log.error("【添加商城订单支付成功提醒发货】",e);
        }
    }

    /**
     * 售后订单处理通知 -目标，商户所有接收通知的账号
     * @param companyWechatId
     * @param orderId 订单号
     * @param goodsName 商品名称
     * @param payment 订单金额
     * @param receName 客户名称
     * @param createTime 申请时间
     */
    public void addAfter(String companyWechatId, String orderId, String goodsName, BigDecimal payment,String receName,Date createTime){
        try {
            if (StringUtils.isBlank(companyWechatId)) {
                return;
            }
            List<AdminUser> adminUserList = getAdminUserList(companyWechatId);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
            AdminCompanyWechat adminCompanyWechat = adminCompanyWechatService.getById(companyWechatId);
            String templateId = adminCompanyWechat.getPubTemplateId3();
            Map<String, String> map = new HashMap<>();
            map.put("character_string1", orderId);
            map.put("thing5", getThing(goodsName));
            map.put("amount2", payment.toString());
            map.put("thing11", getThing(receName));
            map.put("time6", sdf.format(createTime));

            for (AdminUser adminUser : adminUserList) {
                User user = getUserByMobile(adminUser.getLinkPhone(), companyWechatId);
                if (user == null) {
                    continue;
                }
                NoticeParam bean = new NoticeParam();
                bean.setMobile(user.getMobile());
                bean.setMpOpenId(user.getMpOpenId());
                bean.setTitle("售后订单处理通知");
                bean.setTemplateId(templateId);
                bean.setContent(JSONObject.toJSONString(map));
                bean.setPagePath("");//小程序跳转地址，没就空着
                bean.setSubAppId(adminCompanyWechat.getSubAppId());
                bean.setCompanyWechatId(adminCompanyWechat.getCompanyWechatId());
                bean.setCompanyWechatName(adminCompanyWechat.getCompanyName());
                bean.insert();
            }
        }catch(Exception e){
            log.error("【添加售后订单处理通知失败】",e);
        }
    }


    /**
     * 订单支付成功(包含销售订单和延保单)-目标后台人员和客户
     * @param mobile
     * @param companyWechatId
     * @param orderId 订单号
     * @param goodsName 商品名称
     * @param payment 订单金额
     * @param receName 客户名称
     * @param time 支付时间
     * @param flag 1=商城订单 2=延保订单
     */
    public void addPaid(String mobile, String companyWechatId, String orderId, String goodsName, BigDecimal payment, String receName, Date time, Integer flag){
        if(StringUtils.isBlank(mobile) || StringUtils.isBlank(companyWechatId)){
            return;
        }
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
            AdminCompanyWechat adminCompanyWechat = adminCompanyWechatService.getById(companyWechatId);
            String templateId = adminCompanyWechat.getPubTemplateId4();
            Map<String, String> map = new HashMap<>();
            map.put("thing3", getThing(goodsName));
            map.put("amount5",payment + "");
            map.put("phrase18",getPhrase(receName));
            map.put("character_string2",orderId);
            map.put("time4", sdf.format(time));

            //客户
            User user = getUserByMobile(mobile, companyWechatId);
            if(user != null && StringUtils.isNotBlank(user.getMpOpenId())){
                NoticeParam bean = new NoticeParam();
                bean.setMobile(mobile);
                bean.setMpOpenId(user.getMpOpenId());
                bean.setTitle("订单支付成功(包含销售订单和延保单)");
                bean.setTemplateId(templateId);
                bean.setContent(JSONObject.toJSONString(map));
                if(flag != null && flag == 1) {
                    //商城订单
                    bean.setPagePath("packageMine/pages/order/detail?orderId=" + orderId);//小程序跳转地址，没就空着
                }else{
                    //延保订单
                    bean.setPagePath("packageHome/pages/addvalue/orderDetail?id=" + orderId);
                }
                bean.setSubAppId(adminCompanyWechat.getSubAppId());
                bean.setCompanyWechatId(adminCompanyWechat.getCompanyWechatId());
                bean.setCompanyWechatName(adminCompanyWechat.getCompanyName());
                bean.insert();
            }

            //商户所有账号
            List<AdminUser> adminUserList = getAdminUserList(companyWechatId);
            for(AdminUser adminUser : adminUserList){
                User user2 = getUserByMobile(adminUser.getLinkPhone(), companyWechatId);
                if(user2 != null && StringUtils.isNotBlank(user2.getMpOpenId())){
                    NoticeParam bean = new NoticeParam();
                    bean.setMobile(mobile);
                    bean.setMpOpenId(user2.getMpOpenId());
                    bean.setTitle("订单支付成功(包含销售订单和延保单)");
                    bean.setTemplateId(templateId);
                    bean.setContent(JSONObject.toJSONString(map));
                    bean.setPagePath("");//小程序跳转地址，没就空着
                    bean.setSubAppId(adminCompanyWechat.getSubAppId());
                    bean.setCompanyWechatId(adminCompanyWechat.getCompanyWechatId());
                    bean.setCompanyWechatName(adminCompanyWechat.getCompanyName());
                    bean.insert();
                }
            }
        }catch(Exception e){
            log.error("【添加订单支付成功失败】",e);
        }
    }


    /**
     * todo 待维保完成
     * 报修申请审批通知
     * @param mobile
     * @param companyWechatId
     * @param username 师傅名称+电话
     * @param time 报修时间
     * @param type 项目名称
     * @param content 收费项目或配件*数量，总金额
     * @param orderBaseId 申请状态 + 单号
     */
    public void addWbAmountApply(String mobile, String companyWechatId, String username, Date time, String type,String content,String orderBaseId,String applyId){
        if(StringUtils.isBlank(mobile) || StringUtils.isBlank(companyWechatId)){
            return;
        }
        try{
            User user = getUserByMobile(mobile, companyWechatId);
            if(user == null || StringUtils.isBlank(user.getMpOpenId())){
                return;
            }
            AdminCompanyWechat adminCompanyWechat = adminCompanyWechatService.getById(companyWechatId);
            String templateId = adminCompanyWechat.getPubTemplateId5();
            Map<String, String> map = new HashMap<>();
            map.put("thing2", getThing(username));
            map.put("time10",sdf.format(time));
            map.put("thing4",getThing(type));
            map.put("thing5",getThing(content));
            map.put("character_string8", orderBaseId);

            NoticeParam bean = new NoticeParam();
            bean.setMobile(mobile);
            bean.setMpOpenId(user.getMpOpenId());
            bean.setTitle("报修申请审批通知");
            bean.setTemplateId(templateId);
            bean.setContent(JSONObject.toJSONString(map));
            bean.setPagePath("packageHome/pages/maintenance/applyDetail?id="+applyId);//小程序跳转地址，没就空着
            bean.setSubAppId(adminCompanyWechat.getSubAppId());
            bean.setCompanyWechatId(adminCompanyWechat.getCompanyWechatId());
            bean.setCompanyWechatName(adminCompanyWechat.getCompanyName());
            bean.insert();
        }catch(Exception e){
            log.error("【添加报修申请审批通知失败】",e);
        }
    }

}
