package controllers

import (
	"Xcx_New/enums"
	"Xcx_New/models"
	"Xcx_New/service"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"regexp"
	"strconv"
	"strings"
	"time"
)

type InvoiceApiController struct {
	BaseServeAPIController
}

func InvoiceApiRegistRouters() {
	beego.Router("/api/invoice/applies", &InvoiceApiController{}, "Get:GetApplies")
	beego.Router("/api/invoice/apply", &InvoiceApiController{}, "Post:CreateInvoice")
	beego.Router("/api/invoice/noinvorders", &InvoiceApiController{}, "Get:GetNoInvOrders")
	beego.Router("/api/invoices", &InvoiceApiController{}, "Get:GetInvoices")
}

func (c *InvoiceApiController) GetApplies() {
	orders := c.GetString("orders")
	if len(orders) == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	if match, _ := regexp.MatchString("^([0-9]+[,])*([0-9]+)$", orders); !match {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	adminUserInfo := c.GetAdminUserInfo()

	ordersIDSlipe := make([]int64, 0)
	ordersSlipe := strings.Split(orders, ",")
	for index := range ordersSlipe {
		orderid, _ := strconv.ParseInt(ordersSlipe[index], 10, 64)
		if orderid > 0 {
			ordersIDSlipe = append(ordersIDSlipe, orderid)
		}
	}
	if len(ordersIDSlipe) == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	has, nos, err := service.FindServeOrdersByIDs(adminUserInfo.CurrentOrgId, ordersIDSlipe)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"has": has,
		"nos": nos,
	})
}

func (c *InvoiceApiController) CreateInvoice() {
	orders := c.GetString("orders")
	if len(orders) == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	if match, _ := regexp.MatchString("^([0-9]+[,])*([0-9]+)$", orders); !match {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	adminUserInfo := c.GetAdminUserInfo()

	ordersIDSlipe := make([]int64, 0)
	ordersSlipe := strings.Split(orders, ",")
	for index := range ordersSlipe {
		orderid, _ := strconv.ParseInt(ordersSlipe[index], 10, 64)
		if orderid > 0 {
			ordersIDSlipe = append(ordersIDSlipe, orderid)
		}
	}
	if len(ordersIDSlipe) == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	_, nos, err := service.FindServeOrdersByIDs(adminUserInfo.CurrentOrgId, ordersIDSlipe)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}
	if len(nos) == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeServeNotExist)
		return
	}

	var invoiceData models.ServeInvoice
	err = json.Unmarshal(c.Ctx.Input.RequestBody, &invoiceData)
	if err != nil {
		fmt.Println(err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	inds := make([]string, 0)
	var inc float64
	for index := range nos {
		inds = append(inds, strconv.FormatInt(nos[index].ID, 10))
		inc += nos[index].PayableAmount
	}

	invoiceData.OrgId = adminUserInfo.CurrentOrgId
	invoiceData.Status = 1
	invoiceData.CreatedTime = time.Now().Unix()
	invoiceData.UpdatedTime = time.Now().Unix()
	invoiceData.InvoiceAmountGross = inc
	orders = "," + strings.Join(inds, ",") + ","
	invoiceData.Orders = orders
	invoiceData.InvoiceStatus = 1

	err = service.CreateInvoice(&invoiceData)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeApplyInvoiceFail)
		return
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"invoice": invoiceData,
	})
}

func (c *InvoiceApiController) GetNoInvOrders() {
	adminUserInfo := c.GetAdminUserInfo()

	orders, err := service.FindUnInvoiceOrders(adminUserInfo.CurrentOrgId)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"orders": orders,
	})
}

func (c *InvoiceApiController) GetInvoices() {
	adminUserInfo := c.GetAdminUserInfo()

	invoices, err := service.FindInvoices(adminUserInfo.CurrentOrgId)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"invoices": invoices,
	})
}
