package svc

import (
	"applet/app/db"
	"applet/app/db/model"
	"applet/app/e"
	"applet/app/md"
	"applet/app/svc"
	"applet/app/utils"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
	"time"
)

func AuditInfo(c *gin.Context) {
	var res md.CommunityTeamStoreAudit
	user := svc.GetUser(c)
	storeCheck := db.StoreAuditByUid(svc.MasterDb(c), user.Info.Uid)
	res.State = "0"
	if storeCheck != nil {
		copier.Copy(&res, &storeCheck)
		res.State = utils.IntToStr(storeCheck.State)
		res.ProvinceId = utils.IntToStr(storeCheck.ProvinceId)
		res.CityId = utils.IntToStr(storeCheck.CityId)
		res.DistrictId = utils.IntToStr(storeCheck.DistrictId)
	}
	userParty := db.GetStoreIdEg(svc.MasterDb(c), utils.IntToStr(user.Info.Uid))
	if userParty != nil {
		if userParty.State == 1 {
			res.State = "2"
		} else if storeCheck != nil && storeCheck.State == 2 {
			res.State = "3"
		}
	}
	e.OutSuc(c, res, nil)
	return
}
func AuditDoing(c *gin.Context) {
	var arg md.CommunityTeamStoreAudit
	if err := c.ShouldBindJSON(&arg); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	user := svc.GetUser(c)
	userParty := db.GetStoreIdEg(svc.MasterDb(c), utils.IntToStr(user.Info.Uid))
	if userParty != nil {
		if userParty.State == 1 {
			e.OutErr(c, 400, e.NewErr(400, "已审核通过"))
			return
		}
	}
	var tmp model.CommunityTeamStoreAudit
	copier.Copy(&tmp, &arg)
	tmp.State = 1
	tmp.ProvinceId = utils.StrToInt(arg.ProvinceId)
	tmp.CityId = utils.StrToInt(arg.CityId)
	tmp.DistrictId = utils.StrToInt(arg.DistrictId)
	tmp.Uid = user.Info.Uid
	tmp.CreateAt = time.Now()
	tmp.UpdateAt = time.Now()
	storeCheck := db.StoreAuditByUid(svc.MasterDb(c), user.Info.Uid)
	if storeCheck != nil {
		if storeCheck.State == 2 {
			e.OutErr(c, 400, e.NewErr(400, "已审核通过"))
			return
		}
		tmp.CreateAt = storeCheck.CreateAt
		svc.MasterDb(c).Where("id=?", storeCheck.Id).Update(&tmp)
	} else {
		svc.MasterDb(c).Insert(&tmp)
	}

	e.OutSuc(c, "success", nil)
	return
}