package services

import (
	"errors"
	"fmt"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/models/system"
	"hongze/hz_crm_api/services/alarm_msg"
	"hongze/hz_crm_api/utils"
	"strings"
	"time"
)

// 消息来源类型，1:客户，2：合同，3：用印，4：指标替换，5：问答社区，6：问答评论，7：视频评论，8：线上路演评论
const (
	CompanyApprovalMessageSourceTypeByCompany          = 1
	CompanyApprovalMessageSourceTypeByContract         = 2
	CompanyApprovalMessageSourceTypeBySeal             = 3
	CompanyApprovalMessageSourceTypeByEdbInfo          = 4
	CompanyApprovalMessageSourceTypeByQuestion         = 5
	CompanyApprovalMessageSourceTypeByQuestionComment  = 6
	CompanyApprovalMessageSourceTypeByVideoComment     = 7
	CompanyApprovalMessageSourceTypeByRoadVideoComment = 8
)

// 1:申请消息，2:审批结果，3：消息通知
const (
	CompanyApprovalMessageMessageTypeByApply          = 1
	CompanyApprovalMessageMessageTypeByApprovalResult = 2
	CompanyApprovalMessageMessageTypeByMessage        = 3
)

// 审批状态,1:待审批，2:已审批，3:已驳回
const (
	CompanyApprovalMessageApprovalStatusByPending  = 1
	CompanyApprovalMessageApprovalStatusByApproved = 2
	CompanyApprovalMessageApprovalStatusByRejected = 3
)

// MessageInfo 消息主要内容
type MessageInfo struct {
	CompanyName          string    `json:"company_name"`
	ProductId            int       `json:"product_id"`
	CompanyProductStatus string    `json:"company_product_status"`
	Title                string    `json:"title"`
	Content              string    `json:"content"`
	UserId               uint64    `json:"user_id"`
	UserName             string    `json:"user_name"`
	CreateTime           time.Time `json:"create_time"`
}

func AddCompanyApprovalMessage(createUserId, receiveUserId, companyId, companyApprovalId, msgType, sourceType, approvalStatus int, companyName, remark, content, mobile string) (err error) {
	var err1 error
	defer func() {
		if err != nil {
			fmt.Println("AddCompanyApprovalMessage Err:", err)
		}
		if err1 != nil {
			fmt.Println("ModifyCompanyApprovalMessage Err:", err)
		}
	}()
	if msgType == 2 {
		company.ModifyCompanyApprovalMessage(companyApprovalId, sourceType)
	}
	msgItem := new(company.CompanyApprovalMessage)
	msgItem.CreateUserId = createUserId
	msgItem.ReceiveUserId = receiveUserId
	msgItem.MessageStatus = 0
	msgItem.Remark = remark
	msgItem.Content = content
	msgItem.CompanyId = companyId
	msgItem.CompanyName = companyName
	msgItem.CreateTime = time.Now()
	msgItem.ModifyTime = time.Now()
	msgItem.CompanyApprovalId = companyApprovalId
	msgItem.OperationStatus = 1
	msgItem.MessageType = msgType           //1:申请消息，2:审批结果，3：文字消息
	msgItem.SourceType = sourceType         //消息来源
	msgItem.ApprovalStatus = approvalStatus //审批状态,1:待审批，2:已审批，3:已驳回
	err = company.AddCompanyApprovalMessage(msgItem)

	if mobile != "" {
		//跳转地址
		redirectUrl := ""
		//微信小程序路径
		wxAppPath := ``
		//微信消息map数据
		wxMsgMap := make(map[int]string)
		switch msgType {
		case 1:
			wxMsgMap[0] = "Hi,您有新的审批单待处理"
		case 2:
			wxMsgMap[0] = "Hi,您有新的审批单已处理"
		case 3:
			wxMsgMap[0] = "Hi,有新的消息待查看"
			wxAppPath = "pages-todomessages/list/list?type=" + fmt.Sprint(sourceType)
		}
		//审批类型
		switch sourceType {
		case 2:
			wxMsgMap[1] = "合同审批"
		case 3:
			wxMsgMap[1] = "用印审批"
		default:
			wxMsgMap[1] = "客户审批"
		}
		//产生时间
		wxMsgMap[2] = time.Now().Format(utils.FormatDateTime)
		//任务描述
		wxMsgMap[3] = content

		//pages-todomessages/list/list?type=1(1:客户，2：合同，3：用印)
		if sourceType == 1 { //目前只有客户审批才有手机端审核页面
			redirectUrl = utils.TemplateCompanyApplyRedirectUrl
		}
		if wxAppPath == "" {
			//小程序跳转路径map；下标是：来源_消息类型
			wxAppPathMap := map[string]string{
				"1_1": "pages-approve/custome/list",
				"1_2": "pages-approve/custome/detail?id=" + fmt.Sprint(companyApprovalId),
				"2_1": "pages-approve/contract/list",
				"2_2": "pages-approve/contract/detail?ContractApprovalId=0&ContractId=0&ContractApprovalRecordId=" + fmt.Sprint(companyApprovalId),
				"3_1": "pages-approve/seal/list",
				"3_2": "pages-approve/seal/detail?ContractApprovalId=0&SealId=0&ContractApprovalRecordId=" + fmt.Sprint(companyApprovalId),
			}
			key := fmt.Sprint(sourceType, "_", msgType)
			if tmpWxAppPath, ok := wxAppPathMap[key]; ok {
				wxAppPath = tmpWxAppPath
			}
		}

		go SendCompanyApplyWxTemplateMsg(mobile, redirectUrl, wxAppPath, wxMsgMap)
	}
	return
}

