package services

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/tealeg/xlsx"
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/utils"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

type GetShangHaiTokenResultApi struct {
	Code int                   `json:"code"`
	Msg  string                `json:"msg"`
	Time int                   `json:"time"`
	Data ShangHaiResultApidate `json:"data"`
}

type ShangHaiResultApidate struct {
	AccessToken string `json:"access_token"`
	ExpireIn    int    `json:"expire_in"`
}

type GetShangHaiTokenResultApiComPany struct {
	Code int       `json:"code"`
	Msg  string    `json:"msg"`
	Time int       `json:"time"`
	Data FailInfos `json:"data"`
}
type FailInfos struct {
	TotalCount int                            `json:"total_count"`
	FailInfo   []ShangHaiResultApidateComPany `json:"fail_info"`
}

type ShangHaiResultApidateComPany struct {
	ErrVal string `json:"errVal"`
	ErrMsg string `json:"errMsg"`
}

type OriginalUserInfoResp struct {
	Mobile   string `json:"Mobile"`
	RealName string `json:"RealName"`
}

// c
func SendComapnyToShanghai(url, jsonCompany, postType string) (err error) {
	var msg string
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(msg, 1)
			go utils.SendEmail("同步策略平台获取数据信息失败"+"【"+utils.APPNAME+"】"+time.Now().Format("2006-01-02 15:04:05"), msg+";Err:"+err.Error(), utils.EmailSendToExpert)
		}
	}()
	method := "POST"
	payload := strings.NewReader(jsonCompany)
	client := &http.Client{}
	req, err := http.NewRequest(method, url, payload)
	if err != nil {
		msg = "NewRequest Err:" + err.Error()
		return err
	}
	req.Header.Add("Content-Type", "application/json")
	res, err := client.Do(req)
	if err != nil {
		msg = "client.Do Err:" + err.Error()
		return err
	}
	defer res.Body.Close()
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		msg = "ioutil.ReadAll Err:" + err.Error()
		return err
	}
	var result GetShangHaiTokenResultApiComPany
	err = json.Unmarshal(body, &result)
	if err != nil {
		msg = "json.Unmarshal Err:" + err.Error()
		return err

	}
	item := new(models.CygxShanghaiCompanyLog)
	item.CreateTime = time.Now()
	item.Url = url
	item.Body = jsonCompany
	item.Result = string(body)
	go models.AddCygxShanghaiCompanyLog(item)

	for _, v := range result.Data.FailInfo {
		if v.ErrMsg != "" {
			//companyCode += "'" + v.ErrVal + "',"
			item := new(models.CygxShanghaiErrLog)
			item.CreateTime = time.Now()
			item.ErrMsg = v.ErrMsg
			item.ErrVal = v.ErrVal
			item.ErrType = postType
			go models.AddCygxShanghaiErrLog(item)
		}
	}
	return
}

