/*
 * 机具损坏换新申请
 */

using System;
using System.Web;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MySystem.Models;
using Library;
using LitJson;
using MySystemLib;

namespace MySystem.Areas.Admin.Controllers
{
    [Area("Admin")]
    [Route("Admin/[controller]/[action]")]
    public class MachineRenewController : BaseController
    {
        public MachineRenewController(IHttpContextAccessor accessor, ILogger<BaseController> logger, IOptions<Setting> setting) : base(accessor, logger, setting)
        {
            OtherMySqlConn.connstr = ConfigurationManager.AppSettings["SqlConnStr"].ToString();
        }

        #region 机具损坏换新申请列表

        /// <summary>
        /// 根据条件查询机具损坏换新申请列表
        /// </summary>
        /// <returns></returns>
        public IActionResult Index(MachineRenew data, string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            return View();
        }

        #endregion

        #region 根据条件查询机具损坏换新申请列表

        /// <summary>
        /// 机具损坏换新申请列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(MachineRenew data, string MakerCode, string RealName, string DamagedSnTypeSelect, string AuditStatusSelect, int page = 1, int limit = 30)
        {

            Dictionary<string, string> Fields = new Dictionary<string, string>();

            Fields.Add("CreateDate", "3"); //机具售后换新申请时间
            Fields.Add("DamagedBrandId", "0"); //损坏的机具产品类型
            Fields.Add("DamagedSnNo", "1"); //创客损坏的机具SN
            Fields.Add("AuditDate", "3"); //审核时间

            string condition = " and Status>-1";
            //创客编号
            if (!string.IsNullOrEmpty(MakerCode))
            {
                condition += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + MakerCode + "')";
            }
            //创客名称
            if (!string.IsNullOrEmpty(RealName))
            {
                condition += " and UserId in (select UserId from UserForRealName where RealName='" + RealName + "')";
            }
            //损坏机具SN类型
            if(!string.IsNullOrEmpty(DamagedSnTypeSelect))
            {
                condition += " and DamagedSnType=" + DamagedSnTypeSelect;
            }
            //审核状态
            if(!string.IsNullOrEmpty(AuditStatusSelect))
            {
                condition += " and AuditStatus=" + AuditStatusSelect;
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("MachineRenew", Fields, "Id desc", "0", page, limit, condition);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                dic["DamagedBrandId"] = RelationClass.GetKqProductBrandInfo(int.Parse(dic["DamagedBrandId"].ToString()));
                dic["ReplaceBrandId"] = RelationClass.GetKqProductBrandInfo(int.Parse(dic["ReplaceBrandId"].ToString()));
                dic["DeliverBrandId"] = RelationClass.GetKqProductBrandInfo(int.Parse(dic["DeliverBrandId"].ToString()));

                int UserId = int.Parse(dic["UserId"].ToString());
                Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["MakerCode"] = user.MakerCode;
                dic["RealName"] = user.RealName;

                int DamagedSnType = int.Parse(dic["DamagedSnType"].ToString());
                if(DamagedSnType == 0) dic["DamagedSnType"] = "兑换机具";
                if(DamagedSnType == 1) dic["DamagedSnType"] = "循环机具";
                
                int ReplaceSnType = int.Parse(dic["ReplaceSnType"].ToString());
                if(ReplaceSnType == 0) dic["ReplaceSnType"] = "兑换机具";
                if(ReplaceSnType == 1) dic["ReplaceSnType"] = "循环机具";
                
                int AuditStatus = int.Parse(dic["AuditStatus"].ToString());
                if(AuditStatus == 0) dic["AuditStatus"] = "未审核";
                if(AuditStatus == 1) dic["AuditStatus"] = "同步循环通过";
                if(AuditStatus == 2) dic["AuditStatus"] = "审核失败";

            }
            return Json(obj);
        }

        #endregion

        #region 增加机具损坏换新申请

        /// <summary>
        /// 增加或修改机具损坏换新申请信息
        /// </summary>
        /// <returns></returns>
        public IActionResult Add(string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;


            return View();
        }

        #endregion

        #region 增加机具损坏换新申请

