using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using static DbTableClass;
using static resultClass;
using System.Data.SqlClient;
using Dapper.Contrib.Extensions;
using Dapper;
using Newtonsoft.Json;

namespace QuotationMaker.Controllers
{
    [Route("AuthApi")]
    public class AuthApiController : ControllerBase
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        DbConn dbConn = new DbConn();
        SqlConnection conn = new SqlConnection(GlobalClass.appsettings("ConnectionStrings:SQLConnectionString"));
        SqlConnection elabConn = new SqlConnection(GlobalClass.appsettings("ConnectionStrings:ElabConnectionString"));

        public AuthApiController(IHttpContextAccessor httpContextAccessor)
        {
            this._httpContextAccessor = httpContextAccessor;
        }

        [Route("authModelQuotationList")]
        public ActionResult AuthModelQuotationList(IFormCollection obj) {
            modelQuotationResult ret = new modelQuotationResult();

            authToken token = new authToken(this._httpContextAccessor);
            if (token.user_isLogin == false)
            {
                HttpContext.Response.Cookies.Delete("token_key");
                ret.ret = "no";
                ret.err_code = "99999";
                ret.message = "非登入狀態!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (token.user_perm != "system")
            {
                ret.ret = "no";
                ret.err_code = "90001";
                ret.message = "此帳號無此api使用權限!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            string dept_uid = obj["dept_uid"].ToString();
            string modelProj_uid = obj["modelProj_uid"].ToString();

            List<modelQuotation> modelQuotations = conn.Query<modelQuotation>("select * from modelQuotation where dept_uid = @dept_uid and modelProj_uid = @modelProj_uid", new { dept_uid = dept_uid, modelProj_uid  = modelProj_uid }).ToList();

            foreach (modelQuotation modelQuotation in modelQuotations) { 
             ret.modelQuotationDetails.Add(new modelQuotationDetail(modelQuotation));
            }

            ret.ret = "yes";
            return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
        }

        [Route("addEditDelGetModelQuotation")]
        public ActionResult AddEditDelGetModelQuotation(IFormCollection obj)
        {
            modelQuotationResult ret = new modelQuotationResult();

            authToken token = new authToken(this._httpContextAccessor);
            if (token.user_isLogin == false)
            {
                HttpContext.Response.Cookies.Delete("token_key");
                ret.ret = "no";
                ret.err_code = "99999";
                ret.message = "非登入狀態!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (token.user_perm != "system")
            {
                ret.ret = "no";
                ret.err_code = "90001";
                ret.message = "此帳號無此api使用權限!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            string method = obj["method"].ToString();
            string dept_uid = obj["dept_uid"].ToString();
            string modelProj_uid = obj["modelProj_uid"].ToString();
            string modelQuotation_uid = obj["modelQuotation_uid"].ToString();
            string modelQuotation_name = obj["modelQuotation_name"].ToString();
            string mainItemsJsonTxt = obj["mainItemsJson"].ToString();
            string deledMainItemsJsonTxt = obj["deledMainItemsJson"].ToString();
            string deledSubItemsJsonTxt = obj["deledSubItemsJson"].ToString(); 

            if (method == "")
            {
                ret.ret = "no";
                ret.err_code = "0001";
                ret.message = "沒有method!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }



            if (dept_uid.Trim() == "")
            {
                ret.ret = "no";
                ret.err_code = "0003";
                ret.message = "沒有dept_uid!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (modelProj_uid.Trim() == "")
            {
                ret.ret = "no";
                ret.err_code = "0003";
                ret.message = "沒有modelProj_uid!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (method == "add") {
                modelQuotation_uid = GlobalClass.CreateRandomCode(24);

                dynamic mainItemsJson;
                dynamic deledMainItemsJson;
                dynamic deledSubItemsJson;

                try
                {
                    mainItemsJson = JsonConvert.DeserializeObject(mainItemsJsonTxt);
                    deledMainItemsJson = JsonConvert.DeserializeObject(deledMainItemsJsonTxt);
                    deledSubItemsJson = JsonConvert.DeserializeObject(deledSubItemsJsonTxt);

                }
                catch (Exception ex)
                {
                    ret.ret = "no";
                    ret.err_code = "0003";
                    ret.message = "json error," + ex.Message;
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                List<modelMainItem> modelMainItems = new List<modelMainItem>();
                List<modelSubItem> newModelSubItems = new List<modelSubItem>();

                foreach (dynamic item in mainItemsJson)
                {
                    string mainItem_uid = item.mainItem_uid;
                    string modelMainItem_uid = item.modelMainItem_uid;
                    modelMainItem_uid = GlobalClass.CreateRandomCode(24);

                    string modelMainItem_name = item.modelMainItem_name;
                    string modelMainItem_ac = item.modelMainItem_ac;

                    modelMainItem newModelMainItem = new modelMainItem();

                    if (modelMainItem_ac == "") {
                        modelMainItem_ac = "0";
                    }

                    newModelMainItem.mainItem_uid = mainItem_uid;
                    newModelMainItem.modelMainItem_uid = modelMainItem_uid;
                    newModelMainItem.modelMainItem_name = modelMainItem_name;
                    newModelMainItem.modelMainItem_ac = double.Parse(modelMainItem_ac);
                    newModelMainItem.modelQuotation_uid = modelQuotation_uid;
                    newModelMainItem.modelMainItem_lastModify_uid = token.user_uid;

                    double acValue = double.Parse(modelMainItem_ac) / 100;
                    double total = 0;

                    foreach (dynamic subItem in item.subItems) { 
                        string subItem_method = subItem.method;
                        string modelSubItem_uid = subItem.modelSubItem_uid;
                        modelSubItem_uid = GlobalClass.CreateRandomCode(24);
                        string modelSubItem_name = subItem.modelSubItem_name;
                        string modelSubItem_descript = subItem.modelSubItem_descript;
                        
                        double modelSubItem_price = double.Parse(Convert.ToString(subItem.modelSubItem_price));
                        string modelSubItem_unitType = subItem.modelSubItem_unitType;
                        double modelSubItem_number = double.Parse(Convert.ToString(subItem.modelSubItem_number));
                        double modelSubItem_subTotal = double.Parse(Convert.ToString(subItem.modelSubItem_subTotal));
                        string modelSubItem_hasAC = subItem.modelSubItem_hasAC;

                        if (modelSubItem_hasAC == "Y")
                        {
                            total += modelSubItem_subTotal * (1 + acValue);
                        }
                        else {
                            total += modelSubItem_subTotal;
                        }

                        modelSubItem newModelSubItem = new modelSubItem();
                        newModelSubItem.modelMainItem_uid = modelMainItem_uid;
                        newModelSubItem.modelSubItem_uid = modelSubItem_uid;
                        newModelSubItem.modelSubItem_name = modelSubItem_name;
                        newModelSubItem.modelSubItem_descript = modelSubItem_descript;
                        newModelSubItem.modelSubItem_price = modelSubItem_price;
                        newModelSubItem.modelSubItem_number = modelSubItem_number;
                        newModelSubItem.modelSubItem_subTotal = modelSubItem_subTotal;
                        newModelSubItem.modelSubItem_unitType = modelSubItem_unitType;
                        newModelSubItem.modelSubItem_hasAC = modelSubItem_hasAC;
                        newModelSubItem.modelSubItem_lastModify_uid = token.user_uid;

                        newModelSubItems.Add(newModelSubItem);
                    }

                    newModelMainItem.modelMainItem_subTotal = total;

                    modelMainItems.Add(newModelMainItem);

                    
                }

                modelQuotation newQuotation = new modelQuotation();
                newQuotation.modelQuotation_uid = modelQuotation_uid;
                newQuotation.dept_uid = dept_uid;
                newQuotation.modelProj_uid = modelProj_uid;
                newQuotation.modelQuotation_name = modelQuotation_name;
                newQuotation.modelQuotation_lastmodify_uid = token.user_uid;

                conn.Insert(newModelSubItems);
                conn.Insert(modelMainItems);
                conn.Insert(newQuotation);

                ret.modelQuotationDetails.Add(new modelQuotationDetail(newQuotation));
                ret.ret = "yes";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (modelQuotation_uid.Trim() == "")
            {
                ret.ret = "no";
                ret.err_code = "0002";
                ret.message = "沒有modelQuotation_uid!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            modelQuotation modelQuotation = conn.QueryFirstOrDefault<modelQuotation>("select * from modelQuotation where modelQuotation_uid = @modelQuotation_uid ", new { modelQuotation_uid = modelQuotation_uid });

            if (method == "get") {
                if (modelQuotation == null) {
                    ret.ret = "no";
                    ret.err_code = "0009";
                    ret.message = "沒有此modelQuotation_uid資料!";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                ret.modelQuotationDetails.Add(new modelQuotationDetail(modelQuotation));
                ret.ret = "yes";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (method == "edit") {
                if (modelQuotation == null)
                {
                    ret.ret = "no";
                    ret.err_code = "0009";
                    ret.message = "沒有此modelQuotation_uid資料!";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                modelQuotation.modelQuotation_name = modelQuotation_name;
                modelQuotation.modelQuotation_lastmodify_uid = token.user_uid;
                modelQuotation.modelQuotation_modifydate = DateTime.Now;

                dynamic mainItemsJson;
                dynamic deledMainItemsJson;
                dynamic deledSubItemsJson;

                try
                {
                    mainItemsJson = JsonConvert.DeserializeObject(mainItemsJsonTxt);
                    deledMainItemsJson = JsonConvert.DeserializeObject(deledMainItemsJsonTxt);
                    deledSubItemsJson = JsonConvert.DeserializeObject(deledSubItemsJsonTxt);

                }
                catch (Exception ex)
                {
                    ret.ret = "no";
                    ret.err_code = "0003";
                    ret.message = "json error," + ex.Message;
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                foreach (dynamic item in deledSubItemsJson) {
                    string modelSubItem_uid = item.modelSubItem_uid;

                    conn.Execute("delete modelSubItem where modelSubItem_uid = @modelSubItem_uid", new { modelSubItem_uid = modelSubItem_uid });

                }

                foreach (dynamic item in deledMainItemsJson) {
                    string modelMainItem_uid = item.modelMainItem_uid;

                    conn.Execute("delete modelMainItem where modelMainItem_uid = @modelMainItem_uid", new { modelMainItem_uid = modelMainItem_uid });
                    conn.Execute("delete modelSubItem where modelMainItem_uid = @modelMainItem_uid", new { modelMainItem_uid = modelMainItem_uid });
                }

                foreach (dynamic item in mainItemsJson)
                {
                    string mainItem_method = item.method;
                    string mainItem_uid = item.mainItem_uid;
                    string modelMainItem_uid = item.modelMainItem_uid;
                    

                    string modelMainItem_name = item.modelMainItem_name;
                    string modelMainItem_ac = item.modelMainItem_ac;

                    if (modelMainItem_ac == "") {
                        modelMainItem_ac = "0";
                    }


                    if (mainItem_method == "add") {
                        modelMainItem_uid = GlobalClass.CreateRandomCode(24);

                        modelMainItem newModelMainItem = new modelMainItem();

                        newModelMainItem.mainItem_uid = mainItem_uid;
                        newModelMainItem.modelMainItem_uid = modelMainItem_uid;
                        newModelMainItem.modelMainItem_name = modelMainItem_name;
                        newModelMainItem.modelMainItem_ac = double.Parse(modelMainItem_ac);
                        newModelMainItem.modelQuotation_uid = modelQuotation_uid;
                        newModelMainItem.modelMainItem_lastModify_uid = token.user_uid;

                        double acValue = double.Parse(modelMainItem_ac) / 100;
                        double total = 0;

                        foreach (dynamic subItem in item.subItems)
                        {
                            string subItem_method = subItem.method;
                            string modelSubItem_uid = subItem.modelSubItem_uid;
                            modelSubItem_uid = GlobalClass.CreateRandomCode(24);
                            string modelSubItem_name = subItem.modelSubItem_name;
                            string modelSubItem_descript = subItem.modelSubItem_descript;

                            double modelSubItem_price = double.Parse(Convert.ToString(subItem.modelSubItem_price));
                            string modelSubItem_unitType = subItem.modelSubItem_unitType;
                            double modelSubItem_number = double.Parse(Convert.ToString(subItem.modelSubItem_number));
                            double modelSubItem_subTotal = double.Parse(Convert.ToString(subItem.modelSubItem_subTotal));
                            string modelSubItem_hasAC = subItem.modelSubItem_hasAC;

                            if (modelSubItem_hasAC == "Y")
                            {
                                total += modelSubItem_subTotal * (1 + acValue);
                            }
                            else
                            {
                                total += modelSubItem_subTotal;
                            }

                            modelSubItem newModelSubItem = new modelSubItem();
                            newModelSubItem.modelMainItem_uid = modelMainItem_uid;
                            newModelSubItem.modelSubItem_uid = modelSubItem_uid;
                            newModelSubItem.modelSubItem_name = modelSubItem_name;
                            newModelSubItem.modelSubItem_descript = modelSubItem_descript;
                            newModelSubItem.modelSubItem_price = modelSubItem_price;
                            newModelSubItem.modelSubItem_number = modelSubItem_number;
                            newModelSubItem.modelSubItem_subTotal = modelSubItem_subTotal;
                            newModelSubItem.modelSubItem_unitType = modelSubItem_unitType;
                            newModelSubItem.modelSubItem_hasAC = modelSubItem_hasAC;
                            newModelSubItem.modelSubItem_lastModify_uid = token.user_uid;

                            conn.Insert(newModelSubItem);
                        }

                        newModelMainItem.modelMainItem_subTotal = total;

                        conn.Insert(newModelMainItem);
                    }

                    if (mainItem_method == "edit") {
                        modelMainItem editModelMainItem = conn.QueryFirstOrDefault<modelMainItem>("select * from modelMainItem where modelMainItem_uid = @modelMainItem_uid", new { modelMainItem_uid  = modelMainItem_uid });

                        if (editModelMainItem != null) {
                            editModelMainItem.mainItem_uid = mainItem_uid;
                            editModelMainItem.modelMainItem_uid = modelMainItem_uid;
                            editModelMainItem.modelMainItem_name = modelMainItem_name;
                            editModelMainItem.modelMainItem_ac = double.Parse(modelMainItem_ac);
                            editModelMainItem.modelQuotation_uid = modelQuotation_uid;
                            editModelMainItem.modelMainItem_lastModify_uid = token.user_uid;
                            editModelMainItem.modelMainItem_modifydate = DateTime.Now;

                            double acValue = double.Parse(modelMainItem_ac) / 100;
                            double total = 0;

                            foreach (dynamic subItem in item.subItems)
                            {
                                string subItem_method = subItem.method;
                                string modelSubItem_uid = subItem.modelSubItem_uid;
                                string modelSubItem_name = subItem.modelSubItem_name;
                                string modelSubItem_descript = subItem.modelSubItem_descript;

                                double modelSubItem_price = double.Parse(Convert.ToString(subItem.modelSubItem_price));
                                string modelSubItem_unitType = subItem.modelSubItem_unitType;
                                double modelSubItem_number = double.Parse(Convert.ToString(subItem.modelSubItem_number));
                                double modelSubItem_subTotal = double.Parse(Convert.ToString(subItem.modelSubItem_subTotal));
                                string modelSubItem_hasAC = subItem.modelSubItem_hasAC;

                                if (modelSubItem_hasAC == "Y")
                                {
                                    total += modelSubItem_subTotal * (1 + acValue);
                                }
                                else
                                {
                                    total += modelSubItem_subTotal;
                                }

                                if (subItem_method == "add") {
                                    
                                    modelSubItem_uid = GlobalClass.CreateRandomCode(24);
                                    

                                    modelSubItem newModelSubItem = new modelSubItem();
                                    newModelSubItem.modelMainItem_uid = modelMainItem_uid;
                                    newModelSubItem.modelSubItem_uid = modelSubItem_uid;
                                    newModelSubItem.modelSubItem_name = modelSubItem_name;
                                    newModelSubItem.modelSubItem_descript = modelSubItem_descript;
                                    newModelSubItem.modelSubItem_price = modelSubItem_price;
                                    newModelSubItem.modelSubItem_number = modelSubItem_number;
                                    newModelSubItem.modelSubItem_subTotal = modelSubItem_subTotal;
                                    newModelSubItem.modelSubItem_unitType = modelSubItem_unitType;
                                    newModelSubItem.modelSubItem_hasAC = modelSubItem_hasAC;
                                    newModelSubItem.modelSubItem_lastModify_uid = token.user_uid;

                                    conn.Insert(newModelSubItem);
                                }

                                if (subItem_method == "edit") {
                                    

                                    modelSubItem editSubItem = conn.QueryFirstOrDefault<modelSubItem>("select * from modelSubItem where modelSubItem_uid = @modelSubItem_uid ", new { modelSubItem_uid = modelSubItem_uid });

                                    if (editSubItem != null) {
                                        
                                        editSubItem.modelMainItem_uid = modelMainItem_uid;
                                        editSubItem.modelSubItem_name = modelSubItem_name;
                                        editSubItem.modelSubItem_descript = modelSubItem_descript;
                                        editSubItem.modelSubItem_price = modelSubItem_price;
                                        editSubItem.modelSubItem_number = modelSubItem_number;
                                        editSubItem.modelSubItem_subTotal = modelSubItem_subTotal;
                                        editSubItem.modelSubItem_unitType = modelSubItem_unitType;
                                        editSubItem.modelSubItem_hasAC = modelSubItem_hasAC;
                                        editSubItem.modelSubItem_lastModify_uid = token.user_uid;
                                        editSubItem.modelSubItem_modifydate = DateTime.Now;

                                        conn.Update(editSubItem);
                                    }
                                }
                                
                            }

                            editModelMainItem.modelMainItem_subTotal = total;

                            conn.Update(editModelMainItem);
                        }
                    }
                }

                conn.Update(modelQuotation);

                ret.modelQuotationDetails.Add(new modelQuotationDetail(modelQuotation));
                ret.ret = "yes";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (method == "del") {

                if (modelQuotation == null)
                {
                    ret.ret = "no";
                    ret.err_code = "0009";
                    ret.message = "沒有此modelQuotation_uid資料可刪除!";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                List<modelMainItem> modelMainItems = conn.Query<modelMainItem>("select * from modelMainItem where modelQuotation_uid = @modelQuotation_uid", new { modelQuotation_uid = modelQuotation.modelQuotation_uid }).ToList();

                foreach (modelMainItem modelMainItem in modelMainItems) { 
                    string modelMainItem_uid = modelMainItem.modelMainItem_uid;
                    conn.Execute("delete modelSubItem where modelMainItem_uid = @modelMainItem_uid", new { modelMainItem_uid = modelMainItem_uid });
                    conn.Delete(modelMainItem);
                }

                conn.Delete(modelQuotation);
                ret.ret = "yes";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
        }

        [Route("authModalQuotationList")]
        public ActionResult AuthModalQuotationList(IFormCollection obj)
        {
            modelQuotationListResult ret = new modelQuotationListResult();

            authToken token = new authToken(this._httpContextAccessor);
            if (token.user_isLogin == false)
            {
                HttpContext.Response.Cookies.Delete("token_key");
                ret.ret = "no";
                ret.err_code = "99999";
                ret.message = "非登入狀態!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (token.user_perm != "system")
            {
                ret.ret = "no";
                ret.err_code = "90001";
                ret.message = "此帳號無此api使用權限!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            string dept_uid = obj["dept_uid"].ToString();
            string modelProj_uid = obj["modelProj_uid"].ToString();

            ret.modelQuotations = conn.Query<modelQuotation>("select * from modelQuotation where modelProj_uid = @modelProj_uid and dept_uid = @dept_uid", new { modelProj_uid = modelProj_uid, dept_uid = dept_uid }).ToList();
            ret.ret = "yes";

            return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
        }

        [Route("addEditDelGetModelProj")]
        public ActionResult AddEditDelGetModelProj(IFormCollection obj) {
            modelProjListResult ret = new modelProjListResult();

            authToken token = new authToken(this._httpContextAccessor);
            if (token.user_isLogin == false)
            {
                HttpContext.Response.Cookies.Delete("token_key");
                ret.ret = "no";
                ret.err_code = "99999";
                ret.message = "非登入狀態!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (token.user_perm != "system")
            {
                ret.ret = "no";
                ret.err_code = "90001";
                ret.message = "此帳號無此api使用權限!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }
            string modelProj_uid = obj["modelProj_uid"].ToString();
            string modelProj_name = obj["modelProj_name"].ToString();
            string method = obj["method"].ToString();
            string dept_uid = obj["dept_uid"].ToString();

            if (method == "")
            {
                ret.ret = "no";
                ret.err_code = "0001";
                ret.message = "沒有method!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }



            if (dept_uid.Trim() == "")
            {
                ret.ret = "no";
                ret.err_code = "0003";
                ret.message = "沒有dept_uid!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (method == "add")
            {



                modelProj_uid = GlobalClass.CreateRandomCode(24);
                modelProj newItem = new modelProj();
                newItem.modelProj_name = modelProj_name;
                newItem.dept_uid = dept_uid;
                newItem.modelProj_uid = modelProj_uid;


                newItem.modelProj_lastmodify_uid = token.user_uid;
                newItem.modelProj_createdate = DateTime.Now;
                newItem.modelProj_modifydate = DateTime.Now;
                newItem.modelProj_isdel = "N";

                conn.Insert(newItem);
                ret.modelProjs.Add(newItem);
                ret.ret = "yes";

                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (modelProj_uid.Trim() == "")
            {
                ret.ret = "no";
                ret.err_code = "0002";
                ret.message = "沒有modelProj_uid!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            modelProj editItem = conn.QueryFirstOrDefault<modelProj>("select * from modelProj where modelProj_isdel = 'N' and modelProj_uid = @modelProj_uid ", new { modelProj_uid = modelProj_uid });

            if (editItem == null)
            {
                ret.ret = "no";
                ret.err_code = "0004";
                ret.message = "沒有modelProj_uid此筆資料!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (method == "edit")
            {
                

                if (modelProj_name.Trim() == "")
                {
                    ret.ret = "no";
                    ret.err_code = "0002";
                    ret.message = "沒有modelProj_name!";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                editItem.modelProj_name = modelProj_name;
                

                editItem.modelProj_lastmodify_uid = token.user_uid;
                editItem.modelProj_modifydate = DateTime.Now;
                editItem.dept_uid = dept_uid;

                conn.Update(editItem);
                ret.modelProjs.Add(editItem);
                ret.ret = "yes";

                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (method == "get")
            {
                ret.modelProjs.Add(editItem);
                ret.ret = "yes";

                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (method == "del")
            {
                editItem.modelProj_isdel= "Y";


                editItem.modelProj_lastmodify_uid = token.user_uid;
                editItem.modelProj_modifydate = DateTime.Now;

                conn.Update(editItem);
                ret.ret = "yes";

                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
        }

        [Route("authModalProjList")]
        public ActionResult AuthModalProjList(IFormCollection obj) {
            modelProjListResult ret = new modelProjListResult();

            authToken token = new authToken(this._httpContextAccessor);
            if (token.user_isLogin == false)
            {
                HttpContext.Response.Cookies.Delete("token_key");
                ret.ret = "no";
                ret.err_code = "99999";
                ret.message = "非登入狀態!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (token.user_perm != "system")
            {
                ret.ret = "no";
                ret.err_code = "90001";
                ret.message = "此帳號無此api使用權限!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            string dept_uid = obj["dept_uid"].ToString();

            ret.modelProjs = conn.Query<modelProj>("select * from modelProj where modelProj_isdel = 'N' and dept_uid = @dept_uid", new { dept_uid = dept_uid}).ToList();
            ret.ret = "yes";

            return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
        }

        [Route("addEditDelGetSubItem")]
        public ActionResult AddEditDelSubItem(IFormCollection obj) {
            authSubItemResult ret = new authSubItemResult();

            authToken token = new authToken(this._httpContextAccessor);
            if (token.user_isLogin == false)
            {
                HttpContext.Response.Cookies.Delete("token_key");
                ret.ret = "no";
                ret.err_code = "99999";
                ret.message = "非登入狀態!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (token.user_perm != "system")
            {
                ret.ret = "no";
                ret.err_code = "90001";
                ret.message = "此帳號無此api使用權限!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            string dept_uid = obj["dept_uid"].ToString();
            string mainItem_uid = obj["mainItem_uid"].ToString();
            string subItem_uid = obj["subItem_uid"].ToString();
            string subItem_name = obj["subItem_name"].ToString();
            string subItem_descript = obj["subItem_descript"].ToString();
            string subItem_priceStr = obj["subItem_price"].ToString();
            string subItem_unitType = obj["subItem_unitType"].ToString();
            string method = obj["method"].ToString();

            


            if (method == "") {
                ret.ret = "no";
                ret.err_code = "0001";
                ret.message = "沒有method!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            

            if (dept_uid.Trim() == "")
            {
                ret.ret = "no";
                ret.err_code = "0003";
                ret.message = "沒有dept_uid!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (method == "add")
            {
                double subItem_price = 0.0;

                try
                {
                    subItem_price = Double.Parse(subItem_priceStr);
                }
                catch
                {
                    ret.ret = "no";
                    ret.err_code = "0005";
                    ret.message = "subItem_price非數字!";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }


                subItem_uid = GlobalClass.CreateRandomCode(24);
                subItem newItem = new subItem();
                newItem.subItem_name = subItem_name;
                newItem.mainItem_uid = mainItem_uid;
                newItem.subItem_uid = subItem_uid;
                newItem.subItem_descript = subItem_descript;
                newItem.subItem_price = subItem_price;
                newItem.subItem_unitType = subItem_unitType;

                newItem.subItem_lastmodify_uid = token.user_uid;
                newItem.subItem_createdate = DateTime.Now;
                newItem.subItem_modifydate = DateTime.Now;

                conn.Insert(newItem);
                ret.subItems.Add(newItem);
                ret.ret = "yes";

                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (subItem_uid.Trim() == "")
            {
                ret.ret = "no";
                ret.err_code = "0002";
                ret.message = "沒有mainItem_uid!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            

            subItem editItem = conn.QueryFirstOrDefault<subItem>("select * from subItem where subItem_uid = @subItem_uid ", new { subItem_uid = subItem_uid });

            if (editItem == null) {
                ret.ret = "no";
                ret.err_code = "0004";
                ret.message = "沒有subItem_uid此筆資料!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (method == "edit") {
                double subItem_price = 0.0;

                try
                {
                    subItem_price = Double.Parse(subItem_priceStr);
                }
                catch {
                    ret.ret = "no";
                    ret.err_code = "0005";
                    ret.message = "subItem_price非數字!";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                if (subItem_name.Trim() == "")
                {
                    ret.ret = "no";
                    ret.err_code = "0002";
                    ret.message = "沒有mainItem_name!";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                editItem.subItem_name = subItem_name;
                editItem.subItem_descript = subItem_descript;
                editItem.subItem_price = subItem_price;
                editItem.subItem_unitType = subItem_unitType;

                editItem.subItem_lastmodify_uid = token.user_uid;
                editItem.subItem_modifydate = DateTime.Now;

                conn.Update(editItem);
                ret.subItems.Add(editItem);
                ret.ret = "yes";

                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (method == "get") {
                ret.subItems.Add(editItem);
                ret.ret = "yes";

                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (method == "del") {
                conn.Delete(editItem);
                ret.ret = "yes";

                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
        }

        [Route("authSubItemList")]
        public ActionResult AuthSubItemList(IFormCollection obj) { 
            authSubItemResult ret = new authSubItemResult();

            authToken token = new authToken(this._httpContextAccessor);
            if (token.user_isLogin == false)
            {
                HttpContext.Response.Cookies.Delete("token_key");
                ret.ret = "no";
                ret.err_code = "99999";
                ret.message = "非登入狀態!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (token.user_perm != "system")
            {
                ret.ret = "no";
                ret.err_code = "90001";
                ret.message = "此帳號無此api使用權限!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            string dept_uid = obj["dept_uid"].ToString();
            string mainItem_uid = obj["mainItem_uid"].ToString();

            ret.subItems = conn.Query<subItem>("select * from subItem where mainItem_uid = @mainItem_uid", new { mainItem_uid = mainItem_uid }).ToList();
            ret.ret = "yes";
            return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
        }

        [Route("addEditDelGetMainItem")]
        public ActionResult AddEditDelMainItem(IFormCollection obj) {
            authMainItemResult ret = new authMainItemResult();

            authToken token = new authToken(this._httpContextAccessor);
            if (token.user_isLogin == false)
            {
                HttpContext.Response.Cookies.Delete("token_key");
                ret.ret = "no";
                ret.err_code = "99999";
                ret.message = "非登入狀態!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (token.user_perm != "system")
            {
                ret.ret = "no";
                ret.err_code = "90001";
                ret.message = "此帳號無此api使用權限!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            string dept_uid = obj["dept_uid"].ToString();
            string mainItem_uid = obj["mainItem_uid"].ToString();
            string mainItem_name = obj["mainItem_name"].ToString();
            string method = obj["method"].ToString();

            if (method == "") {
                ret.ret = "no";
                ret.err_code = "0001";
                ret.message = "沒有method!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            

            if (dept_uid.Trim() == "")
            {
                ret.ret = "no";
                ret.err_code = "0003";
                ret.message = "沒有dept_uid!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (method == "add")
            {
                mainItem_uid = GlobalClass.CreateRandomCode(12);
                mainItem newItem = new mainItem();
                newItem.mainItem_name = mainItem_name;
                newItem.mainItem_uid = mainItem_uid;
                newItem.dept_uid = dept_uid;
                newItem.mainItem_lastmodify_uid = token.user_uid;
                newItem.mainItem_createdate = DateTime.Now;
                newItem.mainItem_modifydate = DateTime.Now;

                conn.Insert(newItem);
                ret.mainItems.Add(newItem);
                ret.ret = "yes";

                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (mainItem_uid.Trim() == "")
            {
                ret.ret = "no";
                ret.err_code = "0002";
                ret.message = "沒有mainItem_uid!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            

            mainItem editItem = conn.QueryFirstOrDefault<mainItem>("select * from mainItem where mainItem_uid = @mainItem_uid ", new { mainItem_uid = mainItem_uid });

            if (editItem == null) {
                ret.ret = "no";
                ret.err_code = "0004";
                ret.message = "沒有mainItem_uid此筆資料!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (method == "edit") {
                if (mainItem_name.Trim() == "")
                {
                    ret.ret = "no";
                    ret.err_code = "0002";
                    ret.message = "沒有mainItem_name!";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                editItem.mainItem_name = mainItem_name;
                editItem.mainItem_lastmodify_uid = token.user_uid;
                editItem.mainItem_modifydate= DateTime.Now;

                conn.Update(editItem);
                ret.mainItems.Add(editItem);
                ret.ret = "yes";

                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (method == "get") {
                ret.mainItems.Add(editItem);
                ret.ret = "yes";

                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (method == "del") {
                conn.Delete(editItem);
                ret.ret = "yes";

                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
        }

        [Route("authMainItemList")]
        public ActionResult AuthMainItemList(IFormCollection obj) {
            authMainItemResult ret = new authMainItemResult();

            authToken token = new authToken(this._httpContextAccessor);
            if (token.user_isLogin == false)
            {
                HttpContext.Response.Cookies.Delete("token_key");
                ret.ret = "no";
                ret.err_code = "99999";
                ret.message = "非登入狀態!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (token.user_perm != "system")
            {
                ret.ret = "no";
                ret.err_code = "90001";
                ret.message = "此帳號無此api使用權限!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            string dept_uid = obj["dept_uid"].ToString();

            ret.mainItems = conn.Query<mainItem>("select * from mainItem where dept_uid = @dept_uid", new { dept_uid = dept_uid }).ToList();
            ret.ret = "yes";

            return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
        }

        [Route("addGroupUser")]
        public ActionResult AddGroupUser(IFormCollection obj) {
            groupUserListResult ret = new groupUserListResult();

            authToken token = new authToken(this._httpContextAccessor);
            if (token.user_isLogin == false)
            {
                HttpContext.Response.Cookies.Delete("token_key");
                ret.ret = "no";
                ret.err_code = "99999";
                ret.message = "非登入狀態!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (token.user_perm != "system")
            {
                ret.ret = "no";
                ret.err_code = "90001";
                ret.message = "此帳號無此api使用權限!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            string dept_uid = obj["dept_uid"].ToString();
            string users_json_str = obj["users_json"].ToString();
            string group_uid = obj["group_uid"].ToString();

            group objGroup = conn.QueryFirstOrDefault<group>("select * from [group] where group_uid = @group_uid", new { group_uid = group_uid });

            if (objGroup == null)
            {
                ret.ret = "no";
                ret.err_code = "0003";
                ret.message = "無此group_uid的群組資料!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            dynamic usersJsonObj;

            try
            {
                usersJsonObj = JsonConvert.DeserializeObject(users_json_str);



            }
            catch (Exception ex)
            {
                ret.ret = "no";
                ret.err_code = "0003";
                ret.message = "使用者列表資料錯誤 users json error," + ex.Message;
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            string nowrite_msg = "";
            int userCount = 0;
            foreach (dynamic item in usersJsonObj)
            {
                string user_uid = item.user_uid;
                string user_name = item.user_name;
                groupUser chk_user = conn.QueryFirstOrDefault<groupUser>("select * from groupUser where user_uid = @user_uid and dept_uid = @dept_uid", new { user_uid = user_uid, dept_uid = dept_uid });

                if (chk_user == null)
                {
                    groupUser newGU = new groupUser();
                    newGU.group_uid = group_uid;
                    newGU.user_uid = user_uid;
                    newGU.groupUser_uid = GlobalClass.CreateRandomCode(16);
                    newGU.dept_uid = dept_uid;
                    conn.Insert<groupUser>(newGU);

                    user objUser = new user();
                    objUser.user_uid=user_uid;
                    objUser.user_name=user_name;
                    ret.users.Add(objUser);
                    userCount++;
                }
                else
                {
                    nowrite_msg += user_name + " 此用戶已經是其他群組的成員，故此員取消加入!\n";
                }
            }

            

            ret.message = nowrite_msg;
            ret.ret = "yes";


            return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
        }

        [Route("delGroup")]
        public ActionResult DelGroup(IFormCollection obj) {
            signinResult ret = new signinResult();

            authToken token = new authToken(this._httpContextAccessor);
            if (token.user_isLogin == false)
            {
                HttpContext.Response.Cookies.Delete("token_key");
                ret.ret = "no";
                ret.err_code = "99999";
                ret.message = "非登入狀態!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (token.user_perm != "system")
            {
                ret.ret = "no";
                ret.err_code = "90001";
                ret.message = "此帳號無此api使用權限!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

      
            string group_uid = obj["group_uid"].ToString();

            group objGroup = conn.QueryFirstOrDefault<group>("select * from [group] where group_uid = @group_uid", new { group_uid = group_uid });

            if (objGroup == null)
            {
                ret.ret = "no";
                ret.err_code = "0003";
                ret.message = "無此group_uid的群組資料!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            conn.Execute("delete groupUser where group_uid = @group_uid", new { group_uid = group_uid});
            conn.Delete(objGroup);

            ret.ret = "yes";
            return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
        }

        [Route("editGroupName")]
        public ActionResult EditGroupName(IFormCollection obj) {
            signinResult ret = new signinResult();

            authToken token = new authToken(this._httpContextAccessor);
            if (token.user_isLogin == false)
            {
                HttpContext.Response.Cookies.Delete("token_key");
                ret.ret = "no";
                ret.err_code = "99999";
                ret.message = "非登入狀態!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (token.user_perm != "system")
            {
                ret.ret = "no";
                ret.err_code = "90001";
                ret.message = "此帳號無此api使用權限!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            string group_name = obj["group_name"].ToString();
            string group_uid = obj["group_uid"].ToString();

            group objGroup = conn.QueryFirstOrDefault<group>("select * from [group] where group_uid = @group_uid", new { group_uid = group_uid });

            if (objGroup == null) {
                ret.ret = "no";
                ret.err_code = "0003";
                ret.message = "無此group_uid的群組資料!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            objGroup.group_name = group_name;
            
            conn.Update(objGroup);

            ret.ret = "yes";
            return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
        }

        [Route("delGroupUser")]
        public ActionResult DelGroupUser(IFormCollection obj) {
            signinResult ret = new signinResult();

            authToken token = new authToken(this._httpContextAccessor);
            if (token.user_isLogin == false)
            {
                HttpContext.Response.Cookies.Delete("token_key");
                ret.ret = "no";
                ret.err_code = "99999";
                ret.message = "非登入狀態!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (token.user_perm != "system")
            {
                ret.ret = "no";
                ret.err_code = "90001";
                ret.message = "此帳號無此api使用權限!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            string dept_uid = obj["dept_uid"].ToString();
            string user_uid = obj["user_uid"].ToString();
            string group_uid = obj["group_uid"].ToString();

            groupUser objUser = conn.QueryFirstOrDefault<groupUser>("select * from groupUser where dept_uid = @dept_uid and user_uid = @user_uid and group_uid = @group_uid ", new { dept_uid = dept_uid, user_uid = user_uid, group_uid = group_uid });

            if (objUser == null) {
                ret.ret = "no";
                ret.err_code = "0002";
                ret.message = "此群組無此帳號可以刪除!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            conn.Delete(objUser);

            ret.ret = "yes";
            return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
        }

        [Route("addNewGroup")]
        public ActionResult AddNewGroup(IFormCollection obj) {
            groupListResult ret = new groupListResult();

            authToken token = new authToken(this._httpContextAccessor);
            if (token.user_isLogin == false)
            {
                HttpContext.Response.Cookies.Delete("token_key");
                ret.ret = "no";
                ret.err_code = "99999";
                ret.message = "非登入狀態!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (token.user_perm != "system")
            {
                ret.ret = "no";
                ret.err_code = "90001";
                ret.message = "此帳號無此api使用權限!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            string dept_uid = obj["dept_uid"].ToString();
            string group_name = obj["group_name"].ToString();
            string users_json_str = obj["users_json"].ToString();
            string group_uid = GlobalClass.CreateRandomCode(10);

            group newGroup = new group();
            newGroup.group_uid = group_uid;
            newGroup.group_name = group_name;
            newGroup.dept_uid = dept_uid;

            
            dynamic usersJsonObj;

            try
            {
                usersJsonObj = JsonConvert.DeserializeObject(users_json_str);
                


            }
            catch (Exception ex) {
                ret.ret = "no";
                ret.err_code = "0003";
                ret.message = "使用者列表資料錯誤 users json error," + ex.Message;
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            string nowrite_msg = "";
            int userCount = 0;
            foreach (dynamic item in usersJsonObj) { 
                string user_uid = item.user_uid;
                string user_name = item.user_name;
                groupUser chk_user = conn.QueryFirstOrDefault<groupUser>("select * from groupUser where user_uid = @user_uid and dept_uid = @dept_uid", new { user_uid = user_uid, dept_uid = dept_uid });

                if (chk_user == null)
                {
                    groupUser newGU = new groupUser();
                    newGU.group_uid = group_uid;
                    newGU.user_uid = user_uid;
                    newGU.groupUser_uid = GlobalClass.CreateRandomCode(16);
                    newGU.dept_uid = dept_uid;
                    conn.Insert<groupUser>(newGU);
                    userCount++;
                }
                else {
                    nowrite_msg += user_name + " 此用戶已經是其他群組的成員，故此員取消加入!\n";
                }
            }

            if (userCount == 0) {
                nowrite_msg += "成員數量不得為0，故取消建立群組!";
                ret.ret = "no";
                ret.err_code = "0007";
                ret.message = nowrite_msg;
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }
            conn.Insert(newGroup);
            ret.groups.Add(new groupDetail(newGroup));

            ret.message = nowrite_msg;
            ret.ret = "yes";


            return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
        }

        [Route("noGroupUserList")]
        public ActionResult NoGroupUserList(IFormCollection obj) { 
            userListResult ret = new userListResult();

            authToken token = new authToken(this._httpContextAccessor);
            if (token.user_isLogin == false)
            {
                HttpContext.Response.Cookies.Delete("token_key");
                ret.ret = "no";
                ret.err_code = "99999";
                ret.message = "非登入狀態!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (token.user_perm != "system")
            {
                ret.ret = "no";
                ret.err_code = "90001";
                ret.message = "此帳號無此api使用權限!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            string dept_uid = obj["dept_uid"].ToString();

            if (dept_uid == "")
            {
                ret.ret = "no";
                ret.err_code = "00002";
                ret.message = "無dept_uid參數!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            List<user> userList = conn.Query<user>("select A.* from users A, userDept B where A.user_uid = B.user_uid and A.user_ishidden = 'N' and A.user_onjob= 'Y' and B.dept_uid = @dept_uid and A.user_uid not in (select user_uid from groupUser) ", new { dept_uid = dept_uid }).ToList(); 
        
            ret.userList = userList;
            ret.ret = "yes";

            return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
        }

        [Route("authDeptList")]
        public ActionResult AuthDeptList(IFormCollection obj)
        { 
            deptListResult ret = new deptListResult();

            authToken token = new authToken(this._httpContextAccessor);
            if (token.user_isLogin == false)
            {
                HttpContext.Response.Cookies.Delete("token_key");
                ret.ret = "no";
                ret.err_code = "99999";
                ret.message = "非登入狀態!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (token.user_perm != "system")
            {
                ret.ret = "no";
                ret.err_code = "90001";
                ret.message = "此帳號無此api使用權限!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            string sqlString = "select * from depts order by dept_order";

            if (token.user_id != GlobalClass.appsettings("Admin:id")) {
                sqlString = "select * from depts where dept_uid in (select dept_uid from userDept where user_uid = '" + token.user_uid + "' ) order by dept_order ";
            }

            ret.depts = conn.Query<depts>(sqlString).ToList();
            ret.ret = "yes";
            return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
        }

        [Route("groupList")]
        public ActionResult GroupList(IFormCollection obj)
        {
            groupListResult ret = new groupListResult();

            authToken token = new authToken(this._httpContextAccessor);
            if (token.user_isLogin == false)
            {
                HttpContext.Response.Cookies.Delete("token_key");
                ret.ret = "no";
                ret.err_code = "99999";
                ret.message = "非登入狀態!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (token.user_perm != "system")
            {
                ret.ret = "no";
                ret.err_code = "90001";
                ret.message = "此帳號無此api使用權限!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            string dept_uid = obj["dept_uid"].ToString();

            if (dept_uid == "") {
                ret.ret = "no";
                ret.err_code = "00002";
                ret.message = "無dept_uid參數!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            List<group> groupList = conn.Query<group>("select * from [group] where dept_uid = @dept_uid", new { dept_uid = dept_uid}).ToList();

            foreach (group objGroup in groupList)
            {
                ret.groups.Add(new groupDetail(objGroup));
            }

            ret.ret = "yes";

            return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
    }

        [Route("addEditGetUser")]
        public ActionResult AddEditGetUser(IFormCollection obj)
        {
            updateUserResult ret = new updateUserResult();

            authToken token = new authToken(this._httpContextAccessor);
            if (token.user_isLogin == false)
            {
                HttpContext.Response.Cookies.Delete("token_key");
                ret.ret = "no";
                ret.err_code = "99999";
                ret.message = "非登入狀態!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (token.user_perm != "system")
            {
                ret.ret = "no";
                ret.err_code = "90001";
                ret.message = "此帳號無此api使用權限!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            string method = obj["method"].ToString();

            if (method == "")
            {
                ret.ret = "no";
                ret.err_code = "0001";
                ret.message = "沒有method參數";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }


            if (method == "add")
            {
                string user_type = obj["user_type"].ToString();
                string user_perm = obj["user_perm"].ToString();
                string user_depts = obj["user_depts"].ToString().Trim(',');

                string[] depts = user_depts.Split(",");

                if (depts.Length == 0) {
                    ret.ret = "no";
                    ret.err_code = "0002";
                    ret.message = "沒有所屬單位";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                if (user_type == "")
                {
                    ret.ret = "no";
                    ret.err_code = "0002";
                    ret.message = "沒有user_type參數";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                //N為E白板帳號
                if (user_type == "N")
                {
                    string user_id = obj["user_elabName"].ToString();
                    string user_engName = obj["user_engName"].ToString();

                    user newUser = conn.QueryFirstOrDefault<user>("select * from users where user_id = @user_id ", new { user_id = user_id });

                    if (newUser != null)
                    {
                        ret.ret = "no";
                        ret.err_code = "0003";
                        ret.message = "此帳號已經存在於系統!";
                        return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");

                    }

                    new_userdata elabUser;

                    try
                    {
                        elabUser = elabConn.QueryFirstOrDefault<new_userdata>("select * from new_userdata where userid = @user_id order by mail, userid", new { user_id = user_id });
                    }
                    catch (Exception ex)
                    {
                        ret.ret = "no";
                        ret.err_code = "90001";
                        ret.message = ex.Message;
                        return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");

                    }

                    if (elabUser == null)
                    {
                        ret.ret = "no";
                        ret.err_code = "0004";
                        ret.message = "E白板無此帳號!";
                        return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                    }


                    string user_uid = GlobalClass.CreateRandomCode(12);
                    newUser = new user();
                    newUser.user_uid = user_uid;
                    newUser.user_name = elabUser.username;
                    newUser.user_engName = user_engName;
                    newUser.user_id = elabUser.userid;
                    newUser.user_email = elabUser.mail;
                    newUser.user_type = user_type;
                    newUser.user_onjob = "Y";
                    newUser.user_perm = user_perm;
                    newUser.user_ishidden = "N";
                    newUser.user_createdate = DateTime.Now;

                    if (user_perm == "")
                    {
                        ret.ret = "no";
                        ret.err_code = "0009";
                        ret.message = "無此帳號的權限設定值!";
                        return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                    }

                    conn.Insert(newUser);

                    foreach (string dept_uid in depts) {
                        if (dept_uid != "")
                        {
                            userDept objUserDept = new userDept();
                            objUserDept.user_uid = user_uid;
                            objUserDept.dept_uid = dept_uid;
                            conn.Insert<userDept>(objUserDept);
                        }
                    }

                    ret.ret = "yes";
                    ret.user = new userWithDept(newUser);
                }
                else
                {
                    string user_id = obj["user_id"].ToString();
                    string user_pwd = obj["user_pwd"].ToString();
                    string user_uid = GlobalClass.CreateRandomCode(12);
                    string user_name = obj["user_name"].ToString();
                    string user_email = obj["user_email"].ToString();
                    string user_engName = obj["user_engName"].ToString();


                    if (user_id == "")
                    {
                        ret.ret = "no";
                        ret.err_code = "0006";
                        ret.message = "請輸入帳號ID!";
                        return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                    }

                    if (user_name == "")
                    {
                        ret.ret = "no";
                        ret.err_code = "0006";
                        ret.message = "請輸入帳號名稱!";
                        return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                    }

                    if (user_perm == "")
                    {
                        ret.ret = "no";
                        ret.err_code = "0009";
                        ret.message = "無此帳號的權限設定值!";
                        return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                    }

                    if (GlobalClass.isEmail(user_email) == false)
                    {
                        ret.ret = "no";
                        ret.err_code = "0007";
                        ret.message = "請輸入正確EMail!";
                        return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                    }

                    user newUser = conn.QueryFirstOrDefault<user>("select * from users where user_id = @user_id ", new { user_id = user_id });

                    if (newUser != null)
                    {
                        ret.ret = "no";
                        ret.err_code = "0003";
                        ret.message = "此帳號已經存在於系統!";
                        return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                    }

                    new_userdata elabUser = elabConn.QueryFirstOrDefault("select * from new_userdata where userid = @user_id order by mail", new { user_id = user_id });

                    if (elabUser != null)
                    {
                        ret.ret = "no";
                        ret.err_code = "0005";
                        ret.message = "E白板系統內有此帳號ID，請換帳號或改以E白板帳號加入!";
                        return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                    }



                    newUser = new user();
                    newUser.user_uid = user_uid;
                    newUser.user_id = user_id;
                    newUser.user_name = user_name;
                    newUser.user_engName = user_engName;
                    newUser.user_pwd = user_pwd;
                    newUser.user_email = user_email;
                    newUser.user_type = user_type;
                    newUser.user_onjob = "Y";
                    newUser.user_perm = user_perm;
                    newUser.user_ishidden = "N";
                    newUser.user_createdate = DateTime.Now;

                    conn.Insert(newUser);

                    foreach (string dept_uid in depts)
                    {
                        if (dept_uid != "")
                        {
                            userDept objUserDept = new userDept();
                            objUserDept.user_uid = user_uid;
                            objUserDept.dept_uid = dept_uid;
                            conn.Insert<userDept>(objUserDept);
                        }
                    }

                    ret.ret = "yes";
                    ret.user = new userWithDept(newUser);
                }

                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (method == "edit")
            {
                string user_type = obj["user_type"].ToString();
                string user_uid = obj["user_uid"].ToString();
                string user_perm = obj["user_perm"].ToString();
                string user_depts = obj["user_depts"].ToString().Trim(',');
                string user_engName = obj["user_engName"].ToString();

                string[] depts = user_depts.Split(",");

                if (depts.Length == 0)
                {
                    ret.ret = "no";
                    ret.err_code = "0002";
                    ret.message = "沒有所屬單位";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                if (user_type == "")
                {
                    ret.ret = "no";
                    ret.err_code = "0002";
                    ret.message = "沒有user_type參數";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                if (user_perm == "")
                {
                    ret.ret = "no";
                    ret.err_code = "0009";
                    ret.message = "無此帳號的權限設定值!";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                user editUser = conn.QueryFirstOrDefault<user>("select * from users where user_uid = @user_uid and user_type = @user_type", new { user_uid = user_uid, user_type = user_type });

                if (editUser == null)
                {
                    ret.ret = "no";
                    ret.err_code = "0008";
                    ret.message = "沒有此用戶資料!";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                //N為E白板帳號
                if (user_type == "N")
                {
                    editUser.user_perm = user_perm;
                    editUser.user_engName = user_engName;
                }
                else
                {
                    string user_pwd = obj["user_pwd"].ToString();
                    string user_name = obj["user_name"].ToString();
                    string user_email = obj["user_email"].ToString();
                    

                    editUser.user_perm = user_perm;

                    if (user_name == "")
                    {
                        ret.ret = "no";
                        ret.err_code = "0006";
                        ret.message = "請輸入帳號名稱!";
                        return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                    }

                    if (GlobalClass.isEmail(user_email) == false)
                    {
                        ret.ret = "no";
                        ret.err_code = "0007";
                        ret.message = "請輸入正確EMail!";
                        return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                    }

                    if (user_pwd != "")
                    {
                        editUser.user_pwd = user_pwd;
                    }

                    editUser.user_name = user_name;
                    editUser.user_email = user_email;
                    editUser.user_engName = user_engName;
                }

                conn.Update<user>(editUser);

                conn.Execute("delete userDept where user_uid = @user_uid", new { user_uid = user_uid});

                foreach (string dept_uid in depts)
                {
                    if (dept_uid != "") {
                        userDept objUserDept = new userDept();
                        objUserDept.user_uid = user_uid;
                        objUserDept.dept_uid = dept_uid;
                        conn.Insert<userDept>(objUserDept);
                    }
                }

                ret.ret = "yes";
                ret.user = new userWithDept(editUser);
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (method == "del")
            {
                string user_uid = obj["user_uid"].ToString();


                user editUser = conn.QueryFirstOrDefault<user>("select * from users where user_ishidden = 'N' and user_uid = @user_uid ", new { user_uid = user_uid });

                if (editUser == null)
                {
                    ret.ret = "no";
                    ret.err_code = "0008";
                    ret.message = "沒有此用戶資料!";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                editUser.user_ishidden = "Y";

                conn.Update(editUser);

                if (editUser.user_lastlogintime == "")
                {
                    conn.Delete(editUser);
                }

                ret.ret = "yes";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (method == "get")
            {
                string user_uid = obj["user_uid"].ToString();

                user editUser = conn.QueryFirstOrDefault<user>("select * from users where user_ishidden = 'N' and user_uid = @user_uid", new { user_uid = user_uid });

                if (editUser == null)
                {
                    ret.ret = "no";
                    ret.err_code = "0008";
                    ret.message = "沒有此用戶資料!";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                

                ret.ret = "yes";
                ret.user = new userWithDept(editUser);
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
        }

        [Route("elab_UserList")]
        public ActionResult Elab_UserList(IFormCollection obj)
        {
            elabUserListResult ret = new elabUserListResult();

            authToken token = new authToken(this._httpContextAccessor);
            if (token.user_isLogin == false)
            {
                HttpContext.Response.Cookies.Delete("token_key");
                ret.ret = "no";
                ret.err_code = "99999";
                ret.message = "非登入狀態!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (token.user_perm != "system")
            {
                ret.ret = "no";
                ret.err_code = "90001";
                ret.message = "此帳號無此api使用權限!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            ret.userList = elabConn.Query<new_userdata>("select * from new_userdata where onjob = 0 order by mail ").ToList();
            ret.ret = "yes";
            return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
        }

        [Route("userList")]
        public ActionResult UserList(IFormCollection obj)
        {
            userListResult ret = new userListResult();

            authToken token = new authToken(this._httpContextAccessor);
            if (token.user_isLogin == false)
            {
                HttpContext.Response.Cookies.Delete("token_key");
                ret.ret = "no";
                ret.err_code = "99999";
                ret.message = "非登入狀態!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (token.user_perm != "system")
            {
                ret.ret = "no";
                ret.err_code = "90001";
                ret.message = "此帳號無此api使用權限!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            ret.userList = conn.Query<user>("select * from users where user_ishidden = 'N' order by user_sn desc").ToList();
            ret.ret = "yes";

            return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
        }

        [Route("logout")]
        public ActionResult Logout()
        {
            signinResult ret = new signinResult();

            authToken _objToken = new authToken(this._httpContextAccessor);

            if (_objToken.user_isLogin == true)
            {
                string token_key = _httpContextAccessor.HttpContext.Request.Cookies["token_key"];


                conn.Execute("delete token where token_key = @token_key", new { token_key = token_key });

            }

            HttpContext.Response.Cookies.Delete("token_key");

            ret.ret = "yes";


            return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
        }

        [Route("signin")]
        public ActionResult Signin(IFormCollection obj)
        {
            signinResult ret = new signinResult();

            string input_ID = obj["id"].ToString();
            string input_PWD = obj["pwd"].ToString();
            string input_isRemember = obj["remember"].ToString();

            string sys_ID = GlobalClass.appsettings("Admin:id");
            string sys_PWD = GlobalClass.Sha256(GlobalClass.appsettings("Admin:pwd"));

            if (input_ID == "")
            {
                ret.ret = "no";
                ret.err_code = "0001";
                ret.message = "帳號或密碼錯誤!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            //判斷是否為系統預設帳號
            if (input_ID == sys_ID)
            {
                if (input_PWD != sys_PWD)
                {
                    ret.ret = "no";
                    ret.err_code = "0001";
                    ret.message = "帳號或密碼錯誤!";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                token adminToken = new token();

                int intexpireMin = 20;

                if (input_isRemember == "Y")
                {
                    intexpireMin = 60 * 24 * 7;
                }

                string token_key = GlobalClass.CreateRandomCode(24);

                adminToken.user_uid = GlobalClass.appsettings("Admin:uid");
                adminToken.user_id = GlobalClass.appsettings("Admin:id");
               
                adminToken.token_isremember = input_isRemember;
                adminToken.token_key = token_key;
                adminToken.token_createdate = DateTime.Now;
                adminToken.token_expireddate = DateTime.Now.AddMinutes(intexpireMin);

                conn.Insert<token>(adminToken);

                CookieOptions options = new CookieOptions();

                options.Secure = true;
                options.Expires = DateTime.Now.AddMinutes(intexpireMin);

                HttpContext.Response.Cookies.Delete("token_key");

                _httpContextAccessor.HttpContext.Response.Cookies.Append("token_key", token_key, options);

                ret.ret = "yes";

                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }
            else
            {
                //非系統帳號
                user webUser = conn.QueryFirstOrDefault<user>("select * from users where user_ishidden = 'N' and user_id = @user_id", new { user_id = input_ID });

                if (webUser == null)
                {
                    ret.ret = "no";
                    ret.err_code = "0002";
                    ret.message = "系統無此帳號!";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                if (webUser.user_onjob == "N")
                {
                    ret.ret = "no";
                    ret.err_code = "0003";
                    ret.message = "此帳號已經離職，無法登入";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                webUser.user_lastlogintime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");

                if (webUser.user_type == "Y")
                {
                    if (input_PWD != webUser.user_pwd)
                    {
                        ret.ret = "no";
                        ret.err_code = "0004";
                        ret.message = "密碼錯誤!";
                        return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                    }
                }
                else
                {
                    new_userdata elabUser = elabConn.QueryFirstOrDefault<new_userdata>("select * from new_userdata where userid = @userid order by mail, userid", new { userid = webUser.user_id });

                    if (input_PWD != GlobalClass.Sha256(elabUser.userpw))
                    {
                        ret.ret = "no";
                        ret.err_code = "0004";
                        ret.message = "密碼錯誤!";
                        return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                    }

                    if (elabUser.onjob == 1)
                    {
                        webUser.user_onjob = "N";

                        conn.Update(webUser);

                        ret.ret = "no";
                        ret.err_code = "0003";
                        ret.message = "此帳號已經離職，無法登入";
                        return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                    }
                }

                token userToken = new token();

                int intexpireMin = 20;

                if (input_isRemember == "Y")
                {
                    intexpireMin = 60 * 24 * 7;
                }

                string token_key = GlobalClass.CreateRandomCode(24);

                userToken.user_uid = webUser.user_uid;
                userToken.user_id = input_ID;
                userToken.token_isremember = input_isRemember;
                userToken.token_key = token_key;
                userToken.token_createdate = DateTime.Now;
                userToken.token_expireddate = DateTime.Now.AddMinutes(intexpireMin);

                conn.Insert<token>(userToken);
                conn.Update<user>(webUser);

                CookieOptions options = new CookieOptions();

                options.Secure = true;
                options.Expires = DateTime.Now.AddMinutes(intexpireMin);

                HttpContext.Response.Cookies.Delete("token_key");

                _httpContextAccessor.HttpContext.Response.Cookies.Append("token_key", token_key, options);

                ret.ret = "yes";

                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");

            }

            ret.ret = "no";
            ret.err_code = "9999";
            ret.message = "無參數錯誤";


            return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
        }

        public class signinResult
        {
            public string ret = "no";
            public string err_code = "0000";
            public string message = "";
        }

        public class userListResult
        {
            public string ret = "no";
            public string err_code = "0000";
            public string message = "";
            public List<user> userList = new List<user>();
        }

        public class elabUserListResult
        {
            public string ret = "no";
            public string err_code = "0000";
            public string message = "";
            public List<new_userdata> userList = new List<new_userdata>();
        }

        public class updateUserResult
        {
            public string ret = "no";
            public string err_code = "0000";
            public string message = "";
            public userWithDept user = new userWithDept();
        }

    }
}
