using Sugar.Enties;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;

public class AttachMentManager : DbContext<AttachMent>
{

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

    //这里面写的代码不会给覆盖,如果要重新生成请删除 AttachMentManager.cs
    /// <summary>
    /// 存储模式
    /// </summary>
    private AttachmentSaveMode _SaveMode;

    /// <summary>
    /// 文件目录模式
    /// </summary>
    private AttachmentSavePathMode _SavePathMode;
    /// <summary>
    /// 文件存储目录 
    /// </summary>
    private string _Path;

    public AttachMentManager()
    {
        var configitemManager = new ConfigItemValueManager();
        string itemLower = configitemManager.GetConfigItemValue("基础模块-附件存储设置-存储模式");
        _Path = configitemManager.GetConfigItemValue("基础模块-附件存储设置-文件存储目录");
        if (itemLower != null && itemLower == "file")
        {
            _SaveMode = AttachmentSaveMode.file;
            if (_Path == null || _Path == "")
            {
                throw new Exception("未定义文档存储目录，请检查附件存储路径参数配置");
            }
            try
            {
                if (!Directory.Exists(_Path))
                {
                    Directory.CreateDirectory(_Path);
                }
            }
            catch
            {
                throw new Exception("文档存储目录有误，请检查附件存储路径参数配置");
            }
        }
        else
        {
            _SaveMode = AttachmentSaveMode.database;
        }
        string itemLower2 = configitemManager.GetConfigItemValue("基础模块-附件存储设置-文件目录模式");
        try
        {
            _SavePathMode = (AttachmentSavePathMode)Enum.Parse(typeof(AttachmentSavePathMode), itemLower2.ToUpper());
        }
        catch
        {
            _SavePathMode = AttachmentSavePathMode.ROOT;
        }
    }

    /// <summary>
    /// 插入附件
    /// </summary>
    /// <param name="attachMent"></param>
    /// <returns></returns>
    public int InsertAttachMent(AttachMent attachMent)
    {
        var row = Db.Insertable<AttachMent>(attachMent).ExecuteCommand();
        return row;
    }
    /// <summary>
    /// 更新附件
    /// </summary>
    /// <param name="attachMent"></param>
    /// <returns></returns>
    public int UpdateAttachMent(AttachMent attachMent)
    {
        var row = Db.Updateable(attachMent).ExecuteCommand();
        return row;
    }
    /// <summary>
    /// 根据主键判定重复记录是否存在
    /// </summary>
    /// <param name="attachMentCode"></param>
    /// <returns></returns>
    public bool IsExist(string attachMentCode)
    {
        string sql = $"select attachMentCode from AttachMent where attachMentCode='{attachMentCode}'";
        var str = Db.Ado.GetString(sql);
        if (string.IsNullOrEmpty(str))
        {
            return false;
        }
        return true;
    }
    /// <summary>
    /// 添加或更新附件表
    /// </summary>
    /// <param name="attachMent"></param>
    /// <returns></returns>
    public string AddOrUpdate(AttachMent attachMent)
    {
        if (!IsExist(attachMent.AttachMentCode))
        {
            string sql = $"SELECT attachmentcode FROM AttachMent WHERE MasterCode='{attachMent.MasterCode}' AND FileName='{attachMent.FileName}' AND AttachMentType='{attachMent.AttachMentType}' ";
            var code = Db.Ado.GetString(sql);
            if (!string.IsNullOrEmpty(code))   //存在重复，则删除
            {
                AttachMentDb.Delete(m => m.AttachMentCode == code);
            }
            attachMent.AttachMentCode = new SysCodeManager().GetSysCodeValue("AttachMentCode");
            attachMent.CreateDate = DateTime.Now;
            InsertAttachMent(attachMent);
        }

        return attachMent.AttachMentCode;
    }
    public List<AttachMent> FixedListAttachment(List<AttachMent> list)
    {
        foreach (var item in list)
        {

            if (_SaveMode == AttachmentSaveMode.database)   //数据库模式，附件存入数据库
            {
                item.GuidName = null;
            }
            else      //文件模式，存入文件
            {
                item.GuidName = Guid.NewGuid().ToString();
                item.Content = null;
                //SaveFile(length, array, guidname, dataRow["CreateDate"].ToString());
            }
        }
        return list;

    }