// 给用户发送通知类信息
func AddCompanyMessage(createUserId, receiveUserId, companyId, companyApprovalId, sourceType int, companyName, remark, content string) (err error) {
	defer func() {
		if err != nil {
			fmt.Println("AddCompanyApprovalMessage Err:", err)
		}
	}()
	msgItem := new(company.CompanyApprovalMessage)
	msgItem.CreateUserId = createUserId
	msgItem.ReceiveUserId = receiveUserId
	msgItem.MessageStatus = 0
	msgItem.Remark = remark
	msgItem.Content = content
	msgItem.CompanyId = companyId
	msgItem.CompanyName = companyName
	msgItem.CreateTime = time.Now()
	msgItem.ModifyTime = time.Now()
	msgItem.CompanyApprovalId = companyApprovalId
	msgItem.OperationStatus = 1
	msgItem.MessageType = 3         //1:申请消息，2:审批结果，3：文字消息
	msgItem.SourceType = sourceType //消息来源类型，1:客户，2：合同，3：用印
	msgItem.ApprovalStatus = 2      //审批状态,1:待审批，2:已审批，3:已驳回
	err = company.AddCompanyApprovalMessage(msgItem)
	//if mobile != "" {
	//	redirectUrl := "" //跳转地址
	//	//审批消息的时候，才允许跳转
	//	if msgType == 1 {
	//		switch sourceType {
	//		case 1: //目前只有客户审批才有手机端审核页面
	//			redirectUrl = utils.TemplateCompanyApplyRedirectUrl
	//		default:
	//			redirectUrl = ""
	//		}
	//	}
	//	go SendCompanyApplyWxTemplateMsg(mobile, content, redirectUrl)
	//}
	return
}

