package basic

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"go-admin/app/admin/middleware"
	"go-admin/app/admin/models"
	orm "go-admin/common/global"
	"go-admin/logger"
	"go-admin/tools"
	"go-admin/tools/app"
	"net/http"
)

type SupplierCreateRequest struct {
	Name           string                    `json:"name" validate:"required"`       // 供应商名称
	Contact        string                    `json:"contact"`                        // 联系人
	Tel            string                    `json:"tel"`                            // 手机号
	Address        string                    `json:"address"`                        // 地址
	OpeningBank    string                    `json:"opening_bank"`                   // 开户行
	AccountHolder  string                    `json:"account_holder"`                 // 开户人
	BankAccount    string                    `json:"bank_account"`                   // 银行卡号
	PaymentCycle   uint32                    `json:"payment_cycle" `                 // 支付周期
	TaxNumber      string                    `json:"tax_number"`                     // 税点
	Landline       string                    `json:"landline"`                       // 固话
	Email          string                    `json:"email"`                          // 邮箱
	CompanyWebsite string                    `json:"company_website"`                // 网站
	Province       string                    `json:"province"`                       // 省份
	City           string                    `json:"city"`                           // 城市
	Area           string                    `json:"area"`                           // 地区
	BankList       []models.SupplierBankInfo `json:"bank_list"  validate:"required"` // 开户银行信息列表
}