func DotongbuShangHai(cont context.Context) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("把权限信息同步到上海策略品台失败，DotongbuShangHai："+err.Error(), 2)
		}
	}()
	//先删除被禁用的用户
	DeleteUserDotongbuShangHaiApi()
	var condition string
	updateTime := time.Now().Add(-time.Minute * 22).Format("2006-01-02 15:04:05")
	listUpdateUser, e := models.GetWxUserOpLog(updateTime)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetWxUserOpLog, Err: " + e.Error())
		return
	}
	var companyIds string
	if len(listUpdateUser) > 0 {
		for _, v := range listUpdateUser {
			companyIds += strconv.Itoa(v.CompanyId) + ","
		}
	}
	////获取冻结跟流失的客户
	listFreezeAndLoss, e := models.GetCompanyFreezeAndLoss(updateTime)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyFreezeAndLoss, Err: " + e.Error())
		return
	}
	if len(listFreezeAndLoss) > 0 {
		for _, v := range listFreezeAndLoss {
			companyIds += strconv.Itoa(v.CompanyId) + ","
		}
	}

	listDeleteUser, e := models.GetWxUserOpLogDelete(updateTime)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetWxUserOpLogDelete, Err: " + e.Error())
		return
	}

	////获取删除客户
	if len(listDeleteUser) > 0 {
		for _, v := range listDeleteUser {
			companyIds += strconv.Itoa(v.CompanyId) + ","
		}
	}

	//获取指定时间内被移动的客户
	listOperationRecord, e := models.GetCompanyOperationRecord(updateTime)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyOperationRecord, Err: " + e.Error())
		return
	}
	if len(listOperationRecord) > 0 {
		for _, v := range listOperationRecord {
			companyIds += strconv.Itoa(v.CompanyId) + ","
		}
	}

	//获取正式转试用的客户ID
	var conditionPer string
	var parsPer []interface{}
	conditionPer += "  AND product_id = 2  AND modify_time > ?  GROUP BY company_id   "
	parsPer = append(parsPer, updateTime)
	companyReportPermissionList, e := models.GetCompanyReportPermissionList(conditionPer, parsPer)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetCompanyReportPermissionList, Err: " + e.Error())
		return
	}
	if len(companyReportPermissionList) > 0 {
		for _, v := range companyReportPermissionList {
			companyIds += strconv.Itoa(v.CompanyId) + ","
		}
	}

	condition = ` AND p.is_suspend = 0  AND a.modify_time > ` + "'" + updateTime + "'"
	companyIds = strings.TrimRight(companyIds, ",")

	fmt.Println("获取冻结跟流失的用户", len(listFreezeAndLoss))
	//return err
	if companyIds != "" {
		//这一部分先不推送，避免并发推送
		condition += ` AND c.company_id  NOT  IN (` + companyIds + ") "
	}

	//偶尔需要单独同步某一个公司的人员
	//condition = ` AND c.company_id  =  13902  `

	//同30小时有变更的公司
	DotongbuShangHaApi(condition)

	//原有的公司如果新增了也同步
	companyIds = strings.TrimRight(companyIds, ",")
	if companyIds != "" {
		condition = ` AND p.is_suspend = 0  AND c.company_id  IN (` + companyIds + ")"
		DotongbuShangHaApi(condition)
	}

	//处理被禁用的用户，将禁用用户的状态同步
	CompanySuspend()
	return
}