    public AttachMent GetAttachMent(string code)
    {
        var model = Db.Queryable<AttachMent>().Where(m => m.AttachMentCode == code).First();
        return model;
    }

    #region 教学方法
    /// <summary>
    /// 如果DbContext中的增删查改方法满足不了你，你可以看下具体用法
    /// </summary>
    public void Study()
    {

        /*********查询*********/

        var data1 = AttachMentDb.GetById(1);//根据ID查询
        var data2 = AttachMentDb.GetList();//查询所有
        var data3 = AttachMentDb.GetList(it => 1 == 1);  //根据条件查询  
        //var data4 = AttachMentDb.GetSingle(it => 1 == 1);//根据条件查询一条,如果超过一条会报错

        var p = new PageModel() { PageIndex = 1, PageSize = 2 };// 分页查询
        var data5 = AttachMentDb.GetPageList(it => 1 == 1, p);
        Console.Write(p.PageCount);//返回总数

        var data6 = AttachMentDb.GetPageList(it => 1 == 1, p, it => SqlFunc.GetRandom(), OrderByType.Asc);// 分页查询加排序
        Console.Write(p.PageCount);//返回总数

        List<IConditionalModel> conModels = new List<IConditionalModel>(); //组装条件查询作为条件实现 分页查询加排序
        conModels.Add(new ConditionalModel() { FieldName = typeof(AttachMent).GetProperties()[0].Name, ConditionalType = ConditionalType.Equal, FieldValue = "1" });//id=1
        var data7 = AttachMentDb.GetPageList(conModels, p, it => SqlFunc.GetRandom(), OrderByType.Asc);

        AttachMentDb.AsQueryable().Where(x => 1 == 1).ToList();//支持了转换成queryable,我们可以用queryable实现复杂功能

        //我要用事务
        var result = Db.Ado.UseTran(() =>
         {
             //写事务代码
         });
        if (result.IsSuccess)
        {
            //事务成功
        }

        //多表查询地址 http://www.codeisbug.com/Doc/8/1124



        /*********插入*********/
        var insertData = new AttachMent() { };//测试参数
        var insertArray = new AttachMent[] { insertData };
        AttachMentDb.Insert(insertData);//插入
        AttachMentDb.InsertRange(insertArray);//批量插入
        var id = AttachMentDb.InsertReturnIdentity(insertData);//插入返回自增列
        AttachMentDb.AsInsertable(insertData).ExecuteCommand();//我们可以转成 Insertable实现复杂插入



        /*********更新*********/
        var updateData = new AttachMent() { };//测试参数
        var updateArray = new AttachMent[] { updateData };//测试参数
        AttachMentDb.Update(updateData);//根据实体更新
        AttachMentDb.UpdateRange(updateArray);//批量更新
        //AttachMentDb.Update(it => new AttachMent() { Name = "a", CreateTime = DateTime.Now }, it => it.id==1);// 只更新Name列和CreateTime列，其它列不更新，条件id=1
        AttachMentDb.AsUpdateable(updateData).ExecuteCommand();



        /*********删除*********/
        var deldata = new AttachMent() { };//测试参数
        AttachMentDb.Delete(deldata);//根据实体删除
        AttachMentDb.DeleteById(1);//根据主键删除
        AttachMentDb.DeleteById(new int[] { 1, 2 });//根据主键数组删除
        AttachMentDb.Delete(it => 1 == 2);//根据条件删除
        AttachMentDb.AsDeleteable().Where(it => 1 == 2).ExecuteCommand();//转成Deleteable实现复杂的操作
    }
    #endregion



}
