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;
using Org.BouncyCastle.Bcpg.OpenPgp;
using NPOI.OpenXmlFormats.Shared;
using NPOI.SS.Formula.PTG;
using System.Data;
using System;
using AutoMapper;
using Org.BouncyCastle.Asn1.X509;
using NPOI.XSSF.UserModel;
using NPOI.HPSF;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using System.Text;
using System.Web;
using NPOI.SS.Util;
using NPOI.XSSF.Streaming;
using System.IO;

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

        public ISheet sheet;
        public FileStream fileStream;
        public IWorkbook workbook = null; //新建IWorkbook對象 

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

        public ApiController(IHttpContextAccessor httpContextAccessor)
        {
            this._httpContextAccessor = httpContextAccessor;


        }

        [Route("exportXlsx")]
        public ActionResult ExportXlsx(IFormCollection obj) {
            normalResult ret = new normalResult();

            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");
            }

            string quotation_uid = obj["quotation_uid"].ToString();
            string quotation_version = obj["quotation_version"].ToString();

            quotation objData = conn.QueryFirstOrDefault<quotation>("select * from quotation where quotation_isdel = 'N' and quotation_uid = @quotation_uid and quotation_version = @quotation_version ", new { quotation_uid = quotation_uid, quotation_version = quotation_version });

            if (objData == null) {
                ret.ret = "no";
                ret.err_code = "00009";
                ret.message = "無此quotation_uid 與 quotation_version資料!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            quotationDetail objDetail = new quotationDetail(objData);

            string excelName = "";
            string ourCompany_name = "";

            if (objDetail.dept_uid == "bremen") {
                excelName = "bremen_temp.xlsx";
                ourCompany_name = "不來梅股份有限公司";
            }

            if (objDetail.dept_uid == "journeys") {
                excelName = "journeys_temp.xlsx";
                ourCompany_name = "奇異之旅媒體股份有限公司";
            }

            string excelFullPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/logo/" + excelName);

            FileStream fileStream = new FileStream(excelFullPath, FileMode.Open, FileAccess.ReadWrite);

            workbook = new XSSFWorkbook(fileStream);

            sheet = workbook.GetSheetAt(0); //獲取第一個工作表 

            XSSFRow row;
            ICell cell = null;

            double saHeight = 0.0;

            

            row = (XSSFRow)sheet.GetRow(1);
            //估價單名稱與報價日期
            row.Cells[0].SetCellValue(row.Cells[0].StringCellValue.Replace("{quotation_date}", objDetail.quotation_date));
            row.Cells[3].SetCellValue(row.Cells[3].StringCellValue.Replace("{quotation_name}", objDetail.quotation_name));

            //估價單收件人 公司名稱 承辦人
            row = (XSSFRow)sheet.GetRow(2);
            row.Cells[0].SetCellValue(row.Cells[0].StringCellValue.Replace("{contactPerson_name}", objDetail.contactPerson.contactPerson_name));
            row.Cells[2].SetCellValue(row.Cells[2].StringCellValue.Replace("{company_name}", objDetail.company.company_name));
            row.Cells[3].SetCellValue(row.Cells[3].StringCellValue.Replace("{user_name}", objDetail.user.user_name + " " + objDetail.user.user_engName));

            row = (XSSFRow)sheet.GetRow(3);
            row.Cells[0].SetCellValue(row.Cells[0].StringCellValue.Replace("{contactPerson_email}", objDetail.contactPerson.contactPerson_email));
            row.Cells[2].SetCellValue(row.Cells[2].StringCellValue.Replace("{company_address}", objDetail.company.company_address));
            row.Cells[3].SetCellValue(row.Cells[3].StringCellValue.Replace("{user_email}", objDetail.user.user_email));

            row = (XSSFRow)sheet.GetRow(4);
            row.Cells[0].SetCellValue(row.Cells[0].StringCellValue.Replace("{company_serialNo}", objDetail.company.company_serialNo));

            string fax_string = "";

            if (objDetail.contactPerson.contactPerson_fax != "") {
                fax_string = " FAX：" + objDetail.contactPerson.contactPerson_fax;
            }

            row.Cells[2].SetCellValue(row.Cells[2].StringCellValue.Replace("{contactPerson_tel}", objDetail.contactPerson.contactPerson_tel + fax_string));

            //估價單契約有效期限
            UpperConvert upcov = new UpperConvert();
            string startDateStr = upcov.dateToUpper(DateTime.Parse(objDetail.quotation_expStart));
            string endDateStr = upcov.dateToUpper(DateTime.Parse(objDetail.quotation_expEnd));
            row = (XSSFRow)sheet.GetRow(5);
            row.Cells[0].SetCellValue(row.Cells[0].StringCellValue.Replace("{date_range}", startDateStr + " 至 " + endDateStr));

            // Copy style from old cell and apply to new cell
            XSSFCellStyle copyTempCellStyle = (XSSFCellStyle)workbook.CreateCellStyle();
            // Copy style from old cell and apply to new cell
            XSSFCellStyle copyTempCellFloatStyle = (XSSFCellStyle)workbook.CreateCellStyle();

            //估價單總價項目
            row = (XSSFRow)sheet.GetRow(11);
            copyTempCellStyle.CloneStyleFrom(row.Cells[6].CellStyle);
            copyTempCellFloatStyle.CloneStyleFrom(row.Cells[6].CellStyle);
            copyTempCellStyle.DataFormat = workbook.CreateDataFormat().GetFormat("\"NTD \"#,##0");
            copyTempCellFloatStyle.DataFormat = workbook.CreateDataFormat().GetFormat("\"NTD \"#,##0.#");

            row.Cells[6].SetCellType(CellType.Numeric);
            row.Cells[6].SetCellValue(objDetail.quotation_noTaxTotal);
            if (objDetail.quotation_noTaxTotal.ToString().IndexOf('.') >= 0)
            {
                row.Cells[6].CellStyle = copyTempCellFloatStyle;
            }
            else {
                row.Cells[6].CellStyle = copyTempCellStyle;
            }

            
            
            
            row = (XSSFRow)sheet.GetRow(12);

            //string quotation_specTotal = "";

            if (objDetail.quotation_specTotal > 0) {
                row.Cells[6].SetCellType(CellType.Numeric);
                row.Cells[6].SetCellValue(objDetail.quotation_specTotal);

                

                row.Cells[6].CellStyle = copyTempCellStyle;
            } else {
                row.Cells[6].SetCellValue("");
            }

            
            //row.Cells[6].SetCellValue(row.Cells[6].StringCellValue.Replace("{quotation_specTotal}", quotation_specTotal));
            
            row = (XSSFRow)sheet.GetRow(13);
            //row.Cells[6].SetCellValue(row.Cells[6].StringCellValue.Replace("{quotation_tax}", objDetail.quotation_tax.ToString("###,###")));
            row.Cells[6].SetCellType(CellType.Numeric);
            row.Cells[6].SetCellValue(objDetail.quotation_tax);

            if (objDetail.quotation_tax.ToString().IndexOf('.') >= 0)
            {
                row.Cells[6].CellStyle = copyTempCellFloatStyle;
            }
            else
            {
                row.Cells[6].CellStyle = copyTempCellStyle;
            }

            //row.Cells[6].CellStyle = copyTempCellStyle;

            row = (XSSFRow)sheet.GetRow(14);
            //row.Cells[6].SetCellValue(row.Cells[6].StringCellValue.Replace("{quotation_grandTotal}", objDetail.quotation_grandTotal.ToString("###,###")));
            row.Cells[6].SetCellType(CellType.Numeric);
            row.Cells[6].SetCellValue(objDetail.quotation_grandTotal);
            row.Cells[6].CellStyle = copyTempCellStyle;

            //服務協議
            string services_aggrement = objDetail.quotation_sa;
            services_aggrement = services_aggrement.Replace("##客戶公司##", objDetail.company.company_name + " ");
            services_aggrement = services_aggrement.Replace("##我們公司##", ourCompany_name + " ");
            row = (XSSFRow)sheet.GetRow(16);
            row.Cells[0].SetCellValue(row.Cells[0].StringCellValue.Replace("{quotation_sa}", services_aggrement));

      

            //付款方式與發票
            string quotation_grandTotal = ChtNumConverter.ToChtNum((long)objDetail.quotation_grandTotal);
            string quotation_grandTotalStr = "本專案費用總計新台幣"+ quotation_grandTotal + "圓整  (即NTD" + objDetail.quotation_grandTotal.ToString("###,###") + "含稅)";
            row = (XSSFRow)sheet.GetRow(20);
            row.Cells[0].SetCellValue(quotation_grandTotalStr);

            //簽章欄
            row = (XSSFRow)sheet.GetRow(27);
            row.Cells[0].SetCellValue(row.Cells[0].StringCellValue.Replace("{user_name}", objDetail.user.user_name));

            //匯款項目與發票
            int payment_count = objDetail.payments.Count;
            int invoice_count = objDetail.invoices.Count;
            int real_count = 0;

            if (payment_count > invoice_count)
            {
                real_count = payment_count;
            }
            else { 
                real_count = invoice_count;
            }

            for (int i = 1; i <= real_count; i++) {
                int rowIndex = 20 + i;
                CopyRow((XSSFWorkbook)workbook, (XSSFSheet)sheet, rowIndex, rowIndex + 1);

                if (i <= objDetail.payments.Count) {
                    //付款方式
                    row = (XSSFRow)sheet.GetRow(rowIndex);

                    string paymentStr = objDetail.payments[i - 1].payment_methodname;

                    if (objDetail.payments[i - 1].payment_descript != "") {
                        paymentStr += "; " + objDetail.payments[i - 1].payment_descript;
                    }

                    row.Cells[0].SetCellValue(paymentStr);
                }

                if (i <= objDetail.invoices.Count) {
                    //發票
                    row = (XSSFRow)sheet.GetRow(rowIndex);

                    row.Cells[3].SetCellValue(objDetail.invoices[i - 1].invoice_name);

                    if (objDetail.invoices[i - 1].invoice_type == "date")
                    {
                        row.Cells[4].SetCellValue(objDetail.invoices[i - 1].invoice_year.ToString() + "/" + objDetail.invoices[i - 1].invoice_month.ToString().PadLeft(2, '0'));
                    }
                    else {
                        row.Cells[4].SetCellValue(objDetail.invoices[i - 1].invoice_text);
                    }

                    
                    //row.Cells[6].SetCellValue("$NT" + objDetail.invoices[i - 1].invoice_noTaxMoney.ToString("###,###"));
                    row.Cells[6].SetCellType(CellType.Numeric);
                    row.Cells[6].SetCellValue(objDetail.invoices[i - 1].invoice_noTaxMoney);
                    row.Cells[6].CellStyle = copyTempCellStyle;
                }
            }

            int saRowIndex = 16;

            //紀錄範例列位置
            //目前編輯列
            int editRowIndex = 7;

            //空白編輯列
            int blankIndex = 7;
            //小計列位置
            int subTotalIndex = 8;
            //AC列位置
            int acIndex = 9;
            //此項目總金額位置 
            int sutTotalAcIndex = 10;
            //優惠總價為置
            int specTotalIndex = 12;

            //服務協議位置
            int saIndex = 16;

            //主項目編號
            int itemNumber = 0;
            //開始產生項目價格列
            foreach (quotationMainItemDetail objMain in objDetail.quotationMainItemDetails)
            {
                itemNumber++;

                //目前開始要填資料的位置
                int editIndex = editRowIndex;
                //目前主項目的個數(子項目加主項目)
                int rowCount = 0;

                CopyRow((XSSFWorkbook)workbook, (XSSFSheet)sheet, editRowIndex, editRowIndex + 1);
                blankIndex++;  
                subTotalIndex++;
                acIndex++;
                sutTotalAcIndex++;
                specTotalIndex++;
                saRowIndex++;
                saIndex++;

                foreach (quotationSubItem objSub in objMain.quotationSubItems) {
                    CopyRow((XSSFWorkbook)workbook, (XSSFSheet)sheet, editRowIndex, editRowIndex + 1);
                    editRowIndex++;
                    blankIndex++;
                    subTotalIndex++;
                    acIndex++;
                    sutTotalAcIndex++;
                    specTotalIndex ++;
                    saRowIndex++;
                    saIndex++;

                    rowCount++;
                }

                //項目編號合併並填入編號
                //sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(editIndex, editIndex + rowCount, 0, 0));
                sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(editIndex, editIndex, 1, 6));

                row = (XSSFRow)sheet.GetRow(editIndex);
                row.Cells[0].SetCellValue(itemNumber);
                row.Cells[1].SetCellValue(objMain.quotationMainItem_name);

                int acTotal = 0;

                int subItemNum = 0;
                //合併子項目row
                foreach (quotationSubItem objSub in objMain.quotationSubItems)
                {
                    subItemNum++;

                    string subItemNumberTxt = itemNumber.ToString() + "-" + subItemNum.ToString();

                    string descript = objSub.quotationSubItem_descript;

                    if (objSub.quotationSubItem_hasAC == "N" && objMain.quotationMainItem_ac > 0)
                    {
                        descript = descript + " (此項不加AC)"; 
                    }

                    editIndex++;
                    row = (XSSFRow)sheet.GetRow(editIndex);
                    row.Height = -1;
                    row.Cells[0].SetCellValue(subItemNumberTxt);
                    row.Cells[1].SetCellValue(objSub.quotationSubItem_name);
                    row.Cells[2].SetCellValue(descript);

                    row.Cells[3].SetCellType(CellType.Numeric);
                    row.Cells[3].SetCellValue(objSub.quotationSubItem_price);

                    if (objSub.quotationSubItem_price.ToString().IndexOf('.') >= 0)
                    {
                        row.Cells[3].CellStyle = copyTempCellFloatStyle;
                    }
                    else
                    {
                        row.Cells[3].CellStyle = copyTempCellStyle;
                    }

                    //row.Cells[3].CellStyle = copyTempCellStyle;

                    row.Cells[4].SetCellType(CellType.Numeric);
                    row.Cells[4].SetCellValue(objSub.quotationSubItem_number);

                    if (objSub.quotationSubItem_number.ToString().IndexOf('.') >= 0)
                    {
                        row.Cells[4].CellStyle = copyTempCellFloatStyle;
                    }
                    else
                    {
                        row.Cells[4].CellStyle = copyTempCellStyle;
                    }

                    //row.Cells[4].CellStyle = copyTempCellStyle;

                    row.Cells[5].SetCellValue(objSub.quotationSubItem_unitType);


                    row.Cells[6].SetCellType(CellType.Numeric);
                    row.Cells[6].SetCellValue(objSub.quotationSubItem_subTotal);

                    if (objSub.quotationSubItem_subTotal.ToString().IndexOf('.') >= 0)
                    {
                        row.Cells[6].CellStyle = copyTempCellFloatStyle;
                    }
                    else
                    {
                        row.Cells[6].CellStyle = copyTempCellStyle;
                    }

                    //row.Cells[6].CellStyle = copyTempCellStyle;

                    //row.Cells[3].SetCellValue("NTD " + objSub.quotationSubItem_price.ToString("###,###"));
                    //row.Cells[4].SetCellValue(objSub.quotationSubItem_number.ToString("###,###"));
                    //row.Cells[5].SetCellValue(objSub.quotationSubItem_unitType);
                    //row.Cells[6].SetCellValue(objSub.quotationSubItem_subTotal);

                    if (objSub.quotationSubItem_hasAC == "Y") {
                        acTotal += (int)Math.Round((objSub.quotationSubItem_price * objSub.quotationSubItem_number) * (objMain.quotationMainItem_ac / 100));
                    }
                }
                editIndex++;
                editRowIndex++;

                sheet.ShiftRows(editIndex, sheet.LastRowNum, 3);
                
                blankIndex+=3;
                subTotalIndex+=3;
                acIndex+=3;
                sutTotalAcIndex+=3;
                specTotalIndex+=3;
                saRowIndex += 3;
                saIndex +=3;

                //複製小計欄
                CopyRow((XSSFWorkbook)workbook, (XSSFSheet)sheet, subTotalIndex, editIndex);

                row = (XSSFRow)sheet.GetRow(editIndex);
                //row.Cells[6].SetCellValue("NTD " + (objMain.quotationMainItem_subTotal - acTotal).ToString("###,###"));
                row.Cells[6].SetCellType(CellType.Numeric);
                row.Cells[6].SetCellValue((objMain.quotationMainItem_subTotal - acTotal));
                row.Cells[6].CellStyle = copyTempCellStyle;

                rowCount++;

                editIndex++;
                editRowIndex++;

                //複製AC欄
                CopyRow((XSSFWorkbook)workbook, (XSSFSheet)sheet, acIndex, editIndex);

                row = (XSSFRow)sheet.GetRow(editIndex);
                //row.Cells[6].SetCellValue("NTD " + acTotal.ToString("###,###"));
                row.Cells[6].SetCellType(CellType.Numeric);
                row.Cells[6].SetCellValue(acTotal);
                row.Cells[6].CellStyle = copyTempCellStyle;
                row.Cells[0].SetCellValue(row.Cells[0].StringCellValue.Replace("{quotationMainItem_ac}", objMain.quotationMainItem_ac.ToString()));

                rowCount++;

                editIndex++;
                editRowIndex++;

                if (objMain.quotationMainItem_ac <= 0) {
                    row.ZeroHeight = true;
                }

                


                //複製此項目總金額欄
                CopyRow((XSSFWorkbook)workbook, (XSSFSheet)sheet, sutTotalAcIndex, editIndex);
                row = (XSSFRow)sheet.GetRow(editIndex);
                //row.Cells[6].SetCellValue("NTD " + (objMain.quotationMainItem_subTotal).ToString("###,###"));
                row.Cells[6].SetCellType(CellType.Numeric);
                row.Cells[6].SetCellValue(objMain.quotationMainItem_subTotal);
                row.Cells[6].CellStyle = copyTempCellStyle;
                rowCount++;
                editRowIndex++;
                //break;
            }

            //刪除不需要的優惠價格欄
            if (objDetail.quotation_specTotal == 0) {

                row = (XSSFRow)sheet.GetRow(specTotalIndex);
                if (row != null)
                {
                    sheet.RemoveRow(row);
                    sheet.ShiftRows(specTotalIndex + 1, sheet.LastRowNum, -1);
                    saRowIndex--;
                }
            }

            //刪除sutTotalAc
            row = (XSSFRow)sheet.GetRow(sutTotalAcIndex);
            if (row != null)
            {
                sheet.RemoveRow(row);
                sheet.ShiftRows(sutTotalAcIndex + 1, sheet.LastRowNum, -1);
                saRowIndex--;
            }

            row = (XSSFRow)sheet.GetRow(acIndex);
            if (row != null)
            {
                sheet.RemoveRow(row);
                sheet.ShiftRows(acIndex + 1, sheet.LastRowNum, -1);
                saRowIndex--;
            }

            row = (XSSFRow)sheet.GetRow(subTotalIndex);
            if (row != null)
            {
                sheet.RemoveRow(row);
                sheet.ShiftRows(subTotalIndex + 1, sheet.LastRowNum, -1);
                saRowIndex--;
            }

            row = (XSSFRow)sheet.GetRow(blankIndex);
            if (row != null)
            {
                sheet.RemoveRow(row);
                sheet.ShiftRows(blankIndex + 1, sheet.LastRowNum, -1);
                saRowIndex--;
            }

            string agent = Request.Headers["User-Agent"].ToString();

            string post_pc = "win";

            if (agent.Contains("Macintosh"))
            {
                post_pc = "mac";
            }

            //自适应高度，9代表从第10行开始，表头部分不会多行；endRow是结束的行，也就是有数据内容的行数，毕竟没内容的单元格，也没必要自适应行高
            for (int i = saRowIndex; i < saRowIndex + 3; i++)
            {
                if (sheet.GetRow(i) == null)
                {
                    continue;
                }
                IRow ICurRow = sheet.GetRow(i);
                int OldHg = ICurRow.Height;//当前行高
                int newHg = ICurRow.Height;//新行高，默认与当前行高一致

                for (int j = 0; j < 1; j++) {
                    if (ICurRow.GetCell(j) == null)
                    {
                        continue;
                    }
                    ICell CurCell = ICurRow.GetCell(j);

                    double cellWidth = 0;

                    for (int k = 0; k < 7; k++) {
                        cellWidth += sheet.GetColumnWidth(k);
                    }

                    int cellStringLength = GetCellStringLength(CurCell.StringCellValue, post_pc);

                    if (cellStringLength > cellWidth) {
                        double newHg1 = (double)(OldHg * (cellStringLength / cellWidth + 1));

                        double lastHg = newHg1;

                        if (lastHg > 8190) {
                            row = (XSSFRow)sheet.GetRow(saRowIndex);
                            row.Height = 8190;

                            lastHg = lastHg - 8190;
                        }

                        if (lastHg > 8190)
                        {
                            

                            row = (XSSFRow)sheet.GetRow(saRowIndex + 1);

                            row.Height = 8190;

                            lastHg = lastHg - 8190;
                        }
                        else {
                            row = (XSSFRow)sheet.GetRow(saRowIndex + 1);

                            row.Height = (short)lastHg;

                            lastHg = lastHg - 8190;
                        }

                        if (lastHg > 0) {
                            

                            row = (XSSFRow)sheet.GetRow(saRowIndex + 2);

                            if (lastHg > 8190)
                            {

                                row.Height = 8190;
                            }
                            else
                            {
                                row.Height = (short)lastHg;
                            }
                        }

                    }


                    
                }

               
            }


            //sheet.AutoSizeRow(saRowIndex);
            //sheet.AutoSizeRow(saRowIndex + 1);
            //sheet.AutoSizeRow(saRowIndex + 2);

            //row = (XSSFRow)sheet.GetRow(saRowIndex);
            //row.Height = 8190;

            //row = (XSSFRow)sheet.GetRow(saRowIndex + 1);
            //row.Height = 8190;

            //row = (XSSFRow)sheet.GetRow(saRowIndex + 2);
            //row.Height = 8000;

            MemoryStream ms = new MemoryStream();
            workbook.Write(ms);
            ms.Flush();

            var arrBites = ms.ToArray();

            MemoryStream newStream = new MemoryStream(arrBites);

            string downloadName = objDetail.quotation_name + " 報價單_" + DateTime.Now.ToString("yyyy-MM-dd");

            

            //if (agent.Contains("Macintosh"))
            //{
            //    downloadName = HttpUtility.UrlEncode(downloadName, Encoding.UTF8);
            //}

            return File(newStream, "application/vnd.ms-excel", downloadName + ".xlsx");

            

           

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


        /// <summary>
        /// 计算单元格内容长度
        /// 用 ASCII 码范围判断字符是不是汉字
        /// </summary>
        /// <param name="text">待判断字符或字符串</param>
        /// <returns>宽度</returns>
        public int GetCellStringLength(string text, string pc_type)
        {
            //汉字 453、数字和字母 239
            //这里的汉字与字母的宽度值，要根据Excel的字体大小计算
            //例如你单元格宽度1000，能放10个汉字，那汉字宽度就是1000/10=100
            //同理计算字母宽度
            int result = 0;
            foreach (char t in text)
            {
                if (t == 10)
                {
                    //忽略字符串中的换行符\n
                    continue;
                }
                else if (t > 127)
                {

                    if (pc_type == "win")
                    {
                        result += 660;
                    }
                    else {
                        result += 760;
                    }
                    
                }
                else
                {
                    if (pc_type == "win")
                    {
                        result += 370;
                    }
                    else {
                        result += 440;
                    }
                    
                }
            }
            return result;
        }


        /// 

        /// HSSFRow Copy Command
        ///
        /// Description:  Inserts a existing row into a new row, will automatically push down
        ///               any existing rows.  Copy is done cell by cell and supports, and the
        ///               command tries to copy all properties available (style, merged cells, values, etc...)
        /// 

        private void CopyRow(XSSFWorkbook workbook, XSSFSheet worksheet, int sourceRowNum, int destinationRowNum)
        {
            // Get the source / new row
            XSSFRow newRow = (XSSFRow)worksheet.GetRow(destinationRowNum);
            XSSFRow sourceRow = (XSSFRow)worksheet.GetRow(sourceRowNum);

            // If the row exist in destination, push down all rows by 1 else create a new row
            if (newRow != null)
            {
                worksheet.ShiftRows(destinationRowNum, worksheet.LastRowNum, 1);
                
                newRow = (XSSFRow)worksheet.CreateRow(destinationRowNum);
                newRow.Height = sourceRow.Height;
            }
            else
            {
                newRow = (XSSFRow)worksheet.CreateRow(destinationRowNum);
            }

            // Loop through source columns to add to new row
            for (int i = 0; i < sourceRow.LastCellNum; i++)
            {
                // Grab a copy of the old/new cell
                XSSFCell oldCell = (XSSFCell)sourceRow.GetCell(i);
                XSSFCell newCell = (XSSFCell)newRow.CreateCell(i);

                // If the old cell is null jump to next cell
                if (oldCell == null)
                {
                    newCell = null;
                    continue;
                }

                // Copy style from old cell and apply to new cell
                XSSFCellStyle newCellStyle = (XSSFCellStyle)workbook.CreateCellStyle();
                newCellStyle.CloneStyleFrom(oldCell.CellStyle); 
                newCell.CellStyle = newCellStyle;

                // If there is a cell comment, copy
                if (newCell.CellComment != null) newCell.CellComment = oldCell.CellComment;

                // If there is a cell hyperlink, copy
                if (oldCell.Hyperlink != null) newCell.Hyperlink = oldCell.Hyperlink;

                // Set the cell data type
                newCell.SetCellType(oldCell.CellType);

                // Set the cell data value
                switch (oldCell.CellType)
                {
                    case CellType.Blank:
                        newCell.SetCellValue(oldCell.StringCellValue);
                        break;
                    case CellType.Boolean:
                        newCell.SetCellValue(oldCell.BooleanCellValue);
                        break;
                    case CellType.Error:
                        newCell.SetCellErrorValue(oldCell.ErrorCellValue);
                        break;
                    case CellType.Formula:
                        newCell.SetCellFormula(oldCell.CellFormula);
                        break;
                    case CellType.Numeric:
                        newCell.SetCellValue(oldCell.NumericCellValue);
                        break;
                    case CellType.String:
                        newCell.SetCellValue(oldCell.RichStringCellValue);
                        break;
                    case CellType.Unknown:
                        newCell.SetCellValue(oldCell.StringCellValue);
                        break;
                }
            }

            // If there are are any merged regions in the source row, copy to new row
            for (int i = 0; i < worksheet.NumMergedRegions; i++)
            {
                CellRangeAddress cellRangeAddress = worksheet.GetMergedRegion(i);
                if (cellRangeAddress.FirstRow == sourceRow.RowNum)
                {
                    CellRangeAddress newCellRangeAddress = new CellRangeAddress(newRow.RowNum,
                                                                                (newRow.RowNum +
                                                                                 (cellRangeAddress.FirstRow -
                                                                                  cellRangeAddress.LastRow)),
                                                                                cellRangeAddress.FirstColumn,
                                                                                cellRangeAddress.LastColumn);
                    worksheet.AddMergedRegion(newCellRangeAddress);
                }
            }

        }

        [Route("saveas")]
        public ActionResult SaveAs(IFormCollection obj) {
            saveasResult ret = new saveasResult();

            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");
            }

            string quotation_uid = obj["quotation_uid"].ToString();
            string quotation_name = obj["quotation_name"].ToString();
            string quotation_version = obj["quotation_version"].ToString();
            string project_uid = obj["project_uid"].ToString();
            string project_name = obj["project_name"].ToString();
            string company_uid = obj["company_uid"].ToString();
            string contactPerson_uid = obj["contactPerson_uid"].ToString();
            string method = obj["method"].ToString();

            if (method == "save_to_other") {
                quotation oldQuotation = conn.QueryFirstOrDefault<quotation>("select * from quotation where quotation_isdel = 'N' and quotation_uid = @quotation_uid and quotation_version = @quotation_version ", new { quotation_uid = quotation_uid, quotation_version = quotation_version });

                if (oldQuotation == null)
                {
                    ret.ret = "no";
                    ret.err_code = "0005";
                    ret.message = "無此版本號的 quotation_uid 資料!";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                string new_quotation_uid = "q_" + GlobalClass.CreateRandomCode(24);

                var config = new MapperConfiguration(cfg =>
                {
                    cfg.CreateMap<quotation, quotation>();
                });
                var mapper = config.CreateMapper();
                quotation quotation = new quotation();

                mapper.Map(oldQuotation, quotation);

                quotation.quotation_uid = new_quotation_uid;
                quotation.quotation_name = quotation_name;
                quotation.quotation_log = "由 [" + oldQuotation.quotation_name + "] 此報價單另存產生!";
                quotation.quotation_version = 1;
                quotation.quotation_createdate = DateTime.Now;
                quotation.quotation_modifydate = DateTime.Now;
                quotation.quotation_create_uid = token.user_uid;
                quotation.quotation_modify_uid = token.user_uid;
                quotation.quotation_revoke = "N";
                quotation.company_uid = company_uid;
                quotation.contactPerson_uid = contactPerson_uid;
                quotation.project_uid = project_uid;


                List<quotationMainItem> quotationMainItems = new List<quotationMainItem>();
                List<quotationSubItem> quotationSubItems = new List<quotationSubItem>();
                List<payment> payments = new List<payment>();
                List<invoice> invoices = new List<invoice>();

                List<quotationMainItem> old_quotationMainItems = conn.Query<quotationMainItem>("select * from quotationMainItem where quotation_uid = @quotation_uid and quotationMainItem_version = @quotation_version", new { quotation_uid = quotation_uid, quotation_version = quotation_version }).ToList();

                List<payment> old_payments = conn.Query<payment>("select * from payment where quotation_uid = @quotation_uid and payment_version = @quotation_version", new { quotation_uid = quotation_uid, quotation_version = quotation_version }).ToList();
                List<invoice> old_invoices = conn.Query<invoice>("select * from invoice where quotation_uid = @quotation_uid and invoice_version = @quotation_version", new { quotation_uid = quotation_uid, quotation_version = quotation_version }).ToList();

                //主項目複製
                foreach (quotationMainItem item in old_quotationMainItems)
                {
                    var configItem = new MapperConfiguration(cfg =>
                    {
                        cfg.CreateMap<quotationMainItem, quotationMainItem>();
                    });
                    var mapperItem = configItem.CreateMapper();

                    quotationMainItem quotationMainItem = new quotationMainItem();

                    mapperItem.Map(item, quotationMainItem);

                    quotationMainItem.quotation_uid = new_quotation_uid;
                    quotationMainItem.quotationMainItem_version = 1;
                    quotationMainItem.quotationMainItem_revoke = "N";
                    quotationMainItem.quotationMainItem_uid = "qm_" + GlobalClass.CreateRandomCode(24);
                    quotationMainItem.quotationMainItem_createdate = DateTime.Now;
                    quotationMainItem.quotationMainItem_modifydate = DateTime.Now;
                  

                    quotationMainItems.Add(quotationMainItem);

                    List<quotationSubItem> old_quotationSubItems = conn.Query<quotationSubItem>("select * from quotationSubItem where quotation_uid = @quotation_uid and quotationSubItem_version = @quotation_version and quotationMainItem_uid = @quotationMainItem_uid ", new { quotation_uid = quotation_uid, quotation_version = quotation_version, quotationMainItem_uid = item.quotationMainItem_uid }).ToList();

                    foreach (quotationSubItem subItem in old_quotationSubItems)
                    {
                        var configSubItem = new MapperConfiguration(cfg =>
                        {
                            cfg.CreateMap<quotationSubItem, quotationSubItem>();
                        });
                        var mapperSubItem = configSubItem.CreateMapper();

                        quotationSubItem quotationSubItem = new quotationSubItem();

                        mapperSubItem.Map(subItem, quotationSubItem);

                        quotationSubItem.quotationMainItem_uid = quotationMainItem.quotationMainItem_uid;
                        quotationSubItem.quotation_uid = new_quotation_uid;
                        quotationSubItem.quotationSubItem_version = 1;
                        quotationSubItem.quotationSubItem_uid = "qs_" + GlobalClass.CreateRandomCode(24);
                        quotationSubItem.quotationSubItem_createdate = DateTime.Now;
                        quotationSubItem.quotationSubItem_modifydate = DateTime.Now;

                        quotationSubItems.Add(quotationSubItem);
                    }

                }

                foreach (payment item in old_payments)
                {
                    var configItem = new MapperConfiguration(cfg =>
                    {
                        cfg.CreateMap<payment, payment>();
                    });
                    var mapperItem = configItem.CreateMapper();

                    payment paymentItem = new payment();

                    mapperItem.Map(item, paymentItem);

                    paymentItem.payment_uid = "pay_" + GlobalClass.CreateRandomCode(24);
                    paymentItem.quotation_uid = new_quotation_uid;
                    paymentItem.payment_version = 1;
                    paymentItem.payment_createdate = DateTime.Now;
                    paymentItem.payment_modifydate = DateTime.Now;

                    payments.Add(paymentItem);
                }

                foreach (invoice item in old_invoices)
                {
                    var configItem = new MapperConfiguration(cfg =>
                    {
                        cfg.CreateMap<invoice, invoice>();
                    });
                    var mapperItem = configItem.CreateMapper();

                    invoice invoiceItem = new invoice();

                    mapperItem.Map(item, invoiceItem);

                    invoiceItem.invoice_uid = "inv_" + GlobalClass.CreateRandomCode(24);
                    invoiceItem.invoice_version = 1;
                    invoiceItem.invoice_revoke = "N";
                    invoiceItem.quotation_uid = new_quotation_uid;

                    invoices.Add(invoiceItem);

                }

                conn.Insert(invoices);
                conn.Insert(payments);
                conn.Insert(quotationSubItems);
                conn.Insert(quotationMainItems);
                conn.Insert(quotation);

                ret.ret = "yes";
                ret.quotationView = conn.QueryFirstOrDefault<quotationView>("select * from quotationView where quotation_isdel = 'N' and quotation_revoke = 'N' and quotation_uid = @quotation_uid", new { quotation_uid = new_quotation_uid });

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

            if (method == "save_to_same") {
                quotation oldQuotation = conn.QueryFirstOrDefault<quotation>("select * from quotation where quotation_isdel = 'N' and quotation_uid = @quotation_uid and quotation_version = @quotation_version ", new { quotation_uid = quotation_uid, quotation_version = quotation_version });

                if (oldQuotation == null) {
                    ret.ret = "no";
                    ret.err_code = "0005";
                    ret.message = "無此版本號的 quotation_uid 資料!";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                string new_quotation_uid = "q_" + GlobalClass.CreateRandomCode(24);

                var config = new MapperConfiguration(cfg =>
                {
                    cfg.CreateMap<quotation, quotation>();
                });
                var mapper = config.CreateMapper();
                quotation quotation = new quotation();

                mapper.Map(oldQuotation, quotation);

                quotation.quotation_uid = new_quotation_uid;
                quotation.quotation_name = quotation_name;
                quotation.quotation_log = "由 [" + oldQuotation.quotation_name + "] 此報價單另存產生!";
                quotation.quotation_version = 1;
                quotation.quotation_createdate = DateTime.Now;
                quotation.quotation_modifydate = DateTime.Now;
                quotation.quotation_create_uid = token.user_uid;
                quotation.quotation_modify_uid = token.user_uid;
                quotation.quotation_revoke = "N";

                List<quotationMainItem> quotationMainItems = new List<quotationMainItem>();
                List<quotationSubItem> quotationSubItems = new List<quotationSubItem>();
                List<payment> payments = new List<payment>();
                List<invoice> invoices = new List<invoice>();

                List<quotationMainItem> old_quotationMainItems = conn.Query<quotationMainItem>("select * from quotationMainItem where quotation_uid = @quotation_uid and quotationMainItem_version = @quotation_version", new { quotation_uid = quotation_uid, quotation_version = quotation_version }).ToList();

                List<payment> old_payments = conn.Query<payment>("select * from payment where quotation_uid = @quotation_uid and payment_version = @quotation_version", new { quotation_uid = quotation_uid, quotation_version = quotation_version }).ToList();
                List<invoice> old_invoices = conn.Query<invoice>("select * from invoice where quotation_uid = @quotation_uid and invoice_version = @quotation_version", new { quotation_uid = quotation_uid, quotation_version = quotation_version }).ToList();

                //主項目複製
                foreach (quotationMainItem item in old_quotationMainItems) {
                    var configItem = new MapperConfiguration(cfg =>
                    {
                        cfg.CreateMap<quotationMainItem, quotationMainItem>();
                    });
                    var mapperItem = configItem.CreateMapper();

                    quotationMainItem quotationMainItem = new quotationMainItem();

                    mapperItem.Map(item, quotationMainItem);

                    quotationMainItem.quotation_uid = new_quotation_uid;
                    quotationMainItem.quotationMainItem_version = 1;
                    quotationMainItem.quotationMainItem_revoke = "N";
                    quotationMainItem.quotationMainItem_uid = "qm_" + GlobalClass.CreateRandomCode(24);
                    quotationMainItem.quotationMainItem_createdate = DateTime.Now;
                    quotationMainItem.quotationMainItem_modifydate = DateTime.Now;

                    quotationMainItems.Add(quotationMainItem);

                    List<quotationSubItem> old_quotationSubItems = conn.Query<quotationSubItem>("select * from quotationSubItem where quotation_uid = @quotation_uid and quotationSubItem_version = @quotation_version and quotationMainItem_uid = @quotationMainItem_uid ", new { quotation_uid = quotation_uid, quotation_version = quotation_version, quotationMainItem_uid = item.quotationMainItem_uid }).ToList();

                    foreach (quotationSubItem subItem in old_quotationSubItems)
                    {
                        var configSubItem = new MapperConfiguration(cfg =>
                        {
                            cfg.CreateMap<quotationSubItem, quotationSubItem>();
                        });
                        var mapperSubItem = configSubItem.CreateMapper();

                        quotationSubItem quotationSubItem = new quotationSubItem();

                        mapperSubItem.Map(subItem, quotationSubItem);

                        quotationSubItem.quotationMainItem_uid = quotationMainItem.quotationMainItem_uid;
                        quotationSubItem.quotation_uid = new_quotation_uid;
                        quotationSubItem.quotationSubItem_version = 1;
                        quotationSubItem.quotationSubItem_uid = "qs_" + GlobalClass.CreateRandomCode(24);
                        quotationSubItem.quotationSubItem_createdate = DateTime.Now;
                        quotationSubItem.quotationSubItem_modifydate = DateTime.Now;

                        quotationSubItems.Add(quotationSubItem);
                    }

                }

                foreach (payment item in old_payments) {
                    var configItem = new MapperConfiguration(cfg =>
                    {
                        cfg.CreateMap<payment, payment>();
                    });
                    var mapperItem = configItem.CreateMapper();

                    payment paymentItem = new payment();

                    mapperItem.Map(item, paymentItem);

                    paymentItem.payment_uid = "pay_" + GlobalClass.CreateRandomCode(24);
                    paymentItem.quotation_uid = new_quotation_uid;
                    paymentItem.payment_version = 1;
                    paymentItem.payment_createdate = DateTime.Now;
                    paymentItem.payment_modifydate = DateTime.Now;

                    payments.Add(paymentItem);
                }

                foreach (invoice item in old_invoices) {
                    var configItem = new MapperConfiguration(cfg =>
                    {
                        cfg.CreateMap<invoice, invoice>();
                    });
                    var mapperItem = configItem.CreateMapper();

                    invoice invoiceItem = new invoice();

                    mapperItem.Map(item, invoiceItem);

                    invoiceItem.invoice_uid = "inv_" + GlobalClass.CreateRandomCode(24);
                    invoiceItem.invoice_version = 1;
                    invoiceItem.invoice_revoke = "N";
                    invoiceItem.quotation_uid = new_quotation_uid;

                    invoices.Add(invoiceItem);

                }

                conn.Insert(invoices);
                conn.Insert(payments);
                conn.Insert(quotationSubItems);
                conn.Insert(quotationMainItems);
                conn.Insert(quotation);

                ret.ret = "yes";
                ret.quotationView = conn.QueryFirstOrDefault<quotationView>("select * from quotationView where quotation_isdel = 'N' and quotation_revoke = 'N' and quotation_uid = @quotation_uid", new { quotation_uid = new_quotation_uid });

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

            if (method == "save_to_new") {
                quotation oldQuotation = conn.QueryFirstOrDefault<quotation>("select * from quotation where quotation_isdel = 'N' and quotation_uid = @quotation_uid and quotation_version = @quotation_version ", new { quotation_uid = quotation_uid, quotation_version = quotation_version });

                if (oldQuotation == null)
                {
                    ret.ret = "no";
                    ret.err_code = "0005";
                    ret.message = "無此版本號的 quotation_uid 資料!";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                project_uid = "p_" + GlobalClass.CreateRandomCode(24);
                project new_project = new project();
                new_project.project_uid = project_uid;
                new_project.dept_uid = oldQuotation.dept_uid;
                new_project.company_uid = company_uid;
                new_project.project_datetime = DateTime.Now.ToString("yyyy/MM/dd");
                new_project.project_creative_uid = token.user_uid;
                new_project.project_lastmodify_uid = token.user_uid;
                new_project.project_isdel = "N";
                new_project.project_modifydate = DateTime.Now;
                new_project.project_createdate = DateTime.Now;
                new_project.project_name = project_name;

                string new_quotation_uid = "q_" + GlobalClass.CreateRandomCode(24);

                var config = new MapperConfiguration(cfg =>
                {
                    cfg.CreateMap<quotation, quotation>();
                });
                var mapper = config.CreateMapper();
                quotation quotation = new quotation();

                mapper.Map(oldQuotation, quotation);

                quotation.quotation_uid = new_quotation_uid;
                quotation.quotation_name = quotation_name;
                quotation.quotation_log = "由 [" + oldQuotation.quotation_name + "] 此報價單另存產生!";
                quotation.quotation_version = 1;
                quotation.quotation_createdate = DateTime.Now;
                quotation.quotation_modifydate = DateTime.Now;
                quotation.quotation_create_uid = token.user_uid;
                quotation.quotation_modify_uid = token.user_uid;
                quotation.quotation_revoke = "N";
                quotation.company_uid = company_uid;
                quotation.contactPerson_uid = contactPerson_uid;
                quotation.project_uid = project_uid;


                List<quotationMainItem> quotationMainItems = new List<quotationMainItem>();
                List<quotationSubItem> quotationSubItems = new List<quotationSubItem>();
                List<payment> payments = new List<payment>();
                List<invoice> invoices = new List<invoice>();

                List<quotationMainItem> old_quotationMainItems = conn.Query<quotationMainItem>("select * from quotationMainItem where quotation_uid = @quotation_uid and quotationMainItem_version = @quotation_version", new { quotation_uid = quotation_uid, quotation_version = quotation_version }).ToList();

                List<payment> old_payments = conn.Query<payment>("select * from payment where quotation_uid = @quotation_uid and payment_version = @quotation_version", new { quotation_uid = quotation_uid, quotation_version = quotation_version }).ToList();
                List<invoice> old_invoices = conn.Query<invoice>("select * from invoice where quotation_uid = @quotation_uid and invoice_version = @quotation_version", new { quotation_uid = quotation_uid, quotation_version = quotation_version }).ToList();

                //主項目複製
                foreach (quotationMainItem item in old_quotationMainItems)
                {
                    var configItem = new MapperConfiguration(cfg =>
                    {
                        cfg.CreateMap<quotationMainItem, quotationMainItem>();
                    });
                    var mapperItem = configItem.CreateMapper();

                    quotationMainItem quotationMainItem = new quotationMainItem();

                    mapperItem.Map(item, quotationMainItem);

                    quotationMainItem.quotation_uid = new_quotation_uid;
                    quotationMainItem.quotationMainItem_version = 1;
                    quotationMainItem.quotationMainItem_revoke = "N";
                    quotationMainItem.quotationMainItem_uid = "qm_" + GlobalClass.CreateRandomCode(24);
                    quotationMainItem.quotationMainItem_createdate = DateTime.Now;
                    quotationMainItem.quotationMainItem_modifydate = DateTime.Now;


                    quotationMainItems.Add(quotationMainItem);

                    List<quotationSubItem> old_quotationSubItems = conn.Query<quotationSubItem>("select * from quotationSubItem where quotation_uid = @quotation_uid and quotationSubItem_version = @quotation_version and quotationMainItem_uid = @quotationMainItem_uid ", new { quotation_uid = quotation_uid, quotation_version = quotation_version, quotationMainItem_uid = item.quotationMainItem_uid }).ToList();

                    foreach (quotationSubItem subItem in old_quotationSubItems)
                    {
                        var configSubItem = new MapperConfiguration(cfg =>
                        {
                            cfg.CreateMap<quotationSubItem, quotationSubItem>();
                        });
                        var mapperSubItem = configSubItem.CreateMapper();

                        quotationSubItem quotationSubItem = new quotationSubItem();

                        mapperSubItem.Map(subItem, quotationSubItem);

                        quotationSubItem.quotationMainItem_uid = quotationMainItem.quotationMainItem_uid;
                        quotationSubItem.quotation_uid = new_quotation_uid;
                        quotationSubItem.quotationSubItem_version = 1;
                        quotationSubItem.quotationSubItem_uid = "qs_" + GlobalClass.CreateRandomCode(24);
                        quotationSubItem.quotationSubItem_createdate = DateTime.Now;
                        quotationSubItem.quotationSubItem_modifydate = DateTime.Now;

                        quotationSubItems.Add(quotationSubItem);
                    }

                }

                foreach (payment item in old_payments)
                {
                    var configItem = new MapperConfiguration(cfg =>
                    {
                        cfg.CreateMap<payment, payment>();
                    });
                    var mapperItem = configItem.CreateMapper();

                    payment paymentItem = new payment();

                    mapperItem.Map(item, paymentItem);

                    paymentItem.payment_uid = "pay_" + GlobalClass.CreateRandomCode(24);
                    paymentItem.quotation_uid = new_quotation_uid;
                    paymentItem.payment_version = 1;
                    paymentItem.payment_createdate = DateTime.Now;
                    paymentItem.payment_modifydate = DateTime.Now;

                    payments.Add(paymentItem);
                }

                foreach (invoice item in old_invoices)
                {
                    var configItem = new MapperConfiguration(cfg =>
                    {
                        cfg.CreateMap<invoice, invoice>();
                    });
                    var mapperItem = configItem.CreateMapper();

                    invoice invoiceItem = new invoice();

                    mapperItem.Map(item, invoiceItem);

                    invoiceItem.invoice_uid = "inv_" + GlobalClass.CreateRandomCode(24);
                    invoiceItem.invoice_version = 1;
                    invoiceItem.invoice_revoke = "N";
                    invoiceItem.quotation_uid = new_quotation_uid;

                    invoices.Add(invoiceItem);

                }

                conn.Insert(invoices);
                conn.Insert(payments);
                conn.Insert(quotationSubItems);
                conn.Insert(quotationMainItems);
                conn.Insert(quotation);
                conn.Insert(new_project);

                ret.ret = "yes";
                ret.quotationView = conn.QueryFirstOrDefault<quotationView>("select * from quotationView where quotation_isdel = 'N' and quotation_revoke = 'N' and quotation_uid = @quotation_uid", new { quotation_uid = new_quotation_uid });
                ret.projectView = conn.QueryFirstOrDefault<projectView>("select * from projectView where project_isdel = 'N' and project_uid = @project_uid ", new { project_uid = project_uid });

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

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

        }

        [Route("getHistoryList")]
        public ActionResult GetHistoryList(IFormCollection obj) {
            quotationViewListResult ret = new quotationViewListResult();
            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");
            }

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

            quotation quotation = conn.QueryFirstOrDefault<quotation>("select * from quotation where quotation_isdel = 'N' and quotation_revoke = 'N' and quotation_uid = @quotation_uid ", new { quotation_uid = quotation_uid });

            if (quotation == null) {
                ret.ret = "no";
                ret.err_code = "0009";
                ret.message = "無此筆 quotation_uid 資料!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            ret.quotationViews = conn.Query<quotationView>("select * from quotationView where quotation_isdel = 'N' and quotation_uid = @quotation_uid order by quotation_version desc  ", new { quotation_uid = quotation_uid }).ToList();
            ret.ret = "yes";
            return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
        }

        [Route("addEditDelQuotation")]
        public ActionResult AddEditDelQuotation(IFormCollection obj) {
            quotationDetailResult ret = new quotationDetailResult();

            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");
            }



            string method = obj["method"].ToString();
            string dept_uid = obj["dept_uid"].ToString();
            string project_uid = obj["project_uid"].ToString();
            string quotation_uid = obj["quotation_uid"].ToString();
            string quotation_version = obj["quotation_version"].ToString();
            string quotation_prodMethod = obj["quotation_prodMethod"].ToString();
            string quotation_date = obj["quotation_date"].ToString();
            string quotation_expStart = obj["quotation_expStart"].ToString();
            string quotation_expEnd = obj["quotation_expEnd"].ToString();
            string quotation_name = obj["quotation_name"].ToString();
            string contactPerson_uid = obj["contactPerson_uid"].ToString();
            string company_uid = obj["company_uid"].ToString();
            string quotation_log = obj["quotation_log"].ToString();
            string quotation_noTaxTotal = obj["quotation_noTaxTotal"].ToString();
            string quotation_specTotal = obj["quotation_specTotal"].ToString();
            string quotation_tax = obj["quotation_tax"].ToString();
            string quotation_grandTotal = obj["quotation_grandTotal"].ToString();
            string quotation_sa = obj["quotation_sa"].ToString();
            string mainItems_jsonstr = obj["mainItems"].ToString();
            string payments_jsonstr = obj["payments"].ToString();
            string invoices_jsonstr = obj["invoices"].ToString();
            string quotation_revoke = "N";
            string quotation_isdel = "N";

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

            if (method == "del") {
                quotation objQuotation = conn.QueryFirstOrDefault<quotation>("select * from quotation where quotation_isdel = 'N' and quotation_revoke = 'N' and quotation_uid = @quotation_uid order by quotation_version desc", new { quotation_uid = quotation_uid });

                if (objQuotation == null)
                {
                    ret.ret = "no";
                    ret.err_code = "0009";
                    ret.message = "此筆資料不存在或已被刪除!";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                objQuotation.quotation_isdel = "Y";
                objQuotation.quotation_modifydate = DateTime.Now;
                objQuotation.quotation_modify_uid = token.user_uid;
                objQuotation.quotation_log = token.user_name + " 刪除了此張報價單!";

                conn.Update(objQuotation);

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

            if (method == "edit")
            {
                quotation oldQuotation = conn.QueryFirstOrDefault<quotation>("select * from quotation where quotation_version = @quotation_version and quotation_uid = @quotation_uid ", new { quotation_version = quotation_version, quotation_uid = quotation_uid });

                if (oldQuotation == null)
                {
                    ret.ret = "no";
                    ret.err_code = "0002";
                    ret.message = "找不到此筆報價單資料!";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                quotation lastVerQuotation = conn.QueryFirstOrDefault<quotation>("select * from quotation where quotation_isdel = 'N' and quotation_revoke = 'N' and quotation_uid = @quotation_uid order by quotation_version desc ", new { quotation_uid = quotation_uid });

                if (lastVerQuotation == null)
                {
                    ret.ret = "no";
                    ret.err_code = "0002";
                    ret.message = "找不到此筆報價單資料!";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                int new_version = lastVerQuotation.quotation_version + 1;

                //--- start update
                quotation objQuotation = new quotation();

                //quotation_log = quotation_log;
                //quotation_uid = quotation_uid;
                quotation_version = new_version.ToString();
                objQuotation.quotation_uid = quotation_uid;
                objQuotation.quotation_version = int.Parse(quotation_version);
                objQuotation.dept_uid = dept_uid;
                objQuotation.quotation_prodMethod = lastVerQuotation.quotation_prodMethod;
                objQuotation.quotation_date = quotation_date;
                objQuotation.quotation_expStart = quotation_expStart;
                objQuotation.quotation_expEnd = quotation_expEnd;
                objQuotation.quotation_name = quotation_name;
                objQuotation.project_uid = project_uid;
                objQuotation.contactPerson_uid = contactPerson_uid;
                objQuotation.company_uid = company_uid;
                objQuotation.quotation_log = quotation_log;
                objQuotation.quotation_create_uid = oldQuotation.quotation_create_uid;
                objQuotation.quotation_modify_uid = token.user_uid;
                objQuotation.quotation_noTaxTotal = double.Parse(quotation_noTaxTotal);
                objQuotation.quotation_specTotal = double.Parse(quotation_specTotal);
                objQuotation.quotation_tax = double.Parse(quotation_tax);
                objQuotation.quotation_grandTotal = double.Parse(quotation_grandTotal);
                objQuotation.quotation_sa = quotation_sa;
                objQuotation.quotation_isdel = quotation_isdel;
                objQuotation.quotation_revoke = quotation_revoke;
                objQuotation.quotation_createdate = DateTime.Now;
                objQuotation.quotation_modifydate = DateTime.Now;

                dynamic mainItems_Json;
                dynamic payments_Json;
                dynamic invoices_Json;

                try
                {
                    mainItems_Json = JsonConvert.DeserializeObject(mainItems_jsonstr);
                    payments_Json = JsonConvert.DeserializeObject(payments_jsonstr);
                    invoices_Json = JsonConvert.DeserializeObject(invoices_jsonstr);

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

                List<quotationMainItem> quotationMainItems = new List<quotationMainItem>();
                List<quotationSubItem> quotationSubItems = new List<quotationSubItem>();

                foreach (dynamic item in mainItems_Json)
                {
                    string quotationMainItem_uid = "qm_" + GlobalClass.CreateRandomCode(24);

                    quotationMainItem newItem = new quotationMainItem();
                    newItem.quotation_uid = quotation_uid;
                    newItem.mainItem_uid = item.mainItem_uid;
                    newItem.quotationMainItem_uid = quotationMainItem_uid;
                    newItem.quotationMainItem_name = item.quotationMainItem_name;
                    newItem.quotationMainItem_ac = double.Parse((string)item.quotationMainItem_ac);
                    newItem.quotationMainItem_subTotal = double.Parse((string)item.quotationMainItem_subTotal);
                    newItem.quotationMainItem_revoke = "N";
                    newItem.quotationMainItem_version = int.Parse((string)quotation_version);

                    quotationMainItems.Add(newItem);

                    foreach (dynamic subItem in item.subitems)
                    {
                        quotationSubItem newSubItem = new quotationSubItem();
                        newSubItem.quotationSubItem_uid = "qs" + GlobalClass.CreateRandomCode(24);
                        newSubItem.quotationMainItem_uid = quotationMainItem_uid;
                        newSubItem.quotation_uid = quotation_uid;
                        newSubItem.subItem_uid = subItem.subItem_uid;
                        newSubItem.quotationSubItem_name = subItem.quotationSubItem_name;
                        newSubItem.quotationSubItem_descript = subItem.quotationSubItem_descript;
                        newSubItem.quotationSubItem_price = double.Parse((string)subItem.quotationSubItem_price);
                        newSubItem.quotationSubItem_unitType = subItem.quotationSubItem_unitType;
                        newSubItem.quotationSubItem_number = double.Parse((string)subItem.quotationSubItem_number);
                        newSubItem.quotationSubItem_subTotal = double.Parse((string)subItem.quotationSubItem_subTotal);
                        newSubItem.quotationSubItem_hasAC = subItem.quotationSubItem_hasAC;
                        newSubItem.quotationSubItem_revoke = "N";
                        newSubItem.quotationSubItem_version = int.Parse((string)quotation_version);

                        quotationSubItems.Add(newSubItem);
                    }
                }

                List<payment> payments = new List<payment>();

                foreach (dynamic item in payments_Json)
                {
                    payment newItem = new payment();

                    newItem.payment_uid = "pay_" + GlobalClass.CreateRandomCode(20);
                    newItem.quotation_uid = quotation_uid;
                    newItem.payment_method = item.payment_method;
                    newItem.payment_methodname = item.payment_methodname;
                    newItem.payment_descript = item.payment_descript;
                    newItem.payment_revoke = "N";
                    newItem.payment_version = int.Parse((string)quotation_version);

                    payments.Add(newItem);
                }

                List<invoice> invoices = new List<invoice>();

                foreach (dynamic item in invoices_Json)
                {
                    invoice newItem = new invoice();

                    newItem.invoice_uid = "inv_" + GlobalClass.CreateRandomCode(20);
                    newItem.quotation_uid = quotation_uid;
                    newItem.invoice_name = item.invoice_name;
                    newItem.invoice_type = item.invoice_type;

                    if (newItem.invoice_type == "date")
                    {
                        string yearmonth = item.invoice_date;
                        string strYear = yearmonth.Split('/')[0];
                        string strMonth = yearmonth.Split("/")[1];

                        newItem.invoice_year = int.Parse(strYear);
                        newItem.invoice_month = int.Parse(strMonth);
                        newItem.invoice_text = "";
                    }
                    else {
                        newItem.invoice_year = 0;
                        newItem.invoice_month = 0;
                        newItem.invoice_text = item.invoice_text;
                    }


                    
                    newItem.invoice_noTaxMoney = int.Parse((string)item.invoice_noTaxMoney);
                    newItem.invoice_revoke = "N";
                    newItem.invoice_version = int.Parse((string)quotation_version);

                    invoices.Add(newItem);
                }

                string old_version = lastVerQuotation.quotation_version.ToString();

                conn.Execute("update invoice set invoice_revoke = 'Y', invoice_modifydate = @invoice_modifydate where quotation_uid = @quotation_uid and invoice_version = @quotation_version ", new { invoice_modifydate = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), quotation_uid = quotation_uid, quotation_version = old_version });
                conn.Execute("update payment set payment_revoke = 'Y', payment_modifydate = @payment_modifydate where quotation_uid = @quotation_uid and payment_version = @quotation_version ", new { payment_modifydate = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), quotation_uid = quotation_uid, quotation_version = old_version });
                conn.Execute("update quotationSubItem set quotationSubItem_revoke = 'Y', quotationSubItem_modifydate = @quotationSubItem_modifydate where quotation_uid = @quotation_uid and quotationSubItem_version = @quotation_version ", new { quotationSubItem_modifydate = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), quotation_uid = quotation_uid, quotation_version = old_version });
                conn.Execute("update quotationMainItem set quotationMainItem_revoke = 'Y', quotationMainItem_modifydate = @quotationMainItem_modifydate where quotation_uid = @quotation_uid and quotationMainItem_version = @quotation_version ", new { quotationMainItem_modifydate = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), quotation_uid = quotation_uid, quotation_version = old_version });
                conn.Execute("update quotation set quotation_modify_uid = @quotation_modify_uid, quotation_revoke = 'Y', quotation_modifydate = @quotation_modifydate where quotation_uid = @quotation_uid and quotation_version = @quotation_version ", new { quotation_modify_uid = token.user_uid, quotation_modifydate = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), quotation_uid = quotation_uid, quotation_version = old_version });



                conn.Insert(invoices);
                conn.Insert(payments);
                conn.Insert(quotationSubItems);
                conn.Insert(quotationMainItems);
                conn.Insert<quotation>(objQuotation);

                //--- end update
                ret.quotationView = conn.QueryFirstOrDefault<quotationView>("select * from quotationView where quotation_uid = @quotation_uid and quotation_isdel = 'N' and quotation_revoke = 'N' ", new { quotation_uid = quotation_uid });
                ret.ret = "yes";

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

            if (method == "history") {
                quotation objQuotation = conn.QueryFirstOrDefault<quotation>("select * from quotation where quotation_isdel = 'N' and quotation_uid = @quotation_uid and quotation_version = @quotation_version order by quotation_version desc", new { quotation_uid = quotation_uid, quotation_version = quotation_version });

                if (objQuotation == null)
                {
                    ret.ret = "no";
                    ret.err_code = "0009";
                    ret.message = "此筆資料不存在或已被刪除!";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                ret.quotationDetail = new quotationDetail(objQuotation);
                ret.quotationView = conn.QueryFirstOrDefault<quotationView>("select * from quotationView where quotation_isdel = 'N' and quotation_revoke = 'N' and quotation_uid = @quotation_uid ", new { quotation_uid = quotation_uid });
                ret.ret = "yes";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (method == "get") {
                quotation objQuotation = conn.QueryFirstOrDefault<quotation>("select * from quotation where quotation_isdel = 'N' and quotation_revoke = 'N' and quotation_uid = @quotation_uid order by quotation_version desc", new { quotation_uid = quotation_uid  });

                if (objQuotation == null) {
                    ret.ret = "no";
                    ret.err_code = "0009";
                    ret.message = "此筆資料不存在或已被刪除!";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                ret.quotationDetail = new quotationDetail(objQuotation);
                ret.quotationView = conn.QueryFirstOrDefault<quotationView>("select * from quotationView where quotation_isdel = 'N' and quotation_revoke = 'N' and quotation_uid = @quotation_uid ", new { quotation_uid = quotation_uid });
                ret.ret = "yes";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (method == "add") {
                quotation objQuotation = new quotation();

                quotation_log = "報價單資料成立";
                quotation_uid = "q_" + GlobalClass.CreateRandomCode(24);
                quotation_version = "1";
                objQuotation.quotation_uid = quotation_uid;
                objQuotation.quotation_version = int.Parse(quotation_version);
                objQuotation.dept_uid = dept_uid;
                objQuotation.quotation_prodMethod = quotation_prodMethod;
                objQuotation.quotation_date = quotation_date;
                objQuotation.quotation_expStart = quotation_expStart;
                objQuotation.quotation_expEnd= quotation_expEnd;
                objQuotation.quotation_name = quotation_name;
                objQuotation.project_uid = project_uid;
                objQuotation.contactPerson_uid = contactPerson_uid;
                objQuotation.company_uid = company_uid;
                objQuotation.quotation_log = quotation_log;
                objQuotation.quotation_create_uid = token.user_uid;
                objQuotation.quotation_modify_uid = token.user_uid;
                objQuotation.quotation_noTaxTotal = double.Parse(quotation_noTaxTotal);
                objQuotation.quotation_specTotal = double.Parse(quotation_specTotal);
                objQuotation.quotation_tax = double.Parse(quotation_tax);
                objQuotation.quotation_grandTotal = double.Parse(quotation_grandTotal);
                objQuotation.quotation_sa = quotation_sa;
                objQuotation.quotation_isdel = quotation_isdel;
                objQuotation.quotation_revoke = quotation_revoke;
                objQuotation.quotation_createdate = DateTime.Now;
                objQuotation.quotation_modifydate = DateTime.Now;

                dynamic mainItems_Json;
                dynamic payments_Json;
                dynamic invoices_Json;

                try
                {
                    mainItems_Json = JsonConvert.DeserializeObject(mainItems_jsonstr);
                    payments_Json = JsonConvert.DeserializeObject(payments_jsonstr);
                    invoices_Json = JsonConvert.DeserializeObject(invoices_jsonstr);

                }
                catch (Exception ex)
                {
                    ret.ret = "no";
                    ret.err_code = "0003";
                    ret.message = "mainItems or payments or invoices json error," + ex.Message;
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }
                 
                List<quotationMainItem> quotationMainItems = new List<quotationMainItem>();
                List<quotationSubItem> quotationSubItems = new List<quotationSubItem>();

                foreach (dynamic item in mainItems_Json) {
                    string quotationMainItem_uid = "qm_" + GlobalClass.CreateRandomCode(24);
                    
                    quotationMainItem newItem = new quotationMainItem();
                    newItem.quotation_uid = quotation_uid;
                    newItem.mainItem_uid = item.mainItem_uid;
                    newItem.quotationMainItem_uid = quotationMainItem_uid;
                    newItem.quotationMainItem_name = item.quotationMainItem_name;
                    newItem.quotationMainItem_ac = double.Parse((string)item.quotationMainItem_ac);
                    newItem.quotationMainItem_subTotal = double.Parse((string)item.quotationMainItem_subTotal);
                    newItem.quotationMainItem_revoke = "N";
                    newItem.quotationMainItem_version = int.Parse((string)quotation_version);

                    quotationMainItems.Add(newItem);

                    foreach (dynamic subItem in item.subitems) { 
                        quotationSubItem newSubItem = new quotationSubItem();
                        newSubItem.quotationSubItem_uid = "qs" +GlobalClass.CreateRandomCode(24);
                        newSubItem.quotationMainItem_uid = quotationMainItem_uid;
                        newSubItem.quotation_uid = quotation_uid;
                        newSubItem.subItem_uid = subItem.subItem_uid;
                        newSubItem.quotationSubItem_name = subItem.quotationSubItem_name;
                        newSubItem.quotationSubItem_descript = subItem.quotationSubItem_descript;
                        newSubItem.quotationSubItem_price = double.Parse((string)subItem.quotationSubItem_price);
                        newSubItem.quotationSubItem_unitType = subItem.quotationSubItem_unitType;
                        newSubItem.quotationSubItem_number = double.Parse((string)subItem.quotationSubItem_number);
                        newSubItem.quotationSubItem_subTotal = double.Parse((string)subItem.quotationSubItem_subTotal);
                        newSubItem.quotationSubItem_hasAC = subItem.quotationSubItem_hasAC;
                        newSubItem.quotationSubItem_revoke = "N";
                        newSubItem.quotationSubItem_version = int.Parse((string)quotation_version);

                        quotationSubItems.Add(newSubItem);
                    }
                }

                List<payment> payments = new List<payment>();

                foreach (dynamic item in payments_Json) { 
                    payment newItem = new payment();

                    newItem.payment_uid = "pay_" + GlobalClass.CreateRandomCode(20);
                    newItem.quotation_uid = quotation_uid;
                    newItem.payment_method = item.payment_method;
                    newItem.payment_methodname = item.payment_methodname;
                    newItem.payment_descript = item.payment_descript;
                    newItem.payment_revoke = "N";
                    newItem.payment_version = int.Parse((string)quotation_version);
                    
                    payments.Add(newItem);
                }

                List<invoice> invoices = new List<invoice>();

                foreach (dynamic item in invoices_Json) { 
                    invoice newItem = new invoice();

                    newItem.invoice_uid = "inv_" + GlobalClass.CreateRandomCode(20);
                    newItem.quotation_uid = quotation_uid;
                    newItem.invoice_name = item.invoice_name;

                    if (newItem.invoice_type == "date")
                    {
                        string yearmonth = item.invoice_date;
                        string strYear = yearmonth.Split('/')[0];
                        string strMonth = yearmonth.Split("/")[1];

                        newItem.invoice_year = int.Parse(strYear);
                        newItem.invoice_month = int.Parse(strMonth);
                        newItem.invoice_text = "";
                    }
                    else
                    {
                        newItem.invoice_year = 0;
                        newItem.invoice_month = 0;
                        newItem.invoice_text = item.invoice_text;
                    }

                    newItem.invoice_noTaxMoney = int.Parse((string)item.invoice_noTaxMoney);
                    newItem.invoice_revoke = "N";
                    newItem.invoice_version = int.Parse((string)quotation_version);

                    invoices.Add(newItem);
                }

                conn.Insert(invoices);
                conn.Insert(payments);
                conn.Insert(quotationSubItems);
                conn.Insert(quotationMainItems);
                conn.Insert<quotation>(objQuotation);

                ret.quotationView = conn.QueryFirstOrDefault<quotationView>("select * from quotationView where quotation_uid = @quotation_uid and quotation_version = 1", new {quotation_uid = quotation_uid});
                ret.ret = "yes";

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

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

        [Route("getModelQuotation")]
        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");
            }

            

            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();
            

            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 (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");
            }

            

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

        [Route("modalQuotationList")]
        public ActionResult ModalQuotationList(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");
            }

            

            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("modalProjList")]
        public ActionResult ModalProjList(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");
            }

            

            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("quotationList")]
        public ActionResult QuotationList(IFormCollection obj)
        {
            quotationViewListResult ret = new quotationViewListResult();
            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");
            }

            string user_uid = token.user_uid;
            string user_perm = token.user_perm;
            string project_uid = obj["project_uid"].ToString();
            string dept_uid = obj["dept_uid"].ToString();

            string user_uid_list = "'" + user_uid + "'";

            if (user_perm == "system" && token.user_id != GlobalClass.appsettings("Admin:id"))
            {
                groupUser gpUser = conn.QueryFirstOrDefault<groupUser>("select * from groupUser where dept_uid = @dept_uid and user_uid = @user_uid ", new { dept_uid = dept_uid, user_uid = user_uid });

                if (gpUser != null)
                {
                    List<groupUser> groupUsers = conn.Query<groupUser>("select * from groupUser where group_uid = @group_uid", new { group_uid = gpUser.group_uid }).ToList();

                    foreach (groupUser groupUser in groupUsers)
                    {
                        user_uid_list += ", '" + groupUser.user_uid + "'";
                    }
                }
            }

            if (token.user_id != GlobalClass.appsettings("Admin:id"))
            {
                ret.quotationViews = conn.Query<quotationView>("select * from quotationView where quotationView_isdel = 'N' and quotationView_revoke = 'N' and project_uid = @project_uid and quotation_create_uid in (@user_list) order by quotation_modifydate desc", new { project_uid = project_uid, user_list = user_uid_list }).ToList();

            }
            else {
                ret.quotationViews = conn.Query<quotationView>("select * from quotationView where quotation_isdel = 'N' and quotation_revoke = 'N' and project_uid = @project_uid order by quotation_modifydate desc", new { project_uid = project_uid }).ToList();
            }

            ret.ret = "yes";

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

        [Route("deptList")]
        public ActionResult DeptList(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");
            }

           

            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("addEditDelGetProject")]
        public ActionResult AddEditDelGetProject(IFormCollection obj) {
            projectViewResult ret = new projectViewResult();
            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");
            }

            string user_uid = token.user_uid;
            string user_perm = token.user_perm;
            string dept_uid = obj["dept_uid"].ToString();
            string method = obj["method"].ToString();
            string project_uid = obj["project_uid"].ToString();
            string project_name = obj["project_name"].ToString();
            string company_uid = obj["company_uid"].ToString();
            string project_ps = obj["project_ps"].ToString();

            if (token.user_id != GlobalClass.appsettings("Admin:id")) {
                groupUser gpUser = conn.QueryFirstOrDefault<groupUser>("select * from groupUser where dept_uid = @dept_uid and user_uid = @user_uid ", new { dept_uid = dept_uid, user_uid = user_uid });

                if (gpUser == null) {
                    ret.ret = "no";
                    ret.err_code = "99991";
                    ret.message = "新增的專案資料其部門不屬於目前登入的使用者!";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }
            }

            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 errmsg = "";

                if (project_name == "")
                {
                    errmsg += "無專案名稱!\n";
                }

                if (company_uid == "")
                {
                    errmsg += "請選擇客戶公司!\n";
                }

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

                project_uid = GlobalClass.CreateRandomCode(24);

                project newProject = new project();
                newProject.project_uid = project_uid;
                newProject.dept_uid = dept_uid;
                newProject.company_uid = company_uid;
                newProject.project_ps = project_ps;
                newProject.project_creative_uid = token.user_uid;
                newProject.project_lastmodify_uid = token.user_uid;
                newProject.project_name = project_name;
                newProject.project_datetime = DateTime.Now.ToString("yyyy/MM/dd");
                
                conn.Insert<project>(newProject);

                projectView objView = conn.QueryFirstOrDefault<projectView>("select * from projectView where project_isdel = 'N' and project_uid = @project_uid", new { project_uid = project_uid});

                if (objView != null)
                {
                    ret.projectViews.Add(objView);
                }


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

            }

            project editProject = conn.QueryFirstOrDefault<project>("select * from project where project_isdel = 'N' and project_uid = @project_uid ", new { project_uid = project_uid });

            if (editProject == null) {
                ret.ret = "no";
                ret.err_code = "0004";
                ret.message = "無此project_uid資料!";
                return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
            }

            if (method == "get") {
                projectView objView = conn.QueryFirstOrDefault<projectView>("select * from projectView where project_isdel = 'N' and  project_uid = @project_uid", new { project_uid = project_uid });

                if (objView != null)
                {
                    ret.projectViews.Add(objView);
                }


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

            if (method == "edit") {
                string errmsg = "";

                if (project_name == "")
                {
                    errmsg += "無專案名稱!\n";
                }

                if (company_uid == "")
                {
                    errmsg += "請選擇客戶公司!\n";
                }

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

                editProject.dept_uid = dept_uid;
                editProject.company_uid = company_uid;
                editProject.project_ps = project_ps;
                editProject.project_lastmodify_uid = token.user_uid;
                editProject.project_name = project_name;
                editProject.project_modifydate = DateTime.Now;

                conn.Update(editProject);

                projectView objView = conn.QueryFirstOrDefault<projectView>("select * from projectView where project_isdel = 'N' and project_uid = @project_uid", new { project_uid = project_uid });

                if (objView != null)
                {
                    ret.projectViews.Add(objView);
                }


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

            if (method == "del") {
                editProject.project_lastmodify_uid = token.user_uid;
                editProject.project_isdel = "Y";
                editProject.project_modifydate = DateTime.Now;

                conn.Update(editProject);

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

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

        [Route("projectViewList")]
        public ActionResult ProjectViewList(IFormCollection obj) {
            projectViewResult ret = new projectViewResult();
            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");
            }

            string user_uid = token.user_uid;
            string user_perm = token.user_perm;
            string dept_uid = obj["dept_uid"].ToString();
            string start_txt = obj["start_txt"].ToString();
            string end_txt = obj["end_txt"].ToString();

            DateTime startDateTime = DateTime.Parse(start_txt + "/1");
            DateTime endDateTime = DateTime.Parse(end_txt + "/1").AddMonths(1).AddDays(-1);

            string user_uid_list = "'" + user_uid + "'";

            if (user_perm == "system" && token.user_id != GlobalClass.appsettings("Admin:id")) {
                groupUser gpUser = conn.QueryFirstOrDefault<groupUser>("select * from groupUser where dept_uid = @dept_uid and user_uid = @user_uid ", new { dept_uid = dept_uid, user_uid = user_uid });

                if (gpUser != null) {
                    List<groupUser> groupUsers = conn.Query<groupUser>("select * from groupUser where group_uid = @group_uid", new { group_uid = gpUser.group_uid }).ToList();

                    foreach (groupUser groupUser in groupUsers)
                    {
                        user_uid_list += ", '" + groupUser.user_uid + "'";
                    }
                }

                
            }

            if (user_perm == "system" && token.user_id == GlobalClass.appsettings("Admin:id"))
            {
                List<groupUser> groupUsers = conn.Query<groupUser>("select * from groupUser where dept_uid = @dept_uid", new { dept_uid = dept_uid }).ToList();

                foreach (groupUser groupUser in groupUsers)
                {
                    user_uid_list += ", '" + groupUser.user_uid + "'";
                }
            }

            string sqlString = "select * from projectView where project_isdel = 'N' and project_creative_uid in (" + user_uid_list + ") and project_createdate >= '" + startDateTime.ToString("yyyy/MM/dd") + "' and project_createdate <= '" + endDateTime.ToString("yyyy/MM/dd 23:59:59")  +  "' and dept_uid = '" + dept_uid + "'";

            ret.projectViews = conn.Query<projectView>(sqlString).ToList();
            ret.ret = "yes";

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

        [Route("addEditDelGetContactPerson")]
        public ActionResult AddEditDelContactPerson(IFormCollection obj)
        {
            contactPersonListResult ret = new contactPersonListResult();

            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");
            }



            string company_uid = obj["company_uid"].ToString();
            string contactPerson_uid = obj["contactPerson_uid"].ToString();
            string contactPerson_name = obj["contactPerson_name"].ToString();
            string contactPerson_email = obj["contactPerson_email"].ToString();
            string contactPerson_tel = obj["contactPerson_tel"].ToString();
            string contactPerson_fax = obj["contactPerson_fax"].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 (method == "add")
            {
                if (contactPerson_name.Trim() == "")
                {
                    ret.ret = "no";
                    ret.err_code = "0003";
                    ret.message = "沒有contactPerson_name!";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                contactPerson_uid = GlobalClass.CreateRandomCode(24);
                contactPerson newItem = new contactPerson();
                newItem.contactPerson_name = contactPerson_name;
                newItem.contactPerson_uid = contactPerson_uid;
                newItem.company_uid = company_uid;
        
                newItem.contactPerson_tel = contactPerson_tel;
                newItem.contactPerson_email = contactPerson_email;
                newItem.contactPerson_fax = contactPerson_fax;

                newItem.contactPerson_lastmodify_uid = token.user_uid;
                newItem.contactPerson_createdate = DateTime.Now;
                newItem.contactPerson_modifydate = DateTime.Now;

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

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

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



            contactPerson editItem = conn.QueryFirstOrDefault<contactPerson>("select * from contactPerson where contactPerson_isdel = 'N' and contactPerson_uid = @contactPerson_uid ", new { contactPerson_uid = contactPerson_uid });

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

            if (method == "edit")
            {


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

                editItem.contactPerson_name = contactPerson_name;

      
                editItem.contactPerson_tel = contactPerson_tel;
                editItem.contactPerson_email = contactPerson_email;
                editItem.contactPerson_fax = contactPerson_fax;

                editItem.contactPerson_lastmodify_uid = token.user_uid;
                editItem.contactPerson_modifydate = DateTime.Now;

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

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

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

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

            if (method == "del")
            {
                editItem.contactPerson_isdel = "Y";
                editItem.contactPerson_lastmodify_uid = token.user_uid;
                editItem.contactPerson_modifydate = DateTime.Now;

                conn.Execute("update contactPerson set contactPerson_isdel = 'Y' where contactPerson_uid = @contactPerson_uid ", new { contactPerson_uid = contactPerson_uid });

                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("contactPersonList")]
        public ActionResult ContactPersonList(IFormCollection obj)
        {
            contactPersonListResult ret = new contactPersonListResult();

            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");
            }

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

            ret.contactPersons = conn.Query<contactPerson>("select * from contactPerson where contactPerson_isdel = 'N' and company_uid = @company_uid ", new { company_uid = company_uid }).ToList();
            ret.ret = "yes";
            return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
        }

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

            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");
            }

           

            string company_uid = obj["company_uid"].ToString();
            string company_name = obj["company_name"].ToString();
            string company_serialNo = obj["company_serialNo"].ToString();
            string company_address = obj["company_address"].ToString();
            string company_tel = obj["company_tel"].ToString();
            string company_fax = obj["company_fax"].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 (method == "add")
            {
                if (company_name.Trim() == "")
                {
                    ret.ret = "no";
                    ret.err_code = "0003";
                    ret.message = "沒有company_name!";
                    return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
                }

                company_uid = GlobalClass.CreateRandomCode(24);
                company newItem = new company();
                newItem.company_name = company_name;
                newItem.company_uid = company_uid;
                newItem.company_serialNo = company_serialNo;
                newItem.company_address = company_address;
                newItem.company_tel = company_tel;
                newItem.company_fax = company_fax;

                newItem.company_lastmodify_uid = token.user_uid;
                newItem.company_createdate = DateTime.Now;
                newItem.company_modifydate = DateTime.Now;

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

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

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



            company editItem = conn.QueryFirstOrDefault<company>("select * from company where company_isdel = 'N' and company_uid = @company_uid ", new { company_uid = company_uid });

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

            if (method == "edit")
            {
                

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

                editItem.company_name = company_name;

                editItem.company_serialNo = company_serialNo;
                editItem.company_address = company_address;
                editItem.company_tel = company_tel;
                editItem.company_fax = company_fax;

                editItem.company_lastmodify_uid = token.user_uid;
                editItem.company_modifydate = DateTime.Now;

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

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

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

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

            if (method == "del")
            {
                editItem.company_isdel = "Y";
                editItem.company_lastmodify_uid = token.user_uid;
                editItem.company_modifydate = DateTime.Now;

                conn.Execute("update contactPerson set contactPerson_isdel = 'Y' where company_uid = @company_uid ", new { company_uid = company_uid });

                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("companyList")]
        public ActionResult AuthSubItemList(IFormCollection obj)
        {
            companyListResult ret = new companyListResult();

            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");
            }

  

            ret.companys = conn.Query<company>("select * from company where company_isdel = 'N' ").ToList();
            ret.ret = "yes";
            return Content(JsonConvert.SerializeObject(ret), "application/json;charset=utf-8");
        }
    }
}