func DotongbuShangHaApi(condition string) (err error) {
	var msg string
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("同步策略平台获取数据信息失败", 2)
			go utils.SendEmail("同步策略平台获取数据信息失败"+"【"+utils.APPNAME+"】"+time.Now().Format("2006-01-02 15:04:05"), msg+";Err:"+err.Error(), utils.EmailSendToExpert)
		}
	}()
	var url string
	accessToken, err := GetShangHaiCrmApiToken()
	if err != nil {
		return
	}
	//同步权益客户
	companyList, err := models.GetSendCompanyList(condition)
	if err != nil {
		msg = "GetSendCompanyList Err:" + err.Error()
		return
	}
	mappermissionData := make(map[int][]*models.PermissionData)
	mappermissionDataNoChekcStatus := make(map[int][]*models.PermissionData)
	if len(companyList) > 0 {
		comapnyIdArr := make([]int, 0)
		for _, v := range companyList {
			comapnyIdArr = append(comapnyIdArr, v.Cid)
		}
		var conditionComapny string
		var pars []interface{}
		conditionComapny += ` AND cp.company_id  IN (` + utils.GetOrmInReplace(len(comapnyIdArr)) + ` )  `
		pars = append(pars, comapnyIdArr)
		permissionDataList, e := models.GetSendCompanyPermissionDataList(conditionComapny, pars)
		if e != nil {
			err = errors.New("GetSendCompanyPermissionDataList, Err: " + e.Error())
			return
		}
		var IsTryOut int
		for _, v := range permissionDataList {
			if v.Status == "试用" {
				IsTryOut = 1
			} else {
				IsTryOut = 0
			}
			if v.PermissionName == utils.YAN_XUAN_KOU_DIAN_BAO_NAME {
				v.PermissionName = utils.MAI_FANG_YAN_XUAN_NAME
			}
			if v.PermissionName == utils.CHART_PERMISSION_NAME_MF_YANXUAN {
				v.PermissionName = utils.MAI_FANG_YAN_XUAN_NAME
			}
			if v.PermissionName == utils.GU_SHOU_NAME {
				v.PermissionName = "固定收益"
			}
			mappermissionData[v.CompanyId] = append(mappermissionData[v.CompanyId], &models.PermissionData{
				PermissionName: v.PermissionName,
				StartTime:      strconv.Itoa(int(v.StartDate.Unix())),
				EndTime:        strconv.Itoa(int(v.EndDate.Unix())),
				IsTryOut:       IsTryOut,
			})
		}

		permissionDataListNoChekcStatus, e := models.GetSendCompanyPermissionDataListNoChekcStatus(conditionComapny, pars)
		if e != nil {
			err = errors.New("GetSendCompanyPermissionDataListNoChekcStatus, Err: " + e.Error())
			return
		}
		//var IsTryOut int
		for _, v := range permissionDataListNoChekcStatus {
			if v.PermissionName == utils.YAN_XUAN_KOU_DIAN_BAO_NAME {
				v.PermissionName = utils.MAI_FANG_YAN_XUAN_NAME
			}
			if v.PermissionName == utils.GU_SHOU_NAME {
				v.PermissionName = "固定收益"
			}
			mappermissionDataNoChekcStatus[v.CompanyId] = append(mappermissionDataNoChekcStatus[v.CompanyId], &models.PermissionData{
				PermissionName: v.PermissionName,
				StartTime:      strconv.Itoa(int(v.StartDate.Unix())),
				EndTime:        strconv.Itoa(int(v.EndDate.Unix())),
				IsTryOut:       1,
			})
		}
	}

	fmt.Println("权益客户", len(companyList))
	var companyItems []*models.CompanyJson
	if len(companyList) > 0 {
		//url = "https://crm.hzinsights.com/openapi/v1/Customer/batchSyncFiccCustomer?access_token=" + accessToken
		url = utils.ShangHaiCrmApiLink + "openapi/v1/Customer/batchSyncFiccCustomer?access_token=" + accessToken
		for k, _ := range companyList {
			if companyList[k].Status == "永续" {
				companyList[k].Status = "试用"
			}
			companyList[k].Fe = "权益"
			companyList[k].EndDate = strconv.Itoa(int(companyList[k].EndDateTime.Unix()))
			//一次同步一百条
			if len(mappermissionData[companyList[k].Cid]) > 0 {
				companyList[k].PermissionData = mappermissionData[companyList[k].Cid]
			} else if len(mappermissionDataNoChekcStatus[companyList[k].Cid]) > 0 {
				companyList[k].PermissionData = mappermissionDataNoChekcStatus[companyList[k].Cid]
			}
			companyItems = append(companyItems, companyList[k])
			if (k+1)%100 == 0 {
				data, err := json.Marshal(companyItems)
				if err != nil {
					msg = "companyItems Err:" + err.Error()
					return err
				}
				jsonstr := string(data)
				jsonstr = "{\"sync_data\": " + jsonstr + " }"
				SendComapnyToShanghai(url, jsonstr, "权益")
				companyItems = make([]*models.CompanyJson, 0)
			}
		}
		//如果剩下还有则同步剩下的部分
		if len(companyItems) > 0 {
			data, err := json.Marshal(companyItems)
			if err != nil {
				msg = "companyItems Err:" + err.Error()
				return err
			}
			jsonstr := string(data)
			jsonstr = "{\"sync_data\": " + jsonstr + " }"
			SendComapnyToShanghai(url, jsonstr, "权益")
			utils.FileLog.Info("发送模版消息失败,msg:%s", jsonstr)
			companyItems = make([]*models.CompanyJson, 0)
		}
	}
	//同步FICC客户
	companyFiccList, err := models.GetSendCompanyFiccList(condition)
	if err != nil {
		msg = "GetSendCompanyFiccList Err:" + err.Error()
		return err
	}
	mappermissionDataFicc := make(map[int][]*models.PermissionData)
	mappermissionDataFiccNoChekcStatus := make(map[int][]*models.PermissionData)
	if len(companyFiccList) > 0 {
		comapnyIdArr := make([]int, 0)
		for _, v := range companyFiccList {
			comapnyIdArr = append(comapnyIdArr, v.Cid)
		}
		var conditionComapny string
		var pars []interface{}
		conditionComapny = ` AND cp.company_id  IN (` + utils.GetOrmInReplace(len(comapnyIdArr)) + ` )  `
		pars = append(pars, comapnyIdArr)
		permissionDataList, e := models.GetSendCompanyPermissionDataList(conditionComapny, pars)
		if e != nil {
			err = errors.New("GetSendCompanyPermissionDataList, Err: " + e.Error())
			return
		}
		var IsTryOut int
		for _, v := range permissionDataList {
			if v.Status == "试用" {
				IsTryOut = 1
			} else {
				IsTryOut = 0
			}
			if v.PermissionName == utils.YAN_XUAN_KOU_DIAN_BAO_NAME {
				v.PermissionName = utils.MAI_FANG_YAN_XUAN_NAME
			}
			if v.PermissionName == utils.GU_SHOU_NAME {
				v.PermissionName = "固定收益"
			}
			mappermissionDataFicc[v.CompanyId] = append(mappermissionDataFicc[v.CompanyId], &models.PermissionData{
				PermissionName: v.PermissionName,
				StartTime:      strconv.Itoa(int(v.StartDate.Unix())),
				EndTime:        strconv.Itoa(int(v.EndDate.Unix())),
				IsTryOut:       IsTryOut,
			})
		}

		permissionDataListNoChekcStatus, e := models.GetSendCompanyPermissionDataListNoChekcStatus(conditionComapny, pars)
		if e != nil {
			err = errors.New("GetSendCompanyPermissionDataListNoChekcStatus, Err: " + e.Error())
			return
		}
		//var IsTryOut int
		for _, v := range permissionDataListNoChekcStatus {
			if v.PermissionName == utils.YAN_XUAN_KOU_DIAN_BAO_NAME {
				v.PermissionName = utils.MAI_FANG_YAN_XUAN_NAME
			}
			if v.PermissionName == utils.GU_SHOU_NAME {
				v.PermissionName = "固定收益"
			}
			mappermissionDataFiccNoChekcStatus[v.CompanyId] = append(mappermissionDataFiccNoChekcStatus[v.CompanyId], &models.PermissionData{
				PermissionName: v.PermissionName,
				StartTime:      strconv.Itoa(int(v.StartDate.Unix())),
				EndTime:        strconv.Itoa(int(v.EndDate.Unix())),
				IsTryOut:       1,
			})
		}
	}

	fmt.Println("FICC客户", len(companyFiccList))
	var companyFiccItems []*models.CompanyJson
	if len(companyFiccList) > 0 {
		//url = "https://crm.hzinsights.com/openapi/v1/Customer/batchSyncFiccCustomer?access_token=" + accessToken
		url = utils.ShangHaiCrmApiLink + "openapi/v1/Customer/batchSyncFiccCustomer?access_token=" + accessToken
		for k, _ := range companyFiccList {
			companyFiccList[k].Fe = "FICC"
			companyFiccList[k].EndDate = strconv.Itoa(int(companyFiccList[k].EndDateTime.Unix()))
			if len(mappermissionDataFicc[companyFiccList[k].Cid]) > 0 {
				companyFiccList[k].PermissionData = mappermissionDataFicc[companyFiccList[k].Cid]
			} else if len(mappermissionDataFiccNoChekcStatus[companyFiccList[k].Cid]) > 0 {
				companyFiccList[k].PermissionData = mappermissionDataFiccNoChekcStatus[companyFiccList[k].Cid]
			}
			//一次同步一百条
			companyFiccItems = append(companyFiccItems, companyFiccList[k])
			if (k+1)%100 == 0 {
				data, err := json.Marshal(companyFiccItems)
				if err != nil {
					msg = "companyFiccItems Err:" + err.Error()
					return err
				}
				jsonstr := string(data)
				jsonstr = "{\"sync_data\": " + jsonstr + " }"
				SendComapnyToShanghai(url, jsonstr, "FICC")
				companyFiccItems = make([]*models.CompanyJson, 0)
			}
		}
		//如果剩下还有则同步剩下的部分
		if len(companyFiccItems) > 0 {
			data, err := json.Marshal(companyFiccItems)
			if err != nil {
				msg = "companyFiccItems Err:" + err.Error()
				return err
			}
			jsonstr := string(data)
			jsonstr = "{\"sync_data\": " + jsonstr + " }"
			SendComapnyToShanghai(url, jsonstr, "FICC")
		}
	}

	userList, err := models.GetSendUserList(condition)
	if err != nil {
		msg = "GetSendUserList Err:" + err.Error()
		return err
	}
	fmt.Println("用户", len(userList))
	var userItems []*models.UserJson
	if len(userList) > 0 {
		//url = "https://crm.hzinsights.com/openapi/v1/CustomerContact/batchSyncFiccCustomerContact?access_token=" + accessToken
		url = utils.ShangHaiCrmApiLink + "openapi/v1/CustomerContact/batchSyncFiccCustomerContact?access_token=" + accessToken
		for k, v := range userList {
			if v.Sex == "1" {
				userList[k].Sex = "男"
			} else {
				userList[k].Sex = "女"
			}
			if v.IsMaker == "1" {
				userList[k].IsMaker = "是"
			} else {
				userList[k].IsMaker = "否"
			}
			userList[k].CountryCode = "+" + v.CountryCode
			userList[k].OutboundCountryCode = "+" + v.OutboundCountryCode
			if userList[k].Mobile != "" && userList[k].OutboundMobile != "" && userList[k].Mobile == userList[k].OutboundMobile {
				userList[k].OutboundMobile = ""
				userList[k].OutboundCountryCode = ""
			}
			//一次同步一百条
			userItems = append(userItems, userList[k])
			if (k+1)%100 == 0 {
				data, err := json.Marshal(userItems)
				if err != nil {
					msg = "userItems Err:" + err.Error()
					return err
				}
				fmt.Println(k)
				jsonstr := string(data)
				jsonstr = "{\"sync_data\": " + jsonstr + " }"
				SendComapnyToShanghai(url, jsonstr, "user")
				userItems = make([]*models.UserJson, 0)
			}
		}

		//如果剩下还有则同步剩下的部分
		if len(userItems) > 0 {
			data, err := json.Marshal(userItems)
			if err != nil {
				msg = "userItems Err:" + err.Error()
				return err
			}
			jsonstr := string(data)
			jsonstr = "{\"sync_data\": " + jsonstr + " }"
			SendComapnyToShanghai(url, jsonstr, "user")
			companyItems = make([]*models.CompanyJson, 0)
		}
	}
	return
}

