/*
 * @description:项目用户相关数据处理
 * @Author: CP
 * @Date: 2020-08-27 17:23:58
 * @FilePath: \construction_management\services\project_account_service.go
 */
package services

import (
	"encoding/json"
	"errors"
	"html"
	"log"
	"strconv"
	"strings"
	"time"

	"github.com/kataras/iris/v12"
	"go.mod/comm"
	"go.mod/models"
	"go.mod/web/utils"
	"go.mod/web/viewmodels"

	"go.mod/dao"
	"go.mod/datasource"
)

//定义项目用户Service接口
type ProjectAccountService interface {
	ValidRule(ctx iris.Context) (viewmodels.ProjectAccount, error)
	ValidRulePermission(ctx iris.Context) (viewmodels.Permission, error)

	Get(accountId int, projectId int) *viewmodels.ProjectAccount
	GetAll(projectId int) []viewmodels.ProjectAccount
	GetBidAccount(bidsectionId int, projectId int, projectAccountId int) []viewmodels.ProjectAccount
	Search(name string, projectId int) []viewmodels.ProjectAccount
	Add(viewAccount viewmodels.ProjectAccount, projectId int) error
	Save(viewAccount viewmodels.ProjectAccount, id int, projectId int) error
	Enable(id int, projectId int, enable int) error
	ChangeAccount(id int, projectId int, viewAccount viewmodels.ProjectAccount) error
	GetProjectInfo(id int) (viewmodels.ProjectInfo, error)
	Delete(id int, projectId int) error

	SaveAuth(permission viewmodels.Permission, projectId int, accountId int) error
}

//返回service操作类
type projectAccountService struct {
	dao           *dao.ProjectAccountDao
	bidAccountDao *dao.BidAccountDao
	validSave     string
	validAdd      string
	validPassword string
}

//创建项目用户service
func NewProjectAccountService() ProjectAccountService {
	return &projectAccountService{
		dao:           dao.NewProjectAccountDao(datasource.InstanceDbMaster()),
		bidAccountDao: dao.NewBidAccountDao(datasource.InstanceDbMaster()),
		validSave:     "/api/projectSetting/account/save",
		validAdd:      "/api/projectSetting/account/create",
		validPassword: "/api/projectSetting/account/change",
	}
}

// 用户规则验证
func (s *projectAccountService) ValidRule(ctx iris.Context) (viewmodels.ProjectAccount, error) {
	accountVaild := viewmodels.ProjectAccount{}
	err := ctx.ReadJSON(&accountVaild)
	if err != nil {
		log.Println("account-ValidRule-ReadForm转换异常, error=", err)
		return accountVaild, err
	}

	if ctx.Path() == s.validAdd {
		err = accountVaild.Validate()
	} else if ctx.Path() == s.validSave {
		err = accountVaild.ValidateUpdate()
	} else if ctx.Path() == s.validPassword {
		err = accountVaild.ValidatePassword()
	} else {
		log.Println("请求路径找不到对应的验证规则")
		return accountVaild, errors.New("验证错误-未找到验证规则")
	}

	if err != nil {
		log.Println("用户验证, error=", err)
		return accountVaild, err
	}

	// 验证账号组
	if ctx.Path() != s.validPassword {
		accountGroup := comm.NewAccountGroup()
		err = accountGroup.ValidRule(accountVaild.AccountGroup)
		if err != nil {
			log.Println("用户验证, error=", err)
			return accountVaild, err
		}
	}
	// xss
	accountVaild.Account = html.EscapeString(accountVaild.Account)
	accountVaild.Password = html.EscapeString(accountVaild.Password)
	accountVaild.Name = html.EscapeString(accountVaild.Name)
	accountVaild.Company = html.EscapeString(accountVaild.Company)
	accountVaild.Position = html.EscapeString(accountVaild.Position)
	accountVaild.Mobile = html.EscapeString(accountVaild.Mobile)
	accountVaild.Telephone = html.EscapeString(accountVaild.Telephone)

	return accountVaild, nil
}

// 用户规则验证
func (s *projectAccountService) ValidRulePermission(ctx iris.Context) (viewmodels.Permission, error) {
	accountVaild := viewmodels.Permission{}
	err := ctx.ReadJSON(&accountVaild)
	if err != nil {
		log.Println("account-ValidRule-ReadForm转换异常, error=", err)
		return accountVaild, err
	}

	err = accountVaild.Validate()

	if err != nil {
		log.Println("权限验证, error=", err)
		return accountVaild, err
	}

	return accountVaild, nil
}

// 获得一个项目用户
func (s *projectAccountService) Get(id int, projectId int) *viewmodels.ProjectAccount {
	modelsAccount := s.dao.Get(id, projectId)
	viewAccountData := viewmodels.ProjectAccount{}
	if modelsAccount.Id == 0 {
		viewAccountData.Id = "0"
		return &viewAccountData
	}

	viewAccountData = comm.MakeProjectAccountVM(modelsAccount)
	return &viewAccountData
}

// 获得项目下所有账号信息
func (s *projectAccountService) GetAll(projectId int) []viewmodels.ProjectAccount {
	accountList := s.dao.GetAll(projectId)
	accountListVM := make([]viewmodels.ProjectAccount, 0)
	for _, data := range accountList {
		//if data.IsAdmin != 1 {
		account := comm.MakeProjectAccountVM(&data)
		accountListVM = append(accountListVM, account)
		//}
	}
	return accountListVM
}

