package api

import (
	"crm-api/api"
	"crm-api/internal/app/ami/action"
	"crm-api/internal/app/mysql"
	"crm-api/pkg/lfshook"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

type DialParam struct {
	Dest string `json:"dest" binding:"required"`
	Src  string `json:"src" binding:"required"`
}

type HangupParam struct {
	Extensions []string `json:"extensions" binding:"required"`
}

// @tags API
// @Summary 点击拨号
// @Description 点击拨号
// @Security ApiKeyAuth
// @Accept  json
// @Produce  json
// @Param   data body  DialParam true  "拨号参数"
// @Router /api/call-dial/dial [post]
func dialExtension(ctx *gin.Context) {
	var param DialParam
	err := ctx.ShouldBindJSON(&param)
	if err != nil {
		lfshook.NewLogger().Infof("Error : %+v", err)
		api.Error(ctx, http.StatusBadRequest, err.Error())
		return
	}
	dialrule := mysql.GetDialPlanByExtension(param.Src)
	action.Dial(param.Src, param.Dest, dialrule, param.Dest, param.Dest)
	api.Success(ctx, gin.H{"msg": "ami dial"})
}

// @tags API
// @Summary zoho点击拨号
// @Description zoho点击拨号
// @Security ApiKeyAuth
// @Accept  json
// @Produce  json
// @Param   data body  DialParam true  "拨号参数"
// @Router /api/call-dial/zoho-dial [post]
func zohoDialExtension(ctx *gin.Context) {
	// Zoho CRM 拨号对应 POST /pbx/api/call-dial/dial tonumber=12300000001&dest=302
	// requestURI := ctx.Request.RequestURI
	// fmt.Println("requestURI = ", requestURI) // requestURI =  /pbx/api/call-dial/dial
	// requestBody := ctx.Request.Body
	// fmt.Println("requestBody = ", requestBody) // requestBody =  {tonumber=12300000001&dest=302}

	requestBody, _ := ioutil.ReadAll(ctx.Request.Body)
	// fmt.Println("requestBody = ", requestBody)                 // requestBody =  [116 111 110 117 109 98 101 114 61 49 50 51 48 48 48 48 48 48 48 49 38 100 101 115 116 61 51 48 50]
	// fmt.Println("string(requestBody) = ", string(requestBody)) // string(requestBody) =  tonumber=12300000001&src=302
	if strings.Contains(string(requestBody), "tonumber") && strings.Contains(string(requestBody), "src") {
		srcNum := strings.Split(string(requestBody), "=")[2]
		fmt.Println("srcNum = ", srcNum) // srcNum =  302

		destNum := strings.Split(strings.Split(string(requestBody), "=")[1], "&")[0]
		fmt.Println("destNum = ", destNum) //  destNum =  12300000001

		dialrule := mysql.GetDialPlanByExtension(srcNum)
		fmt.Println("dialrule = ", dialrule)
		action.Dial(srcNum, destNum, dialrule, destNum, destNum)
	}
	api.Success(ctx, gin.H{"msg": "ami dial"})
}

// @tags API
// @Summary 挂断指定分机
// @Description 挂断指定分机
// @Security ApiKeyAuth
// @Accept  json
// @Produce  json
// @Param   data body  HangupParam true  "挂断参数"
// @Router /api/call-dial/hangup [post]
func dialHangup(ctx *gin.Context) {
	data := &HangupParam{}
	err := ctx.ShouldBindJSON(data)
	if err != nil {
		api.Error(ctx, http.StatusInternalServerError, "no data")
		return
	}
	for _, extension := range data.Extensions {
		action.Hangup(extension)
	}
	api.Success(ctx, gin.H{"msg": "ami hangup"})
}