// AddCompanyApprovalMessageRai 权益销售客户申请转正后，消息群发给所有销售
func AddCompanyApprovalMessageRai(companyId, companyContractId int, applyRealName, companyName string) (err error) {
	defer func() {
		if err != nil {
			fmt.Println("err：", err)
			go alarm_msg.SendAlarmMsg("权益销售客户申请转正后，消息群发给所有销售，Err："+err.Error()+fmt.Sprint("companyId:", companyId, "companyContractId:", companyContractId, "applyRealName:", applyRealName, "companyName:", companyName), 3)
		}
	}()
	companyProduct, err := company.GetCompanyProductByCompanyIdAndProductId(companyId, 2)
	if err != nil {
		return
	}
	if companyProduct == nil {
		return
	}
	contractDetail, err := company.GetCompanyContractDetail(companyId, 2, companyContractId)
	if err != nil {
		return
	}

	var first, keyword1, keyword2, keyword3, keyword4 string
	keyword1 = applyRealName + "已签约" + companyName
	keyword2 = time.Now().Format(utils.FormatDate)
	keyword3 = contractDetail.StartDate
	adminList, err := system.GetSysuserRaiList()
	if err != nil {
		return
	}
	var mobiles []string
	for _, v := range adminList {
		mobiles = append(mobiles, v.Mobile)
	}

	openIdList, err := cygx.GetUserRecordListByMobileArr(mobiles)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}
	if len(openIdList) == 0 {
		return
	}
	go SendWxMsgWithRaiSell(first, keyword1, keyword2, keyword3, keyword4, openIdList)

	list, e := company.GetCompanyContractPermissionByCompanyContractId(companyContractId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyContractPermissionByCompanyContractId, Err: " + e.Error())
		return
	}

	if len(list) == 0 {
		return
	}

	for _, v := range list {
		if v.ChartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN || v.ChartPermissionId == utils.YAN_XUAN_KOU_DIAN_BAO_ID {
			go SendWxCategoryMsgWithRaiSell(companyName, "销售："+applyRealName, "已签约研选", time.Now().Format(utils.FormatDateTimeMinute2), openIdList)
		}
	}
	return
}

// AddCompanyApprovalMessageWangYang 客户研选行业转正时(王芳审批通过)，模板消息提醒汪洋
func AddCompanyApprovalMessageWangYang(companyId, companyContractId int, applyRealName, companyName string) (err error) {
	defer func() {
		if err != nil {
			go alarm_msg.SendAlarmMsg("客户研选行业转正时(王芳审批通过)，模板消息提醒汪洋，Err："+err.Error()+fmt.Sprint("companyId:", companyId, "companyContractId:", companyContractId, "applyRealName:", applyRealName, "companyName:", companyName), 3)
		}
	}()
	var mobiles []string
	cnf, e := cygx.GetCygxConfigDetailByCode(utils.TPL_MSG_YANXAUN_APPROVAL)
	if e != nil {
		err = errors.New("GetCygxConfigDetailByCode, Err: " + e.Error())
		return
	}
	mobiles = strings.Split(cnf.ConfigValue, ",")
	openIdList, e := cygx.GetUserRecordListByMobileArr(mobiles)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetUserRecordListByMobileArr, Err: " + e.Error())
		return
	}
	if len(openIdList) == 0 {
		return
	}

	list, e := company.GetCompanyContractPermissionByCompanyContractId(companyContractId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyContractPermissionByCompanyContractId, Err: " + e.Error())
		return
	}

	if len(list) == 0 {
		return
	}

	var haveDingYue bool // 是否签约了研选订阅
	var points float64   // 是否签约了研选扣点包，以及对应的点数
	for _, v := range list {
		if v.ChartPermissionId == utils.CHART_PERMISSION_ID_YANXUAN {
			haveDingYue = true
		}
		if v.ChartPermissionId == utils.YAN_XUAN_KOU_DIAN_BAO_ID {
			points = v.Points
		}
	}
	var keyword1, keyword2, keyword3, keyword4 string
	if haveDingYue {
		keyword1 = companyName + "(" + applyRealName + ")"
		keyword2 = time.Now().Format(utils.FormatDateTime)
		keyword3 = "签约【研选订阅】"
		go SendWxMsgWithRaiWangYang(keyword1, keyword2, keyword3, keyword4, openIdList)
		go SendWxCategoryMsgWithRaiWangYang(companyName, "销售："+applyRealName, keyword3, time.Now().Format(utils.FormatDateTimeMinute2), openIdList)
	}

	if points > 0 {
		keyword1 = companyName + "(" + applyRealName + ")"
		keyword2 = time.Now().Format(utils.FormatDateTime)
		keyword3 = "签约【研选扣点包（" + fmt.Sprint(points) + "个点）】"
		go SendWxMsgWithRaiWangYang(keyword1, keyword2, keyword3, keyword4, openIdList)
		go SendWxCategoryMsgWithRaiWangYang(companyName, "销售："+applyRealName, keyword3, time.Now().Format(utils.FormatDateTimeMinute2), openIdList)
	}

	return
}
