using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Authorization;

using System.Web;
using MySystem.MainModels;
using LitJson;
using Library;

namespace MySystem.Areas.Api.Controllers.v1
{
    [Area("Api")]
    [Route("Api/v1/[controller]/[action]")]
    public class MerchantQrCodeController : BaseController
    {
        public MerchantQrCodeController(IHttpContextAccessor accessor, ILogger<BaseController> logger, IOptions<Setting> setting) : base(accessor, logger, setting)
        {
        }




        #region 商户-已绑二维码
        [Authorize]
        public JsonResult List(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            List<Dictionary<string, object>> dataList = ListDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList });
        }
        public List<Dictionary<string, object>> ListDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int MerchantId = int.Parse(function.CheckInt(data["MerchantId"].ToString())); //商户
            int PageSize = int.Parse(function.CheckInt(data["PageSize"].ToString()));
            int PageNum = int.Parse(function.CheckInt(data["PageNum"].ToString()));
            List<Dictionary<string, object>> dataList = new List<Dictionary<string, object>>();
            MerchantInfo merchant = MerchantInfoDbconn.Instance.Get(MerchantId) ?? new MerchantInfo();
            IQueryable<MerchantQrCode> query = maindb.MerchantQrCode.Where(m => m.MerchantId == MerchantId && m.QueryCount == 1);
            if (PageNum == 1)
            {
                query = query.Take(PageSize);
            }
            else
            {
                int skipNum = PageSize * (PageNum - 1);
                query = query.Skip(skipNum).Take(PageSize);
            }
            foreach (MerchantQrCode subdata in query.ToList())
            {
                Dictionary<string, object> curData = new Dictionary<string, object>();
                curData.Add("SnNo", subdata.SnNo); //Sn编号
                curData.Add("Id", subdata.Id); //Id
                curData.Add("BindDate", subdata.CreateDate == null ? "" : subdata.CreateDate.Value.ToString("yyyy-MM-dd")); //绑定时间
                curData.Add("MerchantName", merchant.Name); //商户名称
                PosMachines machine = PosMachinesDbconn.Instance.Get(subdata.MachineId) ?? new PosMachines();
                curData.Add("MachineSnNo", machine.PosSn); //音箱SN
                curData.Add("BindFlag", machine.BindingState); //绑定状态
                dataList.Add(curData);
            }
            return dataList;
        }
        #endregion


        #region 商户-绑定收款码
        [Authorize]
        public JsonResult Bind(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = BindDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson BindDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int MerchantId = int.Parse(function.CheckInt(data["MerchantId"].ToString())); //商户
            string SnNo = data["SnNo"].ToString(); //Sn编号
            string MachineNo = data["Machine"].ToString(); //音箱码
            if (SnNo.Length > 20)
            {
                SnNo = System.Web.HttpUtility.UrlDecode(SnNo);
                if (!SnNo.EndsWith("="))
                {
                    SnNo += "=";
                }
                SnNo = dbconn.Decrypt3DES(SnNo, "l2k0b2#3");
                SnNo = SnNo.TrimEnd('\0');
                SnNo = SnNo.Substring(0, 20);
            }
            if(!string.IsNullOrEmpty(MachineNo))
            {
                if (MachineNo.Length > 20)
                {
                    MachineNo = System.Web.HttpUtility.UrlDecode(MachineNo);
                    if (!MachineNo.EndsWith("="))
                    {
                        MachineNo += "=";
                    }
                    MachineNo = dbconn.Decrypt3DES(MachineNo, "l2k0b2#3");
                    MachineNo = MachineNo.TrimEnd('\0');
                    MachineNo = MachineNo.Substring(0, 20);
                }
            }
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            MerchantQrCode query = new MerchantQrCodeService().Query(SnNo);
            PosMachinesTwo pos = new PosMachinesTwoService().Query(SnNo);
            PosMachines machines = new PosMachinesService().Query(SnNo);
            MerchantInfo merchant = new MerchantInfoService().Query(MerchantId);
            if (pos.BindingState == 1)
            {
                return new AppResultJson() { Status = "-1", Info = "此码已被绑定" };
            }
            if (machines.BindingState == 1)
            {
                return new AppResultJson() { Status = "-1", Info = "此码已被绑定" };
            }
            int PosId = 0;
            if (SnNo == MachineNo || string.IsNullOrEmpty(MachineNo))
            {
                if (pos.Id == 0)
                {
                    return new AppResultJson() { Status = "-1", Info = "绑定失败" };
                }
                PosId = pos.Id;
            }
            else if (SnNo != MachineNo)
            {
                if (machines.Id == 0)
                {
                    return new AppResultJson() { Status = "-1", Info = "绑定失败" };
                }
                PosId = machines.Id;
            }
            if (query.Id > 0)
            {
                if (query.MerchantId > 0)
                {
                    return new AppResultJson() { Status = "-1", Info = "此二维码已被绑定，请勿重复绑定" };
                }
            }
            Dictionary<string, object> fields = new Dictionary<string, object>();
            if (SnNo == MachineNo || string.IsNullOrEmpty(MachineNo))
            {
                fields.Add("MerchantId", MerchantId);
                fields.Add("SnNo", SnNo);
                fields.Add("QueryCount", 1);
                new MerchantQrCodeService().Add(fields);
            }
            else
            {
                string DataId = PosId + "_1";
                MachineForQrCode forQrCode = maindb.MachineForQrCode.FirstOrDefault(m => m.DataId == DataId);
                if (forQrCode == null)
                {
                    forQrCode = maindb.MachineForQrCode.Add(new MachineForQrCode(){
                        DataId = DataId,
                        SnNo = SnNo,
                        MachineSnNo = MachineNo,
                        BindDate = DateTime.Now,
                        MerchantId = MerchantId,
                    }).Entity;
                }
                else
                { 
                    forQrCode.SnNo = SnNo;
                    forQrCode.MachineSnNo = MachineNo;
                    forQrCode.BindDate = DateTime.Now;
                    forQrCode.MerchantId = MerchantId;
                }
            }
            maindb.SaveChanges();
            if (SnNo == MachineNo || string.IsNullOrEmpty(MachineNo))
            {
                fields = new Dictionary<string, object>();
                fields.Add("BuyUserId", merchant.UserId);
                fields.Add("UserId", merchant.UserId);
                fields.Add("BindingTime", DateTime.Now);
                fields.Add("BindingState", 1);
                fields.Add("BindMerchantId", MerchantId);
                fields.Add("OpId", 1);
                new PosMachinesTwoService().Edit(fields, pos.Id);
            }
            else if (SnNo != MachineNo && !string.IsNullOrEmpty(MachineNo))
            {
                fields = new Dictionary<string, object>();
                fields.Add("BindMerchantId", MerchantId);
                fields.Add("DeviceKind", "1");
                new PosMachinesService().Edit(fields, machines.Id);
            }
            if (SnNo == MachineNo || string.IsNullOrEmpty(MachineNo))
            {
                PublicFunction.BindUserMachineData(maindb, merchant.UserId, 0, 1, SnNo);
            }
            else
            {
                PublicFunction.BindUserMachineData(maindb, merchant.UserId, 1, 1, SnNo);
            }
            
            return new AppResultJson() { Status = "1", Info = "绑定成功" };
        }
        #endregion


        #region 商户-确认替换音箱码
        [Authorize]
        public JsonResult ConfirmReplace(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = ConfirmReplaceDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson ConfirmReplaceDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int MerchantId = int.Parse(function.CheckInt(data["MerchantId"].ToString())); //商户
            int MachineId = int.Parse(function.CheckInt(data["MachineId"].ToString())); //设备
            int QrCodeId = int.Parse(function.CheckInt(data["QrCodeId"].ToString())); //收款码Id
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            MerchantQrCode query = new MerchantQrCodeService().Query(QrCodeId) ?? new MerchantQrCode();
            PosMachines machine = PosMachinesDbconn.Instance.Get(MachineId) ?? new PosMachines();
            query.MerchantId = MerchantId; //商户
            query.MachineId = MachineId; //设备
            MachineForQrCode qrcode = new MachineForQrCode()
            { 
                MerchantId = MerchantId,
                DataId = QrCodeId + "_" + MachineId,
                BindDate = DateTime.Now,
                SnNo = query.SnNo,
                MachineSnNo = machine.PosSn,
            };
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion


        #region 商户-已绑收款码解除关联
        [Authorize]
        public JsonResult Remove(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = RemoveDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson RemoveDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int MerchantId = int.Parse(function.CheckInt(data["MerchantId"].ToString())); //商户
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            string CheckKey = Id + "_";
            var list = maindb.MachineForQrCode.Select(m => new { m.MerchantId, m.DataId }).Where(m => m.MerchantId == MerchantId && m.DataId.StartsWith(CheckKey)).ToList();
            foreach (var sub in list)
            {
                MachineForQrCode edit = maindb.MachineForQrCode.FirstOrDefault(m => m.DataId == sub.DataId);
                if (edit != null)
                {
                    maindb.MachineForQrCode.Remove(edit);
                    int MachineId = int.Parse(function.CheckInt(edit.DataId.Split('_')[1]));
                    MerchantQrCode qrCode = maindb.MerchantQrCode.FirstOrDefault(m => m.MerchantId == MachineId);
                    if (qrCode != null)
                    {
                        qrCode.MerchantId = 0;
                    }
                }
            }
            maindb.SaveChanges();
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion



        #region 检查签名是否合法，合法返回1，不合法返回提示信息

        /// <summary>
        /// 检查签名是否合法，合法返回1，不合法返回提示信息
        /// </summary>
        /// <param name="value">请求的参数(json字符串)</param>
        /// <param name="signField">要签名的字段</param>
        /// <returns></returns>
        private string CheckSign(string value, string[] signField)
        {
            JsonData json = JsonMapper.ToObject(value);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            for (int i = 0; i < signField.Length; i++)
            {
                dic.Add(signField[i], json[signField[i]].ToString());
            }
            string sign = json["sign"].ToString(); //客户端签名字符串
            return new Sign().sign(dic, sign);
        }

        #endregion

    }
}