// SupplierCreate 添加供应商
// @Summary 创建供应商
// @Tags 供应商管理，V1.4.1
// @Produce json
// @Accept json
// @Param request body SupplierCreateRequest true "供应商模型"
// @Success 200 {object} models.Supplier
// @Router /api/v1/supplier/create [post]
func SupplierCreate(c *gin.Context) {
	req := new(SupplierCreateRequest)
	if err := c.ShouldBindJSON(&req); err != nil {
		fmt.Println(err.Error())
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	err := tools.Validate(req)
	if err != nil {
		app.Error(c, http.StatusBadRequest, err, err.Error())
		return
	}

	supplier := &models.Supplier{
		Name:                  req.Name,
		Contact:               req.Contact,
		Tel:                   req.Tel,
		Address:               req.Address,
		OpeningBank:           req.OpeningBank,
		BankAccount:           req.BankAccount,
		PaymentCycle:          req.PaymentCycle,
		TaxNumber:             req.TaxNumber,
		Landline:              req.Landline,
		Email:                 req.Email,
		CompanyWebsite:        req.CompanyWebsite,
		Province:              req.Province,
		City:                  req.City,
		Area:                  req.Area,
		CooperativeBusinessId: middleware.GetCooperativeBusinessId(c),
		AccountHolder:         req.AccountHolder,
	}

	if len(req.BankList) != 0 {
		// 将 BankList 转换为 JSON 字符串
		bankDataJSON, err := json.Marshal(req.BankList)
		if err != nil {
			tools.HasError(err, "数据解析失败", 500)
		}
		supplier.BankData = string(bankDataJSON)
	} else {
		supplier.BankData = ""
	}

	err = orm.Eloquent.Create(supplier).Error
	if err != nil {
		logger.Error("[SupplierCreate]:create supplier err", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}

	app.OK(c, supplier, "创建成功")
	return
}

type SupplierUpdateRequest struct {
	SupplierCreateRequest
	Id uint32 `json:"id" validate:"required"`
}

// SupplierUpdate 更新供应商
// @Summary 更新供应商
// @Tags 供应商管理，V1.4.1
// @Produce json
// @Accept json
// @Param request body SupplierUpdateRequest true "供应商模型"
// @Success 200 {object} app.Response
// @Router /api/v1/supplier/update [post]
func SupplierUpdate(c *gin.Context) {
	req := new(SupplierUpdateRequest)
	if err := c.ShouldBindJSON(&req); err != nil {
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	var supplierInfo models.Supplier
	err := orm.Eloquent.Model(models.Supplier{}).Where("id", req.Id).Find(&supplierInfo).Error
	if err != nil || err == models.RecordNotFound {
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	supplier := &models.Supplier{
		Number:                supplierInfo.Number,
		Name:                  req.Name,
		Contact:               req.Contact,
		Tel:                   req.Tel,
		Address:               req.Address,
		OpeningBank:           req.OpeningBank,
		BankAccount:           req.BankAccount,
		PaymentCycle:          req.PaymentCycle,
		TaxNumber:             req.TaxNumber,
		Landline:              req.Landline,
		Email:                 req.Email,
		CompanyWebsite:        req.CompanyWebsite,
		Province:              req.Province,
		City:                  req.City,
		Area:                  req.Area,
		AccountHolder:         req.AccountHolder,
		CooperativeBusinessId: middleware.GetCooperativeBusinessId(c),
	}

	if len(req.BankList) != 0 {
		// 将 BankList 转换为 JSON 字符串
		bankDataJSON, err := json.Marshal(req.BankList)
		if err != nil {
			tools.HasError(err, "数据解析失败", 500)
		}
		supplier.BankData = string(bankDataJSON)
	} else {
		supplier.BankData = ""
	}

	err = orm.Eloquent.Where("id", req.Id).Omit("created_at").Save(&supplier).Error
	if err != nil {
		logger.Error("update supplier err :", logger.Field("err", err), logger.Field("s", supplier))
		app.Error(c, http.StatusInternalServerError, err, "更新失败")
		return
	}
	app.OK(c, nil, "更新成功")
	return
}

// SupplierList 供应商列表
// @Summary 供应商列表
// @Tags 供应商管理，V1.4.1
// @Produce json
// @Accept json
// @Param request body models.GetSupplierRequest true "供应商查询模型"
// @Success 200 {array} models.GetSupplierResp
// @Router /api/v1/supplier/list [post]
func SupplierList(c *gin.Context) {
	req := new(models.GetSupplierRequest)
	if err := c.ShouldBindJSON(&req); err != nil {
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	if req.CooperativeBusinessId == 0 {
		req.CooperativeBusinessId = middleware.GetCooperativeBusinessId(c)
	}

	list, err := models.GetSupplier(req)
	if err != nil {
		app.Error(c, http.StatusInternalServerError, err, "获取列表失败")
		return
	}

	app.OK(c, list, "")
	return
}

// SupplierDetail 供应商详情
// @Summary 供应商详情
// @Tags 供应商管理，V1.4.1
// @Produce json
// @Param id path int true "供应商id"
// @Success 200 {object} models.Supplier
// @Router /api/v1/supplier/detail/{id} [get]
func SupplierDetail(c *gin.Context) {
	id := c.Param("id")

	var supplier models.Supplier
	err := orm.Eloquent.Table("erp_supplier").Where("id=?", id).Find(&supplier).Error
	if err != nil {
		logger.Error("get supplier detail failed", logger.Field("err", err), logger.Field("id", id))
		app.Error(c, http.StatusInternalServerError, err, "供应商不存在")
		return
	}

	if supplier.BankData != "" {
		supplier.BankList = models.DeserializeBankData(supplier.BankData)
		supplier.BankData = ""
	}

	app.OK(c, supplier, "ok")
	return
}

// SupplierDel  删除供应商
// @Summary 删除供应商
// @Tags 供应商管理，V1.4.1
// @Produce json
// @Param id path int true "供应商id"
// @Success 200 {object} app.Response
// @Router /api/v1/supplier/delete/{id} [delete]
func SupplierDel(c *gin.Context) {
	id := c.Param("id")

	err := orm.
		Eloquent.Table("erp_supplier").
		Delete(&models.Supplier{}, id).Error
	if err != nil {
		logger.Error("get supplier detail failed", logger.Field("err", err), logger.Field("id", id))
		app.Error(c, http.StatusInternalServerError, err, "删除失败")
		return
	}

	app.OK(c, nil, "删除成功")
	return
}
