/*
 * @description:已支付相关数据操作
 * @Author: CP
 * @Date: 2020-12-22 14:46:06
 * @FilePath: \construction_management\dao\contract_paid_dao.go
 */
package dao

import (
	"errors"
	"fmt"
	"strconv"

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

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

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

// 获得回款
func (d *ContractPaidDao) Get(id int, contractsId int, bidsectionId int) *models.CmContractsPaid {
	data := &models.CmContractsPaid{Id: id, ContractsId: contractsId, BidsectionId: bidsectionId}
	ok, err := d.engine.Get(data)
	if ok && err == nil {
		return data
	} else {
		data.Id = 0
		return data
	}

}

func (d *ContractPaidDao) GetAll(projectId int, bidsectionId int, contractsId int) []models.CmContractsPaid {
	datalist := make([]models.CmContractsPaid, 0)

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

// 创建已支付
func (d *ContractPaidDao) Add(contractsPaid *models.CmContractsPaid) error {
	_, err := d.engine.Insert(contractsPaid)
	return err
}

// 更新已支付
func (d *ContractPaidDao) Update(contractsReturn *models.CmContractsPaid, contracts_id int, bidsectionId int) error {
	_, err := d.engine.Where("id = ? and contracts_id = ? and bidsection_id=? ", contractsReturn.Id, contracts_id, bidsectionId).Update(contractsReturn)
	return err
}

// 删除回款
func (d *ContractPaidDao) Delete(id int, contractsId int, bidsectionId int, projectId int) error {
	data := &models.CmContractsPaid{}
	_, err := d.engine.Where("id = ? and contracts_id = ? and project_id =? and bidsection_id = ? ", id, contractsId, projectId, bidsectionId).Delete(data)
	return err
}

// 更新已支付总金额
func (d *ContractPaidDao) UpdatePaidTotalPrice(projectId int, bidsectionId int, contractsId int) error {
	session := d.engine.NewSession()
	defer session.Close()
	err := session.Begin()
	if err != nil {
		return errors.New("session出错-db")
	}

	// 0.获得合同金额
	contractsDetail := &models.CmContracts{}
	_, err = d.engine.Where(" id = ? ", contractsId).Get(contractsDetail)
	if err != nil {
		return errors.New("未找到合同")
	}

	// 1.获得合同支付总金额
	datalist := make([]models.CmContractsPaid, 0)
	err = d.engine.Where(" project_id =? and bidsection_id = ? ", projectId, bidsectionId).Find(&datalist)
	if err != nil {
		session.Rollback()
		return errors.New("编辑合同出错-项目节更新失败")
	}
	priceTotal := 0.00
	contractsPrice := 0.00
	for _, item := range datalist {
		price, _ := strconv.ParseFloat(item.Price, 64)
		priceTotal = priceTotal + price
		if item.ContractsId == contractsId {
			contractsPrice = contractsPrice + price
		}
	}
	priceTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", priceTotal), 64)
	contractsPrice, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", contractsPrice), 64)

	// 1-1合同状态的判定
	contractsDetailPrice, _ := strconv.ParseFloat(contractsDetail.Price, 64)
	// 总回款大于等于合同金额 待关闭
	contractStatus := 0
	if contractsPrice >= contractsDetailPrice {
		contractStatus = 1
	}

	// 2.更新合同表 合同下回款总金额
	_, err = session.Exec("UPDATE  cm_contracts SET `paid` = ? , status = ?,locking=0 where id = ? ", contractsPrice, contractStatus, contractsId)
	if err != nil {
		session.Rollback()
		return errors.New("金额更新失败")
	}
	// 3.更新项目节 合同下回款总金额
	_, err = session.Exec("UPDATE  cm_tree_contracts SET `contracts_paid` = ? , contract_status = ?,contract_locking=0 where project_id = ? and bidsection_id=? and contract_id=? ",
		contractsPrice, contractStatus, projectId, bidsectionId, contractsId)
	if err != nil {
		session.Rollback()
		return errors.New("金额更新失败")
	}
	// 4.更新标段树 整个标段下回款总金额
	_, err = session.Exec("UPDATE  cm_tree SET `contracts_paid` = ? where project_id = ? and bidsection_id=? ", priceTotal, projectId, bidsectionId)
	if err != nil {
		session.Rollback()
		return errors.New("金额更新失败")
	}

	err = session.Commit()
	if err != nil {
		session.Rollback()
		return errors.New("session出错-db")
	}
	return nil
}

// 筛选出应用了当前规则的条数
func (d *ContractPaidDao) CountPaidRuleCode(bid int) (int64, error) {
	data := &models.CmContractsPaid{}
	total, err := d.engine.Where("`bidsection_id` = ?", bid).Count(data)
	if err != nil {
		total = 0
	}
	return total, err
}
