/*
 * @description: 标段账号的-数据库操作
 * @Author: CP
 * @Date: 2020-10-21 11:54:10
 * @FilePath: \construction_management\dao\bid_account_dao.go
 */
package dao

import (
	"encoding/json"
	"errors"
	"log"

	"github.com/go-xorm/xorm"
	"go.mod/lib"
	"go.mod/models"
)

//数据库操作引擎
type BidAccountDao struct {
	engine *xorm.Engine
}

//获得一个DAO对象
func NewBidAccountDao(engine *xorm.Engine) *BidAccountDao {
	return &BidAccountDao{
		engine: engine,
	}
}

//获得标段下的账号数据
func (d *BidAccountDao) GetBidAccount(bidsectionId int, projectId int) []models.CmBidAccount {
	datalist := make([]models.CmBidAccount, 0)

	err := d.engine.
		Where("bidsection_id = ? and project_id=?", bidsectionId, projectId).
		Asc("id").
		Find(&datalist)
	if err != nil {
		return datalist
	} else {
		return datalist
	}
}

//获得标段下的账号数据
func (d *BidAccountDao) GetAccountId(projectId int, bidsectionId int, accountId int) *models.CmBidAccount {
	data := &models.CmBidAccount{}
	ok, err := d.engine.
		Where("project_id=? and bidsection_id = ? and account_id= ? ", projectId, bidsectionId, accountId).
		Get(data)
	if ok && err == nil {
		return data
	} else {
		data.Id = 0
		return data
	}
}

// 创建标段成员关系
func (d *BidAccountDao) Create(bidsectionId int, accountData *models.CmProjectAccount, treeId int, projectId int) error {

	session := d.engine.NewSession()
	defer session.Close()
	err := session.Begin()
	if err != nil {
		return errors.New("新增标段成员出错-dbsession")
	}

	// -更新树成员量
	// 1.获得标段成员量
	bidAccountData := d.GetBidAccount(bidsectionId, projectId)
	accounts := len(bidAccountData) + 1
	_, err = session.Exec("UPDATE cm_tree SET `accounts` = ? where id = ?", accounts, treeId)
	if err != nil {
		session.Rollback()
		log.Println(err)
		return errors.New("更新标段成员量出错")
	}

	// 2.初始化账号权限
	permissionAccount := &models.CmPermissionAccount{}
	_, err = d.engine.
		Where("project_id=? and bidsection_id = ? and account_id= ? ", projectId, bidsectionId, accountData.Id).
		Get(permissionAccount)
	// 2-1
	permiss := "{\"access\":1,\"add\":0,\"delete\":0}"
	if permissionAccount.Id == 0 {
		permissionAccount.ProjectId = projectId
		permissionAccount.BidsectionId = bidsectionId
		permissionAccount.AccountId = accountData.Id
		permissionAccount.ContractPermission = permiss
		permissionAccount.QualityPermission = permiss
		permissionAccount.SafePermission = permiss
		_, err = session.Insert(permissionAccount)
		if err != nil {
			session.Rollback()
			return errors.New("初始化账号权限出错")
		}
	} else {
		_, err = session.Exec("UPDATE cm_permission_account SET `contract_permission` = ? ,`quality_permission` = ? ,`safe_permission` = ?  where id = ?",
			permiss, permiss, permiss, permissionAccount.Id)
		if err != nil {
			session.Rollback()
			return errors.New("更新账号下标段出错")
		}
	}

	// -更新账号表的标段ID
	// 1.获得账号中已绑定的标段
	bidsectionIdsString := accountData.BidsectionIds
	bidsectionIds := make([]lib.BidsectionIds, 0)
	bidsectionIdsByte := []byte("")
	// 2.未有标段
	if bidsectionIdsString == "" {
		BidsectionIdsItem := lib.BidsectionIds{}
		BidsectionIdsItem.Id = bidsectionId
		bidsectionIds = append(bidsectionIds, BidsectionIdsItem)
		bidsectionIdsByte, err = json.Marshal(bidsectionIds)
		if err != nil {
			session.Rollback()
			return err
		}
	} else {
		// 2.获得已有的标段ID
		err := json.Unmarshal([]byte(bidsectionIdsString), &bidsectionIds)
		if err != nil {
			session.Rollback()
			return err
		}
		bidId := lib.BidsectionIds{}
		bidId.Id = bidsectionId
		// 加入ID
		bidsectionIds = append(bidsectionIds, bidId)
		// 转换JSON字符byte
		bidsectionIdsByte, err = json.Marshal(bidsectionIds)
		if err != nil {
			return err
		}
	}
	bidsectionIdsString = string(bidsectionIdsByte[:])
	// 3.更新账号标段ID组
	_, err = session.Exec("UPDATE cm_project_account SET `bidsection_ids` = ? where id = ?", bidsectionIdsString, accountData.Id)
	if err != nil {
		session.Rollback()
		return errors.New("更新账号下标段出错")
	}

	// -写入标段用户关系
	bidAccount := models.CmBidAccount{}
	bidAccount.AccountId = accountData.Id
	bidAccount.BidsectionId = bidsectionId
	bidAccount.ProjectId = projectId
	_, err = session.Insert(bidAccount)
	if err != nil {
		session.Rollback()
		return errors.New("账号关联标段出错")
	}

	err = session.Commit()
	if err != nil {
		session.Rollback()
		return errors.New("新增标段成员出错-dbsession")
	}
	return nil
}

