package typeManage

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"log-server/global"
	"log-server/model/common/request"
	"log-server/model/typeManage"
	typeReq "log-server/model/typeManage/request"
	"math/rand"
)

func RandomString(n int) string {
	var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

	b := make([]rune, n)
	for i := range b {
		b[i] = letterRunes[rand.Intn(len(letterRunes))]
	}
	return string(b)
}

type ResponsiblePersonService struct {
}

// 创建负责人
func (r *ResponsiblePersonService) CreateResponsiblePerson(person typeManage.ResponsiblePerson) (err error) {
	//先查找是否存在同名员工
	err = global.GVA_DB.Table("responsible_person").Where("name = ? and mobile_phone_number = ?", person.Name, person.MobilePhoneNumber).First(&typeManage.ResponsiblePerson{}).Error
	if !errors.Is(err, gorm.ErrRecordNotFound) {
		return errors.New("已存在同名员工，请勿重复添加")
	}
	//不存在同名员工
	//根据image是否为空来判断是否需要图片处理
	//fmt.Println(person.Img)
	//if person.Img != "" {
	//	var (
	//		enc  = base64.StdEncoding
	//		path string
	//	)
	//	img := person.Img
	//	timestamp:=strconv.Itoa(int(time.Now().UnixNano()))
	//	randomStr := (RandomString(5))
	//	imgId := timestamp+"_"+randomStr
	//
	//	if img[11] == 'j' {
	//		img = img[23:]
	//		path = fmt.Sprintf("/img/%s.jpg", imgId)
	//	} else if img[11] == 'p' {
	//		img = img[22:]
	//		path = fmt.Sprintf("/img/%s.png", imgId)
	//	} else if img[11] == 'g' {
	//		img = img[22:]
	//		path = fmt.Sprintf("/img/%s.gif", imgId)
	//	} else {
	//		fmt.Println("不支持该文件类型")
	//	}
	//
	//	data, err := enc.DecodeString(img)
	//	if err != nil {
	//		log.Println(err.Error())
	//	}
	//	// 图片写入文件
	//	f, _ := os.OpenFile(path, os.O_RDWR|os.O_CREATE, os.ModePerm)
	//	defer f.Close()
	//	if _, err := f.Write(data); err != nil {
	//		log.Println(err)
	//	}
	//	//记录图片保存的地址
	//	path = "https://qmplusimg.henrongyi.top" + path
	//	person.Img = path
	//
	//}
	//数据库插入
	return global.GVA_DB.Table("responsible_person").Omit("create_time", "update_time").Create(&person).Error
}

// 删除负责人
func (r *ResponsiblePersonService) DeleteResponsiblePerson(person typeManage.ResponsiblePerson) (err error) {
	var entity typeManage.ResponsiblePerson
	err = global.GVA_DB.Table("responsible_person").Where("id = ?", person.Id).First(&entity).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return errors.New("未找到记录，删除失败")
	}
	return global.GVA_DB.Table("responsible_person").Delete(&entity).Error
}

// 批量删除
func (r *ResponsiblePersonService) DeleteResponsiblePersonsByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Table("responsible_person").Delete(&[]typeManage.ResponsiblePerson{}, "id in ?", ids.Ids).Error
	return err
}

// 更改记录
func (r *ResponsiblePersonService) UpdateResponsiblePerson(person typeManage.ResponsiblePerson) (err error) {
	err = global.GVA_DB.Table("responsible_person").Where("id != ? and name = ?", person.Id, person.Name).First(&typeManage.ResponsiblePerson{}).Error
	if !errors.Is(err, gorm.ErrRecordNotFound) {
		return errors.New("已存在相同名字，无法更改")
	}
	return global.GVA_DB.Table("responsible_person").Omit("create_time, update_time").Save(&person).Error
}

// 通过id查询负责人
func (r *ResponsiblePersonService) GetResponsiblePersonById(id int) (person typeManage.ResponsiblePerson, err error) {
	err = global.GVA_DB.Table("responsible_person").Where("id = ?", id).First(&person).Error
	return
}

// 条件查询负责人
func (r *ResponsiblePersonService) GetResponsiblePerson(person typeManage.ResponsiblePerson, info request.PageInfo, order string, desc bool) (list interface{}, total int64, err error) {
	//获取分页数据
	limit := info.PageSize
	offset := (info.Page - 1) * info.PageSize
	//绑定操作结构体
	db := global.GVA_DB.Table("responsible_person").Model(&typeManage.ResponsiblePerson{})
	var personList []typeManage.ResponsiblePerson
	//条件查询
	if person.Name != "" {
		db.Where("name like ?", "%"+person.Name+"%")
	}
	//先过滤在排序
	if err = db.Count(&total).Error; err != nil {
		return personList, total, err
	} else {
		//分页
		db.Limit(limit).Offset(offset)
		//判断是否有排序字段
		if order != "" {
			var orderStr string
			orderMap := make(map[string]bool, 1)
			orderMap["create_time"] = true
			if orderMap[order] {
				//合法排序字符
				if desc {
					orderStr = order + " desc"
				} else {
					orderStr = order
				}
			} else {
				//传入排序字段非法
				err = fmt.Errorf("传入非法字段 %v", order)
				return personList, total, err
			}
			err = db.Order(orderStr).Find(&personList).Error
		} else {
			//默认按照名字升序排序
			err = db.Order("name").Find(&personList).Error
		}
	}
	return personList, total, err
}

// GetResponsiblePersonAll 条件查询负责人
func (r *ResponsiblePersonService) GetResponsiblePersonAll() (list interface{}, err error) {
	var personList []typeManage.ResponsiblePerson
	db := global.GVA_DB.Table("responsible_person").Model(&typeManage.ResponsiblePerson{})
	db.Where("state = 1")
	err = db.Order("name").Find(&personList).Error
	return personList, err
}

func (r *ResponsiblePersonService) SelectResponsiblePersonList() (list interface{}, err error) {
	//绑定操作结构体
	db := global.GVA_DB.Table("responsible_person").Model(&typeManage.ResponsiblePerson{})
	db = db.Where("state = ?", 1)
	var personList []typeManage.ResponsiblePerson
	//条件查询
	err = db.Find(&personList).Error
	return personList, err
}

//更改负责人启用状态
func (r *ResponsiblePersonService) UpdateResponsibleStatus(c typeReq.UpdateResponsibleStatusRequest) (err error) {
	err = global.GVA_DB.Table("responsible_person").Where("id = ?", c.Id).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return errors.New("请传入正确的Id")
	}
	err = global.GVA_DB.Table("responsible_person").Where("id = ?", c.Id).Update("state", c.State).Error
	return err
}

//更改负责人推送状态
func (r *ResponsiblePersonService) UpdatePushStatus(c typeReq.UpdatePushStatusRequest) (err error) {
	err = global.GVA_DB.Table("responsible_person").Where("id = ?", c.Id).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return errors.New("请传入正确的Id")
	}
	err = global.GVA_DB.Table("responsible_person").Where("id = ?", c.Id).Update("push_status", c.PushStatus).Error
	return err
}