func DotongbuShangHaiSendEmail(cont context.Context) (err error) {
	var msg string
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg("发送邮件：同步用户到策略平台信息失败", 2)
			go utils.SendEmail("发送邮件：同步用户到策略平台信息失败"+"【"+utils.APPNAME+"】"+time.Now().Format("2006-01-02 15:04:05"), msg+";Err:"+err.Error(), utils.EmailSendToExpert)
		}
	}()
	list, err := models.GetCygxShanghaiCompanyLog()
	if err != nil {
		msg = "GetCygxShanghaiCompanyLog Err:" + err.Error()
		return err
	}
	mapErrMsg := make(map[string]string)
	for _, v := range list {
		data := new(GetShangHaiTokenResultApiComPany)
		err := json.Unmarshal([]byte(v.Result), &data)
		if err != nil {
			msg = "GetShangHaiTokenResultApiComPany Err:" + err.Error()
			return err
		}
		if len(data.Data.FailInfo) > 0 {
			for _, vCompany := range data.Data.FailInfo {
				mapErrMsg[vCompany.ErrVal] = vCompany.ErrMsg
			}
		}
	}
	//创建excel
	dir, err := os.Executable()
	exPath := filepath.Dir(dir)
	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + utils.GetRandDigit(5) + ".xlsx"
	xlsxFile := xlsx.NewFile()
	if err != nil {
		return
	}
	style := xlsx.NewStyle()
	alignment := xlsx.Alignment{
		Horizontal: "center",
		Vertical:   "center",
		WrapText:   true,
	}
	style.Alignment = alignment
	style.ApplyAlignment = true
	sheet, err := xlsxFile.AddSheet("上海策略品台同步名单")
	if err != nil {
		return
	}
	//设置宽度
	_ = sheet.SetColWidth(0, 1, 30)
	_ = sheet.SetColWidth(2, 2, 10)
	_ = sheet.SetColWidth(3, 3, 30)

	//标头
	rowTitle := sheet.AddRow()
	cellA := rowTitle.AddCell()
	cellA.Value = "客户名称"
	cellB := rowTitle.AddCell()
	cellB.Value = "社会信用码"
	cellC := rowTitle.AddCell()
	cellC.Value = "客户类型"
	cellD := rowTitle.AddCell()
	cellD.Value = "错误消息"
	for _, v := range list {
		data := new(models.CompanyUnJsonList)
		err := json.Unmarshal([]byte(v.Body), &data)
		if err != nil {
			msg = "CompanyUnJsonList Err:" + err.Error()
			return err
		}
		if len(data.SyncData) > 0 {
			for _, item := range data.SyncData {
				row := sheet.AddRow()
				cellA := row.AddCell()
				cellA.Value = item.CompanyName
				cellB := row.AddCell()
				cellB.Value = item.CreditCode
				cellC := row.AddCell()
				cellC.Value = item.Fe
				if mapErrMsg[item.CreditCode] != "" {
					cellD := row.AddCell()
					cellD.Value = mapErrMsg[item.CreditCode]
				}
			}
		}
	}
	title := time.Now().Format(utils.FormatDate) + "上海策略品台同步名单"
	content := time.Now().Format(utils.FormatDate) + "上海策略品台同步名单"
	fileName := downLoadnFilePath
	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		return
	}
	if len(list) > 0 {
		utils.SendEmailByHongze(title, content, "cxzhang@hzinsights.com;tshen@hzinsights.com", fileName, title+".xlsx")
	}
	os.Remove(downLoadnFilePath)
	go models.DeleteCygxShanghaiCompanyLog()
	return
}