// 移除标段中的成员
func (d *BidAccountDao) Delete(bidsectionId int, accountData *models.CmProjectAccount, treeId int, projectId int) error {
	session := d.engine.NewSession()
	defer session.Close()
	err := session.Begin()
	if err != nil {
		return errors.New("移除标段成员出错-dbsession")
	}

	// 1.移除标段账号关系中的账号
	_, err = session.Exec("DELETE FROM `cm_bid_account` WHERE account_id = ? and bidsection_id = ? and project_id= ? limit 1",
		accountData.Id, bidsectionId, projectId)
	if err != nil {
		session.Rollback()
		return errors.New("移除标段成员出错")
	}
	// 1-1 移除账号权限
	_, err = session.Exec("DELETE FROM `cm_permission_account` WHERE project_id= ? and  bidsection_id = ? and  account_id = ? limit 1",
		projectId, bidsectionId, accountData.Id)
	if err != nil {
		session.Rollback()
		return errors.New("移除成员权限出错")
	}

	// -更新树成员量
	// 2.获得标段成员量
	bidAccountData := d.GetBidAccount(bidsectionId, projectId)
	accounts := len(bidAccountData)
	_, err = session.Exec("UPDATE cm_tree SET `accounts` = ? where id = ?", accounts, treeId)
	if err != nil {
		session.Rollback()
		return errors.New("更新标段成员量出错")
	}

	// 3.移除账号表中的标段ID
	bidsectionIdsString := accountData.BidsectionIds
	bidsectionIds := make([]lib.BidsectionIds, 0)
	bidsectionIdsByte := []byte("")
	// 2.未有标段
	if bidsectionIdsString == "" {
		return errors.New("移除标段成员出错")
	}
	// 2.获得已有的标段ID
	err = json.Unmarshal([]byte(bidsectionIdsString), &bidsectionIds)
	if err != nil {
		session.Rollback()
		return err
	}
	// 获得需要删除标段ID的下标
	bidsectionIdsIndex := -1
	for index, data := range bidsectionIds {
		if data.Id == bidsectionId {
			bidsectionIdsIndex = index
			break
		}
	}
	if bidsectionIdsIndex == -1 {
		session.Rollback()
		return errors.New("移除标段成员出错")
	}
	// 删除标段ID
	bidsectionIds = append(bidsectionIds[:bidsectionIdsIndex], bidsectionIds[bidsectionIdsIndex+1:]...)

	// 转换JSON字符byte
	bidsectionIdsByte, err = json.Marshal(bidsectionIds)
	if err != nil {
		session.Rollback()
		return err
	}
	bidsectionIdsString = string(bidsectionIdsByte[:])
	// 3.更新账号标段ID组
	_, err = session.Exec("UPDATE cm_project_account SET `bidsection_ids` = ? where id = ?", bidsectionIdsString, accountData.Id)
	if err != nil {
		session.Rollback()
		return errors.New("移除账号下标段出错")
	}

	err = session.Commit()
	if err != nil {
		session.Rollback()
		return errors.New("移除标段成员出错-dbsession")
	}
	return nil
}
