package consume

import (
	"applet/app/cfg"
	"applet/app/db"
	db2 "applet/app/flexible_employment/db"
	"applet/app/flexible_employment/enum"
	"applet/app/flexible_employment/svc"
	"applet/app/lib/flexible_employment"
	"applet/app/utils"
	"applet/app/utils/logx"
	"applet/consume/md"
	"code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit"
	"code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/streadway/amqp"
	"time"
)

func FlexibleEmploymentWithdrawForGongMaoConsume(queue md.MqQueue) {
	fmt.Println(">>>>>>>>>>>>FlexibleEmploymentWithdrawForGongMaoConsume>>>>>>>>>>>>")
	ch, err := rabbit.Cfg.Pool.GetChannel()
	if err != nil {
		logx.Error(err)
		return
	}
	defer ch.Release()
	//1、将自己绑定到交换机上
	ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey)
	//2、取出数据进行消费
	ch.Qos(1)
	delivery := ch.Consume(queue.Name, false)

	one_circles.Init(cfg.RedisAddr)

	var res amqp.Delivery
	var ok bool
	for {
		res, ok = <-delivery
		if ok == true {
			err = handleFlexibleEmploymentWithdrawForGongMaoConsume(res.Body)
			fmt.Println("err ::: ", err)
			if err != nil {
				fmt.Println("FlexibleEmploymentWithdrawForGongMaoConsume_ERR:::::", err.Error())
				_ = res.Reject(true) //TODO::拒绝 Ack
				//_ = res.Reject(false)
				var msg interface{}
				json.Unmarshal(res.Body, &msg)
				if err.Error() == "Connection timed out" {
					//TODO::重新推回队列末尾,避免造成队列堵塞
					ch.Publish(queue.ExchangeName, msg, queue.RoutKey)
				} else {
					//TODO::推入新的队列中备份
					utils.FilePutContents("FlexibleEmploymentWithdrawForGongMaoConsume_ERR", utils.SerializeStr(err.Error()))
					ch.Publish("zhios.app.user.withdraw.apply.exception.exchange", msg, "gongmao")
				}
			} else {
				err = res.Ack(true)
			}
		} else {
			panic(errors.New("error getting message"))
		}
	}
	fmt.Println("get msg done")
}

func handleFlexibleEmploymentWithdrawForGongMaoConsume(msgData []byte) error {
	var ms string
	err := json.Unmarshal(msgData, &ms)
	if err != nil {
		return err
	}
	time.Sleep(time.Microsecond * 200) // 等待200毫秒
	//1、解析mq中queue的数据结构体
	var msg struct {
		Uid          string      `json:"uid"`
		Nickname     string      `json:"nickname"`
		MasterId     string      `json:"master_id"`
		AppName      string      `json:"app_name"`
		ApplyOrder   string      `json:"apply_order"`
		ActualAmount string      `json:"actual_amount"`
		MobCfg       interface{} `json:"mob_cfg"`
	}
	err = json.Unmarshal([]byte(ms), &msg)
	if err != nil {
		return err
	}
	fmt.Println("gongmao_message:::::::::::>>>>>>>>>")
	fmt.Println(msg)
	if db.DBs[msg.MasterId] == nil {
		return nil
	}
	engine := db.DBs[msg.MasterId]

	//1、查找对应记录
	flexibleEmploymentOrdDb := db2.FlexibleEmploymentOrdDb{}
	flexibleEmploymentOrdDb.Set(msg.MasterId)
	flexibleEmploymentOrd, err := flexibleEmploymentOrdDb.Get(msg.ApplyOrder)
	if err != nil {
		return err
	}
	if flexibleEmploymentOrd == nil {
		return errors.New("未查询到对应订单记录")
	}

	flexibleEmploymentBasicDb := db2.FlexibleEmploymentBasicDb{}
	flexibleEmploymentBasicDb.Set()
	basic, err := flexibleEmploymentBasicDb.Get(msg.MasterId)
	if err != nil {
		return err
	}
	gongMao := flexible_employment.New(basic.AppKey, basic.AppSecret, basic.SecretId)
	result, err := gongMao.Curl(enum.MerchantDoSinglePayment, map[string]interface{}{
		"requestId":   flexibleEmploymentOrd.RequestId,
		"mobile":      flexibleEmploymentOrd.Mobile,
		"name":        flexibleEmploymentOrd.Name,
		"amount":      flexibleEmploymentOrd.Amount,
		"identity":    flexibleEmploymentOrd.Identity,
		"bankAccount": flexibleEmploymentOrd.BankAccount,
		"dateTime":    time.Now().Format("20060102150405"),
		"salaryType":  flexibleEmploymentOrd.SettleType,
	})
	if err != nil {
		return err
	}
	var response struct {
		Success   bool   `json:"success"`
		ErrorCode string `json:"errorCode"`
		ErrorMsg  string `json:"errorMsg"`
		Data      struct {
			RequestId   string `json:"requestId"`
			AppmentTime string `json:"appmentTime"`
		} `json:"data"`
	}
	if err = json.Unmarshal(utils.Serialize(result), &response); err != nil {
		return err
	}
	if !response.Success {
		//TODO::发起提现失败,将处理提现失败状态
		finWithdrawApply, err := db.UserWithDrawApplyByUIDById(engine, flexibleEmploymentOrd.RequestId)
		if err != nil {
			return err
		}
		session := engine.NewSession()
		defer session.Close()
		session.Begin()
		err = svc.DealFailResult(session, finWithdrawApply, msg.MasterId, response.ErrorMsg)
		if err != nil {
			_ = session.Rollback()
			return err
		}
		return session.Commit()
	}
	flexibleEmploymentOrd.State = 1
	updateAck, err := flexibleEmploymentOrdDb.Update(flexibleEmploymentOrd.Id, flexibleEmploymentOrd, "state")
	if err != nil {
		return err
	}
	if updateAck <= 0 {
		return errors.New("更新 flexible_employment_ord 状态失败")
	}
	return nil
}