// DeleteUserDotongbuShangHaApi 删除用户进行同步
func DeleteUserDotongbuShangHaiApi() (err error) {
	var msg string
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg("同步策略平台获取数据信息失败 DeleteUserDotongbuShangHaApi"+err.Error()+msg, 2)
		}
	}()
	updateTime := time.Now().Add(-time.Minute * 22).Format("2006-01-02 15:04:05")
	listDeleteUser, err := models.GetWxUserOpLogDelete(updateTime)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}
	fmt.Println("删除用户", len(listDeleteUser))
	if len(listDeleteUser) > 0 {
		var deleteCompanyIds string
		for k, v := range listDeleteUser {
			deleteCompanyIds += strconv.Itoa(v.CompanyId) + ","
			var resultUser OriginalUserInfoResp
			if err := json.Unmarshal([]byte(v.OriginalUserInfo), &resultUser); err == nil {
				listDeleteUser[k].RealName = resultUser.RealName
			} else {
				return err
			}
		}
	} else {
		return err
	}
	var url string
	accessToken, err := GetShangHaiCrmApiToken()
	if err != nil {
		return
	}
	var userItems []*models.ShangHaiCrmUserDeleteResp
	if len(listDeleteUser) > 0 {
		url = utils.ShangHaiCrmApiLink + "openapi/v1/CustomerContact/batchDisableCustomerContact?access_token=" + accessToken
		for k, v := range listDeleteUser {
			userItem := new(models.ShangHaiCrmUserDeleteResp)
			userItem.Name = v.RealName
			userItem.Mobile = v.Mobile
			userItem.Social = v.CreditCode
			//一次同步一百条
			userItems = append(userItems, userItem)
			if (k+1)%100 == 0 {
				data, err := json.Marshal(userItems)
				if err != nil {
					msg = "companyItems Err:" + err.Error()
					return err
				}
				jsonstr := string(data)
				jsonstr = "{\"data\": " + jsonstr + " }"
				SendComapnyToShanghai(url, jsonstr, "权益")
				userItems = make([]*models.ShangHaiCrmUserDeleteResp, 0)
			}
		}
		//如果剩下还有则同步剩下的部分
		if len(userItems) > 0 {
			data, err := json.Marshal(userItems)
			if err != nil {
				msg = "companyItems Err:" + err.Error()
				return err
			}
			jsonstr := string(data)
			jsonstr = "{\"data\": " + jsonstr + " }"
			SendComapnyToShanghai(url, jsonstr, "权益")
			userItems = make([]*models.ShangHaiCrmUserDeleteResp, 0)
		}
	}
	return
}