// 获得标段下的账号
func (s *projectAccountService) GetBidAccount(bidsectionId int, projectId int, projectAccountId int) []viewmodels.ProjectAccount {
	// 1.获得标段账号ID
	bidAccountData := s.bidAccountDao.GetBidAccount(bidsectionId, projectId)

	// 组合账号ID集合
	idList := []string{}
	// 管理员账号-可能不必要
	// idList = append(idList, strconv.Itoa(projectAccountId))
	for _, item := range bidAccountData {
		idList = append(idList, strconv.Itoa(item.BidsectionId))
	}
	inId := strings.Join(idList, ",")

	// 获得账号信息
	accountData := s.dao.GetInId(inId)
	// 格式化账号数据
	accountListVM := make([]viewmodels.ProjectAccount, 0)
	for _, data := range accountData {
		account := comm.MakeProjectAccountVM(&data)
		accountListVM = append(accountListVM, account)
	}
	return accountListVM
}

// 检索 账号姓名单位手机
func (s *projectAccountService) Search(name string, projectId int) []viewmodels.ProjectAccount {
	accountList := s.dao.Search(name, projectId)
	accountListVM := make([]viewmodels.ProjectAccount, 0)
	for _, data := range accountList {
		account := comm.MakeProjectAccountVM(&data)
		accountListVM = append(accountListVM, account)
	}
	return accountListVM
}

// 新增账号
func (s *projectAccountService) Add(viewAccount viewmodels.ProjectAccount, projectId int) error {

	// 验证该项目下是否有同名账号
	accountValid := s.dao.GetAccount(viewAccount.Account)
	if accountValid.Id != 0 {
		return errors.New("已存在相同的账号")
	}

	account := models.CmProjectAccount{}
	account.ProjectId = projectId
	account.Account = viewAccount.Account
	account.Password = comm.CreatePasswordSign(viewAccount.Password, viewAccount.Account)
	account.Name = viewAccount.Name
	account.Company = viewAccount.Company
	account.Position = viewAccount.Position
	account.Mobile = viewAccount.Mobile
	account.Telephone = viewAccount.Telephone
	account.AccountGroup = viewAccount.AccountGroup
	account.CreateTime = time.Now()
	err := s.dao.Add(&account)
	return err
}

// 保存用户信息
func (s *projectAccountService) Save(viewAccount viewmodels.ProjectAccount, id int, projectId int) error {

	account := models.CmProjectAccount{}
	account.Id = id
	account.ProjectId = projectId
	account.Name = viewAccount.Name
	account.Company = viewAccount.Company
	account.Position = viewAccount.Position
	//account.Mobile = viewAccount.Mobile
	account.Telephone = viewAccount.Telephone
	account.AccountGroup = viewAccount.AccountGroup
	err := s.dao.Update(&account, []string{"Name", "Company", "Position", "Telephone", "AccountGroup"})

	return err
}

// 设置启用/禁止
func (s *projectAccountService) Enable(id int, projectId int, enable int) error {

	account := models.CmProjectAccount{}
	account.Id = id
	account.ProjectId = projectId
	account.Enable = enable
	err := s.dao.Update(&account, []string{"Enable"})

	return err
}

// 删除账号
func (s *projectAccountService) Delete(id int, projectId int) error {
	account := models.CmProjectAccount{}
	account.Id = id
	account.ProjectId = projectId
	err := s.dao.Delete(&account)

	return err
}

// 更改账号或者密码
func (s *projectAccountService) ChangeAccount(id int, projectId int, viewAccount viewmodels.ProjectAccount) error {
	// 1.是否修改账号
	field := []string{"Password"}
	account := models.CmProjectAccount{}
	account.Id = id
	account.ProjectId = projectId

	// 2.修改密码
	account.Password = comm.CreatePasswordSign(viewAccount.Password, viewAccount.Account)

	accountData := s.dao.Get(id, projectId)
	if accountData.Account != viewAccount.Account {
		account.Account = viewAccount.Account
		field = append(field, "Account")
	}

	// 3.发送短信-TODO
	utils.SendSMS()

	s.dao.Update(&account, field)

	return nil
}

func (s *projectAccountService) GetProjectInfo(id int) (viewmodels.ProjectInfo, error) {
	projectInfo, err := s.dao.FindById(id)
	return projectInfo, err
}

// 保存权限设置
func (s *projectAccountService) SaveAuth(permission viewmodels.Permission, projectId int, accountId int) error {
	// 1.构造权限字符串
	// 1-1.合同权限
	contractPermission := map[string]int{
		"add":    permission.ContractAdd,
		"delete": permission.ContractDelete,
		"access": permission.ContractAccess,
	}
	contractPermissionByte, err := json.Marshal(contractPermission)
	if err != nil {
		return errors.New("合同权限解析失败")
	}
	contractPermissionStr := string(contractPermissionByte)
	// 1.2 安全巡检权限
	safePermission := map[string]int{
		"add":    permission.SafeAdd,
		"delete": permission.SafeDelete,
		"access": permission.SafeAccess,
	}
	safePermissionByte, err := json.Marshal(safePermission)
	if err != nil {
		return errors.New("合同权限解析失败")
	}
	safePermissionStr := string(safePermissionByte)
	// 1.3 质量巡检权限
	qualityPermission := map[string]int{
		"add":    permission.QualityAdd,
		"delete": permission.QualityDelete,
		"access": permission.QualityAccess,
	}
	qualityPermissionByte, err := json.Marshal(qualityPermission)
	if err != nil {
		return errors.New("合同权限解析失败")
	}
	qualityPermissionStr := string(qualityPermissionByte)

	// 2.保存权限
	account := models.CmProjectAccount{}
	account.Id = accountId
	account.ProjectId = projectId
	account.Contractpermission = contractPermissionStr
	account.Safepermission = safePermissionStr
	account.Qualitypermission = qualityPermissionStr

	err = s.dao.Update(&account, []string{"Contractpermission", "Safepermission", "Qualitypermission"})
	return err
}
