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.Models.Main;
using LitJson;
using Library;
using MySystem.Service.Main;

namespace MySystem.Areas.Api.Controllers.v1
{
    [Area("Api")]
    [Route("Api/v1/[controller]/[action]")]
    public class MerchantQrCodeController : BaseController
    {
        public MerchantQrCodeController(IHttpContextAccessor accessor) : base(accessor)
        {
        }




        #region 商户-已绑二维码
        // [Authorize]
        public JsonResult List(string value)
        {
            value = DesDecrypt(value);
            value = value.Replace("null", "\"\"");
            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.getItem("MerchantId").ToString())); //商户
            int PageSize = int.Parse(function.CheckInt(data.getItem("PageSize").ToString()));
            int PageNum = int.Parse(function.CheckInt(data.getItem("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 == 2);
            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); //商户名称
                Models.Main1.PosMachines machine = PosMachinesDbconn.Instance.Get(subdata.MachineId) ?? new Models.Main1.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);
            value = value.Replace("null", "\"\"");
            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.getItem("MerchantId").ToString())); //商户
            string SnNo = data.getItem("SnNo").ToString(); //Sn编号
            string MachineNo = data.getItem("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 = MerchantQrCodeService.Query(" SnNo='" + SnNo + "'");
            Models.Main1.PosMachinesTwo pos = PosMachinesTwoService.Query(" PosSn='" + SnNo + "'");
            Models.Main1.PosMachines machines = PosMachinesService.Query(" PosSn='" + SnNo + "'");
            MerchantInfo merchant = 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", 2);
                MerchantQrCodeService.Add(fields);
            }
            else
            {
                string DataId = PosId + "_2";
                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", 2);
                fields.Add("QueryCount", 2);
                PosMachinesTwoService.Edit(fields, pos.Id, false);
            }
            else if (SnNo != MachineNo && !string.IsNullOrEmpty(MachineNo))
            {
                //通过sn获取设备号
                // string result = AliIotFunction.Instance.IotDeviceQuery(MachineNo);
                // JsonData jsonObj = JsonMapper.ToObject(result);
                // if(jsonObj["alipay_commerce_iot_device_baseinfo_query_response"]["code"].ToString() == "10000")
                // {
                // string deviceId = jsonObj["alipay_commerce_iot_device_baseinfo_query_response"]["device_id"].ToString();
                if (machines.BrandId == 1)
                {
                    MerchantAddInfo addinfo = MerchantAddInfoService.Query(MerchantId);
                    //通过商户smid(好哒认证成功后台提供)绑定支付宝设备
                    var result = AliIotFunction.Instance.IotBind(addinfo.AliMerchantId, MachineNo);
                    JsonData jsonObj = JsonMapper.ToObject(result);
                    if (jsonObj["alipay_merchant_indirect_iot_bind_response"]["code"].ToString() == "10000")
                    {
                        fields = new Dictionary<string, object>();
                        fields.Add("BindingTime", DateTime.Now);
                        fields.Add("BuyUserId", merchant.UserId);
                        fields.Add("UserId", merchant.UserId);
                        fields.Add("BindingState", 1);
                        fields.Add("BindMerchantId", MerchantId);
                        fields.Add("DeviceKind", "2");
                        PosMachinesService.Edit(fields, machines.Id, false);
                    }
                }
                else
                {
                    fields = new Dictionary<string, object>();
                    fields.Add("BindingTime", DateTime.Now);
                    fields.Add("BuyUserId", merchant.UserId);
                    fields.Add("UserId", merchant.UserId);
                    fields.Add("BindingState", 1);
                    fields.Add("BindMerchantId", MerchantId);
                    fields.Add("DeviceKind", "2");
                    PosMachinesService.Edit(fields, machines.Id, false);
                }
                // }
            }
            //码牌
            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);
            value = value.Replace("null", "\"\"");
            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.getItem("MerchantId").ToString())); //商户
            int MachineId = int.Parse(function.CheckInt(data.getItem("MachineId").ToString())); //设备
            int QrCodeId = int.Parse(function.CheckInt(data.getItem("QrCodeId").ToString())); //收款码Id
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            MerchantQrCode query = MerchantQrCodeService.Query(QrCodeId) ?? new MerchantQrCode();
            Models.Main1.PosMachines machine = PosMachinesDbconn.Instance.Get(MachineId) ?? new Models.Main1.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);
            value = value.Replace("null", "\"\"");
            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.getItem("MerchantId").ToString())); //商户
            int Id = int.Parse(function.CheckInt(data.getItem("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)
                {
                    if (edit.SnNo != edit.MachineSnNo)
                    {
                        MerchantAddInfo addinfo = MerchantAddInfoService.Query(edit.MerchantId);
                        Models.Main1.PosMachines machine = PosMachinesService.Query(" PosSn='" + edit.MachineSnNo + "'");
                        string result = AliIotFunction.Instance.IotUnBind(addinfo.AliMerchantId, machine.PosSn);
                        JsonData jsonObj = JsonMapper.ToObject(result);
                        if (jsonObj["alipay_merchant_indirect_iot_unbind_response"]["code"].ToString() == "10000")
                        {
                            Dictionary<string, object> fields = new Dictionary<string, object>();
                            fields.Add("BuyUserId", 0);
                            fields.Add("UserId", 0);
                            fields.Add("BindingTime", DateTime.Parse("1900-01-01"));
                            fields.Add("BindingState", 0);
                            fields.Add("BindMerchantId", 0);
                            PosMachinesService.Edit(fields, machine.Id, false);
                        }
                    }
                    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

    }
}