// 获取用户的Token
func GetShangHaiCrmApiToken() (token string, err error) {
	var msg string
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg("同步策略平台获取数据信息失败 GetShangHaiCrmApiToken"+err.Error()+msg, 2)
		}
	}()
	cacheKey := utils.SHANG_HAI_CRM_API_TOKEN
	ttlTime := utils.Rc.GetRedisTTL(cacheKey)
	if ttlTime > 0 {
		token, _ = utils.Rc.RedisString(cacheKey)
	}
	if token == "" {
		//获取token
		url := utils.ShangHaiCrmApiLink + "openapi/v1/auth/getAccessToken?app_key=26945134&app_secret=b99cb2bdec70d20156000f664ec5ac30"
		method := "GET"
		client := &http.Client{}
		req, errReq := http.NewRequest(method, url, nil)
		if errReq != nil {
			err = errReq
			return
		}
		res, errReq := client.Do(req)
		if errReq != nil {
			err = errReq
			return
		}
		defer res.Body.Close()
		body, errReq := ioutil.ReadAll(res.Body)
		if errReq != nil {
			err = errReq
			return
		}
		var result GetShangHaiTokenResultApi
		errReq = json.Unmarshal(body, &result)
		if errReq != nil {
			err = errReq
			return
		}
		token = result.Data.AccessToken
		utils.Rc.Put(cacheKey, token, time.Second*7000)
	}
	return
}

