using Sugar.Enties;
using SqlSugar;
using System;
using System.Collections.Generic;
using WebAPIBase.Utils;
public class DesignChangesManager : DbContext<DesignChanges>
{

    //当前类已经继承了 DbContext增、删、查、改的方法

    //这里面写的代码不会给覆盖,如果要重新生成请删除 DesignChangesManager.cs

    /// <summary>
    /// 根据用户编号和用户代码获取待审变更列表
    /// </summary>
    /// <param name="projectCode"></param>
    /// <param name="userCode"></param>
    /// <returns></returns>
    public List<DesignChangesDTO> GetDesignChangesList(string projectCode, string userCode)
    {
        string sql = $"select dc.DesignChangesCode,dc.ProjectCode,dc.ContractCode,dc.DesignChangesName,dc.DesignChangesNumber,dc.Person,dc.UnitCode,dc.DesignChangesDate,dc.State,con.ContractName,un.UnitName from DesignChanges dc inner join Contract con on dc.ContractCode=con.ContractCode inner join Unit un on dc.UnitCode=un.UnitCode where dc.ProjectCode='{projectCode}' and dc.person='{userCode}' order by dc.DesignChangesCode desc";
        var list = Db.Ado.SqlQuery<DesignChangesDTO>(sql);
        return list;
    }

    /// <summary>
    /// 根据变更编码获取待审变更实例
    /// </summary>
    /// <param name="viseCode"></param>
    /// <returns></returns>
    public DesignChangesDTO GetDesignChanges(string designChangesCode)
    {
        var sql = $"SELECT v.*,dbo.GetUnitFullName(v.UnitCode) unitFullName, c.ContractName from designChanges v INNER JOIN dbo.Contract c ON v.ContractCode=c.ContractCode where  v.DesignChangesCode = '{designChangesCode}'  ";

        var entity = Db.Ado.SqlQuerySingle<DesignChangesDTO>(sql);
        return entity;
    }
    /// <summary>
    /// 待审变更费用明细列表
    /// </summary>
    /// <param name="viseCode"></param>
    /// <returns></returns>
    public List<DesignChangesCostDTO> GetDesignChangesCostDTOs(string designChangesCode)
    {
        var sql = $"SELECT *  FROM DesignChangesCost  WHERE DesignChangesCode='{designChangesCode}'";
        var list = Db.Ado.SqlQuery<DesignChangesCostDTO>(sql);
        return list;
    }