        /// <summary>
        /// 增加或修改机具损坏换新申请信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Add(MachineRenew data, string MakerCode)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();
            UserForMakerCode user = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == MakerCode);
            if (user == null)
            {
                return "创客编号不存在";
            }
            Fields.Add("ApplyNo", DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8));
            Fields.Add("UserId", data.UserId); //创客
            Fields.Add("DamagedBrandId", data.DamagedBrandId); //损坏的机具产品类型
            Fields.Add("DamagedSnNo", data.DamagedSnNo); //创客损坏的机具SN
            Fields.Add("DamagedSnType", data.DamagedSnType); //损坏的机具SN机具类型
            Fields.Add("ReplaceBrandId", data.ReplaceBrandId); //替换的机具产品类型
            Fields.Add("ReplaceSnNo", data.ReplaceSnNo); //创客机具替换SN
            Fields.Add("ReplaceSnType", data.ReplaceSnType); //替换的机具SN机具类型
            Fields.Add("DeliverBrandId", data.DeliverBrandId); //仓库换新发货的机具产品类型
            Fields.Add("DeliverSnNo", data.DeliverSnNo); //仓库换新发货SN
            Fields.Add("DemandDesc", data.DemandDesc); //售后换新机具处理需求描述
            Fields.Add("UpdateMan", SysUserName); //操作人

            int Id = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Add("MachineRenew", Fields, 0);
            AddSysLog(data.Id.ToString(), "MachineRenew", "add");
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 修改机具损坏换新申请

        /// <summary>
        /// 增加或修改机具损坏换新申请信息
        /// </summary>
        /// <returns></returns>
        public IActionResult Edit(string right, int Id = 0)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;


            MachineRenew editData = db.MachineRenew.FirstOrDefault(m => m.Id == Id) ?? new MachineRenew();
            ViewBag.data = editData;
            return View();
        }

        #endregion

        #region 修改机具损坏换新申请

        /// <summary>
        /// 增加或修改机具损坏换新申请信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(MachineRenew data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();


            Fields.Add("SeoTitle", data.SeoTitle);
            Fields.Add("SeoKeyword", data.SeoKeyword);
            Fields.Add("SeoDescription", data.SeoDescription);
            new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("MachineRenew", Fields, data.Id);
            AddSysLog(data.Id.ToString(), "MachineRenew", "update");
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 删除机具损坏换新申请信息

        /// <summary>
        /// 删除机具损坏换新申请信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "MachineRenew", "del");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("Status", -1);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("MachineRenew", Fields, id);
            }
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 开启

        /// <summary>
        /// 开启
        /// </summary>
        /// <returns></returns>
        public string Open(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "MachineRenew", "open");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("Status", 1);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("MachineRenew", Fields, id);
            }
            db.SaveChanges();
            return "success";
        }

        #endregion

        #region 关闭

        /// <summary>
        /// 关闭
        /// </summary>
        /// <returns></returns>
        public string Close(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "MachineRenew", "close");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("Status", 0);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("MachineRenew", Fields, id);
            }
            db.SaveChanges();
            return "success";
        }

        #endregion

        #region 排序
        /// <summary>
        /// 排序
        /// </summary>
        /// <param name="Id"></param>
        public string Sort(int Id, int Sort)
        {
            new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Sort("MachineRenew", Sort, Id);

            AddSysLog(Id.ToString(), "MachineRenew", "sort");
            return "success";
        }
        #endregion

        #region 导入数据
        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="ExcelData"></param>
        public string Import(string ExcelData)
        {
            ExcelData = HttpUtility.UrlDecode(ExcelData);
            JsonData list = JsonMapper.ToObject(ExcelData);
            for (int i = 1; i < list.Count; i++)
            {
                JsonData dr = list[i];
                string MakerCode = dr[0].ToString(); //创客编号
                int DamagedBrandId = int.Parse(dr[1].ToString()); //损坏的机具产品类型
                string DamagedSnNo = dr[2].ToString(); //创客损坏的机具SN
                int DamagedSnType = int.Parse(dr[3].ToString()); //损坏的机具SN机具类型
                int ReplaceBrandId = int.Parse(dr[4].ToString()); //替换的机具产品类型
                string ReplaceSnNo = dr[5].ToString(); //创客机具替换SN
                int ReplaceSnType = int.Parse(dr[6].ToString()); //替换的机具SN机具类型
                int DeliverBrandId = int.Parse(dr[7].ToString()); //仓库换新发货的机具产品类型
                string DeliverSnNo = dr[8].ToString(); //仓库换新发货SN
                string DemandDesc = dr[9].ToString(); //售后换新机具处理需求描述
                string UpdateMan = dr[10].ToString(); //操作人

                UserForMakerCode user = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == MakerCode);
                if (user == null)
                {
                    return "创客编号" + MakerCode + "不存在";
                }
                db.MachineRenew.Add(new MachineRenew()
                {
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now,
                    ApplyNo = DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8),   //机具售后换新申请订单号
                    ApplyDate = DateTime.Now.ToString("yyyyMMdd"),   //机具售后换新申请时间
                    UserId = user.UserId,   //创客
                    DamagedBrandId = DamagedBrandId,   //损坏的机具产品类型
                    DamagedSnNo = DamagedSnNo,   //创客损坏的机具SN
                    DamagedSnType = DamagedSnType,   //损坏的机具SN机具类型
                    ReplaceBrandId = ReplaceBrandId,   //替换的机具产品类型
                    ReplaceSnNo = ReplaceSnNo,   //创客机具替换SN
                    ReplaceSnType = ReplaceSnType,   //替换的机具SN机具类型
                    DeliverBrandId = DeliverBrandId,   //仓库换新发货的机具产品类型
                    DeliverSnNo = DeliverSnNo,   //仓库换新发货SN
                    DemandDesc = DemandDesc,   //售后换新机具处理需求描述
                });
                db.SaveChanges();
            }
            AddSysLog("0", "MachineRenew", "Import");
            return "success";
        }
        #endregion

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(MachineRenew data, string MakerCode, string RealName, string DamagedSnTypeSelect, string AuditStatusSelect)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();

            Fields.Add("CreateDate", "3"); //机具售后换新申请时间
            Fields.Add("DamagedBrandId", "0"); //损坏的机具产品类型
            Fields.Add("DamagedSnNo", "1"); //创客损坏的机具SN
            Fields.Add("AuditDate", "3"); //审核时间

            string condition = " and Status>-1";
            //创客编号
            if (!string.IsNullOrEmpty(MakerCode))
            {
                condition += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + MakerCode + "')";
            }
            //创客名称
            if (!string.IsNullOrEmpty(RealName))
            {
                condition += " and UserId in (select UserId from UserForRealName where RealName='" + RealName + "')";
            }
            //损坏机具SN类型
            if(!string.IsNullOrEmpty(DamagedSnTypeSelect))
            {
                condition += " and DamagedSnType=" + DamagedSnTypeSelect;
            }
            //审核状态
            if(!string.IsNullOrEmpty(AuditStatusSelect))
            {
                condition += " and AuditStatus=" + AuditStatusSelect;
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("MachineRenew", Fields, "Id desc", "0", 1, 20000, condition, "ApplyNo,ApplyDate,UserId,DamagedBrandId,DamagedSnNo,DamagedSnType,ReplaceBrandId,ReplaceSnNo,ReplaceSnType,DeliverBrandId,DeliverSnNo,DemandDesc,AuditStatus,AuditDesc,AuditDate,UpdateMan", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                dic["DamagedBrandId"] = RelationClass.GetKqProductBrandInfo(int.Parse(dic["DamagedBrandId"].ToString()));
                dic["ReplaceBrandId"] = RelationClass.GetKqProductBrandInfo(int.Parse(dic["ReplaceBrandId"].ToString()));
                dic["DeliverBrandId"] = RelationClass.GetKqProductBrandInfo(int.Parse(dic["DeliverBrandId"].ToString()));

                int UserId = int.Parse(dic["UserId"].ToString());
                Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["MakerCode"] = user.MakerCode;
                dic["RealName"] = user.RealName;

                int DamagedSnType = int.Parse(dic["DamagedSnType"].ToString());
                if(DamagedSnType == 0) dic["DamagedSnType"] = "兑换机具";
                if(DamagedSnType == 1) dic["DamagedSnType"] = "循环机具";
                
                int ReplaceSnType = int.Parse(dic["ReplaceSnType"].ToString());
                if(ReplaceSnType == 0) dic["ReplaceSnType"] = "兑换机具";
                if(ReplaceSnType == 1) dic["ReplaceSnType"] = "循环机具";
                
                int AuditStatus = int.Parse(dic["AuditStatus"].ToString());
                if(AuditStatus == 0) dic["AuditStatus"] = "未审核";
                if(AuditStatus == 1) dic["AuditStatus"] = "同步循环通过";
                if(AuditStatus == 2) dic["AuditStatus"] = "审核失败";

                dic.Remove("UserId");
            }

            Dictionary<string, object> result = new Dictionary<string, object>();
            result.Add("Status", "1");
            result.Add("Info", "Excel报表-" + DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss") + ".xlsx");
            result.Add("Obj", diclist);
            Dictionary<string, object> ReturnFields = new Dictionary<string, object>();
            ReturnFields.Add("ApplyNo", "机具售后换新申请订单号");
            ReturnFields.Add("MakerCode", "创客编号");
            ReturnFields.Add("RealName", "创客名称");
            ReturnFields.Add("DamagedBrandId", "损坏的机具产品名称");
            ReturnFields.Add("DamagedSnNo", "损坏的机具SN");
            ReturnFields.Add("DamagedSnType", "损坏的机具SN机具类型");
            ReturnFields.Add("ReplaceBrandId", "替换机具产品名称");
            ReturnFields.Add("ReplaceSnNo", "创客机具替换SN");
            ReturnFields.Add("ReplaceSnType", "替换的机具SN机具类型");
            ReturnFields.Add("DeliverBrandId", "仓库换新发货机具产品名称");
            ReturnFields.Add("DeliverSnNo", "仓库换新发货SN");
            ReturnFields.Add("DemandDesc", "售后换新机具处理需求描述");
            ReturnFields.Add("CreateDate", "机具售后换新申请时间");
            ReturnFields.Add("AuditStatus", "同步循环状态");
            ReturnFields.Add("AuditDesc", "机具售后换新审核描述");
            ReturnFields.Add("AuditDate", "同步循环时间");
            ReturnFields.Add("UpdateMan", "操作人员");

            result.Add("Fields", ReturnFields);
            AddSysLog("0", "MachineRenew", "ExportExcel");
            return Json(result);
        }

        #endregion

    }
}