// 处理被禁用的用户，将禁用用户的状态转冻结
func CompanySuspend() (err error) {
	var msg string
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("同步策略平台处理被禁用的用户，将禁用用户的状态转冻结失败", 2)
			go utils.SendEmail("同步策略平台处理被禁用的用户，将禁用用户的状态转冻结失败"+"【"+utils.APPNAME+"】"+time.Now().Format("2006-01-02 15:04:05"), msg+";Err:"+err.Error(), utils.EmailSendToExpert)
		}
	}()
	var url string
	accessToken, err := GetShangHaiCrmApiToken()
	if err != nil {
		return
	}
	updateTime := time.Now().Add(-time.Minute * 22).Format("2006-01-02 15:04:05")
	listSuspendCompany, err := models.GetWxUserOpLogSuspend(updateTime)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}
	fmt.Println("禁用的用户", len(listSuspendCompany))
	var suspendCompanyIds string
	if len(listSuspendCompany) > 0 {
		for _, v := range listSuspendCompany {
			suspendCompanyIds += strconv.Itoa(v.CompanyId) + ","
		}
	} else {
		return err
	}
	fmt.Println(suspendCompanyIds)
	//同步权益客户
	if suspendCompanyIds == "" {
		return err
	}

	suspendCompanyIds = strings.TrimRight(suspendCompanyIds, ",")
	condition := ` AND c.company_id  IN (` + suspendCompanyIds + ")"

	companyList, err := models.GetSendCompanyList(condition)
	if err != nil {
		msg = "GetSendCompanyList Err:" + err.Error()
		fmt.Println(err)
		return err
	}
	fmt.Println("权益客户", len(companyList))
	var companyItems []*models.CompanyJson
	if len(companyList) > 0 {
		//url = "https://crm.hzinsights.com/openapi/v1/Customer/batchSyncFiccCustomer?access_token=" + accessToken
		url = utils.ShangHaiCrmApiLink + "openapi/v1/Customer/batchSyncFiccCustomer?access_token=" + accessToken
		for k, _ := range companyList {
			companyList[k].Fe = "权益"
			companyList[k].Status = "暂停"
			companyList[k].EndDate = strconv.Itoa(int(companyList[k].EndDateTime.Unix()))
			//一次同步一百条
			companyItems = append(companyItems, companyList[k])
			if (k+1)%100 == 0 {
				data, err := json.Marshal(companyItems)
				if err != nil {
					msg = "companyItems Err:" + err.Error()
					return err
				}
				jsonstr := string(data)
				jsonstr = "{\"sync_data\": " + jsonstr + " }"
				SendComapnyToShanghai(url, jsonstr, "权益")
				companyItems = make([]*models.CompanyJson, 0)
			}
		}
		//如果剩下还有则同步剩下的部分
		if len(companyItems) > 0 {
			data, err := json.Marshal(companyItems)
			if err != nil {
				msg = "companyItems Err:" + err.Error()
				return err
			}
			jsonstr := string(data)
			jsonstr = "{\"sync_data\": " + jsonstr + " }"
			SendComapnyToShanghai(url, jsonstr, "权益")
			companyItems = make([]*models.CompanyJson, 0)
		}
	}
	//同步FICC客户
	companyFiccList, err := models.GetSendCompanyFiccList(condition)
	if err != nil {
		msg = "GetSendCompanyFiccList Err:" + err.Error()
		return err
	}

	fmt.Println("FICC客户", len(companyFiccList))
	var companyFiccItems []*models.CompanyJson
	if len(companyFiccList) > 0 {
		url = utils.ShangHaiCrmApiLink + "openapi/v1/Customer/batchSyncFiccCustomer?access_token=" + accessToken
		for k, _ := range companyFiccList {
			companyFiccList[k].Fe = "FICC"
			companyList[k].Status = "暂停"
			companyFiccList[k].EndDate = strconv.Itoa(int(companyFiccList[k].EndDateTime.Unix()))
			//一次同步一百条
			companyFiccItems = append(companyFiccItems, companyFiccList[k])
			if (k+1)%100 == 0 {
				data, err := json.Marshal(companyFiccItems)
				if err != nil {
					msg = "companyFiccItems Err:" + err.Error()
					return err
				}
				jsonstr := string(data)
				jsonstr = "{\"sync_data\": " + jsonstr + " }"
				SendComapnyToShanghai(url, jsonstr, "FICC")
				companyFiccItems = make([]*models.CompanyJson, 0)
			}
		}
		//如果剩下还有则同步剩下的部分
		if len(companyFiccItems) > 0 {
			data, err := json.Marshal(companyFiccItems)
			if err != nil {
				msg = "companyFiccItems Err:" + err.Error()
				return err
			}
			jsonstr := string(data)
			jsonstr = "{\"sync_data\": " + jsonstr + " }"
			SendComapnyToShanghai(url, jsonstr, "FICC")
		}
	}
	return
}