    /// <summary>
    /// 插入待审变更主表和明细表
    /// </summary>
    /// <param name="designChanges"></param>
    /// <param name="designChangesCosts"></param>
    /// <returns></returns>
    public string InsertDesignChanges(DesignChanges designChanges, List<DesignChangesCost> designChangesCosts)
    {
        var unitManager = new UnitManager();
        string designChangesCode = "";
        try
        {
            Db.BeginTran();
            designChanges.State = "0";
            designChanges.ItemType = "Cost";
            designChanges.Remark = "";
            designChanges.CheckMan = "";
            designChanges.CheckOpinion = "";
            designChangesCode = unitManager.GetSysCodeValue("DesignChanges");
            designChanges.DesignChangesNumber = GetDesignChangesNumber(designChanges.ProjectCode);
            designChanges.DesignChangesCode = designChangesCode;
            designChanges.TotalMoney = designChanges.TotalCash;
            designChanges.RateTotalMoney = designChanges.RateTotalCash;
            designChanges.NoRateTotalMoney = designChanges.NoRateTotalCash;
            Db.Insertable(designChanges).ExecuteCommand();
            foreach (var item in designChangesCosts)
            {
                item.State = "0";
                item.DesignChangesCostCode = unitManager.GetSysCodeValue("DesignChangesCostCode");
                item.DesignChangesCode = designChangesCode;
                item.Remark = "";
                item.CpId = "";
                item.DesignChangesCostContractPlanCode = "";

                item.RateCheckCash = 0;
                item.RateCheckMoney = 0;
                item.NoRateCheckCash = 0;
                item.NoRateCheckMoney = 0;
                Db.Insertable(item).ExecuteCommand();
            }
            Db.CommitTran();
        }
        catch
        {
            Db.RollbackTran();
            throw;
        }

        return designChangesCode;
    }
    /// <summary>
    /// 更新待审变更主表和明细表
    /// </summary>
    /// <param name="designChanges"></param>
    /// <param name="designChangesCosts"></param>
    /// <returns></returns>
    public ApiResponse UpdateDesignChanges(DesignChanges designChanges, List<DesignChangesCost> designChangesCosts)
    {
        var res = new ApiResponse { IsSuccess = false, ErrMsg = "", Code = 0 };
        var unitManager = new UnitManager();
        var entity = DesignChangesDb.GetById(designChanges.DesignChangesCode);
        if (entity == null)
        {
            res.ErrMsg = "业务单据不存在";
            return res;
        }
        if (entity.State != "0")
        {
            res.ErrMsg = "设计变更状态已变，不能修改";
            return res;
        }
        string designChangesCode = designChanges.DesignChangesCode;
        try
        {
            Db.BeginTran();
            decimal totalCash = 0;
            decimal rateTotalCash = 0;
            decimal noRateTotalCash = 0;

            Db.Deleteable<DesignChangesCost>().Where(m => m.DesignChangesCode == designChangesCode).ExecuteCommand();
            int row = 1;
            foreach (var item in designChangesCosts)
            {
                var sql = $"select Cash from ContractCost where ContractCode = '{designChanges.ContractCode}' and CostBudgetSetCode = '{item.CostBudgetSetCode}' and CostCode = '{item.CostCode}'";
                var cash = Db.Ado.GetString(sql);
                if (cash.IsNullOrEmpty())
                {
                    res.ErrMsg = $"第{row}行费用明细：在合同明细中未查询到相应数据";
                    Db.RollbackTran();
                    return res;
                }
                var newCash = cash.ToDecimal() + item.Cash.Value;
                if (newCash < 0)
                {
                    res.ErrMsg = $"第{row}行费用明细：合同变更的预计金额不能为负数（现在是{newCash}），请修改设计变更金额";
                    Db.RollbackTran();
                    return res;
                }
                decimal paymentCash = unitManager.GetPaymentCashByContractCostCode(item.CostCode, 1);
                if (newCash < paymentCash)
                {
                    res.ErrMsg = $"第{row}行费用明细：合同变更的预计金额不能小于已请款金额（预计金额{newCash}、已请款金额{paymentCash}），请修改设计变更金额";
                    Db.RollbackTran();
                    return res;
                }
                if (item.Cash.Value < 0)  //费用明细小于0时做此判断
                {
                    string hint = "";
                    if (unitManager.IsLowerContractCost(designChanges.ContractCode, false, item.CostBudgetSetCode, item.CostCode, item.Cash.Value, ref hint))
                    {
                        res.ErrMsg = $"第{row}行费用明细： {hint}，请修改设计变更金额";
                        Db.RollbackTran();
                        return res;
                    }
                }
                item.State = "0";
                item.DesignChangesCostCode = unitManager.GetSysCodeValue("DesignChangesCostCode");
                item.DesignChangesCode = designChangesCode;
                item.RateCheckCash = 0;
                item.RateCheckMoney = 0;
                item.NoRateCheckCash = 0;
                item.NoRateCheckMoney = 0;
                item.CpId = "";
                item.DesignChangesCostContractPlanCode = "";
                totalCash += item.Cash.Value;
                rateTotalCash += item.RateCash;
                noRateTotalCash += item.NoRateCash;
                Db.Insertable(item).ExecuteCommand();
                row++;
            }

            entity.DesignChangesName = designChanges.DesignChangesName;
            entity.RequisitionCode = designChanges.RequisitionCode;
            entity.ContractCode = designChanges.ContractCode;
            entity.Rate = designChanges.Rate;
            entity.EstimateCash = designChanges.EstimateCash;
            entity.DesignChangesDate = designChanges.DesignChangesDate;
            entity.ChangeType = designChanges.ChangeType;
            entity.DesignChangesReason = designChanges.DesignChangesReason;
            entity.TotalCash = totalCash;
            entity.TotalMoney = totalCash;
            entity.RateTotalCash = rateTotalCash;
            entity.RateTotalMoney = rateTotalCash;
            entity.NoRateTotalCash = noRateTotalCash;
            entity.NoRateTotalMoney = noRateTotalCash;


            Db.Updateable(entity).UpdateColumns(it => new { it.DesignChangesName, it.RequisitionCode, it.ContractCode, it.Rate, it.TotalCash, it.DesignChangesDate, it.ChangeType, it.DesignChangesReason, it.TotalMoney, it.RateTotalCash, it.RateTotalMoney, it.NoRateTotalCash, it.NoRateTotalMoney, it.ProjectCode, it.MoneyType, it.ExchangeRate, it.Person, it.UnitCode,it.EstimateCash }).ExecuteCommand();

            Db.CommitTran();
        }
        catch
        {
            Db.RollbackTran();
            throw;
        }
        res.IsSuccess = true;
        res.ErrMsg = "";
        res.Data = designChangesCode;
        return res;
    }

    /// <summary>
    /// 获取设计变更编号
    /// </summary>
    /// <returns></returns>
    public string GetDesignChangesNumber(string projectCode)
    {
        var manager = new ConfigItemValueManager();
        var unitManager = new UnitManager();
        var codeRule = manager.GetConfigItemValue("项目管理(项目级)-基本参数-设计变更-编号规则", projectCode);   //获取编码规则
        var codeStart = manager.GetConfigItemValue("项目管理(项目级)-基本参数-设计变更-编号起始编码", projectCode);   //获取编码起始规则
        var syscode = unitManager.GetSysCodeValue($"设计变更编号-{projectCode}");
        var index = codeRule.IndexOf('{');
        var pre = codeRule.Substring(0, index - 1) + "-";
        pre += syscode.PadLeft(4, '0');
        return pre;
    }
}