/*
 * @description: 合同相关数据库操作
 * @Author: CP
 * @Date: 2020-11-17 10:41:05
 * @FilePath: \construction_management\dao\contract_dao.go
 */
package dao

import (
	"errors"
	"fmt"
	"log"
	"strconv"

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

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

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

// 获得本项目的合同项目节
func (d *ContractDao) Get(id int) *models.CmContracts {
	data := &models.CmContracts{}
	_, err := d.engine.
		Where("id=? ", id).
		Get(data)
	if err != nil {
		data.Id = 0
		return data
	}
	return data
}

// 获得本项目的合同项目节
func (d *ContractDao) GetByCode(projectId int, bidsectionId int, code string, contractsType int) []models.CmContracts {

	datalist := make([]models.CmContracts, 0)
	_ = d.engine.
		Where("project_id=? and bidsection_id=? and code=? and contracts_type=? ",
			projectId, bidsectionId, code, contractsType).
		Find(&datalist)
	return datalist
}

// 获得本项目的合同项目节
func (d *ContractDao) GetType(bidsectionId int, projectId int, contractsType int) []models.CmContracts {

	datalist := make([]models.CmContracts, 0)
	_ = d.engine.
		Where("project_id=? and bidsection_id=? and contracts_type=? ", projectId, bidsectionId, contractsType).
		Find(&datalist)
	return datalist
}

// 获得本项目的合同项目节
func (d *ContractDao) GetTypeYear(bidsectionId int, projectId int, contractsType int, year int) []models.CmContracts {

	startYear := fmt.Sprintf("%d-01-01:00.00.00", year)
	endYear := fmt.Sprintf("%d-12-31:23.59.59", year)

	datalist := make([]models.CmContracts, 0)
	_ = d.engine.
		Where("project_id=? and bidsection_id=? and contracts_type=? and create_time>='"+startYear+"' and create_time<='"+endYear+"'",
			projectId, bidsectionId, contractsType).
		Find(&datalist)
	return datalist
}

// 合同
func (d *ContractDao) GetInProjectAndBidsection(id int, projectId int, bidsectionId int) *models.CmContracts {
	data := &models.CmContracts{}
	_, err := d.engine.
		Where("id=? and project_id=? and bidsection_id=? ", id, projectId, bidsectionId).
		Get(data)
	if err != nil {
		data.Id = 0
		return data
	}
	return data
}

// 新增合同
// contractData *models.CmContracts
// contractTotal 合同总数
// priceTotal 收入总金额
func (d *ContractDao) Add(contractData *models.CmContracts) error {
	session := d.engine.NewSession()
	defer session.Close()
	err := session.Begin()
	if err != nil {
		return errors.New("新增合同出错-db")
	}

	// 1.写入合同表
	_, err = session.Insert(contractData)
	if err != nil {
		log.Println(err)
		session.Rollback()
		return errors.New("新增合同出错")
	}
	// 2.更新项目节表
	_, err = session.Exec("UPDATE  cm_tree_contracts SET `contract_id` = ?,`contract_name` = ?,`contract_code` = ?,`contract_price` = ? "+
		"where tree_id = ? and project_id = ? and bidsection_id = ? ",
		contractData.Id, contractData.Name, contractData.Code, contractData.Price,
		contractData.TreeId, contractData.ProjectId, contractData.BidsectionId)
	if err != nil {
		session.Rollback()
		return errors.New("新增合同出错-项目节更新失败")
	}

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

// 更新合同
func (d *ContractDao) Update(contractsCm *models.CmContracts, columns []string, projectId int, bidsectionId int, treeId int) error {
	session := d.engine.NewSession()
	defer session.Close()
	err := session.Begin()
	if err != nil {
		return errors.New("session出错-db")
	}

	// 1.更新合同表
	// successNum 是否有值更新的数量 为0，表示没有更新
	// successNum, err := session.Id(contractsCm.Id).MustCols(columns...).Update(contractsCm)
	_, err = session.Id(contractsCm.Id).MustCols(columns...).Update(contractsCm)
	if err != nil {
		session.Rollback()
		return errors.New("更新失败")
	}

	// 3.更新合同状态，合同金额和回款金额比对
	// 3-1获得回款总金额
	datalist := make([]models.CmContractsReturn, 0)
	err = d.engine.Where(" project_id =? and bidsection_id = ? and contracts_id =? ", projectId, bidsectionId, contractsCm.Id).Find(&datalist)
	if err != nil {
		session.Rollback()
		return errors.New("编辑合同出错-项目节更新失败")
	}
	contractsPrice := 0.00
	for _, item := range datalist {
		price, _ := strconv.ParseFloat(item.Price, 64)
		if item.ContractsId == contractsCm.Id {
			contractsPrice = contractsPrice + price
		}
	}
	contractsPrice, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", contractsPrice), 64)
	// 合同状态判定
	contractsDetailPrice, _ := strconv.ParseFloat(contractsCm.Price, 64)
	// 总回款大于等于合同金额 待关闭
	contractStatus := 0
	if contractsPrice >= contractsDetailPrice {
		contractStatus = 1
	}
	// 更新合同表状态
	_, err = session.Exec("UPDATE  cm_contracts SET  status = ? where id = ? ", contractStatus, contractsCm.Id)
	if err != nil {
		session.Rollback()
		return errors.New("合同状态更新失败")
	}

	// 2.更新项目节表
	_, err = session.Exec("UPDATE  cm_tree_contracts SET `contract_name` = ?,`contract_price` = ? , contract_status = ? "+
		"where tree_id = ? and project_id = ? and bidsection_id = ? ",
		contractsCm.Name, contractsCm.Price, contractStatus,
		treeId, 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 *ContractDao) Delete(projectId int, bidsectionId int, treeId int, id int) error {

	contractsCm := models.CmContracts{}

	session := d.engine.NewSession()
	defer session.Close()
	err := session.Begin()
	if err != nil {
		return errors.New("session出错-db")
	}
	// 1.删除合同
	successNum, err := session.Where("id = ? and tree_id=? and bidsection_id= ? and project_id=? ", id, treeId, bidsectionId, projectId).Delete(contractsCm)
	if err != nil {
		session.Rollback()
		return errors.New("删除失败")
	}
	if successNum == 0 {
		session.Rollback()
		return errors.New("合同数据异常,删除失败")
	}

	// 2.删除项目节上合同信息-需求变更-删除项目节
	_, err = session.Exec("DELETE FROM `cm_tree_contracts` WHERE tree_id=? and project_id = ? and bidsection_id = ? ",
		treeId, projectId, bidsectionId)
	if err != nil {
		session.Rollback()
		return errors.New("编辑合同出错-项目节删除失败")
	}
	// _, err = session.Exec("UPDATE  cm_tree_contracts SET `contract_name` = '',`contract_code` = '',`contract_price` = 0,`contract_id` = 0,`contract_returned` = 0,`contracts_paid` = 0,`contract_status` = 0 "+
	// 	",contract_locking=0 where tree_id = ? and project_id = ? and bidsection_id = ? ",
	// 	treeId, projectId, bidsectionId)
	// if err != nil {
	// 	session.Rollback()
	// 	return errors.New("编辑合同出错-项目节更新失败")
	// }

	// 3.删除回款信息
	_, err = session.Exec("DELETE FROM `cm_contracts_return` WHERE contracts_id=? and project_id=? and bidsection_id=? ",
		id, projectId, bidsectionId)
	if err != nil {
		session.Rollback()
		return errors.New("编辑合同出错-删除回款信息失败")
	}

	// 4.删除附件-TODO

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

// 删除支出合同
func (d *ContractDao) DeleteExpenditure(projectId int, bidsectionId int, treeId int, id int) error {

	contractsCm := models.CmContracts{}

	session := d.engine.NewSession()
	defer session.Close()
	err := session.Begin()
	if err != nil {
		return errors.New("session出错-db")
	}
	// 1.删除合同
	successNum, err := session.Where("id = ? and tree_id=? and bidsection_id= ? and project_id=? ", id, treeId, bidsectionId, projectId).Delete(contractsCm)
	if err != nil {
		session.Rollback()
		return errors.New("删除失败")
	}
	if successNum == 0 {
		session.Rollback()
		return errors.New("合同数据异常,删除失败")
	}

	// 2.删除项目节上合同信息--移除项目节需求变更
	_, err = session.Exec("DELETE FROM `cm_tree_contracts` WHERE tree_id=? and project_id = ? and bidsection_id = ?  ",
		treeId, projectId, bidsectionId)
	if err != nil {
		session.Rollback()
		return errors.New("编辑合同出错-删除项目节失败")
	}
	// _, err = session.Exec("UPDATE  cm_tree_contracts SET `contract_name` = '',`contract_code` = '',`contract_price` = 0,`contract_id` = 0,`contract_returned` = 0,`contracts_paid` = 0,`contract_status` = 0 "+
	// 	",contract_locking=0 where tree_id = ? and project_id = ? and bidsection_id = ? ",
	// 	treeId, projectId, bidsectionId)
	// if err != nil {
	// 	session.Rollback()
	// 	return errors.New("删除合同出错-项目节更新失败")
	// }

	// 3.删除已支付信息
	_, err = session.Exec("DELETE FROM `cm_contracts_paid` WHERE contracts_id=? and project_id=? and bidsection_id=? ",
		id, projectId, bidsectionId)
	if err != nil {
		session.Rollback()
		return errors.New("编辑合同出错-删除已支付失败")
	}

	// 4.删除附件-TODO

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

// 关闭合同
func (d *ContractDao) Close(projectId int, bidsectionId int, treeId int, id int) error {

	session := d.engine.NewSession()
	defer session.Close()
	err := session.Begin()
	if err != nil {
		return errors.New("session出错-db")
	}

	// 1.关闭合同-关闭合同，默认锁定合同
	contractsCm := models.CmContracts{}
	contractsCm.Status = 2
	contractsCm.Locking = 1
	successNum, err := session.Where("id = ?", id).Update(contractsCm)
	if err != nil {
		session.Rollback()
		return errors.New("关闭合同出错")
	}
	if successNum == 0 {
		session.Rollback()
		return errors.New("关闭合同异常")
	}

	// 2.更新项目节合同状态,锁定合同
	treeContractsCm := models.CmTreeContracts{}
	successNum, err = session.Where("tree_id = ? ", treeId).Update(treeContractsCm)
	if err != nil {
		session.Rollback()
		return errors.New("关闭合同出错-项目节")
	}
	if successNum == 0 {
		session.Rollback()
		return errors.New("关闭合同异常-项目节")
	}

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

// 删除合同
func (d *ContractDao) Unlock(projectId int, bidsectionId int, treeId int, id int) error {
	session := d.engine.NewSession()
	defer session.Close()
	err := session.Begin()
	if err != nil {
		return errors.New("session出错-db")
	}

	// 1.解锁合同
	contractsCm := models.CmContracts{}
	contractsCm.Locking = 0
	contractsCm.Status = 1
	_, err = session.Where("id = ?", id).Cols("locking,Status").Update(contractsCm)
	if err != nil {
		session.Rollback()
		return errors.New("解锁合同出错")
	}

	// 2.更新项目节上合同锁状态
	treeContractsCm := models.CmTreeContracts{}
	_, err = session.Where("tree_id = ?", treeId).Cols("contract_locking,contract_status").Update(treeContractsCm)
	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 *ContractDao) CountRuleCode(bid int, contractType int) (int64, error) {
	data := &models.CmContracts{}
	total, err := d.engine.Where("`bidsection_id` = ? and `contracts_type` = ?", bid, contractType).Count(data)
	if err != nil {
		total = 0
	}
	return total, err
}
