using AMESCoreStudio.CommonTools.Result;
using AMESCoreStudio.Web.Models;
using AMESCoreStudio.Web.ViewModels;
using AMESCoreStudio.Web.ViewModels.PCS;
using AMESCoreStudio.WebApi.DTO.AMES;
using AMESCoreStudio.WebApi.Models.AMES;
using AMESCoreStudio.WebApi.Models.BAS;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.StaticFiles;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;
using AMESCoreStudio.WebApi.Enum;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Configuration;
using ClosedXML.Excel;

namespace AMESCoreStudio.Web.Controllers
{

    public class PCSController : Controller
    {
        private readonly ILogger<PCSController> _logger;
        private readonly ILogger<LoginController> _log;
        public readonly ISYS _sysApi;
        public readonly IPCS _pcsApi;
        public readonly IBAS _basApi;
        public readonly IPPS _ppsApi;
        public readonly IFQC _fqcApi;
        public readonly IKCS _kcsApi;
        public readonly IBLL _bllApi;
        public readonly IFileServerProvider _fileServerProvider;
        private readonly IWebHostEnvironment _env;
        private readonly IStringLocalizer _sharedLocalizer;
        private readonly IConfiguration _configuration;

        /// <summary>
        /// 流水碼長度
        /// </summary>
        public static int NoLength = 4;

        public PCSController(ILogger<PCSController> logger, ILogger<LoginController> log, ISYS sysApi, IPCS pcsApi, IBAS basApi, IPPS ppsApi, IFQC fqcApi
            , IFileServerProvider fileServerProvider, IWebHostEnvironment env, IKCS kcsApi, IStringLocalizer<SharedResource> sharedLocalizer
            , IConfiguration configuration, IBLL bllApi)
        {
            _logger = logger;
            _log = log;
            _sysApi = sysApi;
            _pcsApi = pcsApi;
            _basApi = basApi;
            _ppsApi = ppsApi;
            _fqcApi = fqcApi;
            _kcsApi = kcsApi;
            _fileServerProvider = fileServerProvider;
            _env = env;
            _sharedLocalizer = sharedLocalizer;
            _configuration = configuration;
            _bllApi = bllApi;
        }

        #region Funcion BLL


        /// <summary>
        /// 工單建立時判斷是否都有資料
        /// </summary>
        /// <param name="model"></param>
        /// <param name="action">New</param>
        /// <returns></returns>
        public string CheckWipInfoInsert(WipDataViewModel model, string action = null)
        {
            string Msg = string.Empty;

            if (string.IsNullOrWhiteSpace(model.wipInfo.LineID.ToString()))
                Msg += model.wipInfo.GetAttributeFrom<DisplayAttribute>(nameof(model.wipInfo.LineID)).Name + ",";

            if (string.IsNullOrWhiteSpace(model.wipInfo.UnitNO))
                Msg += model.wipInfo.GetAttributeFrom<DisplayAttribute>(nameof(model.wipInfo.UnitNO)).Name + ",";

            if (model.wipInfo.WipDueDate == DateTime.MinValue)
                Msg += model.wipInfo.GetAttributeFrom<DisplayAttribute>(nameof(model.wipInfo.WipDueDate)).Name + ",";

            if (model.wipInfo.WipScheduleDate == DateTime.MinValue)
                Msg += model.wipInfo.GetAttributeFrom<DisplayAttribute>(nameof(model.wipInfo.WipScheduleDate)).Name + ",";

            if (model.wipInfo.UnitNO == "全部" || string.IsNullOrWhiteSpace(model.wipInfo.UnitNO))
                Msg += model.wipInfo.GetAttributeFrom<DisplayAttribute>(nameof(model.wipInfo.UnitNO)).Name + ",";


            if (model.wipInfo.PlanQTY == 0)
                Msg += model.wipInfo.GetAttributeFrom<DisplayAttribute>(nameof(model.wipInfo.PlanQTY)).Name + ",";

            // 序號編碼sheet
            // 工單新增不用判斷
            if (action != "New")
            {
                // 安勤統一執行WIP_SYSTEM
                if (ViewBag.WipSpecial == "Y")
                {
                    Msg += CheckWipInfoInsert_WipSystem(model.wipSystem);
                }
                else
                {
                    // 系統
                    if (model.wipInfo.UnitNO == "B" || model.wipInfo.UnitNO == "P" || model.wipInfo.UnitNO == "T")
                    {

                        Msg += CheckWipInfoInsert_WipSystem(model.wipSystem);
                    }
                    // 板卡
                    else
                    {
                        Msg += CheckWipInfoInsert_WipBoard(model.wipBoard);
                    }
                }
            }

            // 內部條碼
            if (model.wipBarcode != null)
            {
                if (string.IsNullOrWhiteSpace(model.wipBarcode.StartNO) != string.IsNullOrWhiteSpace(model.wipBarcode.EndNO))
                {
                    Msg += ",內部序號未填完整";
                }
            }

            // 出貨序號
            if (string.IsNullOrWhiteSpace(model.wipBarcodeOther.StartNO) != string.IsNullOrWhiteSpace(model.wipBarcodeOther.EndNO))
            {
                Msg += ",客戶序號未填完整";
            }

            // MAC
            if (string.IsNullOrWhiteSpace(model.wipMAC.StartNO) != string.IsNullOrWhiteSpace(model.wipMAC.EndNO))
            {
                Msg += ",MAC未填完整";
            }

            if (!string.IsNullOrWhiteSpace(Msg))
                Msg = "必填欄位未填寫:" + Msg.Substring(0, (Msg.Length - 1));

            return Msg;
        }

        /// <summary>
        /// 工單工程 保存判斷
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string CheckWipInfoInsert_WipSystem(WipSystem model)
        {
            string Msg = string.Empty;

            // 當工單-工程資訊有填寫任何一個欄位,就要把必填欄位都填寫
            if (!string.IsNullOrWhiteSpace(model.Engineer) ||
                !string.IsNullOrWhiteSpace(model.BiMemo) ||
                //!string.IsNullOrWhiteSpace(model.BiTime) ||
                //string.IsNullOrWhiteSpace(model.BiRatio.ToString()) ||
                !string.IsNullOrWhiteSpace(model.Checksum) ||
                !string.IsNullOrWhiteSpace(model.Bios) ||
                !string.IsNullOrWhiteSpace(model.BiosVer) ||
                !string.IsNullOrWhiteSpace(model.Cpu) ||
                !string.IsNullOrWhiteSpace(model.Ram) ||
                !string.IsNullOrWhiteSpace(model.Fw) ||
                !string.IsNullOrWhiteSpace(model.Fw1) ||
                !string.IsNullOrWhiteSpace(model.Fw2) ||
                !string.IsNullOrWhiteSpace(model.Ec) ||
                !string.IsNullOrWhiteSpace(model.OsVer) ||
                !string.IsNullOrWhiteSpace(model.Jumper) ||
                !string.IsNullOrWhiteSpace(model.BabMemo) ||
                !string.IsNullOrWhiteSpace(model.TestMemo) ||
                !string.IsNullOrWhiteSpace(model.PackingMemo))
            {

                // 判斷預設值是否更改過,如果有就判斷必填欄位
                if (string.IsNullOrWhiteSpace(model.Engineer) ||
                    string.IsNullOrWhiteSpace(model.BiRatio.ToString()) ||
                    string.IsNullOrWhiteSpace(model.Bios) ||
                    string.IsNullOrWhiteSpace(model.Ec) ||
                    string.IsNullOrWhiteSpace(model.Fw))
                {
                    if (string.IsNullOrWhiteSpace(model.Engineer))
                        Msg += model.GetAttributeFrom<DisplayAttribute>(nameof(model.Engineer)).Name + ",";

                    // 1  N/A , 4 備註說明
                    if (string.IsNullOrWhiteSpace(model.Bios) && model.BiosType != 1 && model.BiosType != 4)
                        Msg += model.GetAttributeFrom<DisplayAttribute>(nameof(model.Bios)).Name + ",";

                    if (string.IsNullOrWhiteSpace(model.Ec) && model.ECType != 1 && model.ECType != 4)
                        Msg += model.GetAttributeFrom<DisplayAttribute>(nameof(model.Ec)).Name + ",";

                    if (string.IsNullOrWhiteSpace(model.Fw) && model.FWType != 1 && model.FWType != 4)
                        Msg += model.GetAttributeFrom<DisplayAttribute>(nameof(model.Fw)).Name + ",";

                    if (string.IsNullOrWhiteSpace(model.BiRatio.ToString()))
                        Msg += model.GetAttributeFrom<DisplayAttribute>(nameof(model.BiRatio)).Name + ",";
                }
            }
            return Msg;
        }

        public string CheckWipInfoInsert_WipBoard(WipBoard model)
        {
            string Msg = string.Empty;

            // 當工單-板卡資訊有填寫任何一個欄位,就要把必填欄位都填寫
            if (string.IsNullOrWhiteSpace(model.BiRatio.ToString()) ||
                !string.IsNullOrWhiteSpace(model.BiosRemarks) ||
                //!string.IsNullOrWhiteSpace(model.BiTemperature) ||
                //!string.IsNullOrWhiteSpace(model.BiTime) ||
                !string.IsNullOrWhiteSpace(model.BiosRemarks) ||
                !string.IsNullOrWhiteSpace(model.BiosVer) ||
                !string.IsNullOrWhiteSpace(model.BiRemarks) ||
                !string.IsNullOrWhiteSpace(model.BurnLocation) ||
                !string.IsNullOrWhiteSpace(model.BurnRemarks) ||
                !string.IsNullOrWhiteSpace(model.Checksum) ||
                !string.IsNullOrWhiteSpace(model.CsRemarks) ||
                !string.IsNullOrWhiteSpace(model.Engineer) ||
                !string.IsNullOrWhiteSpace(model.PartsBakeRemarks) ||
                model.PartsBakeTime != 0 ||
                !string.IsNullOrWhiteSpace(model.PcbBakeRemarks) ||
                !string.IsNullOrWhiteSpace(model.PcbProcessingRemarks))
            {

                // 判斷預設值是否更改過,如果有就判斷必填欄位
                if (string.IsNullOrWhiteSpace(model.BiRatio.ToString()) ||
                model.PartsBakeTime == 0 ||
                 string.IsNullOrWhiteSpace(model.BiosVer) ||
                string.IsNullOrWhiteSpace(model.BiTemperature) ||
                string.IsNullOrWhiteSpace(model.BiTime) ||
                string.IsNullOrWhiteSpace(model.Checksum) ||
                string.IsNullOrWhiteSpace(model.BurnLocation))
                {
                    if (string.IsNullOrWhiteSpace(model.BiRatio.ToString()))
                        Msg += model.GetAttributeFrom<DisplayAttribute>(nameof(model.BiRatio)).Name + ",";

                    if (model.PartsBakeTime == 0)
                        Msg += model.GetAttributeFrom<DisplayAttribute>(nameof(model.PartsBakeTime)).Name + ",";

                    //if (model.PcbBake == 0)
                    //    Msg += model.GetAttributeFrom<DisplayAttribute>(nameof(model.PcbBake)).Name + ",";

                    if (string.IsNullOrWhiteSpace(model.BiosVer))
                        Msg += model.GetAttributeFrom<DisplayAttribute>(nameof(model.BiosVer)).Name + ",";

                    if (string.IsNullOrWhiteSpace(model.BiTemperature))
                        Msg += model.GetAttributeFrom<DisplayAttribute>(nameof(model.BiTemperature)).Name + ",";

                    if (string.IsNullOrWhiteSpace(model.BiTime))
                        Msg += model.GetAttributeFrom<DisplayAttribute>(nameof(model.BiTime)).Name + ",";

                    if (string.IsNullOrWhiteSpace(model.Checksum))
                        Msg += model.GetAttributeFrom<DisplayAttribute>(nameof(model.Checksum)).Name + ",";

                    if (string.IsNullOrWhiteSpace(model.BurnLocation))
                        Msg += model.GetAttributeFrom<DisplayAttribute>(nameof(model.BurnLocation)).Name + ",";

                }
            }
            return Msg;
        }
        #endregion



        #region 下拉選單
        /// <summary>
        /// 產品別
        /// </summary>
        /// <returns></returns>
        private async Task GetProductType()
        {

            var result = await _pcsApi.GetProductTypes();

            var ProductTypes = new List<SelectListItem>();
            for (int i = 0; i < result.Count; i++)
            {
                ProductTypes.Add(new SelectListItem(result[i].ProductTypeNO + "-" + result[i].ProductTypeName, result[i].ProductTypeID.ToString()));
            }

            if (ProductTypes.Count == 0)
            {
                ProductTypes.Add(new SelectListItem("N/A", null));
            }

            ViewBag.ProductTypesList = ProductTypes;
        }

        /// <summary>
        /// 線別
        /// </summary>
        /// <returns></returns>
        private async Task GetLineInfo()
        {
            var result = await _pcsApi.GetLineInfo();
            result = result.Where(w => w.StatusNo == "A").OrderBy(o => o.LineID).ToList();
            var LineInfo = new List<SelectListItem>();
            for (int i = 0; i < result.Count; i++)
            {
                LineInfo.Add(new SelectListItem(result[i].LineID + "-" + result[i].LineDesc, result[i].LineID.ToString()));
            }

            if (LineInfo.Count == 0)
            {
                LineInfo.Add(new SelectListItem("N/A", null));
            }

            ViewBag.LineInfoList = LineInfo;
        }

        /// <summary>
        /// 廠別/委外廠
        /// </summary>
        /// <returns></returns>
        private async Task GetFactoryInfo()
        {
            var result = await _pcsApi.GetFactoryInfo();
            result = result.Where(w => w.StatusNo == "A").OrderBy(o => o.FactoryID).ToList();
            var FactoryInfo = new List<SelectListItem>();
            for (int i = 0; i < result.Count; i++)
            {
                FactoryInfo.Add(new SelectListItem(result[i].FactoryNo + "-" + result[i].FactoryNameCh, result[i].FactoryID.ToString()));
            }

            if (FactoryInfo.Count == 0)
            {
                FactoryInfo.Add(new SelectListItem("N/A", null));
            }

            ViewBag.FactoryInfoList = FactoryInfo;
        }

        /// <summary>
        /// 生產單位
        /// </summary>
        /// <param name="SelectAll">true:Add全部選項</param>
        /// <returns></returns>
        private async Task GetFactoryUnit(bool SelectAll = true)
        {
            var result = await _basApi.GetFactoryUnits();

            var FactoryUnit = new List<SelectListItem>();

            if (SelectAll)
                FactoryUnit.Add(new SelectListItem("全部", ""));

            for (int i = 0; i < result.Count; i++)
            {
                FactoryUnit.Add(new SelectListItem(result[i].UnitName, result[i].UnitNo.ToString()));
            }

            ViewBag.FactoryUnitList = FactoryUnit;
        }

        private async Task GetFactoryUnit(string unit_no)
        {
            var result = await _basApi.GetFactoryUnit(unit_no);

            var FactoryUnit = new List<SelectListItem>();
            for (int i = 0; i < result.Count; i++)
            {
                FactoryUnit.Add(new SelectListItem(result[i].UnitName, result[i].UnitNo.ToString()));
            }

            if (FactoryUnit.Count == 0)
            {
                FactoryUnit.Add(new SelectListItem("N/A", null));
            }

            ViewBag.FactoryUnitList = FactoryUnit;
        }

        /// <summary>
        /// 組件資料
        /// </summary>
        /// <returns></returns>
        private async Task GetItems()
        {
            var result = await _pcsApi.GetItems();

            var ItemsList = new List<SelectListItem>();
            ItemsList.Add(new SelectListItem("請選擇", ""));
            for (int i = 0; i < result.Count; i++)
            {
                ItemsList.Add(new SelectListItem(result[i].ItemName, result[i].ItemNo.ToString()));
            }
            ViewBag.ItemsList = ItemsList;
        }

        /// <summary>
        /// 正背面
        /// </summary>
        /// <returns></returns>
        private async Task GetMFGType()
        {
            var result = await _pcsApi.GetMFGTypes();
            var MFGType = new List<SelectListItem>();
            for (int i = 0; i < result.Count; i++)
            {
                MFGType.Add(new SelectListItem(result[i].MFGTypeName, result[i].MFGTypeNO.ToString()));
            }

            if (MFGType.Count == 0)
            {
                MFGType.Add(new SelectListItem("N/A", null));
            }

            ViewBag.MFGTypeList = MFGType;
        }

        /// <summary>
        /// 工單性質
        /// </summary>
        /// <returns></returns>
        private async Task GetProcessTypes()
        {
            var result = await _pcsApi.GetProcessTypes();

            var ProcessType = new List<SelectListItem>();
            for (int i = 0; i < result.Count; i++)
            {
                ProcessType.Add(new SelectListItem(result[i].ProcessTypeName, result[i].ProcessTypeNO.ToString()));
            }

            if (ProcessType.Count == 0)
            {
                ProcessType.Add(new SelectListItem("N/A", null));
            }

            ViewBag.ProcessTypeList = ProcessType;
        }

        /// <summary>
        /// 制令序號
        /// </summary>
        /// <returns></returns>
        private void GetWipSEQType()
        {
            var WipSEQType = new List<SelectListItem>();
            for (int i = 1; i <= 10; i++)
            {
                WipSEQType.Add(new SelectListItem(i.ToString(), i.ToString()));
            }
            ViewBag.WipSEQTypeList = WipSEQType;
        }

        /// <summary>
        /// 站別
        /// </summary>
        /// <returns></returns>
        private async Task GetStation()
        {
            var result = await _basApi.GetStationses();

            var StationItems = new List<SelectListItem>();
            for (int i = 0; i < result.Count; i++)
            {
                StationItems.Add(new SelectListItem(result[i].StationName, result[i].StationID.ToString()));
            }

            if (StationItems.Count == 0)
            {
                StationItems.Add(new SelectListItem("N/A", null));
            }
            ViewBag.GetStationList = StationItems;
        }

        /// <summary>
        /// 站別
        /// </summary>
        /// <returns></returns>
        private async Task GetRuleStation(string flowruleID = null)
        {
            var result = await _basApi.GetRuleStationByUnit(flowruleID);
            result = result.OrderBy(o => o.Sequence).ToList();
            var Stations = new List<SelectListItem>();
            for (int i = 0; i < result.Count; i++)
            {
                Stations.Add(new SelectListItem(result[i].StationDesc, result[i].StationID.ToString()));
            }

            if (Stations.Count == 0)
            {
                Stations.Add(new SelectListItem("N/A", null));
            }

            ViewBag.GetStationsList = Stations;
        }

        /// <summary>
        /// 流程ID By站別
        /// </summary>
        /// <returns>StationID</returns>
        private async Task<List<RuleStation>> GetRuleStationByFlowRuleID(int flowruleID)
        {
            var result = await _basApi.GetRuleStationsByFlow(flowruleID, 0);
            result = result.Where(w => w.StationType == "M").OrderBy(o => o.Sequence).ToList();
            var RuleStations = new List<SelectListItem>();
            for (int i = 0; i < result.Count; i++)
            {
                RuleStations.Add(new SelectListItem(result[i].Sequence + "-" + result[i].Station.StationName, result[i].StationID.ToString()));
            }

            if (RuleStations.Count == 0)
            {
                RuleStations.Add(new SelectListItem("N/A", null));
            }

            ViewBag.GetRuleStationByFlowRuleIDList = RuleStations;
            return result;
        }

        /// <summary>
        /// 站別 By 主站
        /// </summary>
        /// <param name="unit_no"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> GetRuleStationByTypeJson(string unit_no)
        {
            var result = await _basApi.GetRuleStationByUnit(unit_no);

            result = result.Where(w => w.StationType == "M").OrderBy(o => o.Sequence).ToList();

            var item = new List<SelectListItem>();

            for (int i = 0; i < result.Count; i++)
            {
                item.Add(new SelectListItem(result[i].StationDesc, result[i].StationID.ToString()));
            }

            if (item.Count == 0)
            {
                item.Add(new SelectListItem("N/A", ""));
            }

            //将数据Json化并传到前台视图
            return Json(new { data = item });
        }

        /// <summary>
        /// 流程ID選單
        /// </summary>
        /// <returns></returns>
        private async Task GetFlowRuleList()
        {
            var result = await _basApi.GetFlowRules();

            var FlowRuleItems = new List<SelectListItem>();
            for (int i = 0; i < result.Count; i++)
            {
                FlowRuleItems.Add(new SelectListItem(result[i].FlowRuleName, result[i].FlowRuleID.ToString()));
            }

            if (FlowRuleItems.Count == 0)
            {
                FlowRuleItems.Add(new SelectListItem("N/A", null));
            }

            ViewBag.FlowRuleList = FlowRuleItems;
        }

        /// <summary>
        /// 工單狀態
        /// </summary>
        /// <returns></returns>
        private void GetWipType()
        {
            var WipType = new List<SelectListItem>(){
                new SelectListItem() {
                    Text = "S:標準工單",
                    Value = "S",
                },
                new SelectListItem
                {
                    Text = "R:重工工單",
                    Value = "R",
                },
                  new SelectListItem() {
                    Text = "N:無序號工單",
                    Value = "N",
                }
            };

            ViewBag.GetWipTypeList = WipType;
        }

        /// <summary>
        /// 燒錄
        /// </summary>
        private void GetBurnType()
        {
            var BurnType = new List<SelectListItem>(){
                new SelectListItem() {
                    Text = "燒錄",
                    Value = "Y",
                },
                new SelectListItem
                {
                    Text = "不需燒錄",
                    Value = "N",
                }
            };

            ViewBag.GetBurnTypeList = BurnType;
        }

        /// <summary>
        /// 零件烘烤
        /// </summary>
        private void GetPartsBakeType()
        {
            var PartsBakeType = new List<SelectListItem>(){
                new SelectListItem() {
                    Text = "125℃",
                    Value = "125",
                },
                new SelectListItem
                {
                    Text = "120℃",
                    Value = "120",
                },
                new SelectListItem
                {
                    Text = "80℃",
                    Value = "80",
                },
                new SelectListItem
                {
                    Text = "60℃",
                    Value = "60",
                },
                new SelectListItem
                {
                    Text = "45℃",
                    Value = "45",
                }
            };

            ViewBag.GetPartsBakeTypeList = PartsBakeType;
        }

        /// <summary>
        /// 工單資訊 板卡資訊 PCB烘烤
        /// </summary>
        /// <param name="SelectedValue"></param>
        private void GetPCBBakeTypeSelect(string SelectedValue = null)
        {
            List<string> values = new List<string>();
            if (SelectedValue != null)
            {
                values = SelectedValue.Split(',').ToList();
            }
            var q = Enum.GetValues(typeof(EnumPCS.EnumWipBoardPCBBakeType)).Cast<EnumPCS.EnumWipBoardPCBBakeType>()
                       .Select(s => new SelectListItem
                       {
                           Text = EnumPCS.GetDisplayName(s).ToString(),
                           Value = s.ToString()
                       }).ToList();

            ViewBag.GetPCBBakeTypeSelect = q;
        }

        /// <summary>
        /// 工單資訊 板卡資訊 PCB加工
        /// </summary>
        /// <param name="SelectedValue"></param>
        private void GetPCBProcessingTypeSelect(string SelectedValue = null)
        {
            List<string> values = new List<string>();
            if (SelectedValue != null)
            {
                values = SelectedValue.Split(',').ToList();
            }
            var q = Enum.GetValues(typeof(EnumPCS.EnumWipBoardPCBProcessingType)).Cast<EnumPCS.EnumWipBoardPCBProcessingType>()
                       .Select(s => new SelectListItem
                       {
                           Text = EnumPCS.GetDisplayName(s).ToString(),
                           Value = s.ToString()
                       }).ToList();

            ViewBag.GetPCBProcessingTypeSelect = q;
        }

        /// <summary>
        /// 工單資訊 板卡資訊 錫膏
        /// </summary>
        /// <param name="SelectedValue"></param>
        private void GetSolderPasteSelect(string SelectedValue = null)
        {
            List<string> values = new List<string>();
            if (SelectedValue != null)
            {
                values = SelectedValue.Split(',').ToList();
            }
            var q = Enum.GetValues(typeof(EnumPCS.EnumWipBoardSolderPasteType)).Cast<EnumPCS.EnumWipBoardSolderPasteType>()
                       .Select(s => new SelectListItem
                       {
                           Text = EnumPCS.GetDisplayName(s).ToString(),
                           Value = s.ToString()
                       }).ToList();

            ViewBag.GetSolderPasteSelect = q;
        }


        /// <summary>
        /// 工單資訊 系統工程資訊 PMType
        /// </summary>
        /// <param name="SelectedValue"></param>
        private void GetWipSystemPMTypeSelect(string SelectedValue = null)
        {
            List<string> values = new List<string>();
            if (SelectedValue != null)
            {
                values = SelectedValue.Split(',').ToList();
            }
            var q = Enum.GetValues(typeof(EnumPCS.EnumWipSystemPMType)).Cast<EnumPCS.EnumWipSystemPMType>()
                       .Select(s => new SelectListItem
                       {
                           Text = EnumPCS.GetDisplayName(s).ToString(),
                           Value = Convert.ToInt32(Enum.Parse(typeof(EnumPCS.EnumWipSystemPMType), s.ToString())).ToString()
                       }).ToList();

            ViewBag.GetWipSystemPMTypeSelect = q;
        }

        /// <summary>
        /// 工單資訊 系統工程資訊 Type
        /// </summary>
        /// <param name="SelectedValue"></param>
        private void GetWipSystemTypeSelect(string SelectedValue = null)
        {
            List<string> values = new List<string>();
            if (SelectedValue != null)
            {
                values = SelectedValue.Split(',').ToList();
            }
            var q = Enum.GetValues(typeof(EnumPCS.EnumWipSystemType)).Cast<EnumPCS.EnumWipSystemType>()
                       .Select(s => new SelectListItem
                       {
                           Text = EnumPCS.GetDisplayName(s).ToString(),
                           Value = Convert.ToInt32(Enum.Parse(typeof(EnumPCS.EnumWipSystemType), s.ToString())).ToString()
                       }).ToList();

            ViewBag.GetWipSystemTypeSelect = q;
        }

        /// <summary>
        /// 工單資訊 系統工程資訊 DMI燒入 Type
        /// </summary>
        /// <param name="SelectedValue"></param>
        private void GetWipSystemDMITypeSelect(string SelectedValue = null)
        {
            List<string> values = new List<string>();
            if (SelectedValue != null)
            {
                values = SelectedValue.Split(',').ToList();
            }
            var q = Enum.GetValues(typeof(EnumPCS.EnumWipSystemDMIBIType)).Cast<EnumPCS.EnumWipSystemDMIBIType>()
                       .Select(s => new SelectListItem
                       {
                           Text = EnumPCS.GetDisplayName(s).ToString(),
                           Value = Convert.ToInt32(Enum.Parse(typeof(EnumPCS.EnumWipSystemDMIBIType), s.ToString())).ToString()
                       }).ToList();

            ViewBag.GetWipSystemDMITypeSelect = q;
        }

        /// <summary>
        /// 工單資訊 燒機溫度
        /// </summary>
        /// <param name="SelectedValue"></param>
        private void GetWipBITemperatuerSelect(string SelectedValue = null)
        {
            List<string> values = new List<string>();
            if (SelectedValue != null)
            {
                values = SelectedValue.Split(',').ToList();
            }
            var q = Enum.GetValues(typeof(EnumPCS.EnumWipBITemperatuer)).Cast<EnumPCS.EnumWipBITemperatuer>()
                       .Select(s => new SelectListItem
                       {
                           Text = EnumPCS.GetDisplayName(s).ToString(),
                           Value = EnumPCS.GetDisplayName(s).ToString()
                           //Value = s.ToString()
                       }).ToList();

            ViewBag.GetWipBITemperatuerSelect = q;
        }

        /// <summary>
        /// 工單資訊 燒機軟體
        /// </summary>
        /// <param name="SelectedValue"></param>
        private void GetWipBI_OSSelect(string SelectedValue = null)
        {
            List<string> values = new List<string>();
            if (SelectedValue != null)
            {
                values = SelectedValue.Split(',').ToList();
            }
            var q = Enum.GetValues(typeof(EnumPCS.EnumWipBI_OS)).Cast<EnumPCS.EnumWipBI_OS>()
                       .Select(s => new SelectListItem
                       {
                           Text = EnumPCS.GetDisplayName(s).ToString(),
                           Value = EnumPCS.GetDisplayName(s).ToString()
                           //Value = s.ToString()
                       }).ToList();

            ViewBag.GetWipBI_OSSelect = q;
        }

        /// <summary>
        /// SOP_Type
        /// </summary>
        /// <param name="SelectedValue"></param>
        private void GetSOPTypeSelect(string SelectedValue = null)
        {
            List<string> values = new List<string>();
            if (SelectedValue != null)
            {
                values = SelectedValue.Split(',').ToList();
            }
            var q = Enum.GetValues(typeof(EnumPCS.EnumWipSopType)).Cast<EnumPCS.EnumWipSopType>()
                       .Select(s => new SelectListItem
                       {
                           Text = EnumPCS.GetDisplayName(s).ToString(),
                           Value = s.ToString()
                       }).ToList();

            ViewBag.GetSOPTypeSelect = q;
        }

        /// <summary>
        /// 工單鎖定-鎖定類型
        /// </summary>
        private void GetLockType()
        {
            var LockType = new List<SelectListItem>(){
                new SelectListItem() {
                    Text = "WIP",
                    Value = "WIP",
                },
                  new SelectListItem
                {
                    Text = "BAR",
                    Value = "BAR",
                }
            };

            ViewBag.GetLockTypeList = LockType;
        }

        /// <summary>
        /// 工單鎖定-鎖定原因類別
        /// </summary>
        private void GetLockReasonType()
        {
            var LockReasonType = new List<SelectListItem>(){
                new SelectListItem() {
                    Text = "3C認證工單",
                    Value = "0",
                },
                new SelectListItem
                {
                    Text = "驗證工單",
                    Value = "1",
                },
                new SelectListItem
                {
                    Text = "維修換料待分析",
                    Value = "3",
                }
            };

            //TempData["GetLockReasonTypeList"] = LockReasonType;
            ViewBag.GetLockReasonTypeList = LockReasonType;
        }

        /// <summary>
        /// KP Items
        /// </summary>
        /// <returns></returns>
        private async Task GetItemsList()
        {
            var result = await _kcsApi.GetItems();

            var Items = new List<SelectListItem>();
            for (int i = 0; i < result.Count; i++)
            {
                Items.Add(new SelectListItem(result[i].ItemName, result[i].ItemNo.ToString()));
            }

            if (result.Count == 0)
            {
                Items.Add(new SelectListItem("N/A", null));
            }

            ViewBag.ItemsList = Items;
        }

        #endregion

        #region CheckboxList
        /// <summary>
        /// 列印方式
        /// </summary>
        /// <param name="SelectedValue"></param>
        private void GetCheckboxPrintMode(string SelectedValue = null)
        {

            List<string> values = new List<string>();
            if (SelectedValue != null)
            {
                values = SelectedValue.Split(',').ToList();
            }

            var q = Enum.GetValues(typeof(EnumPCS.EnumPrintMode)).Cast<EnumPCS.EnumPrintMode>()
           .Select(s => new SelectListItem
           {
               Text = EnumPCS.GetDisplayName(s).ToString(),
               Value = s.ToString(),
               Selected = values.Where(v => v.Contains(s.ToString())).Count() != 0
           }).ToList();

            ViewBag.GetCheckboxPrintMode = q;
        }

        /// <summary>
        /// 認證Logo
        /// </summary>
        /// <param name="SelectedValue"></param>
        private void GetCheckboxApproveLogo(string SelectedValue = null)
        {
            List<string> values = new List<string>();
            if (SelectedValue != null)
            {
                values = SelectedValue.Split(',').ToList();
            }
            var q = Enum.GetValues(typeof(EnumPCS.EnumApproveLogo)).Cast<EnumPCS.EnumApproveLogo>()
               .Select(s => new SelectListItem
               {
                   Text = EnumPCS.GetDisplayName(s).ToString(),
                   Value = s.ToString(),
                   Selected = values.Where(v => v == s.ToString()).Count() != 0
               }).ToList();

            ViewBag.GetCheckboxApproveLogo = q;
        }

        /// <summary>
        /// 公司Logo
        /// </summary>
        /// <param name="SelectedValue"></param>
        private void GetCheckboxCompanyLogo(string SelectedValue = null)
        {
            List<string> values = new List<string>();
            if (SelectedValue != null)
            {
                values = SelectedValue.Split(',').ToList();
            }

            var q = Enum.GetValues(typeof(EnumPCS.EnumCompanyLogo)).Cast<EnumPCS.EnumCompanyLogo>()
           .Select(s => new SelectListItem
           {
               Text = EnumPCS.GetDisplayName(s).ToString(),
               Value = s.ToString(),
               Selected = values.Where(v => v.Contains(s.ToString())).Count() != 0
           }).ToList();

            ViewBag.GetCheckboxCompanyLogo = q;
        }

        private void GetCheckboxWipAttr(string SelectedValue = null)
        {
            List<string> values = new List<string>();
            if (SelectedValue != null)
            {
                values = SelectedValue.Split(',').ToList();
            }

            var q = Enum.GetValues(typeof(EnumPCS.EnumWipAttr)).Cast<EnumPCS.EnumWipAttr>()
           .Select(s => new SelectListItem
           {
               Text = EnumPCS.GetDisplayName(s).ToString(),
               Value = s.ToString(),
               Selected = values.Where(v => v.Contains(s.ToString())).Count() != 0
           }).ToList();

            ViewBag.GetCheckboxWipAttr = q;
        }

        /// <summary>
        /// SMD點紅膠
        /// </summary>
        /// <param name="SelectedValue"></param>
        private void GetCheckboxSMD(string SelectedValue = null)
        {
            List<string> values = new List<string>();
            if (SelectedValue == "")
                values.Add("F"); //預設
            else if (SelectedValue != null)
                values = SelectedValue.Split(',').ToList();

            var q = Enum.GetValues(typeof(EnumPCS.EnumWipBoardSMDType)).Cast<EnumPCS.EnumWipBoardSMDType>()
       .Select(s => new SelectListItem
       {
           Text = EnumPCS.GetDisplayName(s).ToString(),
           Value = s.ToString(),
           Selected = values.Where(v => v.Contains(s.ToString())).Count() != 0
       }).ToList();

            ViewBag.GetCheckboxSMD = q;
        }

        /// <summary>
        /// SMD點防焊膠
        /// </summary>
        /// <param name="SelectedValue"></param>
        private void GetCheckboxSMDSolderMa(string SelectedValue = null)
        {
            List<string> values = new List<string>();
            if (SelectedValue == "")
                values.Add("F"); //預設
            else if (SelectedValue != null)
                values = SelectedValue.Split(',').ToList();

            var q = Enum.GetValues(typeof(EnumPCS.EnumWipBoardSMDType)).Cast<EnumPCS.EnumWipBoardSMDType>()
       .Select(s => new SelectListItem
       {
           Text = EnumPCS.GetDisplayName(s).ToString(),
           Value = s.ToString(),
           Selected = values.Where(v => v.Contains(s.ToString())).Count() != 0
       }).ToList();

            ViewBag.GetCheckboxSMDSolderMa = q;
        }

        /// <summary>
        /// DIP
        /// </summary>
        /// <param name="SelectedValue"></param>
        private void GetCheckboxDIP(string SelectedValue = "")
        {
            List<string> values = new List<string>();
            if (SelectedValue == "")
                values.Add("A"); //預設
            else if (SelectedValue != null)
                values = SelectedValue.Split(',').ToList();

            var q = Enum.GetValues(typeof(EnumPCS.EnumWipBoardDIPType)).Cast<EnumPCS.EnumWipBoardDIPType>()
                       .Select(s => new SelectListItem
                       {
                           Text = EnumPCS.GetDisplayName(s).ToString(),
                           Value = s.ToString(),
                           Selected = values.Where(v => v.Contains(s.ToString())).Count() != 0
                       }).ToList();

            ViewBag.GetCheckboxDIP = q;
        }
        #endregion

        #region resut Ajax JSON
        /// <summary>
        /// 生產單位 Json
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> GetFactoryUnitJson(string id, string search)
        {
            var result = await _basApi.GetFactoryUnits();

            var FactoryUnit = new List<SelectListItem>();
            for (int i = 0; i < result.Count; i++)
            {
                FactoryUnit.Add(new SelectListItem(result[i].UnitName, result[i].UnitNo.ToString()));
            }

            if (FactoryUnit.Count == 0)
            {
                FactoryUnit.Add(new SelectListItem("N/A", null));
            }

            if (!string.IsNullOrWhiteSpace(search))
            {
                FactoryUnit = FactoryUnit.Where(w => w.Text.ToUpper().Contains(search.ToUpper())
                                                  || w.Value.ToUpper().Contains(search.ToUpper())).ToList();
            }
            //var result = await _kcsApi.GetItems();

            //var FactoryUnit = new List<SelectListItem>();
            //for (int i = 0; i < result.Count; i++)
            //{
            //    FactoryUnit.Add(new SelectListItem(result[i].ItemName, result[i].ItemNo.ToString()));
            //}

            //if (result.Count == 0)
            //{
            //    FactoryUnit.Add(new SelectListItem("N/A", null));
            //}

            //将数据Json化并传到前台视图
            return Json(new { data = FactoryUnit });
        }

        /// <summary>
        /// 生產單位 Json By WipNo
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> GetFactoryUnitByWipNoJson(string wipNo)
        {
            var result = await _basApi.GetFactoryUnits();
            var result_wipNo = await _pcsApi.GetWipInfoByWipNO(wipNo);

            // 暫時不判斷工單開立哪些生產製程
            // result = result.Where(w => result_wipNo.Select(s => s.UnitNO).Contains(w.UnitNo)).ToList();
            var Item = new List<SelectListItem>();
            for (int i = 0; i < result.Count; i++)
            {
                Item.Add(new SelectListItem(result[i].UnitName, result[i].UnitNo.ToString()));
            }

            if (Item.Count == 0)
            {
                Item.Add(new SelectListItem("N/A", null));
            }

            ViewBag.FactoryUnitByWipNo = Item;
            //将数据Json化并传到前台视图
            return Json(new { data = Item });
        }

        [HttpPost]
        public async Task<JsonResult> GetStationsJson(string unit_no)
        {
            var result = await _basApi.GetStationsByUnit(unit_no);

            var item = new List<SelectListItem>();

            for (int i = 0; i < result.Count; i++)
            {
                item.Add(new SelectListItem(result[i].StationName, result[i].StationID.ToString()));
            }

            if (item.Count == 0)
            {
                item.Add(new SelectListItem("N/A", ""));
            }

            //将数据Json化并传到前台视图
            return Json(new { data = item });
        }

        [HttpPost]
        public JsonResult GetSOPTypeJson(string id, string search)
        {
            var q = Enum.GetValues(typeof(EnumPCS.EnumWipSopType)).Cast<EnumPCS.EnumWipSopType>()
                       .Select(s => new SelectListItem
                       {
                           Text = EnumPCS.GetDisplayName(s).ToString(),
                           Value = s.ToString()
                       }).ToList();

            return Json(new { data = q });
        }

        /// <summary>
        /// 回傳PLM料號品名
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> getPLMMeterial(string value)
        {
            var result = await _pcsApi.GetPlmMeterialInfo(value);
            //将数据Json化并传到前台视图
            if (result.Count() == 0)
                return Json(new { data = "" });
            else

                return Json(new { data = result.FirstOrDefault().MeterialDesc });
        }

        /// <summary>
        /// 回傳PLM料號品名_AutoComplete
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> getPLMMeterialAutoComplete(string search)
        {
            var result = await _pcsApi.GetPlmMeterialInfoAutoComplete(search);
            return Json(new { data = result });
        }

        /// <summary>
        /// KP Items Json
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> getKpItemsJson()
        {
            var result = await _kcsApi.GetItems();

            var KpItems = new List<SelectListItem>();
            for (int i = 0; i < result.Count; i++)
            {
                KpItems.Add(new SelectListItem(result[i].ItemName, result[i].ItemNo.ToString()));
            }

            if (result.Count == 0)
            {
                KpItems.Add(new SelectListItem("N/A", null));
            }

            //将数据Json化并传到前台视图
            return Json(new { data = KpItems });
        }


        public async Task<JsonResult> MaterialKpQueryAsync(string itemno = null, string station = null)
        {

            IEnumerable<MaterialKpDto> result = await _pcsApi.GetMaterialKpQuery(itemno: itemno, station: station);

            if (result.Count() != 0)
            {
                return Json(new Table() { code = 0, msg = "", data = result, count = result.Count() });
            }
            return Json(new Table() { count = 0, data = null });
        }


        public async Task<JsonResult> MaterialOutfitByItemNo(string itemno = null, string station = null)
        {

            var result = await _pcsApi.GetMaterialOutfitByItemNo(itemno);

            if (result.Count() != 0)
            {
                return Json(new Table() { code = 0, msg = "", data = result, count = result.Count() });
            }
            return Json(new Table() { count = 0, data = null });
        }

        /// <summary>
        /// 料號流程
        /// </summary>
        /// <param name="unit_no"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> GetMaterialFlowRuleJson(string itemno, string unit_no)
        {
            var result = await _pcsApi.GetMaterialFlowsByQuery(itemno, unit_no);

            var item = new List<SelectListItem>();
            //item.Add(new SelectListItem("全部", "0"));
            for (int i = 0; i < result.Count; i++)
            {
                item.Add(new SelectListItem(result[i].FlowRule.FlowRuleName, result[i].FlowRuleID.ToString()));
            }

            ViewBag.MaterialFlowRule = item;
            //将数据Json化并传到前台视图
            return Json(new { data = item });
        }

        /// <summary>
        /// 治具種類
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> GetOutfitCommodityInfoJson()
        {
            var result = await _pcsApi.GetOutfitCommodityInfo();

            var item = new List<SelectListItem>();
            //item.Add(new SelectListItem("全部", "0"));
            result = result.Where(w => w.Status == "A").ToList();
            for (int i = 0; i < result.Count; i++)
            {
                item.Add(new SelectListItem(result[i].CommodityName, result[i].CommodityNo));
            }

            ViewBag.OutfitCommodityInfo = item;
            //将数据Json化并传到前台视图
            return Json(new { data = item });
        }

        /// <summary>
        /// 回傳料號流程_備註
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> getMaterialFlowRuleRemark(string itemno, string unit_no, int flowID)
        {
            var q = await _pcsApi.GetMaterialFlowsByQuery(itemno, unit_no);

            var result = q.Where(w => w.FlowRuleID == flowID).FirstOrDefault();

            //将数据Json化并传到前台视图
            if (result == null)
                return Json(new { data = "" });
            else

                return Json(new { data = result.MaterialFlowRemark });
        }

        /// <summary>
        /// 目前已刷數量
        /// </summary>
        /// <param name="wipNo">工單號碼</param>
        /// <param name="unitNo">生產單位</param>
        /// <param name="ststionID">作業站</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> getBarcodeStationByInputQty(string wipNo, string unitNo, int ststionID)
        {
            var q = await _pcsApi.GetWipInfoByWipNO(wipNo);
            var q1 = q.Where(w => w.UnitNO == unitNo).FirstOrDefault();
            if (q1 != null)
            {

                // 工單流程ID 取站別
                var ruleStations = await GetRuleStationByFlowRuleID(q1.FlowRuleID);
                //var rulestationID = ruleStations.Where(w => w.StationID == ststionID).FirstOrDefault().RuleStationID;

                // 工單已刷數量
                int InputQTY = await _pcsApi.GetBarcodeStationByInputQty(q1.WipID, ststionID);

                //将数据Json化并传到前台视图
                return Json(new { data = InputQTY });
            }
            return Json(new { data = 0 });
        }

        /// <summary>
        /// 用工單號碼查詢綁定作業站 
        /// </summary>
        /// <param name="wipNo">工單號碼</param>
        /// <param name="unitNo">生產單位</param>
        /// <returns>StationID</returns>
        [HttpPost]
        public async Task<JsonResult> GetRuleStationByWipNoUnitNoJson(string wipNo, string unitNo = null)
        {

            var result_wipNo = await _pcsApi.GetWipInfoByWipNO(wipNo);

            // 生產單位判斷
            if (!string.IsNullOrWhiteSpace(unitNo))
                result_wipNo = result_wipNo.Where(w => w.UnitNO == unitNo).ToList();

            var items = new List<SelectListItem>();
            var flowRuleIDs = result_wipNo.Select(s => s.FlowRuleID).Distinct();
            items.Add(new SelectListItem("N/A", null));

            foreach (var flowRuleID in flowRuleIDs)
            {
                var group = new SelectListGroup
                {
                    Name = result_wipNo.Where(w => w.FlowRuleID == flowRuleID)
                                                          .FirstOrDefault().GetFactoryUnit.UnitName
                };
                // 將小於資料改換1
                var result = await _pcsApi.GetRuleStationByFlow(flowRuleID <= 0 ? 1 : flowRuleID);

                for (int i = 0; i < result.Count; i++)
                {
                    items.Add(new SelectListItem()
                    {
                        Text = result[i].StationDesc,
                        Value = result[i].StationID.ToString(),
                        Group = group
                    });
                }
            }

            // 排除完工站
            items = items.Where(w => w.Value != "1000").ToList();

            ViewBag.RuleStationByWipNoUnitNoList = items;
            return Json(new { data = items });
        }


        /// <summary>
        /// 取出貨序號 取到資料先儲存出貨序號
        /// </summary>
        /// <param name="itemNo">料號</param>
        /// <param name="lotNo">生產序號</param>
        /// <param name="num">生產數量</param>
        /// <param name="wipNo">工單號碼</param>
        /// <param name="wipShcDate">預計開工日</param>
        /// <returns>RuleStation </returns>
        [HttpPost]
        public async Task<JsonResult> GetBarcodeOther(string itemNo, string lotNo, int num, string wipNo, string wipShcDate)
        {
            var result = await _pcsApi.GetSerialRuleByQurey(itemNo, lotNo.Trim().ToUpper(), num, wipShcDate);
            string StartNO = "";
            string EndNO = "";

            if (result.Success)
            {
                StartNO = result.Msg.Split('~')[0];
                EndNO = result.Msg.Split('~').Count() == 1 ? result.Msg.Split('~')[0] : result.Msg.Split('~')[1];

                if (!string.IsNullOrWhiteSpace(StartNO) && !string.IsNullOrWhiteSpace(EndNO))
                {
                    var type_no = await _pcsApi.GetBarcodeTypeByTypeName("客戶條碼區間");
                    if (type_no != null)
                    {
                        var wipBarcodeOther = await _pcsApi.GetWipBarcodeOther(wipNo);
                        if (wipBarcodeOther != null)
                        {
                            wipBarcodeOther.StartNO = StartNO;
                            wipBarcodeOther.EndNO = EndNO;
                            wipBarcodeOther.UpdateDate = DateTime.Now;
                            wipBarcodeOther.UpdateUserID = GetLogInUserID();
                            await _pcsApi.PutWipBarcodeOther(JsonConvert.SerializeObject(wipBarcodeOther));
                        }
                        else
                        {
                            wipBarcodeOther = new WipBarcodeOther();
                            wipBarcodeOther.WipNO = wipNo;
                            wipBarcodeOther.TypeNO = type_no.TypeNo;
                            wipBarcodeOther.StartNO = StartNO;
                            wipBarcodeOther.EndNO = EndNO;
                            wipBarcodeOther.CreateUserID = GetLogInUserID();
                            wipBarcodeOther.UpdateUserID = GetLogInUserID();
                            await _pcsApi.PostWipBarcodeOther(JsonConvert.SerializeObject(wipBarcodeOther));
                        }
                    }

                }
            }
            return Json(new Result() { success = result.Success, msg = result.Msg, data = new { StartNO, EndNO } });
        }
        #endregion

        ///// <summary>
        ///// 工單資料建立、修改 keyin KP料號對應keyPartType
        ///// </summary>
        ///// <param name="itemNo">料號</param>
        ///// <param name="lotNo">生產序號</param>
        ///// <param name="num">生產數量</param>
        ///// <param name="wipNo">工單號碼</param>
        ///// <returns>RuleStation </returns>
        //[HttpPost]
        //public async Task<JsonResult> GetKeyPartTypeByWip(string KeyPartMaterial, string KeyPartsType)
        //{
        //    var result = await _kcsApi.GetItems();

        //    if (KeyPartMaterial.ToUpper().Trim().StartsWith())



        //    return Json(new Result() { success = result.Success, msg = result.Msg, data = new { StartNO, EndNO } });
        //}

        [ResponseCache(Duration = 0)]
        [HttpGet]
        public async Task<IActionResult> GetWipInfoAsync()
        {
            var result = await _pcsApi.GetWipInfo();

            if (result.Count > 0)
            {
                return Json(new Table() { code = 0, msg = "", data = result, count = result.Count });
            }
            return Json(new Table() { count = 0, data = null });
        }

        [ResponseCache(Duration = 0)]
        [HttpGet]
        public async Task<IActionResult> GetRuleStationByWipNoAsync(string wipNo, int newID, int oldID)
        {
            var result = await _pcsApi.GetRuleStationByWipNo(wipNo, newID, oldID);

            if (result.Count > 0)
            {
                return Json(new Table() { code = 0, msg = "", data = result, count = 0 });
            }

            return Json(new Table() { count = 0, data = null });
        }


        public async Task<IActionResult> GetRuleStationByFlowDto(int flow)
        {
            var result = await _pcsApi.GetRuleStationByFlowDto(flow);

            if (result.Count > 0)
            {
                return Json(new Table() { code = 0, msg = "", data = result, count = 0 });
            }

            return Json(new Table() { count = 0, data = null });
        }


        /// <summary>
        /// 回傳工單號碼相關資料
        /// </summary>
        /// <param name="value">工單號碼</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> getCreateWipNo_Detail(string value)
        {
            var result_WipAtt = await _pcsApi.GetWipAtt(value);
            var result = new WipNoDetailViewModel();
            result.wipAtt = result_WipAtt;
            //将数据Json化并传到前台视图
            if (result == null)
                return Json(new { data = "" });
            else

                return Json(new { data = result });
        }

        #region PCS001 工單資料維護
        public async Task<IActionResult> PCS001(WipDataViewModel model = null)
        {
            await GetProductType();
            await GetFactoryInfo();
            await GetFactoryUnit();
            await GetLineInfo();
            await GetMFGType();
            await GetProcessTypes();
            await GetFlowRuleList();
            GetWipSEQType();
            GetBurnType();
            GetPartsBakeType();
            GetPCBBakeTypeSelect();
            GetPCBProcessingTypeSelect();
            GetSolderPasteSelect();
            GetWipType();
            GetSOPTypeSelect();
            GetWipSystemTypeSelect();
            GetWipSystemPMTypeSelect();
            GetCheckboxApproveLogo();
            GetCheckboxCompanyLogo();
            GetCheckboxPrintMode();
            GetCheckboxWipAttr();
            GetCheckboxDIP();
            GetCheckboxSMD();

            return View(model);
        }

        public async Task<IActionResult> PCS001N(WipDataViewModel model = null)
        {
            if (TempData["request"] != null)
            {
                var model2 = JsonConvert.DeserializeObject<WipDataViewModel>((string)TempData["request"]);
                if (model2 != null)
                {
                    model = model2;
                    TempData["request"] = null;
                }
            }

            if (model.wipAtt == null || model.wipInfo == null)
                await WipDataSelectAll();
            else
                await WipDataSelectAll(model.wipAtt.WipNO, model.wipAtt.ItemNO, model.wipInfo.UnitNO);

            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> PCS001NAsync(WipDataViewModel model, string action, IFormFile formFile)
        {

            // 料號刷新
            if (action == "ItemNo")
            {
                var result_materialKP = await _pcsApi.GetMaterialKpByItemNo(model.wipAtt.ItemNO);
                model.WipKps.Clear();
                foreach (var item in result_materialKP)
                {
                    model.WipKps.Add(new WipKpDto
                    {
                        WipKpID = 0,
                        KpName = item.KpName,
                        KpNo = item.KpNo,
                        KpSeq = item.KpSeq,
                        Length = item.Length,
                        Title = item.Title
                    });
                }
                await WipDataSelectAll(model.wipInfo.WipNO, model.wipAtt.ItemNO, model.wipInfo.UnitNO);
                return View(model);
            }

            // 工單刷新
            if (action == "Copy")
            {
                model.wipInfo.WipDueDate = DateTime.Now;
                model.wipInfo.WipScheduleDate = DateTime.Now;
                model.wipAtt = await _pcsApi.GetWipAtt(model.wipInfo.WipNO);
                model.wipBarcodes = await _pcsApi.GetWipBarcode(model.wipInfo.WipNO);
                model.wipBarcode = model.wipBarcodes.FirstOrDefault();
                model.ruleStations = await _pcsApi.GetRuleStationByWipNo(model.wipInfo.WipNO);


                model.wipMAC = await _pcsApi.GetWipMAC(model.wipInfo.WipNO);
                if (model.wipMAC != null)
                {
                    model.wipMAC.StartNO = model.wipMAC.Title + model.wipMAC.StartNO;
                    model.wipMAC.EndNO = model.wipMAC.Title + model.wipMAC.EndNO;
                }

                model.wipBarcodeOther = await _pcsApi.GetWipBarcodeOther(model.wipInfo.WipNO);

                model.WipKps = await _pcsApi.GetWipKpByWipNo(model.wipInfo.WipNO);


                await WipDataSelectAll(model.wipInfo.WipNO, UnitNo: model.wipInfo.UnitNO);
                TempData["request"] = JsonConvert.SerializeObject(model);
                return Redirect("PCS001N");
            }
            // 保存
            await WipDataSelectAll(model.wipInfo.WipNO, model.wipAtt.ItemNO, model.wipInfo.UnitNO);
            IResultModel result;
            int UserID = GetLogInUserID();
            // Checkbox轉換
            model.wipInfo.ECNCheck = model.wipInfo.ECNCheck == "true" ? "Y" : "N";
            model.wipInfo.ModelCheck = model.wipInfo.ModelCheck == "true" ? "Y" : "N";
            model.wipInfo.InputFlag = model.wipInfo.InputFlag == "true" ? "Y" : "N";
            model.wipInfo.Priority = model.wipInfo.Priority == "true" ? "Y" : "N";
            model.wipInfo.CustomerMedical = model.wipInfo.CustomerMedical == "true" ? "Y" : "N";
            model.wipInfo.CustomerVIP = model.wipInfo.CustomerVIP == "true" ? "Y" : "N";
            model.wipInfo.SFISFlowCk = model.wipInfo.SFISFlowCk == "true" ? "Y" : "N";

            // 判斷資料填寫
            var Msg = CheckWipInfoInsert(model, "New");


            // 判斷是否有開重複工單+生產單位
            var wipInfoQuery = await _pcsApi.GetWipInfoByWipNO(model.wipInfo.WipNO);
            if (wipInfoQuery.Any())
            {
                if (wipInfoQuery.Where(w => w.UnitNO == model.wipInfo.UnitNO).Count() != 0)
                {
                    Msg += "  同樣生產單位已建立相同工單了  ";
                }
            }

            // 判斷WipKp 順序是否重複
            if (model.WipKps.Where(w => w.WipKpID != -1).GroupBy(g => g.KpSeq).Where(w => w.Count() > 1).Any())
            {
                Msg += " KeyParts 順序有重複 ";
            }

            // 判斷MAC是否正確
            var CheckMACMsg = CheckMACData(model);
            if (!string.IsNullOrWhiteSpace(CheckMACMsg))
            {
                Msg += CheckMACMsg;
            }

            if (!string.IsNullOrWhiteSpace(Msg))
            {
                model.wipInfo.ECNCheck = model.wipInfo.ECNCheck == "Y" ? "true" : "false";
                model.wipInfo.ModelCheck = model.wipInfo.ModelCheck == "Y" ? "true" : "false";
                model.wipInfo.InputFlag = model.wipInfo.InputFlag == "Y" ? "true" : "false";
                model.wipInfo.Priority = model.wipInfo.Priority == "Y" ? "true" : "false";
                model.wipInfo.CustomerMedical = model.wipInfo.CustomerMedical == "Y" ? "true" : "false";
                model.wipInfo.CustomerVIP = model.wipInfo.CustomerVIP == "Y" ? "true" : "false";
                model.wipInfo.SFISFlowCk = model.wipInfo.SFISFlowCk == "Y" ? "true" : "false";
                ModelState.AddModelError("error", Msg);

                return View("PCS001N", model);
            }

            model.wipInfo.CreateUserID = UserID;
            result = await _pcsApi.PostWipInfo(JsonConvert.SerializeObject(model.wipInfo));
            if (result.Success)
            {
                int wipID = int.Parse(result.Msg);
                int materialID = 0; // 料號ItemNo

                // 新增工單Log
                WipLog wiplog = new WipLog();
                wiplog.WipID = wipID;
                wiplog.StatusNO = "N";
                wiplog.WipDesc = ".";
                wiplog.CreateUserID = UserID;
                await _pcsApi.PostWipLog(JsonConvert.SerializeObject(wiplog));

                // 料號判斷,沒有就Insert
                var checkMaterialItem = await _pcsApi.GetMaterialItemByItemNO(model.wipAtt.ItemNO);
                if (checkMaterialItem == null)
                {
                    var result_PostMaterial = await _pcsApi.PostMaterialItem(JsonConvert.SerializeObject(
                                                 new MaterialItem
                                                 {
                                                     ItemNo = model.wipAtt.ItemNO,
                                                     CreateUserID = UserID
                                                 }));

                    // 新增料號檔成功 取料號ID
                    if (result_PostMaterial.Success)
                    {
                        materialID = int.Parse(result_PostMaterial.Msg);
                    }
                }


                // 全新工單
                if (wipInfoQuery.Count == 0)
                {
                    // 工單屬性
                    model.wipAtt.WipNO = model.wipInfo.WipNO;
                    model.wipAtt.CreateUserID = UserID;
                    await _pcsApi.PostWipAtt(JsonConvert.SerializeObject(model.wipAtt));

                    // 內部條碼
                    if (!string.IsNullOrWhiteSpace(model.wipBarcode.StartNO) && !string.IsNullOrWhiteSpace(model.wipBarcode.EndNO))
                    {
                        model.wipBarcode.WipID = wipID;
                        model.wipBarcode.WipNO = model.wipInfo.WipNO;
                        model.wipBarcode.UnitNO = model.wipInfo.UnitNO;
                        model.wipBarcode.CreateUserID = UserID;
                        result = await _pcsApi.PostWipBarcode(JsonConvert.SerializeObject(model.wipBarcode));

                        // 工單條碼規則設定文件檔
                        WipRule wipRule = new WipRule();
                        wipRule.WipNO = model.wipInfo.WipNO;
                        wipRule.KeyNo = "00";
                        wipRule.BarcodeLen = 14;
                        wipRule.BarcodeFormat = model.wipInfo.UnitNO;
                        result = await _pcsApi.PostWipRule(JsonConvert.SerializeObject(wipRule));
                    }

                    // 出貨序號
                    //if (!string.IsNullOrWhiteSpace(model.wipBarcodeOther.StartNO) && !string.IsNullOrWhiteSpace(model.wipBarcodeOther.EndNO))
                    //{
                    //    var type_no = await _pcsApi.GetBarcodeTypeByTypeName("客戶條碼區間");
                    //    if (type_no != null)
                    //    {
                    //        model.wipBarcodeOther.WipNO = model.wipInfo.WipNO;
                    //        model.wipBarcodeOther.TypeNO = type_no.TypeNo;
                    //        model.wipBarcodeOther.CreateUserID = UserID;
                    //        model.wipBarcodeOther.UpdateUserID = UserID;
                    //        result = await _pcsApi.PostWipBarcodeOther(JsonConvert.SerializeObject(model.wipBarcodeOther));
                    //    }
                    //}

                    // MAC
                    if (!string.IsNullOrWhiteSpace(model.wipMAC.StartNO) && !string.IsNullOrWhiteSpace(model.wipMAC.EndNO))
                    {
                        if (model.wipMAC.StartNO.Length == 12)
                        {
                            model.wipMAC.Title = model.wipMAC.StartNO.Substring(0, 6).ToUpper();
                            model.wipMAC.StartNO = model.wipMAC.StartNO.Substring(model.wipMAC.StartNO.Length - 6, 6).ToUpper();
                            model.wipMAC.EndNO = model.wipMAC.EndNO.Substring(model.wipMAC.EndNO.Length - 6, 6).ToUpper();

                            // 確認MAC Table是否有料號資料
                            var mACInfo = await _pcsApi.GetMACInfo(model.wipAtt.ItemNO);
                            if (mACInfo != null)
                            {
                                model.wipMAC.ClassGroup = mACInfo.ClassGroup;
                                //result = await _pcsApi.PutMACInfoByClassGroup(mACInfo.ClassGroup, model.wipMAC.EndNO);
                            }

                            if (!string.IsNullOrWhiteSpace(model.wipMAC.WipNO))
                                result = await _pcsApi.PutWipMAC(JsonConvert.SerializeObject(model.wipMAC));
                            else
                            {
                                model.wipMAC.WipNO = model.wipInfo.WipNO;
                                model.wipMAC.CreateUserID = UserID;
                                result = await _pcsApi.PostWipMAC(JsonConvert.SerializeObject(model.wipMAC));
                            }
                        }
                    }

                    // 料號相關
                    var materialItem = await _pcsApi.GetMaterialItemByItemNO(model.wipAtt.ItemNO);
                    if (materialItem != null)
                    {
                        // 
                        if (model.WipKps != null)
                        {
                            await _pcsApi.DeleteMaterialKpByItem(materialItem.ItemID);

                            // 先比對新舊ID 當舊ID有 新的沒有代表已刪除
                            var resultOld_WipKp = await _pcsApi.GetWipKpByWipNo(model.wipInfo.WipNO);
                            var delete_WipKpID = resultOld_WipKp.Select(s => s.WipKpID).Except(model.WipKps.Select(s => s.WipKpID));
                            foreach (var id in delete_WipKpID)
                            {
                                await _pcsApi.DeleteWipKp(id);
                            }

                            foreach (var item in model.WipKps.Where(w => w.WipKpID != -1))
                            {
                                item.WipNo = model.wipInfo.WipNO;
                                item.ItemNo = model.wipAtt.ItemNO;
                                item.UpdateUserID = UserID;
                                item.CreateUserID = UserID;
                                if (item.WipKpID == 0)
                                    await _pcsApi.PostWipKp(JsonConvert.SerializeObject(item));
                                else
                                    await _pcsApi.PutWipKp(JsonConvert.SerializeObject(item));

                                // 新增到料號KP檔
                                await _pcsApi.PostMaterialKp(JsonConvert.SerializeObject(new MaterialKp
                                {
                                    ItemID = materialItem.ItemID,
                                    KpName = item.KpName,
                                    KpNo = item.KpNo,
                                    KpSeq = Convert.ToInt32(item.KpSeq),
                                    Length = item.Length,
                                    StationType = item.UnitNo,
                                    IsRepeat = "N",
                                    Title = item.Title,
                                    CreateUserID = UserID,
                                    UpdateUserID = UserID
                                }));
                            }
                            model.WipKps = model.WipKps.Where(w => w.WipKpID != -1).ToList();
                        }
                        // 將料號KP新增到WIP_KP 上
                        else
                        {
                            // KeyParts 組合
                            var materialKp = await _pcsApi.GetMaterialKpByItemID(materialItem.ItemID);
                            foreach (var item in materialKp.Where(w => w.StationType == model.wipInfo.UnitNO))
                            {
                                var wipKp = new WipKp
                                {
                                    WipNo = model.wipInfo.WipNO,
                                    ItemNo = model.wipAtt.ItemNO,
                                    UnitNo = item.StationType,
                                    KpName = item.KpName,
                                    KpNo = item.KpNo,
                                    KpSeq = item.KpSeq,
                                    Length = item.Length,
                                    Title = item.Title,
                                    CreateUserID = UserID,
                                    UpdateUserID = UserID
                                };
                                await _pcsApi.PostWipKp(JsonConvert.SerializeObject(wipKp));
                            }
                        }

                        // 治具
                        var materialOutfit = await _pcsApi.GetMaterialOutfitByItemNo(model.wipAtt.ItemNO);
                        foreach (var item in materialOutfit.Where(w => w.UnitNo == model.wipInfo.UnitNO))
                        {
                            var wipOutfit = new WipOutfit
                            {
                                WipNo = model.wipInfo.WipNO,
                                ItemNo = model.wipAtt.ItemNO,
                                UnitNo = model.wipInfo.UnitNO,
                                OutfitNo = item.OutfitNo,
                                PartNo = item.StationType,
                                CreateUserID = UserID,
                                UpdateUserID = UserID
                            };
                            await _pcsApi.PostWipOutfit(JsonConvert.SerializeObject(wipOutfit));
                        }

                        // 工單對應SOP
                        var materialSop = await _pcsApi.GetMaterialSopByItemNo(model.wipAtt.ItemNO);
                        foreach (var item in materialSop.Where(w => w.UnitNo == model.wipInfo.UnitNO))
                        {
                            var wipSop = new WipSop
                            {
                                WipNo = model.wipInfo.WipNO,
                                ItemNo = model.wipAtt.ItemNO,
                                UnitNo = model.wipInfo.UnitNO,
                                SOPName = item.SopName,
                                SOPPath = item.SopPath,
                                SOPType = item.SopType,
                                CreateUserID = UserID,
                                UpdateUserID = UserID
                            };
                            await _pcsApi.PostWipSop(JsonConvert.SerializeObject(wipSop));
                        }
                    }
                }
                else
                {
                    // 
                    if (model.WipKps != null)
                    {
                        // KeyParts 
                        // 先比對新舊ID 當舊ID有 新的沒有代表已刪除
                        var resultOld_WipKp = await _pcsApi.GetWipKpByWipNo(model.wipInfo.WipNO);
                        var delete_WipKpID = resultOld_WipKp.Select(s => s.WipKpID).Except(model.WipKps.Select(s => s.WipKpID));
                        foreach (var id in delete_WipKpID)
                        {
                            await _pcsApi.DeleteWipKp(id);
                        }
                        foreach (var item in model.WipKps.Where(w => w.WipKpID != -1))
                        {
                            item.WipNo = model.wipInfo.WipNO;
                            item.ItemNo = model.wipAtt.ItemNO;
                            item.UnitNo = model.wipInfo.UnitNO;
                            if (item.WipKpID == 0)
                                await _pcsApi.PostWipKp(JsonConvert.SerializeObject(item));
                            else
                                await _pcsApi.PutWipKp(JsonConvert.SerializeObject(item));
                        }
                        model.WipKps = model.WipKps.Where(w => w.WipKpID != -1).ToList();
                    }
                }

            }

            if (result.Success)
            {
                ModelState.Clear();
                ModelState.AddModelError("error", "新增成功!");
                var viewModel = new WipDataViewModel();
                return View(viewModel);
            }
            else
            {
                model.wipInfo.ECNCheck = model.wipInfo.ECNCheck == "Y" ? "true" : "false";
                model.wipInfo.ModelCheck = model.wipInfo.ModelCheck == "Y" ? "true" : "false";
                model.wipInfo.InputFlag = model.wipInfo.InputFlag == "Y" ? "true" : "false";
                model.wipInfo.Priority = model.wipInfo.Priority == "Y" ? "true" : "false";
                model.wipInfo.CustomerMedical = model.wipInfo.CustomerMedical == "Y" ? "true" : "false";
                model.wipInfo.CustomerVIP = model.wipInfo.CustomerVIP == "Y" ? "true" : "false";
                model.wipInfo.SFISFlowCk = model.wipInfo.SFISFlowCk == "Y" ? "true" : "false";
                if (result.Errors != null)
                {
                    ModelState.AddModelError(result.Errors[0].Id, result.Errors[0].Msg);
                }
                else
                {
                    ModelState.AddModelError("error", result.Msg);
                }
            }

            return View(model);
        }

        //頁面提交,id=0 添加,id>0 修改
        [HttpPost]
        public async Task<IActionResult> PCS001Async(WipDataViewModel model, IFormFile formFile)
        {
            #region 選單
            await GetProductType();
            await GetFactoryInfo();
            await GetFactoryUnit();
            await GetLineInfo();
            await GetMFGType();
            await GetProcessTypes();
            await GetFlowRuleList();

            GetWipSEQType();
            GetBurnType();
            GetPartsBakeType();
            GetPCBBakeTypeSelect();
            GetPCBProcessingTypeSelect();
            GetSolderPasteSelect();
            GetWipType();
            GetSOPTypeSelect();
            GetWipSystemTypeSelect();
            GetWipSystemPMTypeSelect();
            GetCheckboxApproveLogo();
            GetCheckboxCompanyLogo();
            GetCheckboxPrintMode();
            GetCheckboxWipAttr();
            GetCheckboxDIP();
            GetCheckboxSMD();
            #endregion
            IResultModel result;
            int UserID = GetLogInUserID();
            // Checkbox轉換
            model.wipInfo.ECNCheck = model.wipInfo.ECNCheck == "true" ? "Y" : "N";
            model.wipInfo.ModelCheck = model.wipInfo.ModelCheck == "true" ? "Y" : "N";
            model.wipInfo.InputFlag = model.wipInfo.InputFlag == "true" ? "Y" : "N";
            model.wipInfo.Priority = model.wipInfo.Priority == "true" ? "Y" : "N";
            model.wipInfo.CustomerMedical = model.wipInfo.CustomerMedical == "true" ? "Y" : "N";
            model.wipInfo.CustomerVIP = model.wipInfo.CustomerVIP == "true" ? "Y" : "N";
            model.wipInfo.SFISFlowCk = model.wipInfo.SFISFlowCk == "true" ? "Y" : "N";
            //板卡
            model.wipBoard.DipCarrier = model.wipBoard.DipCarrier == "true" ? "Y" : "N";
            model.wipBoard.DipTape = model.wipBoard.DipTape == "true" ? "Y" : "N";
            model.wipBoard.DipSolderMask = model.wipBoard.DipSolderMask == "true" ? "Y" : "N";
            model.wipBoard.Burn = model.wipBoard.Burn == "true" ? "Y" : "N";
            model.wipBoard.ISPartsBake = model.wipBoard.ISPartsBake == "true" ? "Y" : "N";
            model.wipBoard.PartsBakeOvertime = model.wipBoard.PartsBakeOvertime == "true" ? "Y" : "N";
            model.wipBoard.ISPcbBake = model.wipBoard.ISPcbBake == "true" ? "Y" : "N";
            //系統
            model.wipSystem.FinePackage = model.wipSystem.FinePackage == "true" ? "Y" : "N";

            // 判斷資料填寫
            var Msg = CheckWipInfoInsert(model);


            // 判斷是否有開重複工單+生產單位
            var wipInfoQuery = await _pcsApi.GetWipInfoByWipNO(model.wipInfo.WipNO);
            if (wipInfoQuery.Any())
            {
                if (wipInfoQuery.Where(w => w.UnitNO == model.wipInfo.UnitNO).Count() != 0)
                {
                    Msg += "  同樣生產單位已建立相同工單了  ";
                }
            }

            if (!string.IsNullOrWhiteSpace(Msg))
            {
                model.wipInfo.ECNCheck = model.wipInfo.ECNCheck == "Y" ? "true" : "false";
                model.wipInfo.ModelCheck = model.wipInfo.ModelCheck == "Y" ? "true" : "false";
                model.wipInfo.InputFlag = model.wipInfo.InputFlag == "Y" ? "true" : "false";
                model.wipInfo.Priority = model.wipInfo.Priority == "Y" ? "true" : "false";
                model.wipInfo.CustomerMedical = model.wipInfo.CustomerMedical == "Y" ? "true" : "false";
                model.wipInfo.CustomerVIP = model.wipInfo.CustomerVIP == "Y" ? "true" : "false";
                model.wipInfo.SFISFlowCk = model.wipInfo.SFISFlowCk == "Y" ? "true" : "false";
                //板卡
                model.wipBoard.DipCarrier = model.wipBoard.DipCarrier == "Y" ? "true" : "false";
                model.wipBoard.DipTape = model.wipBoard.DipTape == "Y" ? "true" : "false";
                model.wipBoard.DipSolderMask = model.wipBoard.DipSolderMask == "Y" ? "true" : "false";
                model.wipBoard.ISPartsBake = model.wipBoard.ISPartsBake == "Y" ? "true" : "false";
                model.wipBoard.Burn = model.wipBoard.Burn == "Y" ? "true" : "false";
                model.wipBoard.PartsBakeOvertime = model.wipBoard.PartsBakeOvertime == "Y" ? "true" : "false";
                model.wipBoard.ISPcbBake = model.wipBoard.ISPcbBake == "Y" ? "true" : "false";
                //系統
                model.wipSystem.FinePackage = model.wipSystem.FinePackage == "Y" ? "true" : "false";
                ModelState.AddModelError("error", Msg);

                return View("PCS001", model);
            }

            result = await _pcsApi.PostWipInfo(JsonConvert.SerializeObject(model.wipInfo));
            if (result.Success)
            {
                int wipID = int.Parse(result.Msg);

                // 料號判斷,沒有就Insert
                var checkMaterialItem = await _pcsApi.GetMaterialItemByItemNO(model.wipAtt.ItemNO);
                if (checkMaterialItem == null)
                {
                    await _pcsApi.PostMaterialItem(JsonConvert.SerializeObject(
                        new MaterialItem
                        {
                            ItemNo = model.wipAtt.ItemNO,
                            CreateUserID = UserID
                        }));
                }

                // 工單屬性
                model.wipAtt.WipNO = model.wipInfo.WipNO;
                model.wipAtt.CreateUserID = UserID;
                await _pcsApi.PostWipAtt(JsonConvert.SerializeObject(model.wipAtt));

                // 標籤
                model.wipLabel.ApproveLogo = model.wipLabel.ApproveLogos == null ? null : string.Join(',', model.wipLabel.ApproveLogos);
                model.wipLabel.WipNO = model.wipInfo.WipNO;
                model.wipLabel.CreateUserID = UserID;
                model.wipLabel.UpdateUserID = UserID;
                await _pcsApi.PostWipLabel(JsonConvert.SerializeObject(model.wipLabel));

                // 新增工單Log
                WipLog wiplog = new WipLog();
                wiplog.WipID = wipID;
                wiplog.StatusNO = "N";
                wiplog.WipDesc = ".";
                wiplog.CreateUserID = UserID;
                await _pcsApi.PostWipLog(JsonConvert.SerializeObject(wiplog));

                // 系統
                if (model.wipInfo.UnitNO == "B" || model.wipInfo.UnitNO == "P" || model.wipInfo.UnitNO == "T")
                {
                    if (string.IsNullOrWhiteSpace(CheckWipInfoInsert_WipSystem(model.wipSystem)))
                    {
                        if (!string.IsNullOrWhiteSpace(model.wipSystem.BiTemperature))
                        {
                            model.wipSystem.ItemNo = model.wipAtt.ItemNO;
                            model.wipSystem.WipNo = model.wipInfo.WipNO;
                            model.wipSystem.CreateUserID = UserID;
                            model.wipSystem.UpdateUserID = UserID;
                            await _pcsApi.PostWipSystem(JsonConvert.SerializeObject(model.wipSystem));
                        }
                    }
                }
                else
                // 板卡
                {
                    if (string.IsNullOrWhiteSpace(CheckWipInfoInsert_WipBoard(model.wipBoard)))
                    {
                        if (!string.IsNullOrWhiteSpace(model.wipBoard.BiTemperature))
                        {
                            model.wipBoard.Smd = model.wipBoard.SMDs == null ? null : string.Join(',', model.wipBoard.SMDs);
                            model.wipBoard.DipSide = model.wipBoard.DipSides == null ? null : string.Join(',', model.wipBoard.DipSides);
                            model.wipBoard.SmdSolderMask = model.wipBoard.SmdSolderMasks == null ? null : string.Join(',', model.wipBoard.SmdSolderMasks);
                            model.wipBoard.ItemNo = model.wipAtt.ItemNO;
                            model.wipBoard.WipNo = model.wipInfo.WipNO;
                            model.wipBoard.CreateUserID = UserID;
                            model.wipBoard.UpdateUserID = UserID;
                            await _pcsApi.PostWipBoard(JsonConvert.SerializeObject(model.wipBoard));
                        }
                    }
                }

                // 內部條碼
                if (!string.IsNullOrWhiteSpace(model.wipBarcode.StartNO) && !string.IsNullOrWhiteSpace(model.wipBarcode.EndNO))
                {
                    model.wipBarcode.WipID = wipID;
                    model.wipBarcode.WipNO = model.wipInfo.WipNO;
                    model.wipBarcode.UnitNO = model.wipInfo.UnitNO;
                    model.wipBarcode.CreateUserID = UserID;
                    result = await _pcsApi.PostWipBarcode(JsonConvert.SerializeObject(model.wipBarcode));

                    // 工單條碼規則設定文件檔
                    WipRule wipRule = new WipRule();
                    wipRule.WipNO = model.wipInfo.WipNO;
                    wipRule.KeyNo = "00";
                    wipRule.BarcodeLen = 14;
                    wipRule.BarcodeFormat = model.wipInfo.UnitNO;
                    result = await _pcsApi.PostWipRule(JsonConvert.SerializeObject(wipRule));
                }

                // 出貨序號
                if (!string.IsNullOrWhiteSpace(model.wipBarcodeOther.StartNO) && !string.IsNullOrWhiteSpace(model.wipBarcodeOther.EndNO))
                {
                    var type_no = await _pcsApi.GetBarcodeTypeByTypeName("客戶條碼區間");
                    if (type_no != null)
                    {
                        model.wipBarcodeOther.WipNO = model.wipInfo.WipNO;
                        model.wipBarcodeOther.TypeNO = type_no.TypeNo;
                        model.wipBarcodeOther.CreateUserID = UserID;
                        model.wipBarcodeOther.UpdateUserID = UserID;
                        result = await _pcsApi.PostWipBarcodeOther(JsonConvert.SerializeObject(model.wipBarcodeOther));
                    }
                }

                // MAC
                if (!string.IsNullOrWhiteSpace(model.wipMAC.StartNO) && !string.IsNullOrWhiteSpace(model.wipMAC.EndNO))
                {
                    var mACInfo = await _pcsApi.GetMACInfo(model.wipAtt.ItemNO);
                    if (mACInfo != null)
                    {
                        model.wipMAC.WipNO = model.wipInfo.WipNO;
                        model.wipMAC.Title = mACInfo.Title;
                        model.wipMAC.ClassGroup = mACInfo.ClassGroup;
                        model.wipMAC.CreateUserID = UserID;
                        result = await _pcsApi.PostWipMAC(JsonConvert.SerializeObject(model.wipMAC));
                        result = await _pcsApi.PutMACInfoByClassGroup(mACInfo.ClassGroup, model.wipMAC.EndNO);
                    }
                }

                // 料號相關
                var materialItem = await _pcsApi.GetMaterialItemByItemNO(model.wipAtt.ItemNO);
                if (materialItem != null)
                {
                    // KeyParts 組合
                    var materialKp = await _pcsApi.GetMaterialKpByItemID(materialItem.ItemID);
                    foreach (var item in materialKp.Where(w => w.StationType == model.wipInfo.UnitNO))
                    {
                        var wipKp = new WipKp
                        {
                            WipNo = model.wipInfo.WipNO,
                            ItemNo = model.wipAtt.ItemNO,
                            UnitNo = model.wipInfo.UnitNO,
                            KpName = item.KpName,
                            KpNo = item.KpNo,
                            KpSeq = item.KpSeq,
                            Length = item.Length,
                            Title = item.Title,
                            CreateUserID = UserID,
                            UpdateUserID = UserID
                        };
                        await _pcsApi.PostWipKp(JsonConvert.SerializeObject(wipKp));
                    }

                    // 治具
                    var materialOutfit = await _pcsApi.GetMaterialOutfitByItemNo(model.wipAtt.ItemNO);
                    foreach (var item in materialOutfit.Where(w => w.UnitNo == model.wipInfo.UnitNO))
                    {
                        var wipOutfit = new WipOutfit
                        {
                            WipNo = model.wipInfo.WipNO,
                            ItemNo = model.wipAtt.ItemNO,
                            UnitNo = model.wipInfo.UnitNO,
                            OutfitNo = item.OutfitNo,
                            PartNo = item.StationType,
                            CreateUserID = UserID,
                            UpdateUserID = UserID
                        };
                        await _pcsApi.PostWipOutfit(JsonConvert.SerializeObject(wipOutfit));
                    }

                    // 工單對應SOP
                    var materialSop = await _pcsApi.GetMaterialSopByItemNo(model.wipAtt.ItemNO);
                    foreach (var item in materialSop.Where(w => w.UnitNo == model.wipInfo.UnitNO))
                    {
                        var wipSop = new WipSop
                        {
                            WipNo = model.wipInfo.WipNO,
                            ItemNo = model.wipAtt.ItemNO,
                            UnitNo = model.wipInfo.UnitNO,
                            SOPName = item.SopName,
                            SOPPath = item.SopPath,
                            SOPType = item.SopType,
                            CreateUserID = UserID,
                            UpdateUserID = UserID
                        };
                        await _pcsApi.PostWipSop(JsonConvert.SerializeObject(wipSop));
                    }
                }
            }

            if (result.Success)
            {
                var _msg = "新增成功!";
                return RedirectToAction("Refresh", "Home", new { msg = _msg });
            }
            else
            {
                if (result.Errors != null)
                {
                    ModelState.AddModelError(result.Errors[0].Id, result.Errors[0].Msg);
                }
                else
                {
                    ModelState.AddModelError("error", result.Msg);
                }
            }
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> PCS001CreateWipNo(WipDataViewModel model)
        {
            //await GetUnitList();
            await GetProductType();
            await GetFactoryInfo();
            await GetFactoryUnit();
            await GetLineInfo();
            await GetMFGType();
            await GetProcessTypes();
            await GetFlowRuleList();
            GetWipSEQType();
            GetBurnType();
            GetPartsBakeType();
            GetPCBBakeTypeSelect();
            GetPCBProcessingTypeSelect();
            GetSolderPasteSelect();
            GetWipType();
            GetSOPTypeSelect();
            GetWipSystemTypeSelect();
            GetWipSystemPMTypeSelect();
            GetCheckboxApproveLogo();
            GetCheckboxCompanyLogo();
            GetCheckboxPrintMode();
            GetCheckboxWipAttr();
            GetCheckboxDIP();
            GetCheckboxSMD();

            model.wipAtt = await _pcsApi.GetWipAtt(model.wipInfo.WipNO);
            model.wipBarcodes = await _pcsApi.GetWipBarcode(model.wipInfo.WipNO);
            model.ruleStations = await _pcsApi.GetRuleStationByWipNo(model.wipInfo.WipNO);

            var q1 = await _pcsApi.GetMaterialSopQuery(itemNo: model.wipAtt.ItemNO);
            model.materialSops = q1.Data;

            model.WipKps = await _pcsApi.GetWipKpByWipNo(model.wipInfo.WipNO);

            model.wipBoard = await _pcsApi.GetWipBoard(model.wipInfo.WipNO);

            model.wipSystem = await _pcsApi.GetWipSystem(model.wipInfo.WipNO);

            model.wipMAC = await _pcsApi.GetWipMAC(model.wipInfo.WipNO);

            model.wipLabel = await _pcsApi.GetWipLabel(model.wipInfo.WipNO);

            model.wipBarcodeOther = await _pcsApi.GetWipBarcodeOther(model.wipInfo.WipNO);

            model.Outfits = await _pcsApi.GetMaterialOutfitByItemNo(model.wipAtt.ItemNO);

            return View("PCS001", model);
        }

        public async Task<IActionResult> PCS001R(int id)
        {
            // 針對安勤 工單基本資料統一打開工程資訊
            ViewBag.WipSpecial = _configuration["WipSpecial"];

            WipDataViewModel model = new WipDataViewModel();
            var q = await _pcsApi.GetWipInfo(id);
            if (q.Count != 0)
            {
                model.wipInfo = q.FirstOrDefault();
                model.wipAtt = await _pcsApi.GetWipAtt(model.wipInfo.WipNO);
                model.wipBarcodes = await _pcsApi.GetWipBarcode(model.wipInfo.WipNO);
                model.wipBarcode = model.wipBarcodes.FirstOrDefault();
                model.ruleStations = await _pcsApi.GetRuleStationByWipNo(model.wipInfo.WipNO, model.wipInfo.FlowRuleID);

                //var q1 = await _pcsApi.GetMaterialSopQuery(itemNo: model.wipAtt.ItemNO);
                //model.materialSops = q1.Data;

                model.wipBoard = await _pcsApi.GetWipBoard(model.wipInfo.WipNO);
                if (model.wipBoard != null)
                {
                    if (!string.IsNullOrWhiteSpace(model.wipBoard.Engineer))
                    {
                        var UserInof = _sysApi.GetUserInfoByUserNo(model.wipBoard.Engineer).InvokeAsync().Result;
                        if (UserInof != null)
                            model.wipBoard.Engineer_Name = UserInof.UserName;
                    }
                }

                model.wipSystem = await _pcsApi.GetWipSystem(model.wipInfo.WipNO);
                if (model.wipSystem != null)
                {
                    if (!string.IsNullOrWhiteSpace(model.wipSystem.Engineer))
                    {
                        var UserInof = _sysApi.GetUserInfoByUserNo(model.wipSystem.Engineer).InvokeAsync().Result;
                        if (UserInof != null)
                            model.wipSystem.Engineer_Name = UserInof.UserName;
                    }

                    if (!string.IsNullOrWhiteSpace(model.wipSystem.Ec))
                    {
                        var Ec_Desc = _pcsApi.GetPlmMeterialInfo(model.wipSystem.Ec).InvokeAsync().Result;
                        model.wipSystem.Ec_Desc = Ec_Desc.Count() == 0 ? "" : Ec_Desc.FirstOrDefault().MeterialDesc;
                    }

                    if (!string.IsNullOrWhiteSpace(model.wipSystem.Fw))
                    {
                        var Fw_Desc = _pcsApi.GetPlmMeterialInfo(model.wipSystem.Fw).InvokeAsync().Result;
                        model.wipSystem.Fw_Desc = Fw_Desc.Count() == 0 ? "" : Fw_Desc.FirstOrDefault().MeterialDesc;
                    }

                    if (!string.IsNullOrWhiteSpace(model.wipSystem.Fw1))
                    {
                        var Fw1_Desc = _pcsApi.GetPlmMeterialInfo(model.wipSystem.Fw1).InvokeAsync().Result;
                        model.wipSystem.Fw1_Desc = Fw1_Desc.Count() == 0 ? "" : Fw1_Desc.FirstOrDefault().MeterialDesc;
                    }

                    if (!string.IsNullOrWhiteSpace(model.wipSystem.Fw2))
                    {
                        var Fw2_Desc = _pcsApi.GetPlmMeterialInfo(model.wipSystem.Fw2).InvokeAsync().Result;
                        model.wipSystem.Fw2_Desc = Fw2_Desc.Count() == 0 ? "" : Fw2_Desc.FirstOrDefault().MeterialDesc;
                    }

                    if (!string.IsNullOrWhiteSpace(model.wipSystem.Bios))
                    {
                        var Bios_Desc = _pcsApi.GetPlmMeterialInfo(model.wipSystem.Bios).InvokeAsync().Result;
                        model.wipSystem.Bios_Desc = Bios_Desc.Count() == 0 ? "" : Bios_Desc.FirstOrDefault().MeterialDesc;
                    }

                    if (!string.IsNullOrWhiteSpace(model.wipSystem.OsVer))
                    {
                        var Os_Desc = _pcsApi.GetPlmMeterialInfo(model.wipSystem.OsVer).InvokeAsync().Result;
                        model.wipSystem.OsVer_Desc = Os_Desc.Count() == 0 ? "" : Os_Desc.FirstOrDefault().MeterialDesc;
                    }

                    if (!string.IsNullOrWhiteSpace(model.wipSystem.PowerMode))
                    {
                        var PowerMode_Desc = _pcsApi.GetPlmMeterialInfo(model.wipSystem.PowerMode).InvokeAsync().Result;
                        model.wipSystem.PowerMode_Desc = PowerMode_Desc.Count() == 0 ? "" : PowerMode_Desc.FirstOrDefault().ProductionMemo;
                    }
                }

                model.wipMAC = await _pcsApi.GetWipMAC(model.wipInfo.WipNO);
                if (model.wipMAC != null)
                {
                    model.wipMAC.StartNO = model.wipMAC.Title + model.wipMAC.StartNO;
                    model.wipMAC.EndNO = model.wipMAC.Title + model.wipMAC.EndNO;
                }

                model.wipLabel = await _pcsApi.GetWipLabel(model.wipInfo.WipNO);

                model.wipBarcodeOther = await _pcsApi.GetWipBarcodeOther(model.wipInfo.WipNO);

                model.Outfits = await _pcsApi.GetMaterialOutfitByItemNo(model.wipAtt.ItemNO);

                model.WipKps = await _pcsApi.GetWipKpByWipNo(model.wipInfo.WipNO);

                model.WipOutfits = await _pcsApi.GetWipOutfitByWipNo(model.wipInfo.WipNO);

                model.WipSops = await _pcsApi.GetWipSopByWipNo(model.wipInfo.WipNO);

                model.wipInfoBlobs = await _pcsApi.GetWipInfoBlob(model.wipInfo.WipNO);

                // 取料號對應工時
                var standardWorkTimes = await _pcsApi.GetStandardWorkTimeByItemNo(model.wipAtt.ItemNO);
                // 取消生產單位及線別判斷
                // standardWorkTimes = standardWorkTimes.Where(w => w.LineID == model.wipInfo.LineID &&
                //                                w.UnitNo == model.wipInfo.UnitNO).ToList();

                if (standardWorkTimes.Count != 0)
                    model.itemNoCT1 = standardWorkTimes.Sum(m => m.TotalCT).ToString();
            }

            await WipDataSelectAll(model.wipAtt.WipNO, model.wipAtt.ItemNO, model.wipInfo.UnitNO);

            GetCheckboxApproveLogo(model.wipLabel != null ? model.wipLabel.ApproveLogo : null);
            GetCheckboxCompanyLogo(model.wipLabel != null ? model.wipLabel.CompanyLogo : null);
            GetCheckboxPrintMode(model.wipLabel != null ? model.wipLabel.PrintMode : null);
            GetCheckboxWipAttr(model.wipLabel != null ? model.wipLabel.WipAttr : null);
            GetCheckboxDIP(model.wipBoard != null ? model.wipBoard.DipSide : null);
            GetCheckboxSMD(model.wipBoard != null ? model.wipBoard.Smd : null);
            GetCheckboxSMDSolderMa(model.wipBoard != null ? model.wipBoard.SmdSolderMask : null);
            return View(model);
        }

        public async Task<IActionResult> PCS003(int id)
        {
            // 針對安勤 工單基本資料統一打開工程資訊
            ViewBag.WipSpecial = _configuration["WipSpecial"];

            WipDataViewModel model = new WipDataViewModel();
            var q = await _pcsApi.GetWipInfo(id);
            if (q.Count != 0)
            {
                // 判斷工單號碼是否已經投入
                if (await _pcsApi.GetWipInfoCheckStart(q.FirstOrDefault().WipNO) == "Y")
                {
                    var _msg = "工單號碼【" + q.FirstOrDefault().WipNO + "】,已開始投入,不可修改!";
                    return RedirectToAction("Refresh", "Home", new { msg = _msg });
                }

                // 判斷工單號碼是否已經開線
                if (await _pcsApi.GetWipInfoCheckStartLine(q.FirstOrDefault().WipNO) == "Y")
                {
                    var _msg = "工單號碼【" + q.FirstOrDefault().WipNO + "】,已開線,不可修改!";
                    return RedirectToAction("Refresh", "Home", new { msg = _msg });
                }

                // 判斷是否完工
                if (q.Where(w => w.StatusNO == "E").Any())
                {
                    var _msg = "工單號碼【" + q.FirstOrDefault().WipNO + "】,已經投入完工,不可修改";
                    return RedirectToAction("Refresh", "Home", new { msg = _msg });
                }

                // 判斷是否刪除
                if (q.Where(w => w.StatusNO == "C").Any())
                {
                    var _msg = "工單號碼【" + q.FirstOrDefault().WipNO + "】,已刪除,不可修改";
                    return RedirectToAction("Refresh", "Home", new { msg = _msg });
                }

                model.wipInfo = q.FirstOrDefault();
                model.wipAtt = await _pcsApi.GetWipAtt(model.wipInfo.WipNO);
                model.wipBarcodes = await _pcsApi.GetWipBarcode(model.wipInfo.WipNO);
                model.wipBarcode = model.wipBarcodes.FirstOrDefault();
                model.wipBoard = await _pcsApi.GetWipBoard(model.wipInfo.WipNO);
                //var q1 = await _pcsApi.GetMaterialSopQuery(itemNo: model.wipAtt.ItemNO);
                //model.materialSops = q1.Data;

                if (model.wipBoard != null)
                {
                    if (!string.IsNullOrWhiteSpace(model.wipBoard.Engineer))
                    {
                        var UserInof = _sysApi.GetUserInfoByUserNo(model.wipBoard.Engineer).InvokeAsync().Result;
                        if (UserInof != null)
                            model.wipBoard.Engineer_Name = UserInof.UserName;
                    }
                }

                model.wipSystem = await _pcsApi.GetWipSystem(model.wipInfo.WipNO);
                if (model.wipSystem != null)
                {
                    if (!string.IsNullOrWhiteSpace(model.wipSystem.Ec))
                    {
                        var Ec_Desc = _pcsApi.GetPlmMeterialInfo(model.wipSystem.Ec).InvokeAsync().Result;
                        model.wipSystem.Ec_Desc = Ec_Desc.Count == 0 ? "" : Ec_Desc.FirstOrDefault().MeterialDesc;
                    }

                    if (!string.IsNullOrWhiteSpace(model.wipSystem.Fw))
                    {
                        var Fw_Desc = _pcsApi.GetPlmMeterialInfo(model.wipSystem.Fw).InvokeAsync().Result;
                        model.wipSystem.Fw_Desc = Fw_Desc.Count == 0 ? "" : Fw_Desc.FirstOrDefault().MeterialDesc;
                    }

                    if (!string.IsNullOrWhiteSpace(model.wipSystem.Fw1))
                    {
                        var Fw1_Desc = _pcsApi.GetPlmMeterialInfo(model.wipSystem.Fw1).InvokeAsync().Result;
                        model.wipSystem.Fw1_Desc = Fw1_Desc.Count == 0 ? "" : Fw1_Desc.FirstOrDefault().MeterialDesc;
                    }

                    if (!string.IsNullOrWhiteSpace(model.wipSystem.Fw2))
                    {
                        var Fw2_Desc = _pcsApi.GetPlmMeterialInfo(model.wipSystem.Fw2).InvokeAsync().Result;
                        model.wipSystem.Fw2_Desc = Fw2_Desc.Count == 0 ? "" : Fw2_Desc.FirstOrDefault().MeterialDesc;
                    }

                    if (!string.IsNullOrWhiteSpace(model.wipSystem.Bios))
                    {
                        var Bios_Desc = _pcsApi.GetPlmMeterialInfo(model.wipSystem.Bios).InvokeAsync().Result;
                        model.wipSystem.Bios_Desc = Bios_Desc.Count == 0 ? "" : Bios_Desc.FirstOrDefault().MeterialDesc;
                    }

                    if (!string.IsNullOrWhiteSpace(model.wipSystem.OsVer))
                    {
                        var Os_Desc = _pcsApi.GetPlmMeterialInfo(model.wipSystem.OsVer).InvokeAsync().Result;
                        model.wipSystem.OsVer_Desc = Os_Desc.Count == 0 ? "" : Os_Desc.FirstOrDefault().MeterialDesc;
                    }

                    if (!string.IsNullOrWhiteSpace(model.wipSystem.PowerMode))
                    {
                        var PowerMode_Desc = _pcsApi.GetPlmMeterialInfo(model.wipSystem.PowerMode).InvokeAsync().Result;
                        model.wipSystem.PowerMode_Desc = PowerMode_Desc.Count == 0 ? "" : PowerMode_Desc.FirstOrDefault().ProductionMemo;
                    }

                    if (!string.IsNullOrWhiteSpace(model.wipSystem.Engineer))
                    {
                        var UserInof = _sysApi.GetUserInfoByUserNo(model.wipSystem.Engineer).InvokeAsync().Result;
                        if (UserInof != null)
                            model.wipSystem.Engineer_Name = UserInof.UserName;
                    }
                }

                model.wipMAC = await _pcsApi.GetWipMAC(model.wipInfo.WipNO);
                if (model.wipMAC != null)
                {
                    model.wipMAC.StartNO = model.wipMAC.Title + model.wipMAC.StartNO;
                    model.wipMAC.EndNO = model.wipMAC.Title + model.wipMAC.EndNO;
                }

                model.wipLabel = await _pcsApi.GetWipLabel(model.wipInfo.WipNO);

                model.wipBarcodeOther = await _pcsApi.GetWipBarcodeOther(model.wipInfo.WipNO);

                model.WipKps = await _pcsApi.GetWipKpByWipNo(model.wipInfo.WipNO);

                model.WipOutfits = await _pcsApi.GetWipOutfitByWipNo(model.wipInfo.WipNO);

                model.WipSops = await _pcsApi.GetWipSopByWipNo(model.wipInfo.WipNO);

                model.wipInfoBlobs = await _pcsApi.GetWipInfoBlob(model.wipInfo.WipNO);

                // 取料號對應工時
                var standardWorkTimes = await _pcsApi.GetStandardWorkTimeByItemNo(model.wipAtt.ItemNO);
                // 取消生產單位及線別判斷
                // standardWorkTimes = standardWorkTimes.Where(w => w.LineID == model.wipInfo.LineID &&
                //                                w.UnitNo == model.wipInfo.UnitNO).ToList();

                if (standardWorkTimes.Count != 0)
                    model.itemNoCT1 = standardWorkTimes.Sum(m => m.TotalCT).ToString();

            }

            await WipDataSelectAll(model.wipAtt.WipNO, model.wipAtt.ItemNO, model.wipInfo.UnitNO);

            GetCheckboxApproveLogo(model.wipLabel != null ? model.wipLabel.ApproveLogo : null);
            GetCheckboxCompanyLogo(model.wipLabel != null ? model.wipLabel.CompanyLogo : null);
            GetCheckboxPrintMode(model.wipLabel != null ? model.wipLabel.PrintMode : null);
            GetCheckboxWipAttr(model.wipLabel != null ? model.wipLabel.WipAttr : null);
            GetCheckboxDIP(model.wipBoard != null ? model.wipBoard.DipSide : "");
            GetCheckboxSMD(model.wipBoard != null ? model.wipBoard.Smd : "");
            GetCheckboxSMDSolderMa(model.wipBoard != null ? model.wipBoard.SmdSolderMask : "");
            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> PCS003Async(WipDataViewModel model, string action, IFormFile formFile)
        {
            // 針對安勤 工單基本資料統一打開工程資訊 不判斷製程
            ViewBag.WipSpecial = _configuration["WipSpecial"];

            try
            {
                // 登入UserID
                var UserID = GetLogInUserID();

                #region 選單
                await WipDataSelectAll(model.wipInfo.WipNO, model.wipAtt.ItemNO, model.wipInfo.UnitNO);
                GetCheckboxApproveLogo(model.wipLabel != null ? model.wipLabel.ApproveLogo : null);
                GetCheckboxCompanyLogo(model.wipLabel != null ? model.wipLabel.CompanyLogo : null);
                GetCheckboxPrintMode(model.wipLabel != null ? model.wipLabel.PrintMode : null);
                GetCheckboxWipAttr(model.wipLabel != null ? model.wipLabel.WipAttr : null);
                GetCheckboxDIP(model.wipBoard != null ? model.wipBoard.DipSide : "");
                GetCheckboxSMD(model.wipBoard != null ? model.wipBoard.Smd : "");
                GetCheckboxSMDSolderMa(model.wipBoard != null ? model.wipBoard.SmdSolderMask : "");
                #endregion

                model.ruleStations = await _pcsApi.GetRuleStationByWipNo(model.wipInfo.WipNO);
                model.wipBarcodes = await _pcsApi.GetWipBarcode(model.wipInfo.WipNO);

                #region Checkbox轉換
                model.wipInfo.ECNCheck = model.wipInfo.ECNCheck == "on" ? "Y" : "N";
                model.wipInfo.ModelCheck = model.wipInfo.ModelCheck == "on" ? "Y" : "N";
                model.wipInfo.InputFlag = model.wipInfo.InputFlag == "on" ? "Y" : "N";
                model.wipInfo.Priority = model.wipInfo.Priority == "on" ? "Y" : "N";
                model.wipInfo.CustomerMedical = model.wipInfo.CustomerMedical == "on" ? "Y" : "N";
                model.wipInfo.CustomerVIP = model.wipInfo.CustomerVIP == "on" ? "Y" : "N";
                model.wipInfo.SFISFlowCk = model.wipInfo.SFISFlowCk == "on" ? "Y" : "N";
                //板卡
                model.wipBoard.DipCarrier = model.wipBoard.DipCarrier == "on" ? "Y" : "N";
                model.wipBoard.DipTape = model.wipBoard.DipTape == "on" ? "Y" : "N";
                model.wipBoard.Burn = model.wipBoard.Burn == "on" ? "Y" : "N";
                model.wipBoard.DipSolderMask = model.wipBoard.DipSolderMask == "on" ? "Y" : "N";
                model.wipBoard.ISPartsBake = model.wipBoard.ISPartsBake == "on" ? "Y" : "N";
                model.wipBoard.PartsBakeOvertime = model.wipBoard.PartsBakeOvertime == "on" ? "Y" : "N";
                model.wipBoard.ISPcbBake = model.wipBoard.ISPcbBake == "on" ? "Y" : "N";
                //系統
                model.wipSystem.FinePackage = model.wipSystem.FinePackage == "on" ? "Y" : "N";
                #endregion

                // 判斷資料填寫
                WipDataViewModel wipDataViewModel = new WipDataViewModel();
                wipDataViewModel.wipInfo = model.wipInfo;
                wipDataViewModel.wipSystem = model.wipSystem;
                wipDataViewModel.wipBoard = model.wipBoard;
                wipDataViewModel.wipMAC = model.wipMAC;
                wipDataViewModel.wipBarcodeOther = model.wipBarcodeOther;
                var Msg = CheckWipInfoInsert(wipDataViewModel);



                // 判斷是否有開重複工單+生產單位
                var wipInfoQuery = await _pcsApi.GetWipInfoByWipNO(model.wipInfo.WipNO);
                if (wipInfoQuery.Any())
                {
                    if (wipInfoQuery.Where(w => w.UnitNO == model.wipInfo.UnitNO).Count() == 2)
                    {
                        Msg += ",同樣生產單位已建立相同工單了";
                    }
                }

                // 判斷WipKp 順序是否重複
                if (model.WipKps.Where(w => w.WipKpID != -1).GroupBy(g => g.KpSeq).Where(w => w.Count() > 1).Any())
                {
                    Msg += ",KeyParts 順序有重複 ";

                }

                // 判斷SOP是否沒填文件名稱
                if (model.WipSops.Where(w => string.IsNullOrWhiteSpace(w.SOPName)).Any())
                {
                    Msg += ",SOP文件 請填寫SOP文件敘述 ";
                }

                // 判斷MAC是否正確
                var CheckMACMsg = CheckMACData(model);
                if (!string.IsNullOrWhiteSpace(CheckMACMsg))
                {
                    Msg += "," + CheckMACMsg;
                }

                // 判斷標籤 工單性質選擇 WipAttr非標96工單時,則旁邊欄位必填
                if (model.wipLabel.WipAttr == "B" && string.IsNullOrWhiteSpace(model.wipLabel.NonstandardWoMemo))
                {
                    Msg += ",標籤:工單性質選擇非標96工單時,需填入資料";
                }

                // 判斷治具中生產單位與作業站吻合
                var result_wipNo = await _pcsApi.GetWipInfoByWipNO(model.wipInfo.WipNO);
                foreach (var item in result_wipNo)
                {
                    foreach (var Outfits in model.WipOutfits.Where(w => w.StationID != null && w.UnitNo == item.UnitNO))
                    {
                        var RuleStation = await _pcsApi.GetRuleStationByFlow(item.FlowRuleID);

                        if (!RuleStation.Where(w => Outfits.StationID == w.StationID).Any())
                        {
                            Msg += ",治具組合中生產單位與作業站不匹配";
                        }
                    }
                }

                if (!string.IsNullOrWhiteSpace(Msg))
                {
                    if (Msg.StartsWith(","))
                        Msg = Msg.Substring(1, Msg.Length - 1);

                    ModelState.AddModelError("error", Msg);
                    return View("PCS003", model);
                }

                // 工單相關資料ExecuteDB
                var (WipExecuteMsg, WipExeucteModel) = await WipExecuteDB(model, formFile);
                model = WipExeucteModel;

                if (!string.IsNullOrWhiteSpace(WipExecuteMsg))
                {
                    ModelState.AddModelError("error", $"修改失敗,錯誤訊息:{WipExecuteMsg}");
                    return View("PCS003", model);
                }

                //result = await _pcsApi.PutWipInfo(JsonConvert.SerializeObject(model.wipInfo));
                //if (result.Success)
                //{
                //    // 工單屬性
                //    model.wipAtt.WipNO = model.wipInfo.WipNO;
                //    await _pcsApi.PutWipAtt(JsonConvert.SerializeObject(model.wipAtt));

                //    // 標籤
                //    model.wipLabel.ApproveLogo = model.wipLabel.ApproveLogos == null ? null : string.Join(',', model.wipLabel.ApproveLogos);
                //    model.wipLabel.WipNO = model.wipInfo.WipNO;
                //    model.wipLabel.CreateUserID = UserID;
                //    model.wipLabel.UpdateUserID = UserID;
                //    await _pcsApi.PutWipLabel(JsonConvert.SerializeObject(model.wipLabel));

                //    // 安勤統一執行WIP_SYSTEM
                //    if (ViewBag.WipSpecial == "Y")
                //    {
                //        if (string.IsNullOrWhiteSpace(CheckWipInfoInsert_WipSystem(model.wipSystem)))
                //        {
                //            model.wipSystem.ItemNo = model.wipAtt.ItemNO;
                //            model.wipSystem.WipNo = model.wipInfo.WipNO;
                //            model.wipSystem.CreateUserID = UserID;
                //            model.wipSystem.UpdateUserID = UserID;
                //            await _pcsApi.PutWipSystem(JsonConvert.SerializeObject(model.wipSystem));
                //        }
                //    }
                //    else
                //    {
                //        // 系統
                //        if (model.wipInfo.UnitNO == "B" || model.wipInfo.UnitNO == "P" || model.wipInfo.UnitNO == "T")
                //        {
                //            if (string.IsNullOrWhiteSpace(CheckWipInfoInsert_WipSystem(model.wipSystem)))
                //            {
                //                model.wipSystem.ItemNo = model.wipAtt.ItemNO;
                //                model.wipSystem.WipNo = model.wipInfo.WipNO;
                //                model.wipSystem.CreateUserID = UserID;
                //                model.wipSystem.UpdateUserID = UserID;
                //                await _pcsApi.PutWipSystem(JsonConvert.SerializeObject(model.wipSystem));
                //            }
                //        }
                //        else
                //        // 板卡
                //        {
                //            if (string.IsNullOrWhiteSpace(CheckWipInfoInsert_WipBoard(model.wipBoard)))
                //            {
                //                model.wipBoard.Smd = model.wipBoard.SMDs == null ? null : string.Join(',', model.wipBoard.SMDs);
                //                model.wipBoard.SmdSolderMask = model.wipBoard.SmdSolderMasks == null ? null : string.Join(',', model.wipBoard.SmdSolderMasks);
                //                model.wipBoard.DipSide = model.wipBoard.DipSides == null ? null : string.Join(',', model.wipBoard.DipSides);
                //                model.wipBoard.ItemNo = model.wipAtt.ItemNO;
                //                model.wipBoard.WipNo = model.wipInfo.WipNO;
                //                model.wipBoard.CreateUserID = UserID;
                //                model.wipBoard.UpdateUserID = UserID;
                //                await _pcsApi.PutWipBoard(JsonConvert.SerializeObject(model.wipBoard));
                //            }
                //        }
                //    }

                //    // 內部條碼
                //    if (!string.IsNullOrWhiteSpace(model.wipBarcode.Remarks))
                //    {
                //        model.wipBarcode.WipID = model.wipInfo.WipID;
                //        model.wipBarcode.WipNO = model.wipInfo.WipNO;
                //        model.wipBarcode.UnitNO = model.wipInfo.UnitNO;
                //        model.wipBarcode.CreateUserID = UserID;
                //        result = await _pcsApi.PutWipBarcode(JsonConvert.SerializeObject(model.wipBarcode));
                //    }

                //    // MAC
                //    if (!string.IsNullOrWhiteSpace(model.wipMAC.StartNO) && !string.IsNullOrWhiteSpace(model.wipMAC.EndNO))
                //    {
                //        if (model.wipMAC.StartNO.Length == 12)
                //        {
                //            model.wipMAC.Title = model.wipMAC.StartNO.Substring(0, 6).ToUpper();
                //            model.wipMAC.StartNO = model.wipMAC.StartNO.Substring(model.wipMAC.StartNO.Length - 6, 6).ToUpper();
                //            model.wipMAC.EndNO = model.wipMAC.EndNO.Substring(model.wipMAC.EndNO.Length - 6, 6).ToUpper();

                //            // 確認MAC Table是否有料號資料
                //            var mACInfo = await _pcsApi.GetMACInfo(model.wipAtt.ItemNO);
                //            if (mACInfo != null)
                //            {
                //                model.wipMAC.ClassGroup = mACInfo.ClassGroup;
                //            }

                //            if (!string.IsNullOrWhiteSpace(model.wipMAC.WipNO))
                //                result = await _pcsApi.PutWipMAC(JsonConvert.SerializeObject(model.wipMAC));
                //            else
                //            {
                //                model.wipMAC.WipNO = model.wipInfo.WipNO;
                //                model.wipMAC.CreateUserID = UserID;
                //                result = await _pcsApi.PostWipMAC(JsonConvert.SerializeObject(model.wipMAC));
                //            }
                //        }
                //    }

                //    // KeyParts 
                //    // 判斷料號KP有資料 沒有資料時 一起新增到料號KP
                //    // 2022.10.12 取消判斷 刪除料號KP,在逐一新增
                //    var materialItem = await _pcsApi.GetMaterialItemByItemNO(model.wipAtt.ItemNO);
                //    if (materialItem != null)
                //    {
                //        await _pcsApi.DeleteMaterialKpByItem(materialItem.ItemID);
                //    }

                //    // 先比對新舊ID 當舊ID有 新的沒有代表已刪除
                //    var resultOld_WipKp = await _pcsApi.GetWipKpByWipNo(model.wipInfo.WipNO);
                //    var delete_WipKpID = resultOld_WipKp.Select(s => s.WipKpID).Except(model.WipKps.Select(s => s.WipKpID));
                //    foreach (var id in delete_WipKpID)
                //    {
                //        await _pcsApi.DeleteWipKp(id);
                //    }

                //    foreach (var item in model.WipKps.Where(w => w.WipKpID != -1))
                //    {
                //        item.WipNo = model.wipInfo.WipNO;
                //        item.ItemNo = model.wipAtt.ItemNO;
                //        item.CreateUserID = UserID;
                //        item.UpdateUserID = UserID;
                //        if (item.WipKpID == 0)
                //            await _pcsApi.PostWipKp(JsonConvert.SerializeObject(item));
                //        else
                //            await _pcsApi.PutWipKp(JsonConvert.SerializeObject(item));

                //        // 新增到料號KP檔
                //        await _pcsApi.PostMaterialKp(JsonConvert.SerializeObject(new MaterialKp
                //        {
                //            ItemID = materialItem.ItemID,
                //            KpName = item.KpName,
                //            KpNo = item.KpNo,
                //            KpSeq = Convert.ToInt32(item.KpSeq),
                //            Length = item.Length,
                //            StationType = item.UnitNo,
                //            IsRepeat = "N",
                //            Title = item.Title,
                //            CreateUserID = UserID,
                //            UpdateUserID = UserID
                //        }));
                //    }
                //    model.WipKps = model.WipKps.Where(w => w.WipKpID != -1).ToList();

                //    // 治具
                //    // 先比對新舊ID 當舊ID有 新的沒有代表已刪除
                //    var resultOld_WipOutfit = await _pcsApi.GetWipOutfitByWipNo(model.wipInfo.WipNO);
                //    var delete_WipOutfit = resultOld_WipOutfit.Select(s => s.WipOutfitID).Except(model.WipOutfits.Select(s => s.WipOutfitID));
                //    foreach (var id in delete_WipOutfit)
                //    {
                //        await _pcsApi.DeleteWipOutfit(id);
                //    }
                //    foreach (var item in model.WipOutfits.Where(w => w.WipOutfitID != -1))
                //    {
                //        item.WipNo = model.wipInfo.WipNO;
                //        item.ItemNo = model.wipAtt.ItemNO;
                //        item.UpdateUserID = UserID;
                //        item.CreateUserID = UserID;
                //        item.OutfitNo = ".";
                //        if (item.WipOutfitID == 0)
                //            await _pcsApi.PostWipOutfit(JsonConvert.SerializeObject(item));
                //        else
                //            await _pcsApi.PutWipOutfit(JsonConvert.SerializeObject(item));
                //    }
                //    model.WipOutfits = model.WipOutfits.Where(w => w.WipOutfitID != -1);

                //    // SOP
                //    // 先比對新舊ID 當舊ID有 新的沒有代表已刪除
                //    var resultOld_WipSop = await _pcsApi.GetWipSopByWipNo(model.wipInfo.WipNO);
                //    var delete_WipSop = resultOld_WipSop.Select(s => s.WipSOPID).Except(model.WipSops.Select(s => s.WipSOPID));
                //    foreach (var id in delete_WipSop)
                //    {
                //        await _pcsApi.DeleteWipSop(id);
                //    }
                //    foreach (var item in model.WipSops.Where(w => w.WipSOPID != -1))
                //    {
                //        item.WipNo = model.wipInfo.WipNO;
                //        item.ItemNo = model.wipAtt.ItemNO;
                //        item.CreateUserID = UserID;
                //        item.UpdateUserID = UserID;
                //        if (item.WipSOPID == 0)
                //            await _pcsApi.PostWipSop(JsonConvert.SerializeObject(item));
                //        else
                //            await _pcsApi.PutWipSop(JsonConvert.SerializeObject(item));
                //    }
                //    model.WipSops = model.WipSops.Where(w => w.WipSOPID != -1);

                //    // 檔案上傳
                //    string FileName = string.Empty;
                //    string NewName = string.Empty;
                //    string FilePath = string.Empty;

                //    if (formFile != null)
                //    {
                //        if (formFile.Length > 0)
                //        {
                //            //取得使用者上傳檔案的原始檔名
                //            FileName = Path.GetFileName(formFile.FileName);
                //            //取原始檔名中的副檔名
                //            //var fileExt = Path.GetExtension(FileName);
                //            //為避免使用者上傳的檔案名稱發生重複,重新給一個亂數名稱
                //            //NewName = Path.GetRandomFileName() + fileExt;
                //            //指定要寫入的路徑、檔名和副檔名
                //            FilePath = $@"{_env.WebRootPath}\UploadFolder\{model.wipInfo.WipNO}";
                //            var path = $@"{FilePath}\{FileName}";

                //            if (!System.IO.Directory.Exists(FilePath))
                //            {
                //                System.IO.Directory.CreateDirectory(FilePath);
                //            }

                //            using (var stream = new FileStream(path, FileMode.Create))
                //            {
                //                await formFile.CopyToAsync(stream);
                //            }

                //            model.wipInfoBlob.WipNo = model.wipInfo.WipNO;
                //            model.wipInfoBlob.ImageName = FileName;
                //            model.wipInfoBlob.Filepath = $@"\UploadFolder\{model.wipInfo.WipNO}\";
                //            model.wipInfoBlob.CreateUserID = UserID;
                //            model.wipInfoBlob.UpdateUserID = UserID;
                //            result = await _pcsApi.PostWipInfoBlob(JsonConvert.SerializeObject(model.wipInfoBlob));
                //        }
                //    }
                //}

                WipCheck wipCheck = new WipCheck
                {
                    WipNo = model.wipInfo.WipNO
                };
                if (action == "生管確認")
                {
                    wipCheck.PMCUserID = UserID;
                    await CheckPCS003ToMail(model.wipInfo.WipNO, model.wipAtt.ItemNO, model.wipInfo.UnitNO, model.wipInfo.WipScheduleDate.ToString(), action);
                    await _pcsApi.PutWipCheckByPMC(JsonConvert.SerializeObject(wipCheck));
                }
                else if (action == "工程確認")
                {
                    wipCheck.PEUserID = UserID;
                    await CheckPCS003ToMail(model.wipInfo.WipNO, model.wipAtt.ItemNO, model.wipInfo.UnitNO, model.wipInfo.WipScheduleDate.ToString(), action);
                    await _pcsApi.PutWipCheckByPE(JsonConvert.SerializeObject(wipCheck));
                }
                else if (action == "製造確認")
                {
                    wipCheck.MFUserID = UserID;
                    await _pcsApi.PutWipCheckByMF(JsonConvert.SerializeObject(wipCheck));
                }

                var _msg = "修改成功!";
                ModelState.AddModelError("error", _msg);
                return View("PCS003", model);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("error", "系統錯誤,錯誤訊息:" + ex.Message);
                return View("PCS003", model);
            }
        }

        /// <summary>
        /// 檔案下載
        /// </summary>
        /// <param name="Path">路徑</param>
        /// <param name="FileName">檔名</param>
        /// <returns></returns>
        public async Task<IActionResult> FileDownload(string Path, string FileName)
        {
            var path = $@"{_env.WebRootPath}\{Path}{FileName}";
            var memoryStream = new MemoryStream();
            using (var stream = new FileStream(path, FileMode.Open))
            {
                await stream.CopyToAsync(memoryStream);
            }
            memoryStream.Seek(0, SeekOrigin.Begin);
            string contentType = await GetFileContentTypeAsync(FileName);
            // 回傳檔案到 Client 需要附上 Content Type,否則瀏覽器會解析失敗。
            return File(memoryStream, contentType, FileName);
        }

        /// <summary>
        /// 获取文件ContentType
        /// </summary>
        /// <param name="fileName">文件名称</param>
        /// <returns></returns>
        public async static Task<string> GetFileContentTypeAsync(string fileName)
        {
            return await Task.Run(() =>
            {
                string suffix = Path.GetExtension(fileName);
                var provider = new FileExtensionContentTypeProvider();
                if (suffix.ToUpper().Trim() == ".MSG")
                {
                    return "application/octet-stream";
                }
                var contentType = provider.Mappings[suffix];
                return contentType;
            });
        }

        #region PCS034 工單投產可修改
        public async Task<IActionResult> PCS034(int id)
        {
            // 針對安勤 工單基本資料統一打開工程資訊
            ViewBag.WipSpecial = _configuration["WipSpecial"];

            WipDataViewModel model = new WipDataViewModel();
            var q = await _pcsApi.GetWipInfo(id);
            if (q.Count != 0)
            {
                // 判斷是否完工
                if (q.Where(w => w.StatusNO == "E").Any())
                {
                    var _msg = "工單號碼【" + q.FirstOrDefault().WipNO + "】,已經投入完工,不可修改";
                    return RedirectToAction("Refresh", "Home", new { msg = _msg });
                }

                // 判斷是否刪除
                if (q.Where(w => w.StatusNO == "C").Any())
                {
                    var _msg = "工單號碼【" + q.FirstOrDefault().WipNO + "】,已刪除,不可修改";
                    return RedirectToAction("Refresh", "Home", new { msg = _msg });
                }

                model.wipInfo = q.FirstOrDefault();
                model.wipAtt = await _pcsApi.GetWipAtt(model.wipInfo.WipNO);
                model.wipBarcodes = await _pcsApi.GetWipBarcode(model.wipInfo.WipNO);
                model.wipBarcode = model.wipBarcodes.FirstOrDefault();
                model.ruleStations = await _pcsApi.GetRuleStationByWipNo(model.wipInfo.WipNO);
                model.wipBoard = await _pcsApi.GetWipBoard(model.wipInfo.WipNO);
                if (model.wipBoard != null)
                {
                    if (!string.IsNullOrWhiteSpace(model.wipBoard.Engineer))
                    {
                        var UserInof = _sysApi.GetUserInfoByUserNo(model.wipBoard.Engineer).InvokeAsync().Result;
                        if (UserInof != null)
                            model.wipBoard.Engineer_Name = UserInof.UserName;
                    }
                }

                model.wipSystem = await _pcsApi.GetWipSystem(model.wipInfo.WipNO);
                if (model.wipSystem != null)
                {
                    if (!string.IsNullOrWhiteSpace(model.wipSystem.Ec))
                    {
                        var Ec_Desc = _pcsApi.GetPlmMeterialInfo(model.wipSystem.Ec).InvokeAsync().Result;
                        model.wipSystem.Ec_Desc = Ec_Desc.Count == 0 ? "" : Ec_Desc.FirstOrDefault().MeterialDesc;
                    }

                    if (!string.IsNullOrWhiteSpace(model.wipSystem.Fw))
                    {
                        var Fw_Desc = _pcsApi.GetPlmMeterialInfo(model.wipSystem.Fw).InvokeAsync().Result;
                        model.wipSystem.Fw_Desc = Fw_Desc.Count == 0 ? "" : Fw_Desc.FirstOrDefault().MeterialDesc;
                    }

                    if (!string.IsNullOrWhiteSpace(model.wipSystem.Fw1))
                    {
                        var Fw1_Desc = _pcsApi.GetPlmMeterialInfo(model.wipSystem.Fw1).InvokeAsync().Result;
                        model.wipSystem.Fw1_Desc = Fw1_Desc.Count == 0 ? "" : Fw1_Desc.FirstOrDefault().MeterialDesc;
                    }

                    if (!string.IsNullOrWhiteSpace(model.wipSystem.Fw2))
                    {
                        var Fw2_Desc = _pcsApi.GetPlmMeterialInfo(model.wipSystem.Fw2).InvokeAsync().Result;
                        model.wipSystem.Fw2_Desc = Fw2_Desc.Count == 0 ? "" : Fw2_Desc.FirstOrDefault().MeterialDesc;
                    }

                    if (!string.IsNullOrWhiteSpace(model.wipSystem.Bios))
                    {
                        var Bios_Desc = _pcsApi.GetPlmMeterialInfo(model.wipSystem.Bios).InvokeAsync().Result;
                        model.wipSystem.Bios_Desc = Bios_Desc.Count == 0 ? "" : Bios_Desc.FirstOrDefault().MeterialDesc;
                    }

                    if (!string.IsNullOrWhiteSpace(model.wipSystem.OsVer))
                    {
                        var Os_Desc = _pcsApi.GetPlmMeterialInfo(model.wipSystem.OsVer).InvokeAsync().Result;
                        model.wipSystem.OsVer_Desc = Os_Desc.Count == 0 ? "" : Os_Desc.FirstOrDefault().MeterialDesc;
                    }

                    if (!string.IsNullOrWhiteSpace(model.wipSystem.PowerMode))
                    {
                        var PowerMode_Desc = _pcsApi.GetPlmMeterialInfo(model.wipSystem.PowerMode).InvokeAsync().Result;
                        model.wipSystem.PowerMode_Desc = PowerMode_Desc.Count == 0 ? "" : PowerMode_Desc.FirstOrDefault().ProductionMemo;
                    }

                    if (!string.IsNullOrWhiteSpace(model.wipSystem.Engineer))
                    {
                        var UserInof = _sysApi.GetUserInfoByUserNo(model.wipSystem.Engineer).InvokeAsync().Result;
                        if (UserInof != null)
                            model.wipSystem.Engineer_Name = UserInof.UserName;
                    }
                }

                model.wipMAC = await _pcsApi.GetWipMAC(model.wipInfo.WipNO);
                if (model.wipMAC != null)
                {
                    model.wipMAC.StartNO = model.wipMAC.Title + model.wipMAC.StartNO;
                    model.wipMAC.EndNO = model.wipMAC.Title + model.wipMAC.EndNO;
                }

                model.wipLabel = await _pcsApi.GetWipLabel(model.wipInfo.WipNO);

                model.wipBarcodeOther = await _pcsApi.GetWipBarcodeOther(model.wipInfo.WipNO);

                model.WipKps = await _pcsApi.GetWipKpByWipNo(model.wipInfo.WipNO);

                model.WipOutfits = await _pcsApi.GetWipOutfitByWipNo(model.wipInfo.WipNO);

                model.WipSops = await _pcsApi.GetWipSopByWipNo(model.wipInfo.WipNO);

                model.wipInfoBlobs = await _pcsApi.GetWipInfoBlob(model.wipInfo.WipNO);

                // 取料號對應工時
                var standardWorkTimes = await _pcsApi.GetStandardWorkTimeByItemNo(model.wipAtt.ItemNO);
                // 取消生產單位及線別判斷
                // standardWorkTimes = standardWorkTimes.Where(w => w.LineID == model.wipInfo.LineID &&
                //                                w.UnitNo == model.wipInfo.UnitNO).ToList();

                if (standardWorkTimes.Count != 0)
                    model.itemNoCT1 = standardWorkTimes.Sum(m => m.TotalCT).ToString();

            }

            await WipDataSelectAll(model.wipAtt.WipNO, model.wipAtt.ItemNO, model.wipInfo.UnitNO);

            GetCheckboxApproveLogo(model.wipLabel != null ? model.wipLabel.ApproveLogo : null);
            GetCheckboxCompanyLogo(model.wipLabel != null ? model.wipLabel.CompanyLogo : null);
            GetCheckboxPrintMode(model.wipLabel != null ? model.wipLabel.PrintMode : null);
            GetCheckboxWipAttr(model.wipLabel != null ? model.wipLabel.WipAttr : null);
            GetCheckboxDIP(model.wipBoard != null ? model.wipBoard.DipSide : "");
            GetCheckboxSMD(model.wipBoard != null ? model.wipBoard.Smd : "");
            GetCheckboxSMDSolderMa(model.wipBoard != null ? model.wipBoard.SmdSolderMask : "");
            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> PCS034Async(WipDataViewModel model, string action, IFormFile formFile)
        {
            // 針對安勤 工單基本資料統一打開工程資訊 不判斷製程
            ViewBag.WipSpecial = _configuration["WipSpecial"];

            try
            {
                // 登入UserID
                var UserID = GetLogInUserID();

                #region 選單
                await WipDataSelectAll(model.wipInfo.WipNO, model.wipAtt.ItemNO, model.wipInfo.UnitNO);
                GetCheckboxApproveLogo(model.wipLabel != null ? model.wipLabel.ApproveLogo : null);
                GetCheckboxCompanyLogo(model.wipLabel != null ? model.wipLabel.CompanyLogo : null);
                GetCheckboxPrintMode(model.wipLabel != null ? model.wipLabel.PrintMode : null);
                GetCheckboxWipAttr(model.wipLabel != null ? model.wipLabel.WipAttr : null);
                GetCheckboxDIP(model.wipBoard != null ? model.wipBoard.DipSide : "");
                GetCheckboxSMD(model.wipBoard != null ? model.wipBoard.Smd : "");
                GetCheckboxSMDSolderMa(model.wipBoard != null ? model.wipBoard.SmdSolderMask : "");
                #endregion

                model.ruleStations = await _pcsApi.GetRuleStationByWipNo(model.wipInfo.WipNO);
                model.wipBarcodes = await _pcsApi.GetWipBarcode(model.wipInfo.WipNO);

                // Checkbox轉換
                model.wipInfo.ECNCheck = model.wipInfo.ECNCheck == "on" ? "Y" : "N";
                model.wipInfo.ModelCheck = model.wipInfo.ModelCheck == "on" ? "Y" : "N";
                model.wipInfo.InputFlag = model.wipInfo.InputFlag == "on" ? "Y" : "N";
                model.wipInfo.Priority = model.wipInfo.Priority == "on" ? "Y" : "N";
                model.wipInfo.CustomerMedical = model.wipInfo.CustomerMedical == "on" ? "Y" : "N";
                model.wipInfo.CustomerVIP = model.wipInfo.CustomerVIP == "on" ? "Y" : "N";
                model.wipInfo.SFISFlowCk = model.wipInfo.SFISFlowCk == "on" ? "Y" : "N";
                //板卡
                model.wipBoard.DipCarrier = model.wipBoard.DipCarrier == "on" ? "Y" : "N";
                model.wipBoard.DipTape = model.wipBoard.DipTape == "on" ? "Y" : "N";
                model.wipBoard.Burn = model.wipBoard.Burn == "on" ? "Y" : "N";
                model.wipBoard.DipSolderMask = model.wipBoard.DipSolderMask == "on" ? "Y" : "N";
                model.wipBoard.ISPartsBake = model.wipBoard.ISPartsBake == "on" ? "Y" : "N";
                model.wipBoard.PartsBakeOvertime = model.wipBoard.PartsBakeOvertime == "on" ? "Y" : "N";
                model.wipBoard.ISPcbBake = model.wipBoard.ISPcbBake == "on" ? "Y" : "N";
                //系統
                model.wipSystem.FinePackage = model.wipSystem.FinePackage == "on" ? "Y" : "N";

                // 判斷資料填寫
                WipDataViewModel wipDataViewModel = new WipDataViewModel();
                wipDataViewModel.wipInfo = model.wipInfo;
                wipDataViewModel.wipSystem = model.wipSystem;
                wipDataViewModel.wipBoard = model.wipBoard;
                wipDataViewModel.wipMAC = model.wipMAC;
                wipDataViewModel.wipBarcodeOther = model.wipBarcodeOther;
                var Msg = CheckWipInfoInsert(wipDataViewModel);

                // 判斷WipKp 順序是否重複
                if (model.WipKps.Where(w => w.WipKpID != -1).GroupBy(g => g.KpSeq).Where(w => w.Count() > 1).Any())
                {
                    Msg += ",KeyParts 順序有重複 ";
                }

                // 判斷SOP是否沒填文件名稱
                if (model.WipSops.Where(w => string.IsNullOrWhiteSpace(w.SOPName)).Any())
                {
                    Msg += ",SOP文件 請填寫SOP文件敘述 ";
                }

                // 判斷MAC是否正確
                var CheckMACMsg = CheckMACData(model);
                if (!string.IsNullOrWhiteSpace(CheckMACMsg))
                {
                    Msg += "," + CheckMACMsg;
                }

                // 判斷標籤 工單性質選擇 WipAttr非標96工單時,則旁邊欄位必填
                if (model.wipLabel.WipAttr == "B" && string.IsNullOrWhiteSpace(model.wipLabel.NonstandardWoMemo))
                {
                    Msg += ",標籤:工單性質選擇非標96工單時,需填入資料";
                }

                // 判斷治具中生產單位與作業站吻合
                var result_wipNo = await _pcsApi.GetWipInfoByWipNO(model.wipInfo.WipNO);
                foreach (var item in result_wipNo)
                {
                    foreach (var Outfits in model.WipOutfits.Where(w => w.StationID != null && w.UnitNo == item.UnitNO))
                    {
                        var RuleStation = await _pcsApi.GetRuleStationByFlow(item.FlowRuleID);

                        if (!RuleStation.Where(w => Outfits.StationID == w.StationID).Any())
                        {
                            Msg += ",治具組合中生產單位與作業站不匹配";
                        }
                    }
                }

                if (!string.IsNullOrWhiteSpace(Msg))
                {
                    if (Msg.StartsWith(","))
                        Msg = Msg.Substring(1, Msg.Length - 1);

                    ModelState.AddModelError("error", Msg);
                    return View("PCS034", model);
                }

                // 工單相關資料ExecuteDB
                var (WipExecuteMsg, WipExeucteModel) = await WipExecuteDB(model, formFile);
                model = WipExeucteModel;

                if (!string.IsNullOrWhiteSpace(WipExecuteMsg))
                {
                    ModelState.AddModelError("error", $"修改失敗,錯誤訊息:{WipExecuteMsg}");
                    return View("PCS034", model);
                }

                WipCheck wipCheck = new WipCheck
                {
                    WipNo = model.wipInfo.WipNO
                };
                if (action == "生管確認")
                {
                    wipCheck.PMCUserID = UserID;
                    await CheckPCS003ToMail(model.wipInfo.WipNO, model.wipAtt.ItemNO, model.wipInfo.UnitNO, model.wipInfo.WipScheduleDate.ToString(), action);
                    await _pcsApi.PutWipCheckByPMC(JsonConvert.SerializeObject(wipCheck));
                }
                else if (action == "工程確認")
                {
                    wipCheck.PEUserID = UserID;
                    await CheckPCS003ToMail(model.wipInfo.WipNO, model.wipAtt.ItemNO, model.wipInfo.UnitNO, model.wipInfo.WipScheduleDate.ToString(), action);
                    await _pcsApi.PutWipCheckByPE(JsonConvert.SerializeObject(wipCheck));
                }
                else if (action == "製造確認")
                {
                    wipCheck.MFUserID = UserID;
                    await _pcsApi.PutWipCheckByMF(JsonConvert.SerializeObject(wipCheck));
                }

                var _msg = "修改成功!";
                ModelState.AddModelError("error", _msg);
                return View("PCS034", model);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("error", "系統錯誤,錯誤訊息:" + ex.Message);
                return View("PCS034", model);
            }
        }

        #endregion

        #region 自動寄信
        /// <summary>
        /// 工單維護儲存時寄信通知
        /// </summary>
        /// <param name="WipNo">工單號碼</param>
        /// <param name="Material">工單料號</param>
        /// <param name="Process">製程</param>
        /// <param name="StrDate">預計開工日期</param>
        /// <param name="ReviewType">確認狀態</param>
        /// <returns></returns>
        private async Task CheckPCS003ToMail(string WipNo, string Material, string Process, string StrDate, string ReviewType)
        {
            //工單Review,生管確認,完成後通知工程,mail群組名稱,請建立為[WOVIEW_PE]
            //工單Review,工程確認,完成後通知製造,mail群組名稱,請建立為[WOVIEW_MF]
            string MailGroup = string.Empty;
            string SubjectGroup = "製造單位";
            if (ReviewType == "生管確認")
            {
                SubjectGroup = "工程單位";
                MailGroup = "WOVIEW_PE";
            }
            else
            {
                MailGroup = "WOVIEW_MF";
                SubjectGroup = "製造單位";
            }

            var result = await _basApi.GetFactoryUnits();
            Process = result.Where(w => w.UnitNo == Process).FirstOrDefault().UnitName;

            string Subject = $"[AMES系統通知] 工單:{WipNo},請{SubjectGroup}進行確認";
            string Body = $@"說明:<br/>
                                 工單編號:{WipNo}<br/>
                                 生產料號:{Material}<br/>
                                 所屬製程:{Process}<br/>
                                 預計開工日:{StrDate}<br/>
                                 <br/>{ReviewType}單位,已review完畢,請接續生產參數之確認";

            await _bllApi.PostToMail(Subject, Body, MailGroup, "", false);

        }
        #endregion

        /// <summary>
        /// 工單資料畫面 Select All
        /// </summary>
        /// <param name="WipNo">工單號碼</param>
        /// <param name="ItemNo">工單料號</param>
        /// <param name="UnitNo">生產單位</param>
        /// <returns></returns>
        public async Task WipDataSelectAll(string WipNo = null, string ItemNo = "X", string UnitNo = "X")
        {
            // KP Items
            await GetItemsList();
            // 產品別
            await GetProductType();
            // 廠別 委外廠
            await GetFactoryInfo();
            // 生產單位
            await GetFactoryUnit(false);
            // 線別
            await GetLineInfo();
            // 正背面
            await GetMFGType();
            // 工單類型
            await GetProcessTypes();
            // 料號流程
            await GetMaterialFlowRuleJson(ItemNo, UnitNo);
            // 治具種類
            await GetOutfitCommodityInfoJson();
            // 生產單位 By WipNo
            await GetFactoryUnitByWipNoJson(WipNo);
            // 工單號碼綁定作業站 治具使用
            await GetRuleStationByWipNoUnitNoJson(WipNo);
            // 工程資訊-DMI 燒入
            GetWipSystemDMITypeSelect();
            // 制令序號
            GetWipSEQType();
            // 燒入
            GetBurnType();
            // 零件烘烤
            GetPartsBakeType();
            // 板卡資訊 PCB烘烤
            GetPCBBakeTypeSelect();
            // 板卡資訊 PCB加工
            GetPCBProcessingTypeSelect();
            // 板卡資訊 錫膏
            GetSolderPasteSelect();
            // 工單狀態 標準 重工
            GetWipType();
            // 工程資訊 軟體料號Type
            GetWipSystemTypeSelect();
            // 工程資訊 Power Model 
            GetWipSystemPMTypeSelect();
            // 燒機溫度
            GetWipBITemperatuerSelect();
            // 燒機軟體
            GetWipBI_OSSelect();
            // SOP Type
            GetSOPTypeSelect();

        }

        /// <summary>
        /// CheckMAC 資料是否正確
        /// </summary>
        /// <returns></returns>
        public string CheckMACData(WipDataViewModel model)
        {
            if (model.wipMAC == null)
                return "";

            string StartNO = model.wipMAC.StartNO ?? "";
            string EndNO = model.wipMAC.EndNO ?? "";
            // 資料為空
            if (string.IsNullOrWhiteSpace(StartNO) && string.IsNullOrWhiteSpace(EndNO))
                return "";

            if (StartNO.Length != 12 || EndNO.Length != 12)
                return "MAC長度有誤";

            if (StartNO.ToUpper().Substring(0, 6) != EndNO.ToUpper().Substring(0, 6))
                return "MAC前綴不一樣";

            // 轉十進位
            var Entire = new Code.Entire();
            try
            {
                // 最小值
                var StartNONum = int.Parse(Entire.DecHex(StartNO.Substring(StartNO.Length - 6, 6), "HexToDec"));
                // 最大值
                var EndNONum = int.Parse(Entire.DecHex(EndNO.Substring(EndNO.Length - 6, 6), "HexToDec"));

                // 取MAC區間小於工單數
                if (EndNONum - StartNONum + 1 < model.wipInfo.PlanQTY)
                    return "MAC區間小於工單數量";

                // 判斷MAC區間是否有重複使用
                var result = _pcsApi.GetCheckMAC(model.wipInfo.WipNO, StartNO, EndNO).InvokeAsync().Result;

                if (!result.Success)
                    return result.Msg;
                else
                    return "";
            }
            catch
            {
                return "MAC後6碼格式有誤";
            }
        }

        public async Task<JsonResult> GetMAC(string itemno, int planQTY)
        {
            var q = await _pcsApi.GetMACInfo(itemno);

            if (q != null)
            {
                // 當前值 16 進位
                var Value = q.Value;

                var Entire = new Code.Entire();

                // 最小值
                var Mix = (int.Parse(Entire.DecHex(Value, "HexToDec")) + 1);
                // 最大值
                var Max = (int.Parse(Entire.DecHex(Value, "HexToDec")) + planQTY * q.Qty);

                // 當最大值 > DB設定最大值
                if (Max > int.Parse(Entire.DecHex(q.Max.ToString(), "HexToDec")))
                {
                    return Json(new { _msg = "自動配MAC已超過設定最大值,請在確認!" });
                }

                // 低於安全量 Mail通知
                // 取完剩餘數量
                var NowQty = Max - int.Parse(Entire.DecHex(q.Max.ToString(), "HexToDec"));
                if (NowQty <= q.SafeQty)
                {

                }

                var x = new
                {
                    mix = q.Title + Entire.DecHex(Mix.ToString(), "DecToHex").ToUpper(),
                    max = q.Title + Entire.DecHex(Max.ToString(), "DecToHex").ToUpper(),
                };
                return Json(x);
            }
            return Json(new { _msg = "查無相關MAC對應" });
        }

        /// <summary>
        /// KP整批Excel匯入
        /// </summary>
        /// <param name="Uploader"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> PCS003CKDKeyparts_Excel(IFormFile Uploader)
        {
            List<WipKpDto> Print = new List<WipKpDto>();
            string Msg = string.Empty;
            //通過上傳檔案流初始化Mapper
            using (var workbook = new XLWorkbook(Uploader.OpenReadStream()))
            {
                // 生產單位
                var Units = await _basApi.GetFactoryUnits();
                // KeyPartsItems
                var Items = await _pcsApi.GetItems();
                // 順序
                int Seq = 1;
                try
                {
                    var worksheet = workbook.Worksheet(1);
                    // 定義資料起始/結束 Cell
                    var firstCell = worksheet.FirstCellUsed();
                    var lastCell = worksheet.LastCellUsed();

                    // 使用資料起始/結束 Cell,來定義出一個資料範圍
                    var data = worksheet.Range(firstCell.Address, lastCell.Address);
                    var rowCount = data.RowCount();
                    var columnCount = data.ColumnCount();
                    for (int i = 2; i <= rowCount; i++)
                    {
                        WipKpDto wipKpDto = new WipKpDto();

                        for (int j = 1; j <= columnCount; j++)
                        {
                            if (data.Cell(i, j).Value != null)
                            {
                                switch (j)
                                {
                                    case 1:
                                        wipKpDto.KpName = data.Cell(i, j).Value.ToString();
                                        break;

                                    case 2: // KP_No CPU,RAM 等等
                                        if (Items.Where(w => w.ItemName.Trim().ToUpper() == data.Cell(i, j).Value.ToString().Trim().ToUpper()).Any())
                                        {
                                            wipKpDto.KpNo = Items.Where(w => w.ItemName.Trim().ToUpper() == data.Cell(i, j).Value.ToString().Trim().ToUpper())
                                                                         .Select(s => s.ItemNo).FirstOrDefault();
                                            wipKpDto.KpNoName = data.Cell(i, j).Value.ToString();
                                        }
                                        else
                                        {
                                            Msg += $"找不到【{data.Cell(i, j).Value.ToString()}】相關KeyParts代號</br>";
                                        }
                                        break;
                                    case 3: // 前置碼
                                        wipKpDto.Title = data.Cell(i, j).Value.ToString();
                                        break;
                                    case 4: // 長度
                                        if (data.Cell(i, j).Value != null && !string.IsNullOrWhiteSpace(data.Cell(i, j).Value.ToString()))
                                        {
                                            if (!int.TryParse(data.Cell(i, j).Value.ToString(), out _))
                                            {
                                                Msg += $"【{data.Cell(i, j).Value.ToString()}】長度格式錯誤</br>";
                                            }
                                            wipKpDto.Length = int.Parse(data.Cell(i, j).Value.ToString());
                                        }
                                        break;
                                    case 5: // 生產單位
                                        if (Units.Where(w => w.UnitName.Trim().ToUpper() == data.Cell(i, j).Value.ToString().Trim().ToUpper()).Any())
                                        {
                                            wipKpDto.UnitNo = Units.Where(w => w.UnitName.Trim().ToUpper() == data.Cell(i, j).Value.ToString().Trim().ToUpper())
                                                                   .Select(s => s.UnitNo).FirstOrDefault();
                                            wipKpDto.UnitNoName = data.Cell(i, j).Value.ToString();
                                        }
                                        else
                                        {
                                            Msg += $"找不到【{data.Cell(i, j).Value}】相關生產單位名稱</br>";
                                        }
                                        break;
                                    case 6: // kp數量
                                        if (!string.IsNullOrWhiteSpace(data.Cell(i, j).Value.ToString()))
                                        {
                                            if (!int.TryParse(data.Cell(i, j).Value.ToString(), out _))
                                            {
                                                Msg += $"【{data.Cell(i, j).Value.ToString()}】KP數量格式錯誤</br>";
                                            }

                                            for (int x = 1; x <= int.Parse(data.Cell(i, j).Value.ToString()); x++)
                                            {
                                                Print.Add(new WipKpDto
                                                {
                                                    KpName = wipKpDto.KpName,
                                                    KpNo = wipKpDto.KpNo,
                                                    KpNoName = wipKpDto.KpNoName,
                                                    Length = wipKpDto.Length == null ? 0 : wipKpDto.Length,
                                                    Title = wipKpDto.Title == null ? "" : wipKpDto.Title,
                                                    UnitNo = wipKpDto.UnitNo,
                                                    UnitNoName = wipKpDto.UnitNoName,
                                                    KpSeq = Seq
                                                });
                                                Seq += 1;
                                            }
                                        }
                                        else
                                        {
                                            Msg += $"請輸入KP數量</br>";
                                        }
                                        break;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    return Json(new { data = ex.Message, success = false });
                }
            }

            if (!string.IsNullOrWhiteSpace(Msg))
                return Json(new { data = Msg, success = false });
            else
                //将数据Json化并传到前台视图
                return Json(new { data = Print, success = true });
        }
        #endregion

        #region PCS002 工單設定
        public async Task<IActionResult> PCS002(string id)
        {
            if (id != null)
            {
                await GetFactoryUnit(id);
                ViewBag.UnitNo = id;
            }
            else
            {
                await GetFactoryUnit();
            }

            //await GetFactoryUnit();
            return View();
        }

        /// <summary>
        /// PCS002 Query
        /// </summary>
        /// <param name="unitno">生產單位</param>
        /// <param name="wipNo">工單號碼</param>
        /// <param name="itemNo">料號</param>
        /// <returns></returns>
        public async Task<IActionResult> PCS002QueryAsync(string unitno, string wipNo, string itemNo, int page = 0, int limit = 10)
        {
            IResultModel<dynamic> result = await _pcsApi.GetWipInfoSelectParameter(unitno: unitno
                , wipno: wipNo
                , itemno: itemNo
                , page: page
                , limit: limit
                , statusNo: "N");

            if (result.Data != null)
            {
                return Json(new Table() { code = 0, msg = "", data = result.Data, count = result.DataTotal });
            }
            return Json(new Table() { count = 0, data = null });
        }
        #endregion

        #region PCS004 工單內部條碼區間設定
        [ResponseCache(Duration = 0)]
        [HttpGet]
        public async Task<IActionResult> PCS004()
        {
            await GetFactoryUnit();
            return View();
        }

        /// <summary>
        /// PCS004 Query
        /// </summary>
        /// <param name="unitno">生產單位</param>
        /// <param name="wipno">工單號碼</param>
        /// <returns></returns>
        public async Task<IActionResult> PCS004QueryAsync(string unitno, string wipno, int page = 0, int limit = 10)
        {
            IResultModel<dynamic> result = await _pcsApi.GetWipInfoSelectParameter(unitno: unitno
                , wipno: wipno
                , page: page
                , limit: limit);

            if (result.Data != null)
            {
                return Json(new Table() { code = 0, msg = "", data = result.Data, count = result.DataTotal });
            }
            return Json(new Table() { count = 0, data = null });
        }

        //頁面提交,id=0 添加,id>0 修改
        [HttpPost]
        public async Task<IActionResult> PCS004CAsync(PCS004CViewModel model)
        {
            await GetLineInfo();
            await GetFlowRuleList();

            // 起訖序號沒填寫 或者 綁定序號沒填寫
            if ((string.IsNullOrWhiteSpace(model.WipBarcode.StartNO) || string.IsNullOrWhiteSpace(model.WipBarcode.EndNO))
                && string.IsNullOrWhiteSpace(model.BarcodeNo))
            {
                ModelState.AddModelError("error", "請確認新增的條碼是否有填寫?");
                return View(model);
            }

            if ((!string.IsNullOrWhiteSpace(model.WipBarcode.StartNO) || !string.IsNullOrWhiteSpace(model.WipBarcode.EndNO))
             && !string.IsNullOrWhiteSpace(model.BarcodeNo))
            {
                ModelState.AddModelError("error", "請則一選擇要新增條碼的方式?");
                return View(model);
            }

            // 既有序號綁定
            if (!string.IsNullOrWhiteSpace(model.BarcodeNo))
            {
                // 內部序號
                if (model.Type == "SN")
                {
                    if (_pcsApi.GetBarcodeInfoesByNo(model.BarcodeNo).InvokeAsync().Result.Count() == 0)
                    {
                        ModelState.AddModelError("error", "綁定序號【" + model.BarcodeNo + "】,找不到已綁定的內部序號");
                        return View(model);
                    }
                }
                // 出貨序號
                else if (model.Type == "SSN")
                {
                    var resultExtraNo = await _pcsApi.GetBarcodeInfoesByExtraNo(model.BarcodeNo);
                    if (resultExtraNo.Count() == 0)
                    {
                        ModelState.AddModelError("error", "綁定序號【" + model.BarcodeNo + "】,找不到已綁定的出貨序號");
                        return View(model);
                    }
                    else
                        model.BarcodeNo = resultExtraNo.FirstOrDefault().BarcodeNo;
                }

                model.WipBarcode.StartNO = model.BarcodeNo;
                model.WipBarcode.EndNO = model.BarcodeNo;
            }


            // 流水碼預設長度
            string _msg = string.Empty;
            int WipQty = model.WipInfo.PlanQTY;
            string InputStartNo = model.WipBarcode.StartNO.Trim();
            string InputEndNo = model.WipBarcode.EndNO.Trim();

            if (model.WipBarcodes == null)
            {
                model.WipBarcodes = new List<WipBarcode>();
            }

            if (InputStartNo.Length <= NoLength || InputEndNo.Length <= NoLength)
            {
                _msg += "條碼區間號碼長度不能小於" + (NoLength + 1);
                ModelState.AddModelError("error", _msg);
                return View(model);
            }

            if (InputStartNo.Length != InputEndNo.Length)
            {
                _msg += "起始條碼與結束條碼字串長度不一致";
                ModelState.AddModelError("error", _msg);
                return View(model);
            }

            if (InputStartNo.Substring(0, InputStartNo.Length - NoLength) !=
                InputEndNo.Substring(0, InputEndNo.Length - NoLength))
            {
                _msg += "條碼區間前置號碼不一樣";
                ModelState.AddModelError("error", _msg);
                return View(model);
            }


            if (!int.TryParse(InputStartNo.Substring(InputStartNo.Length - NoLength, NoLength), out _) ||
                !int.TryParse(InputEndNo.Substring(InputEndNo.Length - NoLength, NoLength), out _))
            {
                _msg += "條碼區間流水碼格式錯誤";
                ModelState.AddModelError("error", _msg);
                return View(model);
            }

            // 計算設定條碼區間是否有大於工單數
            int sum = 0;
            // 起始流水碼
            int InputStrNoQty = int.Parse(InputStartNo.Substring(InputStartNo.Length - NoLength, NoLength));
            // 結束流水碼
            int InputEndNoQty = int.Parse(InputEndNo.Substring(InputEndNo.Length - NoLength, NoLength));

            if (InputEndNoQty < InputStrNoQty)
            {
                _msg += "結束流水碼不可以小於起始流水碼";
                ModelState.AddModelError("error", _msg);
                return View(model);
            }

            if (model.WipBarcodes != null)
            {
                // 計算目前已經使用的條碼區間數量
                foreach (var item in model.WipBarcodes)
                {
                    int OldStrNo = int.Parse(item.StartNO.Substring(item.StartNO.Length - NoLength, NoLength));
                    int OldEndNo = int.Parse(item.EndNO.Substring(item.EndNO.Length - NoLength, NoLength));

                    // 判斷是否有設定重複區間
                    if (item.StartNO.Substring(0, item.StartNO.Length - NoLength) ==
                        InputStartNo.Substring(0, InputStartNo.Length - NoLength))
                    {
                        if ((OldStrNo <= InputStrNoQty && InputStrNoQty <= OldEndNo) ||
                            (OldStrNo <= InputEndNoQty && InputEndNoQty <= OldEndNo))
                        {
                            _msg += "設定條碼區間有重複,請確認!";
                            ModelState.AddModelError("error", _msg);
                            return View(model);
                        }
                    }
                    sum += OldEndNo - OldStrNo + 1;
                }
            }

            if (WipQty < sum + (InputEndNoQty - InputStrNoQty + 1))
            {
                _msg += "工單號碼【" + model.WipInfo.WipNO + "】 設定條碼區間數量已超過工單數量,請確認!";
                ModelState.AddModelError("error", _msg);
                return View(model);
            }

            IResultModel result;
            model.WipBarcode.WipNO = model.WipInfo.WipNO;
            model.WipBarcode.CreateUserID = GetLogInUserID();
            //model.WipBarcode.WipID = model.WipInfo.WipID;
            //model.WipBarcode.UnitNO = model.WipInfo.UnitNO;

            result = await _pcsApi.PostWipBarcode(JsonConvert.SerializeObject(model.WipBarcode));

            if (result.Success)
            {
                _msg = "新增成功!";
                return RedirectToAction("PCS004C", "PCS", new { id = model.WipInfo.WipID, msg = _msg });
            }
            else
            {
                if (result.Errors.Count > 0)
                {
                    ModelState.AddModelError(result.Errors[0].Id, result.Errors[0].Msg);
                }
                else
                {
                    ModelState.AddModelError("error", result.Msg);
                }
            }

            return RedirectToAction("PCS004C", "PCS", new { id = model.WipInfo.WipID });
        }

        public async Task<IActionResult> PCS004C(int id, string msg = null)
        {
            ViewBag.Msg = msg;
            await GetLineInfo();
            await GetFlowRuleList();
            PCS004CViewModel model = new PCS004CViewModel();
            var q = await _pcsApi.GetWipInfo(id);
            if (q.Count != 0)
            {
                model.WipInfo = q.FirstOrDefault();
                model.WipAtt = await _pcsApi.GetWipAtt(model.WipInfo.WipNO);
                model.WipBarcodes = await _pcsApi.GetWipBarcode(model.WipInfo.WipNO);
                model.RuleStation = await _basApi.GetRuleStationsByFlow(model.WipInfo.FlowRuleID);
                model.WipInfo.WipType = model.WipInfo.WipType == "S" ? "標準工單" : "重工工單";
                //model.RuleStation = model.RuleStation.OrderBy(o => o.Sequence);
            }
            return View(model);
        }

        public async Task<IActionResult> PCS004R(int id)
        {
            await GetLineInfo();
            await GetFlowRuleList();
            PCS004CViewModel model = new PCS004CViewModel();
            var q = await _pcsApi.GetWipInfo(id);
            if (q.Count != 0)
            {
                model.WipInfo = q.FirstOrDefault();
                model.WipAtt = await _pcsApi.GetWipAtt(model.WipInfo.WipNO);
                model.WipBarcodes = await _pcsApi.GetWipBarcode(model.WipInfo.WipNO);
                model.RuleStation = await _basApi.GetRuleStationsByFlow(model.WipInfo.FlowRuleID);
                model.WipInfo.WipType = model.WipInfo.WipType == "S" ? "標準工單" : "重工工單";
                //model.RuleStation = model.RuleStation.OrderBy(o => o.Sequence);
            }
            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> PCS004D(string WipNo, string StrNo, string EndNo)
        {
            var result = await _pcsApi.DeleteWipBarcode(WipNo, StrNo, EndNo);
            return Json(new Result() { success = true, msg = "" });
        }
        #endregion

        #region PCS005 工單資料查詢
        public async Task<IActionResult> PCS005(string id)
        {
            if (id != null)
            {
                string[] param = id.Split('_');
                if (param[0] != null && param[0] != "")
                {
                    await GetFactoryUnit(param[0]);
                    ViewBag.UnitNo = param[0];
                }
                else
                {
                    await GetFactoryUnit();
                }

                if (param.Length > 1)
                {
                    if (param[1] != null && param[1] == "OC")
                    {
                        if (Request.Cookies["_AMESCookie"] != null)
                        {
                            var userID = "";
                            HttpContext.Request.Cookies.TryGetValue("UserID", out userID);
                            if (userID != null)
                            {
                                if (int.Parse(userID.ToString()) >= 0)
                                {
                                    int user_id = int.Parse(userID.ToString());
                                    var user_info = await _sysApi.GetUserData(user_id);

                                    if (user_info.DataTotal > 0)
                                    {
                                        foreach (var item in user_info.Data)
                                        {
                                            JObject jo = JObject.Parse(item.ToString());
                                            string factoryNo = jo["factoryNo"].ToString();
                                            ViewBag.UserFactory = factoryNo;
                                            ViewData["UserFactory"] = factoryNo;
                                        }
                                    }
                                }
                            }

                        }
                    }
                }
            }
            else
            {
                await GetFactoryUnit();
            }
            //await GetFactoryUnit();
            return View();
        }

        /// <summary>
        /// PCS005 Query
        /// </summary>
        /// <param name="unitNo">生產單位</param>
        /// <param name="wipNo">工單號碼</param>
        /// <param name="itemNo">料號</param>
        /// <param name="factoryNo">廠別</param>
        /// <returns></returns>
        public async Task<IActionResult> PCS005QueryAsync(string unitNo, string wipNo, string itemNo, string factoryNo, string statusNo, int page = 0, int limit = 10)
        {
            string[] param = Request.Path.ToString().Replace("/PCS/PCS005Query/", "").Split('_');
            if (param[0] != null && param[0] != "")
            {
                unitNo = param[0];
            }

            if (param.Length > 1)
            {
                if (param[1] != null && param[1] != "")
                {
                    wipNo = param[1];
                }
                if (param[2] != null && param[2] != "")
                {
                    itemNo = param[2];
                }
                if (param[3] != null && param[3] != "")
                {
                    factoryNo = param[3];
                }
            }

            IResultModel<dynamic> result = await _pcsApi.GetWipInfoSelectParameter(unitno: unitNo
                , wipno: wipNo
                , itemno: itemNo
                , factoryno: factoryNo
                , page: page
                , limit: limit
                , statusNo: statusNo);

            if (result.Data != null)
            {
                return Json(new Table() { code = 0, msg = "", data = result.Data, count = result.DataTotal });
            }
            return Json(new Table() { count = 0, data = null });
        }

        /// <summary>
        /// PCS005 刪除
        /// </summary>
        /// <param name="id">工單號碼</param>
        /// <returns></returns>
        public async Task<IActionResult> PCS005DAsync(string id)
        {
            // 判斷工單號碼是否已經投入
            if (await _pcsApi.GetWipInfoCheckStart(id) == "Y")
            {
                var _msg = "工單號碼【" + id + "】,工單已開始投入,不可刪除!";
                return Json(new Result() { success = false, msg = _msg });
            }

            // 判斷工單號碼是否已經開線
            if (await _pcsApi.GetWipInfoCheckStartLine(id) == "Y")
            {
                var _msg = "工單號碼【" + id + "】,工單已開線,不可刪除!";
                return Json(new Result() { success = false, msg = _msg });
            }

            var result = await _pcsApi.DeleteWipinfo(id);
            return Json(new Result() { success = true, msg = "刪除成功" });
        }
        #endregion

        #region PCS006 工單開線收線作業
        [ResponseCache(Duration = 0)]
        [HttpGet]
        public async Task<IActionResult> PCS006(string id)
        {
            if (id != null)
            {
                string[] param = id.Split('_');
                if (param[0] != null && param[0] != "")
                {
                    await GetFactoryUnit(param[0]);
                    ViewBag.UnitNo = param[0];
                }
                else
                {
                    await GetFactoryUnit();
                }

                if (param.Length > 1)
                {
                    if (param[1] != null && param[1] == "OC")
                    {
                        if (Request.Cookies["_AMESCookie"] != null)
                        {
                            var userID = "";
                            HttpContext.Request.Cookies.TryGetValue("UserID", out userID);
                            if (userID != null)
                            {
                                if (int.Parse(userID.ToString()) >= 0)
                                {
                                    int user_id = int.Parse(userID.ToString());
                                    var user_info = await _sysApi.GetUserData(user_id);

                                    if (user_info.DataTotal > 0)
                                    {
                                        foreach (var item in user_info.Data)
                                        {
                                            JObject jo = JObject.Parse(item.ToString());
                                            string factoryNo = jo["factoryNo"].ToString();
                                            ViewBag.UserFactory = factoryNo;
                                            ViewData["UserFactory"] = factoryNo;
                                        }
                                    }
                                }
                            }

                        }
                    }
                }
            }
            else
            {
                await GetFactoryUnit();
            }

            return View();
        }

        /// <summary>
        /// PCS006 Query 查詢
        /// </summary>

        [ResponseCache(Duration = 0)]
        [HttpGet]
        public async Task<IActionResult> PCS006QueryAsync(string unitNo, string wipNo, string factoryNo, int page = 0, int limit = 10)
        {
            string[] param = Request.Path.ToString().Replace("/PCS/PCS006Query/", "").Split('_');
            if (param[0] != null && param[0] != "")
            {
                unitNo = param[0];
            }

            if (param.Length > 1)
            {
                if (param[1] != null && param[1] != "")
                {
                    wipNo = param[1];
                }
                if (param[2] != null && param[2] != "")
                {
                    factoryNo = param[2];
                }
            }

            // 工單基本資料
            IResultModel<dynamic> result = await _pcsApi.GetWipInfoSelectParameter(unitno: unitNo
                , wipno: wipNo
                , factoryno: factoryNo
                , page: page
                , limit: limit);

            //if (result.Data != null)
            //{
            //    return Json(new Table() { code = 0, msg = "", data = result.Data, count = 0 });
            //}
            //return Json(new Table() { count = 0, data = null });


            // 工單狀態
            var result_StatusType = await _ppsApi.GetWipStatus();
            List<dynamic> result_dy = new List<dynamic>();
            foreach (var item in result.Data)
            {
                var itema = item;
                // 判斷是否開線資料
                var result_LineInfo = await _pcsApi.GetLineInfoByWipID((int)item.wipID);
                // 用工單ID抓最新一筆Log紀錄
                var result_Log = await _pcsApi.GetWipLog((int)item.wipID);
                result_dy.Add(new
                {
                    item.wipID,
                    item.wipNo,
                    item.itemNo,
                    item.lineID,
                    item.lineDesc,
                    item.unitName,
                    item.planQTY,
                    item.createDate,
                    result_StatusType.Where(w => w.StatusNo == (string)item.statusNo).FirstOrDefault().StatusDesc,
                    OnOff = result_LineInfo.Count() != 0 ? "ON" : "OFF",
                    ActiveStop = result_Log.StatusNO
                });
            }


            if (result_dy.Count > 0)
            {
                return Json(new Table() { code = 0, msg = "", data = result_dy, count = result.DataTotal });
            }
            return Json(new Table() { count = 0, data = null });
        }

        [HttpPost]
        public async Task<JsonResult> PCS006ActiveStopAsync(int wipID, string statusNO, int LineID)
        {
            WipLog wipLog = new WipLog();
            wipLog.WipID = wipID;
            wipLog.WipDesc = ".";
            wipLog.StatusNO = statusNO;

            // 當切換STOP時,強制收線
            if (statusNO == "S")
            {
                var LineInfoByWipID = await _pcsApi.GetLineInfoByWipID(wipID);
                if (LineInfoByWipID.Count() != 0)
                {
                    await PCS006OnOffAsync(LineID, -1);
                }
            }
            else
            {
                // 計算工單開工數 +1
                var wipInfos = await _pcsApi.GetWipInfo(wipID);
                var wipInfo = wipInfos.FirstOrDefault();
                wipInfo.WipTimes += 1;
                wipInfo.UpdateDate = DateTime.Now;
                await _pcsApi.PutWipInfo(JsonConvert.SerializeObject(wipInfo));
            }

            await _pcsApi.PostWipLog(JsonConvert.SerializeObject(wipLog));
            await _pcsApi.PutWipinfoToStatusNO(wipID, statusNO);
            var _msg = "修改成功!";
            return Json(_msg);
        }

        [HttpPost]
        public async Task<JsonResult> PCS006OnOffAsync(int LineID, int wipID)
        {
            await _pcsApi.PutLineInfoToWipNO(LineID, wipID);
            var _msg = "修改成功!";
            return Json(_msg);
        }

        #endregion

        #region PCS008 未結工單查詢
        public async Task<IActionResult> PCS008(string id)
        {
            if (id != null)
            {
                string[] param = id.Split('_');
                if (param[0] != null && param[0] != "")
                {
                    await GetFactoryUnit(param[0]);
                    ViewBag.UnitNo = param[0];
                }
                else
                {
                    await GetFactoryUnit();
                }

                if (param[1] != null && param[1] == "OC")
                {
                    if (Request.Cookies["_AMESCookie"] != null)
                    {
                        var userID = "";
                        HttpContext.Request.Cookies.TryGetValue("UserID", out userID);
                        if (userID != null)
                        {
                            if (int.Parse(userID.ToString()) >= 0)
                            {
                                int user_id = int.Parse(userID.ToString());
                                var user_info = await _sysApi.GetUserData(user_id);

                                if (user_info.DataTotal > 0)
                                {
                                    foreach (var item in user_info.Data)
                                    {
                                        JObject jo = JObject.Parse(item.ToString());
                                        string factoryNo = jo["factoryNo"].ToString();
                                        ViewBag.UserFactory = factoryNo;
                                    }
                                }
                            }
                        }

                    }
                }
            }
            else
            {
                await GetFactoryUnit();
            }

            /*
            if (id != null)
            {
                await GetFactoryUnit(id);
                ViewBag.UnitNo = id;
            }
            else
            {
                await GetFactoryUnit();
            }
            */

            //await GetFactoryUnit();
            return View();
        }

        [HttpGet]
        public async Task<IActionResult> PCS008V(string unitNo, string wipNo, string itemNo, string dateStr, string dateEnd, string factoryNo)
        {
            IResultModel<dynamic> result = await _pcsApi.GetWipInfoPCS008(unitno: unitNo, wipno: wipNo, itemno: itemNo,
                date_str: dateStr, date_end: dateEnd, factoryno: factoryNo);

            string wipDataList = "<font size='3'>";
            if (result.DataTotal > 0)
            {
                foreach (var item in result.Data)
                {
                    JObject jo = JObject.Parse(item.ToString());
                    int wip_id = int.Parse(jo["wipID"].ToString());
                    int flow_rule_id = int.Parse(jo["flowRuleID"].ToString());
                    int line_id = int.Parse(jo["lineID"].ToString());
                    string item_no = jo["itemNO"].ToString();
                    string unit_name = jo["unitName"].ToString();
                    string line_desc = jo["lineDesc"].ToString();
                    string wip_no = jo["wipNO"].ToString();
                    int plan_qty = int.Parse(jo["planQTY"].ToString());
                    int input_qty = int.Parse(jo["completeQTY"].ToString());
                    int output_qty = 0;

                    var standardWorkTimes = await _pcsApi.GetStandardWorkTimeByItemNo(item_no);

                    string ct1 = "";
                    if (standardWorkTimes.Count > 0)
                    {
                        if (standardWorkTimes.Where(w => w.LineID == line_id).FirstOrDefault() != null)
                            ct1 = standardWorkTimes.Where(w => w.LineID == line_id).FirstOrDefault().TotalCT.ToString();
                    }

                    wipDataList = wipDataList + "<font color='#FF80FF'>" + unit_name + " - " + line_desc + "</font>" + " - " + "<font color='#0080FF'>" + wip_no + "</font>" + "<font color='#FFC90E'>" + "(" + item_no + ")" + "</font>" + " - " + "<font color='#0080FF'>" + plan_qty + " / " + input_qty + " / " + output_qty + "</font>" + " | " + "<font color='#0080FF'>" + "標準工時: " + "</font>" + ct1 + "<br/>";

                    var rule_sation = await _basApi.GetRuleStationsByFlow(flow_rule_id);
                    wipDataList = wipDataList + "<table><tr><td width='120'></td>";

                    string stationQty = "<table><tr><td width='120'>過站數量</td>";
                    string stationRate = "<table><tr><td width='120'>良率</td>";
                    string stationWip = "<table><tr><td width='120'>WIP</td>";

                    string stationList = "";
                    for (int j = 0; j < rule_sation.Count; j++)
                    {
                        if (rule_sation[j].StationID != 1000 && rule_sation[j].StationType == "M")
                        {
                            stationList = stationList + rule_sation[j].StationID + ",";

                            wipDataList = wipDataList + "<td width='150' style='text-align:left'>" + rule_sation[j].Station.StationName + "</td>";

                            var wip_station = await _pcsApi.GetWipStation4QRS009Group(wip_id, rule_sation[j].StationID);

                            int okQty = 0, ngQty = 0;
                            if (wip_station.DataTotal > 0)
                            {
                                foreach (var data in wip_station.Data)
                                {
                                    JObject j0 = JObject.Parse(data.ToString());
                                    if (j0["ruleStatus"].ToString() == "P")
                                    {
                                        okQty = int.Parse(j0["firstCnt"].ToString());
                                    }
                                    else
                                    {
                                        ngQty = int.Parse(j0["firstCnt"].ToString());
                                    }
                                }
                                /*
                                for (int k = 0; k < wip_station.Count; k++)
                                {
                                    if (wip_station[k].RuleStatus == "P")
                                    {
                                        okQty = wip_station[k].FirstCnt;
                                    }
                                    else
                                    {
                                        ngQty = wip_station[k].FirstCnt;
                                    }
                                }
                                */
                            }

                            //stationQty = stationQty + "<td width='150' style='text-align:left'><a href=\"javascript:hg.open('過站PASS條碼資料','/QRS/QRS009P/" + wip_id + "_" + rule_sation[j].RuleStationID + "','','',true);\">" + okQty + "</a>/<a href=\"javascript:hg.open('過站FAIL條碼資料','/QRS/QRS009F','','',true);\">" + ngQty + "</a></td>";
                            stationQty = stationQty + "<td width='150' style='text-align:left'><a href=\"javascript:hg.open('過站PASS條碼資料','/QRS/QRS009P/" + wip_id + "_" + rule_sation[j].StationID + "',800,600);\">" + okQty + "</a>/<a href=\"javascript:hg.open('過站FAIL條碼資料','/QRS/QRS009F/" + wip_id + "_" + rule_sation[j].StationID + "',800,600);\">" + ngQty + "</a></td>";

                            double rate = ((okQty * 1.0) / (okQty + ngQty)) * 100;

                            if (okQty + ngQty == 0)
                            {
                                rate = 100;
                            }

                            if (j == rule_sation.Count - 2)
                            {
                                if (rate <= 90)
                                {
                                    stationRate = stationRate + "<td width='150' style='text-align:left;color:red'>" + rate.ToString("0.00") + "%" + "</td>";
                                }
                                else if (rate >= 95 && rate <= 97)
                                {
                                    stationRate = stationRate + "<td width='150' style='text-align:left;color:yellow'>" + rate.ToString("0.00") + "%" + "</td>";
                                }
                                else if (rate >= 98)
                                {
                                    stationRate = stationRate + "<td width='150' style='text-align:left;color:green'>" + rate.ToString("0.00") + "%" + "</td>";
                                }
                                else
                                {
                                    stationRate = stationRate + "<td width='150' style='text-align:left'>" + rate.ToString("0.00") + "%" + "</td>";
                                }
                                //stationRate = stationRate + "<td width='150' style='text-align:left'>" + rate.ToString("0.00") + "%" + "</td>";
                            }
                            else
                            {
                                //stationRate = stationRate + "<td width='90' style='text-align:left'>" + rate.ToString("0.00") + "%" + "</td>";
                                if (rate <= 90)
                                {
                                    stationRate = stationRate + "<td width='90' style='text-align:left;color:red'>" + rate.ToString("0.00") + "%" + "</td>";
                                }
                                else if (rate >= 95 && rate <= 97)
                                {
                                    stationRate = stationRate + "<td width='90' style='text-align:left;color:yellow'>" + rate.ToString("0.00") + "%" + "</td>";
                                }
                                else if (rate >= 98)
                                {
                                    stationRate = stationRate + "<td width='90' style='text-align:left;color:green'>" + rate.ToString("0.00") + "%" + "</td>";
                                }
                                else
                                {
                                    stationRate = stationRate + "<td width='90' style='text-align:left'>" + rate.ToString("0.00") + "%" + "</td>";
                                }
                                stationRate = stationRate + "<td width='60' style='text-align:left'>" + "<font color='#FF80FF'>" + " >> " + "</font>" + "</td>";
                            }
                        }
                    }
                    stationQty = stationQty + "</tr></table>";

                    stationRate = stationRate + "</tr></table>";

                    string[] station_list = stationList.Split(",");

                    for (int j = 0; j < station_list.Length - 1; j++)
                    {
                        int wip_qty = 0;
                        var wip_station1 = await _pcsApi.GetWipBarcode4QRS009(wip_id, int.Parse(station_list[j]), 0, 10);

                        if (wip_station1.DataTotal > 0)
                        {
                            wip_qty = wip_station1.DataTotal;
                        }

                        if (wip_qty < 0)
                        {
                            wip_qty = 0;
                        }
                        stationWip = stationWip + "<td width='150' style='text-align:left'><a href=\"javascript:hg.open('條碼資料','/QRS/QRS009W/" + wip_id + "_" + station_list[j] + "',800,600);\">" + wip_qty + "</a></td>";
                    }

                    stationWip = stationWip + "</tr></table><br/>";

                    wipDataList = wipDataList + "</tr></table>";

                    wipDataList = wipDataList + stationQty;
                    wipDataList = wipDataList + stationRate;
                    wipDataList = wipDataList + stationWip;

                    /*
                    wipDataList = wipDataList + "<table><tr><td width='120'>過站數量</td>";
                    for (int j = 0; j < rule_sation.Count; j++)
                    {
                        if (rule_sation[j].StationID != 1000 && rule_sation[j].StationType == "M")
                        {
                            wipDataList = wipDataList + "<td width='150' style='text-align:left'>" + "0/0" + "</td>";
                        }
                    }
                    wipDataList = wipDataList + "</tr></table>";
                    */

                    /*
                    wipDataList = wipDataList + "<table><tr><td width='120'>良率</td>";
                    for (int j = 0; j < rule_sation.Count; j++)
                    {
                        if (rule_sation[j].StationID != 1000 && rule_sation[j].StationType == "M")
                        {
                            if (j == rule_sation.Count - 2)
                            {
                                wipDataList = wipDataList + "<td width='150' style='text-align:left'>" + "100%" + "</td>";
                            }
                            else
                            { 
                                wipDataList = wipDataList + "<td width='90' style='text-align:left'>" + "100%" + "</td>";
                                wipDataList = wipDataList + "<td width='60' style='text-align:left'>" + "<font color='#FF80FF'>" + " >> " + "</font>" + "</td>";
                            }
                        }
                    }
                    wipDataList = wipDataList + "</tr></table>";
                    */

                    /*
                    wipDataList = wipDataList + "<table><tr><td width='120'>WIP</td>";
                    for (int j = 0; j < rule_sation.Count; j++)
                    {
                        if (rule_sation[j].StationID != 1000 && rule_sation[j].StationType == "M")
                        {
                            wipDataList = wipDataList + "<td width='150' style='text-align:left'>" + "0" + "</td>";
                        }
                    }
                    wipDataList = wipDataList + "</tr></table><br/>";
                    */
                }
            }
            else
            {
                wipDataList = wipDataList + "查無資料";
            }
            wipDataList = wipDataList + "</font>";
            ViewData["WipDataList"] = wipDataList;
            return View("PCS008V");
        }

        #endregion

        #region PCS009 條碼生產歷程查詢
        public IActionResult PCS009()
        {
            return View();
        }

        /// <summary>
        /// PCS009 Query By 包裝箱號
        /// </summary>
        /// <param name="boxNo">包裝箱號</param>
        /// <returns></returns>
        public async Task<IActionResult> PCS009QueryAsync(string boxNo)
        {
            var result = await _fqcApi.GetBarcodeInfoesByBoxNo(boxNo);

            if (result.Count != 0)
            {
                return Json(new Table() { code = 0, msg = "", data = result, count = result.Count });
            }

            return Json(new Table() { count = 0, data = null });
        }

        public async Task<IActionResult> PCS009R(PCS009ViewModel model)
        {
            var result_barcodeinfo = new BarcodeInfo();

            // 組件條碼查詢
            if (!string.IsNullOrWhiteSpace(model.PartNo))
            {
                var result_barcodeitem = _pcsApi.GetBarcodeItemByPartNo(model.PartNo).InvokeAsync().Result.FirstOrDefault();
                if (result_barcodeitem != null)
                {
                    model.BarCodeNo = _pcsApi.GetBarcodeInfoes(result_barcodeitem.BarcodeID).InvokeAsync().Result.FirstOrDefault().BarcodeNo;
                }
            }

            // 外部序號查詢
            if (!string.IsNullOrWhiteSpace(model.ExtraBarCodeNo))
            {
                result_barcodeinfo = _fqcApi.GetBarcodeInfoesByExtraNo(model.ExtraBarCodeNo).InvokeAsync().Result.FirstOrDefault();
                if (result_barcodeinfo != null)
                {
                    model.BarCodeNo = result_barcodeinfo.BarcodeNo;
                }
            }

            result_barcodeinfo = _pcsApi.GetBarcodeInfoesByNo(model.BarCodeNo).InvokeAsync().Result.FirstOrDefault();

            if (result_barcodeinfo == null)
            {
                // 判斷是否在BarcodeChange 有被置換過
                var result_BarcodeChangeData = await _pcsApi.GetBarcodeChangeByBarcodeNo(model.BarCodeNo ?? model.ExtraBarCodeNo ?? "A");

                // 判斷查詢是內部還是出貨條碼
                if (!string.IsNullOrWhiteSpace(model.BarCodeNo))
                    result_BarcodeChangeData = result_BarcodeChangeData.Where(w => w.ChangeType == "P").ToList();
                else
                    result_BarcodeChangeData = result_BarcodeChangeData.Where(w => w.ChangeType == "E").ToList();

                if (result_BarcodeChangeData.Count() != 0)
                {
                    var barcodeIDChange = result_BarcodeChangeData.FirstOrDefault().BarcodeID;
                    result_barcodeinfo = _pcsApi.GetBarcodeInfoes(barcodeIDChange).InvokeAsync().Result.FirstOrDefault();
                }
                else
                {
                    var _msg = "查無相關資料!";
                    return RedirectToAction("Refresh", "Home", new { msg = _msg });
                }
            }

            var result = new PCS009RViewModel();
            // 條碼資料
            result.BarCodeNo = result_barcodeinfo.BarcodeNo;
            result.ExtraBarCodeNo = result_barcodeinfo.ExtraBarcodeNo;
            result.BoxNo = result_barcodeinfo.BoxNo;
            result.StatusNo = result_barcodeinfo.StatusNo;

            // 工單資料
            var result_barcodestation = await _pcsApi.GetBarcodeStationByBarCodeID(result_barcodeinfo.BarcodeID);
            foreach (var wipID in result_barcodestation.Select(s => s.WipID).Distinct())
            {
                var result_wipinfo = await _pcsApi.GetWipInfo(wipID);
                foreach (var wipinfo in result_wipinfo)
                {
                    result.WinInfos.Add(new WinInfo
                    {
                        WipNo = wipinfo.WipNO,
                        ItemNo = wipinfo.GetWipAtt.ItemNO,
                        UnitNo = wipinfo.GetFactoryUnit.UnitCode + "[" + wipinfo.GetFactoryUnit.UnitName + "]",
                        Line = wipinfo.GetLineInfo.LineDesc,
                        ECN = wipinfo.GetWipAtt.ECN,
                        EAN = wipinfo.GetWipAtt.EAN,
                        CustomerItemNo = wipinfo.CustomerItemNO,
                        CreateDate = wipinfo.CreateDate.ToString(),
                        Remarks = wipinfo.Remarks,
                        DateCode = ""
                    });
                }
            }

            // 生產歷程
            foreach (var barcodestation in result_barcodestation.OrderBy(o => o.CreateDate))
            {
                result.BarCodeLogs.Add(new BarCodeLog
                {
                    Station = barcodestation.GetRuleStation.StationDesc,
                    RuleStation = barcodestation.RuleStatus,
                    SysType = barcodestation.Systype,
                    User = barcodestation.UserName,
                    InputDate = barcodestation.CreateDate.ToString()
                });
            }

            // 組件清單
            result.BarCodeKPs = await _pcsApi.GetBarcodeItemByBarCodeIDPCS009(result_barcodeinfo.BarcodeID);


            // 治具清單
            var barcodeoutfits = await _pcsApi.GetBarcodeOutfitByBarcodeNo(result.BarCodeNo);
            foreach (var barcodeoutfit in barcodeoutfits.OrderBy(o => o.CreateDate))
            {
                result.Outfits.Add(new Outfit
                {
                    Station = barcodeoutfit.GetStation.StationName,
                    OutfitNo = barcodeoutfit.OutfitNo,
                    InputDate = barcodeoutfit.CreateDate.ToString()
                });
            }

            // 組件變更
            result.KPChanges = await _pcsApi.GetBarcodeItemChangesByBarCodeIDPCS009(result_barcodeinfo.BarcodeID);

            // 維修
            result.nGInfoDtos = await _pcsApi.GetNgInfoByBarcodeNoFromPCS009(result_barcodeinfo.BarcodeID);

            // 條碼變更
            var barcodeChanges = await _pcsApi.GetBarcodeChangeByBarcodeID(result_barcodeinfo.BarcodeID);
            foreach (var item in barcodeChanges)
            {
                result.BarCodeChanges.Add(new BarCodeChange
                {
                    BarCodeOld = item.BarcodeNoOld,
                    BarCodeNew = item.BarcodeNoNew,
                    BarCodeChangeType = item.ChangeType == "P" ? "內部條碼變更" : "出貨條碼變更",
                    Memo = item.Memo,
                    User = item.CreateUserName,
                    Date = item.CreateDate.ToString("yyyy/MM/dd HH:mm:ss")
                });
            }

            return View(result);
        }
        #endregion

        #region PCS010 工單對應站別鎖定
        public async Task<IActionResult> PCS010()
        {
            //var fileProvider = _fileServerProvider.GetProvider("/aa");
            //var fileInfo = fileProvider.GetFileInfo("/");
            await GetStation();
            GetLockReasonType();
            GetLockType();
            //var result = new WipAllViewModel();
            //return View(result);
            return View();
        }

        //[HttpPost]
        //public async Task<JsonResult> PCS010(string wipno, string locktype)
        //{
        //    ModelState.AddModelError("WipNO", "找不到相關工單");
        //    if (locktype == "WIP")
        //    {
        //        var WipInfos = await _pcsApi.GetWipInfoByWipNO(wipno);
        //        if (WipInfos.Count() == 0)
        //            ModelState.AddModelError("WipNO", "找不到相關工單");
        //    }
        //    else if (locktype == "BAR")
        //    {

        //    }

        //    return Json(wipno);
        //}

        //頁面提交,id=0 添加,id>0 修改
        [HttpPost]
        public async Task<IActionResult> PCS010Async(WipLock model)
        {

            //if (formFile.Length > 0)
            //{
            //    var filePath = $"{_env.WebRootPath}\\PDF\\{formFile.FileName}";
            //    using (var stream = new FileStream(filePath, FileMode.Create))
            //    {
            //        await formFile.CopyToAsync(stream);
            //    }

            //    var fileProvider = _fileServerProvider.GetProvider("/aa");
            //    var fileInfo = fileProvider.GetFileInfo(formFile.FileName);
            //    using (var stream = new FileStream(fileInfo.PhysicalPath, FileMode.Create))
            //    {
            //        await formFile.CopyToAsync(stream);
            //    }
            //}
            await GetStation();
            GetLockReasonType();
            GetLockType();
            IResultModel result;
            if (model.LockType == "BAR")
            {
                var CheckBarCode = await _pcsApi.GetBarCodeFromWip(model.WipNO);
                if (!CheckBarCode.Success)
                {
                    ModelState.AddModelError("error", CheckBarCode.Msg);
                    return View(model);
                }
                model.WipNO = (string)CheckBarCode.Msg;
            }


            var q = await _pcsApi.GetWipInfoByWipNO(model.WipNO);
            if (q.Count() == 0)
            {
                ModelState.AddModelError("error", "找不到工單號碼【" + model.WipNO + "】");
                return View(model);
            }

            // 判斷工單是否有該站

            var q1 = await _pcsApi.GetWipLockByWipNO(model.WipNO);

            if (q1.Data.Where(w => w.LockStatus == "0").Count() != 0)
            {
                ModelState.AddModelError("error", "目前此工單號碼【" + model.WipNO + "】尚未解鎖定");
                return View(model);
            }

            if (ModelState.IsValid)
            {
                result = await _pcsApi.PostWipLock(JsonConvert.SerializeObject(model));
                if (result.Success)
                {
                    var _msg = model.WipLockID == 0 ? "新增成功!" : "修改成功!";
                    return RedirectToAction("Refresh", "Home", new { msg = _msg });
                }
                else
                {
                    ModelState.AddModelError("error", result.Msg);
                }
            }

            return View(model);
        }
        #endregion

        #region PCS011 工單對應站別解鎖
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id">WipLockID</param>
        /// <returns></returns>
        public async Task<IActionResult> PCS011(int id)
        {

            var q = await _pcsApi.GetWipLock(id);
            q = q.Where(w => w.UnLockReason == null).ToList();
            await GetStation();
            GetLockReasonType();
            GetLockType();
            //var result = new WipAllViewModel();
            //return View(result);
            return View(q.FirstOrDefault());
        }

        //頁面提交,id=0 添加,id>0 修改
        [HttpPost]
        public async Task<IActionResult> PCS011Async(WipLock model)
        {
            var closeView = true;
            await GetStation();
            GetLockReasonType();
            GetLockType();
            if (model.WipLockID == 0)
            {
                var result_WipLock = await _pcsApi.GetWipLockByWipNO(model.WipNO);
                if (result_WipLock.Data.Where(w => w.LockStatus == "0" && w.StationID == model.StationID)
                    .Count() == 0)
                {
                    ModelState.AddModelError("error", "找不到該筆工單號碼或站別鎖定紀錄");
                    return View();
                }

                model.WipLockID = result_WipLock.Data.FirstOrDefault().WipLockID;
                closeView = false;
            }

            IResultModel result;
            model.UnLockDate = DateTime.Now;
            model.UnLockUserID = 0;
            result = await _pcsApi.PutWipLock(JsonConvert.SerializeObject(model));
            if (result.Success)
            {
                var _msg = "解鎖成功!";
                if (closeView)
                    return RedirectToAction("Refresh", "Home", new { msg = _msg });
                else
                {
                    ModelState.AddModelError("error", _msg);
                    return View();
                }
            }
            else
            {
                ModelState.AddModelError("error", result.Msg);
            }

            return View();
        }

        public async Task<IActionResult> PCS011V(int id)
        {

            var q = await _pcsApi.GetWipLock(id);
            q = q.Where(w => w.UnLockReason == null).ToList();
            await GetStation();
            GetLockReasonType();
            GetLockType();
            //var result = new WipAllViewModel();
            //return View(result);
            return View(q.FirstOrDefault());
        }

        //頁面提交,id=0 添加,id>0 修改
        [HttpPost]
        public async Task<IActionResult> PCS011VAsync(WipLock model)
        {
            await GetStation();
            GetLockReasonType();
            GetLockType();


            IResultModel result;
            model.UnLockDate = DateTime.Now;
            model.UnLockUserID = 0;
            result = await _pcsApi.PutWipLock(JsonConvert.SerializeObject(model));
            if (result.Success)
            {
                var _msg = "解鎖成功!";
                return RedirectToAction("Refresh", "Home", new { msg = _msg });
            }
            else
            {
                ModelState.AddModelError("error", result.Msg);
            }

            return View();
        }
        #endregion

        #region PCS012 製程工單鎖定查詢
        [ResponseCache(Duration = 0)]
        [HttpGet]
        public async Task<IActionResult> PCS012()
        {
            await GetStation();
            GetLockReasonType();
            GetLockType();
            return View();
        }

        /// <summary>
        /// PCS012 Query
        /// </summary>
        /// <param name="lockStatus">工單狀態:鎖定|解鎖</param>
        /// <param name="lockType">鎖定類型</param>
        /// <param name="lockReasonType">鎖定原因類別</param>
        /// <param name="stations">站別</param>
        /// <param name="wipNO">工單</param>
        /// <param name="itemNO">料號</param>
        /// <param name="dateStr">鎖定日期起</param>
        /// <param name="dateEnd">鎖定日期迄</param>
        /// <returns></returns>
        public async Task<IActionResult> PCS012QueryAsync(string lockStatus, string lockType, string lockReasonType, string stations,
            string wipNO, string itemNO, string dateStr, string dateEnd, int page = 0, int limit = 10)
        {
            IResultModel<WipLockDto> result = await _pcsApi.GetWipLockQuery(lockStatus: lockStatus, lockType: lockType, lockReasonType: lockReasonType,
                stations: stations, wipNO: wipNO, itemNO: itemNO, date_str: dateStr, date_end: dateEnd
                , page);

            if (result.Data.Count() != 0)
            {
                return Json(new Table() { code = 0, msg = "", data = result.Data, count = result.DataTotal });
            }
            return Json(new Table() { count = 0, data = null });
        }

        #endregion

        #region PCS013 條碼鎖定
        public IActionResult PCS013()
        {
            return View();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="model"></param>
        /// <param name="select">0:內部條碼 1:工單號碼 2:條碼區間</param>
        /// <returns></returns>
        [HttpPost]

        public async Task<IActionResult> PCS013Async(PCS013ViewModel model, string select)
        {
            IResultModel result;
            var _msg = string.Empty;
            // 內部條碼
            if (select == "0")
            {
                if (string.IsNullOrWhiteSpace(model.BarCodeNo))
                {
                    ModelState.AddModelError("error", "請輸入內部條碼");
                    return View(model);
                }

                var q = await _pcsApi.GetBarcodeInfoesByNo(model.BarCodeNo);
                if (q.Count == 0)
                {
                    ModelState.AddModelError("error", "內部序號【" + model.BarCodeNo + "】,找不到");
                    return View(model);
                }

                // 判斷是否有鎖定中
                var q1 = await _pcsApi.GetBarcodeLockByBarCodeID(q.FirstOrDefault().BarcodeID);
                if (q1.Where(w => w.LockStatus == 0).Count() != 0)
                {
                    ModelState.AddModelError("error", "目前內部序號【" + model.BarCodeNo + "】尚未解鎖定");
                    return View(model);
                }

                BarcodeLock barcodeLock = new BarcodeLock
                {
                    BarcodeID = q.FirstOrDefault().BarcodeID,
                    WipID = q.FirstOrDefault().WipID,
                    StatusID = q.FirstOrDefault().StatusID,
                    LockStatus = 0,
                    LockReason = model.LockReason,
                    LockUserID = 0
                };
                result = await _pcsApi.PostBarcodeLock(JsonConvert.SerializeObject(barcodeLock));
                if (result.Success)
                {
                    _msg = "條碼鎖定成功!";
                    return RedirectToAction("Refresh", "Home", new { msg = _msg });
                }
                else
                {
                    ModelState.AddModelError("error", "條碼鎖定失敗!");
                    return View(model);
                }
            }


            // 工單號碼
            if (select == "1")
            {
                if (string.IsNullOrWhiteSpace(model.WipNo))
                {
                    ModelState.AddModelError("error", "請輸入工單號碼");
                    return View(model);
                }

                var q = await _pcsApi.GetWipBarcode(model.WipNo);
                if (q.Count() == 0)
                {
                    ModelState.AddModelError("error", "工單號碼【" + model.WipNo + "】,找不到內部序號");
                    return View(model);
                }

                var q1 = await _pcsApi.GetBarcodeInfoesByWipNo(model.WipNo);
                if (q1.Count() == 0)
                {
                    ModelState.AddModelError("error", "工單號碼【" + model.WipNo + "】,尚未投入");
                    return View(model);
                }

                foreach (var item in q1)
                {
                    // 判斷是否有鎖定中
                    var q2 = await _pcsApi.GetBarcodeLockByBarCodeID(item.BarcodeID);
                    if (q2.Where(w => w.LockStatus == 0).Any())
                    {
                        _msg += "目前內部序號【" + item.BarcodeNo + "】尚未解鎖</br>";
                    }
                    else
                    {
                        BarcodeLock barcodeLock = new BarcodeLock
                        {
                            BarcodeID = item.BarcodeID,
                            WipID = item.WipID,
                            StatusID = item.StatusID,
                            LockStatus = 0,
                            LockReason = model.LockReason,
                            LockUserID = 0
                        };
                        result = await _pcsApi.PostBarcodeLock(JsonConvert.SerializeObject(barcodeLock));
                        if (result.Success)
                        {
                            _msg += "目前內部序號【" + item.BarcodeNo + "】條碼鎖定成功!</br>";

                        }
                        else
                        {
                            _msg += "目前內部序號【" + item.BarcodeNo + "】條碼鎖定失敗!</br>";
                        }
                    }
                }

                return RedirectToAction("Refresh", "Home", new { msg = _msg });
            }


            // 條碼區間
            if (select == "2")
            {
                if (string.IsNullOrWhiteSpace(model.BarCodeNoStr) || string.IsNullOrWhiteSpace(model.BarCodeNoEnd))
                {
                    ModelState.AddModelError("error", "請確定都有輸入條碼區間");
                    return View(model);
                }

                if (model.BarCodeNoStr.Length != model.BarCodeNoEnd.Length)
                {
                    ModelState.AddModelError("error", "條碼區間起訖長度不相同");
                    return View(model);
                }

                if (model.BarCodeNoStr.Length <= NoLength || model.BarCodeNoEnd.Length <= NoLength)
                {
                    ModelState.AddModelError("error", "條碼區間號碼長度不能小於" + NoLength + 1);
                    return View(model);
                }

                if (model.BarCodeNoStr.Substring(0, model.BarCodeNoStr.Length - NoLength) !=
                    model.BarCodeNoEnd.Substring(0, model.BarCodeNoEnd.Length - NoLength))
                {
                    ModelState.AddModelError("error", "條碼區間前置號碼不一樣");
                    return View(model);
                }


                if (!int.TryParse(model.BarCodeNoStr.Substring(model.BarCodeNoStr.Length - NoLength, NoLength), out _) ||
                    !int.TryParse(model.BarCodeNoEnd.Substring(model.BarCodeNoEnd.Length - NoLength, NoLength), out _))
                {
                    ModelState.AddModelError("error", "條碼區間流水碼格式錯誤");
                    return View(model);
                }

                var NoStr = int.Parse(model.BarCodeNoStr.Substring(model.BarCodeNoStr.Length - NoLength, NoLength));
                var NoEnd = int.Parse(model.BarCodeNoEnd.Substring(model.BarCodeNoEnd.Length - NoLength, NoLength));
                if (NoStr > NoEnd)
                {
                    ModelState.AddModelError("error", "條碼區間結束流水碼不可以小於條碼區間起始流水碼");
                    return View(model);
                }

                var BarCode = model.BarCodeNoEnd.Substring(0, model.BarCodeNoEnd.Length - NoLength);

                for (int i = NoStr; i <= NoEnd; i++)
                {
                    var itemBarcodeNo = BarCode + i.ToString().PadLeft(NoLength, '0');
                    var q_BarcodeInfo = await _pcsApi.GetBarcodeInfoesByNo(itemBarcodeNo);

                    if (q_BarcodeInfo.Count != 0)
                    {
                        // 判斷是否有鎖定中
                        var q2 = await _pcsApi.GetBarcodeLockByBarCodeID(q_BarcodeInfo.FirstOrDefault().BarcodeID);
                        if (q2.Where(w => w.LockStatus == 0).Any())
                        {
                            _msg += "目前內部序號【" + itemBarcodeNo + "】尚未解鎖</br>";
                        }
                        else
                        {
                            BarcodeLock barcodeLock = new BarcodeLock
                            {
                                BarcodeID = q_BarcodeInfo.FirstOrDefault().BarcodeID,
                                WipID = q_BarcodeInfo.FirstOrDefault().WipID,
                                StatusID = q_BarcodeInfo.FirstOrDefault().StatusID,
                                LockStatus = 0,
                                LockReason = model.LockReason,
                                LockUserID = 0
                            };
                            result = await _pcsApi.PostBarcodeLock(JsonConvert.SerializeObject(barcodeLock));
                            if (result.Success)
                            {
                                _msg += "目前內部序號【" + itemBarcodeNo + "】條碼鎖定成功!</br>";

                            }
                            else
                            {
                                _msg += "目前內部序號【" + itemBarcodeNo + "】條碼鎖定失敗!</br>";
                            }

                        }
                    }
                }
                return RedirectToAction("Refresh", "Home", new { msg = _msg });
            }
            return View(model);
        }
        #endregion

        #region PCS014 條碼解鎖
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id">WipLockID</param>
        /// <returns></returns>
        public IActionResult PCS014(string id)
        {
            PCS014ViewModel model = new PCS014ViewModel();
            model.BarCodeNo = id;
            //var result = new WipAllViewModel();
            //return View(result);
            return View(model);
        }

        //頁面提交,id=0 添加,id>0 修改
        [HttpPost]
        public async Task<IActionResult> PCS014Async(PCS014ViewModel model, string select)
        {
            IResultModel result;
            var _msg = string.Empty;
            // 內部條碼
            if (select == "0")
            {
                if (string.IsNullOrWhiteSpace(model.BarCodeNo))
                {
                    ModelState.AddModelError("error", "請輸入內部條碼");
                    return View(model);
                }

                var q = await _pcsApi.GetBarcodeInfoesByNo(model.BarCodeNo);
                if (q.Count == 0)
                {
                    ModelState.AddModelError("error", "內部序號【" + model.BarCodeNo + "】,找不到");
                    return View(model);
                }

                // 判斷是否有鎖定中
                var q1 = await _pcsApi.GetBarcodeLockByBarCodeID(q.FirstOrDefault().BarcodeID);
                if (q1.Where(w => w.LockStatus == 0).Count() == 0)
                {
                    ModelState.AddModelError("error", "目前內部序號【" + model.BarCodeNo + "】尚未鎖定");
                    return View(model);
                }

                BarcodeLock barcodeLock = q1.Where(w => w.LockStatus == 0).FirstOrDefault();
                barcodeLock.LockStatus = 1;
                barcodeLock.UnLockReason = model.UnLockReason;
                barcodeLock.UnLockUserID = 0;
                barcodeLock.UnLockDate = System.DateTime.Now;
                var aaa = JsonConvert.SerializeObject(barcodeLock);
                result = await _pcsApi.PutBarcodeLock(JsonConvert.SerializeObject(barcodeLock));
                if (result.Success)
                {
                    _msg = "條碼解鎖成功!";
                    return RedirectToAction("Refresh", "Home", new { msg = _msg });
                }
                else
                {
                    ModelState.AddModelError("error", "條碼解鎖失敗!");
                    return View(model);
                }
            }


            // 工單號碼
            if (select == "1")
            {
                if (string.IsNullOrWhiteSpace(model.WipNo))
                {
                    ModelState.AddModelError("error", "請輸入工單號碼");
                    return View(model);
                }

                var q = await _pcsApi.GetWipBarcode(model.WipNo);
                if (q.Count() == 0)
                {
                    ModelState.AddModelError("error", "工單號碼【" + model.WipNo + "】,找不到內部序號");
                    return View(model);
                }

                var q1 = await _pcsApi.GetBarcodeInfoesByWipNo(model.WipNo);

                foreach (var item in q1)
                {
                    // 判斷是否有鎖定中
                    var q2 = await _pcsApi.GetBarcodeLockByBarCodeID(item.BarcodeID);
                    if (q2.Where(w => w.LockStatus == 0).Count() == 0)
                    {
                        _msg += "目前內部序號【" + item.BarcodeNo + "】尚未鎖定</br>";
                    }
                    else
                    {
                        BarcodeLock barcodeLock = q2.Where(w => w.LockStatus == 0).FirstOrDefault();
                        barcodeLock.LockStatus = 1;
                        barcodeLock.UnLockReason = model.UnLockReason;
                        barcodeLock.UnLockUserID = 0;
                        barcodeLock.UnLockDate = System.DateTime.Now;
                        result = await _pcsApi.PutBarcodeLock(JsonConvert.SerializeObject(barcodeLock));
                        if (result.Success)
                        {
                            _msg += "目前內部序號【" + item.BarcodeNo + "】條碼解鎖成功!</br>";

                        }
                        else
                        {
                            _msg += "目前內部序號【" + item.BarcodeNo + "】條碼解鎖失敗!</br>";
                        }
                    }
                }

                return RedirectToAction("Refresh", "Home", new { msg = _msg });
            }


            // 條碼區間
            if (select == "2")
            {
                if (string.IsNullOrWhiteSpace(model.BarCodeNoStr) || string.IsNullOrWhiteSpace(model.BarCodeNoEnd))
                {
                    ModelState.AddModelError("error", "請確定都有輸入條碼區間");
                    return View(model);
                }

                if (model.BarCodeNoStr.Length != model.BarCodeNoEnd.Length)
                {
                    ModelState.AddModelError("error", "條碼區間起訖長度不相同");
                    return View(model);
                }

                // 流水碼預設長度
                int NoLength = 4;
                if (model.BarCodeNoStr.Length <= NoLength || model.BarCodeNoEnd.Length <= NoLength)
                {
                    ModelState.AddModelError("error", "條碼區間號碼長度不能小於" + NoLength + 1);
                    return View(model);
                }

                if (model.BarCodeNoStr.Substring(0, model.BarCodeNoStr.Length - NoLength) !=
                    model.BarCodeNoEnd.Substring(0, model.BarCodeNoEnd.Length - NoLength))
                {
                    ModelState.AddModelError("error", "條碼區間前置號碼不一樣");
                    return View(model);
                }


                if (!int.TryParse(model.BarCodeNoStr.Substring(model.BarCodeNoStr.Length - NoLength, NoLength), out _) ||
                    !int.TryParse(model.BarCodeNoEnd.Substring(model.BarCodeNoEnd.Length - NoLength, NoLength), out _))
                {
                    ModelState.AddModelError("error", "條碼區間流水碼格式錯誤");
                    return View(model);
                }

                var NoStr = int.Parse(model.BarCodeNoStr.Substring(model.BarCodeNoStr.Length - NoLength, NoLength));
                var NoEnd = int.Parse(model.BarCodeNoEnd.Substring(model.BarCodeNoEnd.Length - NoLength, NoLength));
                if (NoStr > NoEnd)
                {
                    ModelState.AddModelError("error", "條碼區間結束流水碼不可以小於條碼區間起始流水碼");
                    return View(model);
                }

                var BarCode = model.BarCodeNoEnd.Substring(0, model.BarCodeNoEnd.Length - NoLength);

                for (int i = NoStr; i <= NoEnd; i++)
                {
                    var itemBarcodeNo = BarCode + i.ToString().PadLeft(NoLength, '0');
                    var q_BarcodeInfo = await _pcsApi.GetBarcodeInfoesByNo(itemBarcodeNo);

                    if (q_BarcodeInfo.Count != 0)
                    {
                        // 判斷是否有鎖定中
                        var q2 = await _pcsApi.GetBarcodeLockByBarCodeID(q_BarcodeInfo.FirstOrDefault().BarcodeID);
                        if (q2.Where(w => w.LockStatus == 0).Count() == 0)
                        {
                            _msg += "目前內部序號【" + itemBarcodeNo + "】尚未鎖定</br>";
                        }
                        else
                        {
                            BarcodeLock barcodeLock = q2.Where(w => w.LockStatus == 0).FirstOrDefault();
                            barcodeLock.LockStatus = 1;
                            barcodeLock.UnLockReason = model.UnLockReason;
                            barcodeLock.UnLockUserID = 0;
                            barcodeLock.UnLockDate = System.DateTime.Now;
                            result = await _pcsApi.PutBarcodeLock(JsonConvert.SerializeObject(barcodeLock));
                            if (result.Success)
                            {
                                _msg += "目前內部序號【" + itemBarcodeNo + "】條碼解鎖成功!</br>";

                            }
                            else
                            {
                                _msg += "目前內部序號【" + itemBarcodeNo + "】條碼解鎖失敗!</br>";
                            }

                        }
                    }
                }
                return RedirectToAction("Refresh", "Home", new { msg = _msg });
            }
            return View();
        }
        #endregion

        #region PCS015 鎖定條碼資料查詢
        [ResponseCache(Duration = 0)]
        [HttpGet]
        public IActionResult PCS015()
        {
            return View();
        }

        /// <summary>
        /// PCS015 Query
        /// </summary>
        /// <param name="barCodeNo">內部條碼</param>
        /// <param name="wipNO">工單</param>
        /// <param name="itemNO">料號</param>
        /// <param name="lockStatus">工單狀態:鎖定|解鎖</param>
        /// <param name="dateStr">鎖定日期起</param>
        /// <param name="dateEnd">鎖定日期迄</param>
        /// <returns></returns>
        public async Task<IActionResult> PCS015QueryAsync(string barCodeNo, string wipNO, string itemNO,
           string lockStatus, string dateStr, string dateEnd, int page = 0, int limit = 10)
        {
            IResultModel<BarcodeLockDto> result = await _pcsApi.GetBarcodeLockQuery(barCodeNo: barCodeNo,
                wipNo: wipNO, itemNo: itemNO, lockStatus: lockStatus, date_Str: dateStr, date_End: dateEnd
                , page: page, limit: limit);

            if (result.Data.Count() != 0)
            {
                return Json(new Table() { code = 0, msg = "", data = result.Data, count = result.DataTotal });
            }
            return Json(new Table() { count = 0, data = null });
        }
        #endregion

        #region PCS017 工單出貨條碼區間設定
        [ResponseCache(Duration = 0)]
        [HttpGet]
        public async Task<IActionResult> PCS017()
        {
            await GetFactoryUnit();
            return View();
        }

        /// <summary>
        /// PCS018 Query
        /// </summary>
        /// <param name="unitno">生產單位</param>
        /// <param name="wipno">工單號碼</param>
        /// <returns></returns>
        public async Task<IActionResult> PCS017QueryAsync(string unitno, string wipno, int page = 0, int limit = 10)
        {
            IResultModel<dynamic> result = await _pcsApi.GetWipInfoSelectParameter(unitno: unitno
                , wipno: wipno
                , page: page
                , limit: limit);

            if (result.Data != null)
            {
                return Json(new Table() { code = 0, msg = "", data = result.Data, count = result.DataTotal });
            }
            return Json(new Table() { count = 0, data = null });
        }


        [HttpPost]
        public async Task<IActionResult> PCS017CAsync(PCS004CViewModel model)
        {
            await GetLineInfo();
            await GetFlowRuleList();

            //var aa = GetBarcodeOther(model.WipAtt.ItemNO, model.WipInfo.Werks.Substring(2, 2), model.WipInfo.PlanQTY, model.WipInfo.WipNO , model.WipInfo.WipScheduleDate);

            IResultModel result;
            model.WipBarcode.WipNO = model.WipInfo.WipNO;
            //model.WipBarcode.WipID = model.WipInfo.WipID;
            //model.WipBarcode.UnitNO = model.WipInfo.UnitNO;

            result = await _pcsApi.PostWipBarcode(JsonConvert.SerializeObject(model.WipBarcode));

            if (result.Success)
            {
                var _msg = "新增成功!";
                return RedirectToAction("PCS018C", "PCS", new { id = model.WipInfo.WipID, msg = _msg });
            }
            else
            {
                if (result.Errors.Count > 0)
                {
                    ModelState.AddModelError(result.Errors[0].Id, result.Errors[0].Msg);
                }
                else
                {
                    ModelState.AddModelError("error", result.Msg);
                }
            }

            return RedirectToAction("PCS018C", "PCS", new { id = model.WipInfo.WipID });
        }

        public async Task<IActionResult> PCS017C(int id, string msg = null)
        {
            ViewBag.Msg = msg;
            await GetLineInfo();
            await GetFlowRuleList();
            PCS004CViewModel model = new PCS004CViewModel();
            var q = await _pcsApi.GetWipInfo(id);
            if (q.Count != 0)
            {
                model.WipInfo = q.FirstOrDefault();
                model.WipAtt = await _pcsApi.GetWipAtt(model.WipInfo.WipNO);
                model.WipBarcodeOther = await _pcsApi.GetWipBarcodeOther(model.WipInfo.WipNO);
                model.RuleStation = await _basApi.GetRuleStationsByFlow(model.WipInfo.FlowRuleID);
                model.WipInfo.WipType = model.WipInfo.WipType == "S" ? "標準工單" : "重工工單";
                //model.RuleStation = model.RuleStation.OrderBy(o => o.Sequence);
            }
            return View(model);
        }

        public async Task<IActionResult> PCS017R(int id)
        {
            await GetLineInfo();
            await GetFlowRuleList();
            PCS004CViewModel model = new PCS004CViewModel();
            var q = await _pcsApi.GetWipInfo(id);
            if (q.Count != 0)
            {
                model.WipInfo = q.FirstOrDefault();
                model.WipAtt = await _pcsApi.GetWipAtt(model.WipInfo.WipNO);
                model.WipBarcodes = await _pcsApi.GetWipBarcode(model.WipInfo.WipNO);
                model.RuleStation = await _basApi.GetRuleStationsByFlow(model.WipInfo.FlowRuleID);
                model.WipInfo.WipType = model.WipInfo.WipType == "S" ? "標準工單" : "重工工單";
                //model.RuleStation = model.RuleStation.OrderBy(o => o.Sequence);
            }
            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> PCS017D(string WipNo, string StrNo, string EndNo)
        {
            //var result = await _pcsApi.de(WipNo, StrNo, EndNo);
            return Json(new Result() { success = true, msg = "" });
        }
        #endregion

        #region PCS018 重工工單內部條碼區間設定
        [ResponseCache(Duration = 0)]
        [HttpGet]
        public async Task<IActionResult> PCS018()
        {
            await GetFactoryUnit();
            return View();
        }

        /// <summary>
        /// PCS018 Query
        /// </summary>
        /// <param name="unitno">生產單位</param>
        /// <param name="wipno">工單號碼</param>
        /// <returns></returns>
        public async Task<IActionResult> PCS018QueryAsync(string unitno, string wipno, int page = 0, int limit = 10)
        {
            IResultModel<dynamic> result = await _pcsApi.GetWipInfoSelectParameter(unitno: unitno
                , wipno: wipno
                , wipType: "R"
                , page: page
                , limit: limit);

            if (result.Data != null)
            {
                return Json(new Table() { code = 0, msg = "", data = result.Data, count = result.DataTotal });
            }
            return Json(new Table() { count = 0, data = null });
        }

        //頁面提交,id=0 添加,id>0 修改
        [HttpPost]
        public async Task<IActionResult> PCS018CAsync(PCS004CViewModel model)
        {
            await GetLineInfo();
            await GetFlowRuleList();

            // 起訖序號沒填寫 或者 綁定序號沒填寫
            if ((string.IsNullOrWhiteSpace(model.WipBarcode.StartNO) || string.IsNullOrWhiteSpace(model.WipBarcode.EndNO))
                && string.IsNullOrWhiteSpace(model.BarcodeNo))
            {
                ModelState.AddModelError("error", "請確認新增的條碼是否有填寫?");
                return View(model);
            }

            if ((!string.IsNullOrWhiteSpace(model.WipBarcode.StartNO) || !string.IsNullOrWhiteSpace(model.WipBarcode.EndNO))
             && !string.IsNullOrWhiteSpace(model.BarcodeNo))
            {
                ModelState.AddModelError("error", "請則一選擇要新增條碼的方式?");
                return View(model);
            }

            // 既有序號綁定
            if (!string.IsNullOrWhiteSpace(model.BarcodeNo))
            {
                // 內部序號
                if (model.Type == "SN")
                {
                    if (_pcsApi.GetBarcodeInfoesByNo(model.BarcodeNo).InvokeAsync().Result.Count() == 0)
                    {
                        ModelState.AddModelError("error", "綁定序號【" + model.BarcodeNo + "】,找不到已綁定的內部序號");
                        return View(model);
                    }
                }
                // 出貨序號
                else if (model.Type == "SSN")
                {
                    var resultExtraNo = await _pcsApi.GetBarcodeInfoesByExtraNo(model.BarcodeNo);
                    if (resultExtraNo.Count() == 0)
                    {
                        ModelState.AddModelError("error", "綁定序號【" + model.BarcodeNo + "】,找不到已綁定的出貨序號");
                        return View(model);
                    }
                    else
                        model.BarcodeNo = resultExtraNo.FirstOrDefault().BarcodeNo;
                }

                model.WipBarcode.StartNO = model.BarcodeNo;
                model.WipBarcode.EndNO = model.BarcodeNo;
            }


            // 流水碼預設長度
            string _msg = string.Empty;
            int WipQty = model.WipInfo.PlanQTY;
            string InputStartNo = model.WipBarcode.StartNO.Trim();
            string InputEndNo = model.WipBarcode.EndNO.Trim();

            if (model.WipBarcodes == null)
            {
                model.WipBarcodes = new List<WipBarcode>();
            }

            if (InputStartNo.Length <= NoLength || InputEndNo.Length <= NoLength)
            {
                _msg += "條碼區間號碼長度不能小於" + (NoLength + 1);
                ModelState.AddModelError("error", _msg);
                return View(model);
            }

            if (InputStartNo.Length != InputEndNo.Length)
            {
                _msg += "起始條碼與結束條碼字串長度不一致";
                ModelState.AddModelError("error", _msg);
                return View(model);
            }

            if (InputStartNo.Substring(0, InputStartNo.Length - NoLength) !=
                InputEndNo.Substring(0, InputEndNo.Length - NoLength))
            {
                _msg += "條碼區間前置號碼不一樣";
                ModelState.AddModelError("error", _msg);
                return View(model);
            }


            if (!int.TryParse(InputStartNo.Substring(InputStartNo.Length - NoLength, NoLength), out _) ||
                !int.TryParse(InputEndNo.Substring(InputEndNo.Length - NoLength, NoLength), out _))
            {
                _msg += "條碼區間流水碼格式錯誤";
                ModelState.AddModelError("error", _msg);
                return View(model);
            }

            // 計算設定條碼區間是否有大於工單數
            int sum = 0;
            // 起始流水碼
            int InputStrNoQty = int.Parse(InputStartNo.Substring(InputStartNo.Length - NoLength, NoLength));
            // 結束流水碼
            int InputEndNoQty = int.Parse(InputEndNo.Substring(InputEndNo.Length - NoLength, NoLength));

            if (InputEndNoQty < InputStrNoQty)
            {
                _msg += "結束流水碼不可以小於起始流水碼";
                ModelState.AddModelError("error", _msg);
                return View(model);
            }

            if (model.WipBarcodes != null)
            {
                // 計算目前已經使用的條碼區間數量
                foreach (var item in model.WipBarcodes)
                {
                    int OldStrNo = int.Parse(item.StartNO.Substring(item.StartNO.Length - NoLength, NoLength));
                    int OldEndNo = int.Parse(item.EndNO.Substring(item.EndNO.Length - NoLength, NoLength));

                    // 判斷是否有設定重複區間
                    if (item.StartNO.Substring(0, item.StartNO.Length - NoLength) ==
                        InputStartNo.Substring(0, InputStartNo.Length - NoLength))
                    {
                        if ((OldStrNo <= InputStrNoQty && InputStrNoQty <= OldEndNo) ||
                            (OldStrNo <= InputEndNoQty && InputEndNoQty <= OldEndNo))
                        {
                            _msg += "設定條碼區間有重複,請確認!";
                            ModelState.AddModelError("error", _msg);
                            return View(model);
                        }
                    }
                    sum = OldEndNo - OldStrNo - +1;
                }
            }

            if (WipQty < sum + (InputEndNoQty - InputStrNoQty + 1))
            {
                _msg += "工單號碼【" + model.WipInfo.WipNO + "】 設定條碼區間數量已超過工單數量,請確認!";
                ModelState.AddModelError("error", _msg);
                return View(model);
            }

            IResultModel result;
            model.WipBarcode.WipNO = model.WipInfo.WipNO;
            //model.WipBarcode.WipID = model.WipInfo.WipID;
            //model.WipBarcode.UnitNO = model.WipInfo.UnitNO;

            result = await _pcsApi.PostWipBarcode(JsonConvert.SerializeObject(model.WipBarcode));

            if (result.Success)
            {
                _msg = "新增成功!";
                return RedirectToAction("PCS018C", "PCS", new { id = model.WipInfo.WipID, msg = _msg });
            }
            else
            {
                if (result.Errors.Count > 0)
                {
                    ModelState.AddModelError(result.Errors[0].Id, result.Errors[0].Msg);
                }
                else
                {
                    ModelState.AddModelError("error", result.Msg);
                }
            }

            return RedirectToAction("PCS018C", "PCS", new { id = model.WipInfo.WipID });
        }

        public async Task<IActionResult> PCS018C(int id, string msg = null)
        {
            ViewBag.Msg = msg;
            await GetLineInfo();
            await GetFlowRuleList();
            PCS004CViewModel model = new PCS004CViewModel();
            var q = await _pcsApi.GetWipInfo(id);
            if (q.Count != 0)
            {
                model.WipInfo = q.FirstOrDefault();
                model.WipAtt = await _pcsApi.GetWipAtt(model.WipInfo.WipNO);
                model.WipBarcodes = await _pcsApi.GetWipBarcode(model.WipInfo.WipNO);
                model.RuleStation = await _basApi.GetRuleStationsByFlow(model.WipInfo.FlowRuleID);
                model.WipInfo.WipType = model.WipInfo.WipType == "S" ? "標準工單" : "重工工單";
                //model.RuleStation = model.RuleStation.OrderBy(o => o.Sequence);
            }
            return View(model);
        }

        public async Task<IActionResult> PCS018R(int id)
        {
            await GetLineInfo();
            await GetFlowRuleList();
            PCS004CViewModel model = new PCS004CViewModel();
            var q = await _pcsApi.GetWipInfo(id);
            if (q.Count != 0)
            {
                model.WipInfo = q.FirstOrDefault();
                model.WipAtt = await _pcsApi.GetWipAtt(model.WipInfo.WipNO);
                model.WipBarcodes = await _pcsApi.GetWipBarcode(model.WipInfo.WipNO);
                model.RuleStation = await _basApi.GetRuleStationsByFlow(model.WipInfo.FlowRuleID);
                model.WipInfo.WipType = model.WipInfo.WipType == "S" ? "標準工單" : "重工工單";
                //model.RuleStation = model.RuleStation.OrderBy(o => o.Sequence);
            }
            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> PCS018D(string WipNo, string StrNo, string EndNo)
        {
            var result = await _pcsApi.DeleteWipBarcode(WipNo, StrNo, EndNo);
            return Json(new Result() { success = true, msg = "" });
        }
        #endregion

        #region PCS019 條碼遺漏查詢
        [ResponseCache(Duration = 0)]
        [HttpGet]
        public ActionResult PCS019()
        {
            return View();
        }

        /// <summary>
        /// PCS019 Query
        /// </summary>
        /// <param name="wipNo">工單號碼</param>
        /// <param name="unitNo">生產單位</param>
        /// <param name="stations">作業站</param>
        /// <returns></returns>
        public async Task<IActionResult> PCS019QueryAsync(string wipNo, string unitNo, int stations, int page = 0, int limit = 10)
        {
            string barcodeNo = string.Empty;
            string stationName = string.Empty;
            int ruleStation = 0;
            // retrue View
            List<dynamic> DataList = new List<dynamic>();
            // 流程
            var result_RuleStation = new List<RuleStationDto>();
            // 條碼區間
            var result_WipBarcode = await _pcsApi.GetWipBarcode(wipNo);

            #region 查詢作業站(ruleStationID)
            var result_WipInfo = await _pcsApi.GetWipInfoByWipNO(wipNo);
            result_WipInfo = result_WipInfo.Where(w => w.UnitNO == unitNo).ToList();

            if (result_WipInfo.Count() != 0)
            {
                // 投入數量 = 0 就離開
                if (result_WipInfo.FirstOrDefault().CompleteQTY == 0)
                {
                    return Json(new Table() { count = 0, data = DataList, msg = "" });
                }

                // 找該流程的作業站
                result_RuleStation = await _pcsApi.GetRuleStationByFlow(result_WipInfo.FirstOrDefault().FlowRuleID);
                if (result_RuleStation.Count() != 0)
                {
                    if (result_RuleStation.Any(w => w.StationID == stations))
                    {
                        ruleStation = result_RuleStation.Where(w => w.StationID == stations).FirstOrDefault().RuleStationID;
                    }
                }
            }
            #endregion

            // 有比對到ruleStationID 才往下跑
            if (ruleStation != 0)
            {
                #region 跑條碼區間資料
                foreach (var item in result_WipBarcode)
                {
                    // 條碼(沒有流水碼)
                    string No = item.StartNO.Substring(0, item.StartNO.Length - NoLength);
                    // 起始流水碼
                    int startNo = int.Parse(item.StartNO.Substring(item.StartNO.Length - NoLength, NoLength));
                    // 迄止流水碼
                    int endNo = int.Parse(item.EndNO.Substring(item.EndNO.Length - NoLength, NoLength));

                    for (int i = startNo; i <= endNo; i++)
                    {
                        barcodeNo = No + i.ToString().PadLeft(NoLength, '0');
                        // 取BarcodeID 
                        var BarcodeInfo = _pcsApi.GetBarcodeInfoesByNo(barcodeNo).InvokeAsync().Result.FirstOrDefault();
                        // 沒有BarcodeID = 尚未投入
                        if (BarcodeInfo == null)
                            stationName = "尚未投入過站";
                        else
                        {
                            var result_BarcodeStation = await _pcsApi.GetBarcodeStationByBarCodeID(BarcodeInfo.BarcodeID);
                            // 判斷BarcodeStation 有RulseStation資料 代表有刷過 不顯示
                            if (result_BarcodeStation.Where(w => w.StationID == stations).Any())
                                continue;
                            else
                            {
                                // 沒有過站紀錄
                                if (result_BarcodeStation.Count() == 0)
                                {
                                    stationName = "尚未投入過站";
                                }
                                // 取得BarInfo 當前站別
                                else
                                {
                                    stationName = result_RuleStation.Where(w => w.StationID == BarcodeInfo.StationID)
                                        .FirstOrDefault().StationDesc;
                                }
                            }
                        }

                        var result = new
                        {
                            barcodeNo = barcodeNo,
                            stations = stationName
                        };
                        DataList.Add(result);
                    }
                }
            }
            #endregion

            return Json(new Table() { count = 0, data = DataList, msg = "" });
        }
        #endregion

        #region PCS021 條碼輸入作業
        [ResponseCache(Duration = 0)]
        [HttpGet]
        public async Task<IActionResult> PCS021()
        {
            var model = new PCS021ViewModel();
            await GetFactoryUnit(false);
            //await GetLineInfo();
            //await GetStation();
            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> PCS021_GetWip(PCS021ViewModel model)
        {
            await GetFactoryUnit(false);
            //await GetItemsList();
            //await GetLineInfo();
            model.KpItemName += "null";
            if (string.IsNullOrWhiteSpace(model.WipNO))
            {
                ModelState.AddModelError("error", "請輸入工單號碼");
            }

            if (string.IsNullOrWhiteSpace(model.UnitNO))
            {
                ModelState.AddModelError("error", "請選擇生產單位");
            }

            if (model.LineID == 0)
            {
                ModelState.AddModelError("error", "請選擇線別");
            }

            var q = await _pcsApi.GetWipInfoByWipNO(model.WipNO);
            q = q.Where(w => w.UnitNO == model.UnitNO).ToList();


            if (q.Count() == 0)
            {
                ModelState.AddModelError("error", "找不到該生產單位的工單號碼");
            }

            if (q.Count != 0)
            {
                model.WipID = q.FirstOrDefault().WipID;
                model.PlanQTY = q.FirstOrDefault().PlanQTY;
                model.UnitNO = q.FirstOrDefault().UnitNO;
                model.FlowRuleID = q.FirstOrDefault().FlowRuleID;
                model.ItemNO = (await _pcsApi.GetWipAtt(model.WipNO)).ItemNO;

                // 判斷工單狀態
                var BarCodeWip = await _pcsApi.CheckBarCodeWip(model.WipNO, model.UnitNO, model.LineID, model.FlowRuleID);
                if (!BarCodeWip.Success)
                {
                    ModelState.AddModelError("error", BarCodeWip.Msg);
                    return View("PCS021", model);
                }

                // 工單流程ID 取站別
                var ruleStations = await GetRuleStationByFlowRuleID(model.FlowRuleID);
                var StationNameSt = ""; // 作業站名稱代碼 提供不二過
                if (model.Station == 0)
                    model.Station = ruleStations.FirstOrDefault().StationID;

                // 取作業站的生產製程
                var stationUnit = string.Empty;
                var station = await _basApi.GetStations(model.Station);
                if (station.Count() != 0)
                {
                    stationUnit = station.FirstOrDefault().UnitNo;
                }
                else
                {
                    ModelState.AddModelError("error", "找不到該作業站的生產單位");
                }

                if (model.Station != 0)
                {
                    if (ruleStations.Where(w => w.StationID == model.Station).Any())
                    {
                        model.RuleStation = ruleStations.Where(w => w.StationID == model.Station).FirstOrDefault().RuleStationID;
                        model.StationTypeNo = ruleStations.Where(w => w.StationID == model.Station).FirstOrDefault().Station.TypeNo;
                        StationNameSt = ruleStations.Where(w => w.StationID == model.Station).FirstOrDefault().Station.StationNameSt;
                    }
                    else
                    {
                        model.RuleStation = ruleStations.FirstOrDefault().RuleStationID;
                        model.StationTypeNo = ruleStations.FirstOrDefault().Station.TypeNo;
                        model.Station = ruleStations.FirstOrDefault().StationID;
                        StationNameSt = ruleStations.FirstOrDefault().Station.StationNameSt;
                    }
                }
                else
                {
                    model.RuleStation = ruleStations.FirstOrDefault().RuleStationID;
                    model.StationTypeNo = ruleStations.FirstOrDefault().Station.TypeNo;
                    model.Station = ruleStations.FirstOrDefault().StationID;
                    StationNameSt = ruleStations.FirstOrDefault().Station.StationNameSt;
                }

                // 工單已刷數量
                model.InputQTY = await _pcsApi.GetBarcodeStationByInputQty(model.WipID, model.Station);

                // 工單KeyParts
                model.WipKps = await _pcsApi.GetWipKpByWipNo(model.WipNO);
                model.WipKps = model.WipKps.Where(w => w.UnitNo == stationUnit).OrderBy(o => o.KpSeq).ToList();

                // 料號檔案
                model.MaterialItem = await _pcsApi.GetMaterialItemByItemNO(model.ItemNO);
                if (model.MaterialItem != null)
                {

                    model.MaterialStationsItems = await _pcsApi.GetMaterialStationsItemByItemID(model.MaterialItem.ItemID);
                    model.MaterialStationsItems = model.MaterialStationsItems.Where(w => w.StationID == model.Station).OrderBy(o => o.StationsItemSeq).ToList();
                    if (model.MaterialStationsItems.Count() != 0)
                    {
                        ModelState.AddModelError("error", "該站別有設定作業工項");
                    }

                    // 治具
                    var q1 = await _pcsApi.GetWipOutfitByWipNo(model.WipNO);
                    q1 = q1.Where(w => (w.UnitNo == model.UnitNO && w.StationID == null) ||
                                       (w.UnitNo == model.UnitNO && w.StationID == model.Station)).ToList();
                    model.wipOutfits.Clear();
                    foreach (var item in q1)
                    {
                        model.wipOutfits.Add(new WipOutfitDtos
                        {
                            OutfitNo = item.OutfitNo,
                            PartNo = item.PartNo,
                            PartNoName = item.PartNoName,
                            StationName = item.StationName,
                            UnitNoName = item.UnitNoName
                        });

                    }
                }

                // 工程工單備註
                var wipsystem = await _pcsApi.GetWipSystem(model.WipNO);
                if (wipsystem != null)
                {
                    if (stationUnit == "B")
                        model.SystemMemo = wipsystem.BabMemo;
                    else if (stationUnit == "T")
                        model.SystemMemo = wipsystem.TestMemo;
                    else if (stationUnit == "P")
                        model.SystemMemo = wipsystem.PackingMemo;
                }

                // KPSeq順序清除
                model.KpItemName = string.Empty;

                // 工單SOP
                var wipSOP = await _pcsApi.GetWipSopByWipNo(model.WipNO);
                // 標準SOP A
                if (wipSOP.Where(w => w.UnitNo == stationUnit && w.SOPType == "A").Any())
                {
                    var wipSOPTypeA = wipSOP.Where(w => w.UnitNo == stationUnit && w.SOPType == "A")
                                            .OrderByDescending(w => w.UpdateTime).FirstOrDefault();
                    var Esop = await _pcsApi.GetDocEsopViewByNo(wipSOPTypeA.SOPName);
                    if (Esop.Count != 0)
                    {
                        model.Sops.Add(new PCS021ViewModel_SOP
                        {
                            SopName = "SOP文件",
                            SopPath = $@"/DocEsop/{Esop.FirstOrDefault().file_path}"
                        });
                    }
                }
                // 差異SOP F
                if (wipSOP.Where(w => w.UnitNo == stationUnit && w.SOPType == "F").Any())
                {
                    var wipSOPTypeF = wipSOP.Where(w => w.UnitNo == stationUnit && w.SOPType == "F")
                                            .OrderByDescending(w => w.UpdateTime).FirstOrDefault();
                    var Esop = await _pcsApi.GetDocEsopViewByNo(wipSOPTypeF.SOPName);
                    if (Esop.Count != 0)
                    {
                        model.Sops.Add(new PCS021ViewModel_SOP
                        {
                            SopName = "差異SOP",
                            SopPath = $@"/DocEsop/{Esop.FirstOrDefault().file_path}"
                        });
                    }
                }
                // 暫行SOP D
                if (wipSOP.Where(w => w.UnitNo == stationUnit && w.SOPType == "D").Any())
                {
                    var wipSOPTypeD = wipSOP.Where(w => w.UnitNo == stationUnit && w.SOPType == "D")
                                            .OrderByDescending(w => w.UpdateTime).FirstOrDefault();
                    var Esop = await _pcsApi.GetEsopBySopName(wipSOPTypeD.SOPName);
                    if (Esop.Count != 0)
                    {
                        model.Sops.Add(new PCS021ViewModel_SOP
                        {
                            SopName = "暫行文件",
                            SopPath = $@"/e-sop/{Esop.FirstOrDefault().Process}/{Esop.FirstOrDefault().SopName}.pdf"
                        });
                    }
                }
                // 不二過
                model.Sops.Add(new PCS021ViewModel_SOP
                {
                    SopName = "不二過",
                    SopPath = "https://qazone.avalue.com.tw/qazone/sfislinktopp.aspx?" +
                              "QA_MFID=YS00" +
                              $"&QA_PRDID={model.ItemNO}" +
                              $"&QA_ROUTEID={StationNameSt}"
                }); ;
            }

            return View("PCS021", model);
        }

        [HttpPost]
        public async Task<IActionResult> PCS021_Input(PCS021ViewModel model)
        {
            // ResultModel
            string Msg = string.Empty;
            bool Success = true;
            string Data = model.Input.ToUpper();
            // 刷入條碼+異常欄位
            if (!string.IsNullOrWhiteSpace(model.InputNo))
                Data += "@" + model.InputNo;

            string ExtNo = string.Empty;

            #region 基本Input 輸入判斷
            if (model.WipID == 0)
                Msg += "請確認是否有輸入工單相關訊息</br>";

            // 當有作業站就必須要填治具編號
            if (model.wipOutfits.Where(w => !string.IsNullOrWhiteSpace(w.StationName) && string.IsNullOrWhiteSpace(w.Inputs)).Any())
                Msg += "請刷入治具編號</br>";

            if (model.Station == 0)
            {
                Msg += "請選擇作業站</br>";
            }

            if (string.IsNullOrWhiteSpace(model.Input))
            {
                Msg += "請刷讀條碼</br>";
            }

            if (!string.IsNullOrWhiteSpace(Msg))
            {
                Success = false;
                return Json(new Result() { success = Success, msg = Msg, data = Data });
            }
            #endregion

            var q = await _pcsApi.CheckBarCodeByWipNo(model.Input, model.WipNO.Trim().ToUpper());
            // 判斷是否序號與工單號碼是否對應條碼區間值,沒對應到視為組件或不良代碼
            if (q.Success)
            {
                #region 確認序號的狀態
                // Input為內部序號
                model.Barcode = true;

                // 取RuleStationID
                var RuleStations = await _basApi.GetRuleStationsByFlow(model.FlowRuleID, 0);
                if (RuleStations.Count != 0)
                {
                    // 抓作業站順序
                    model.RuleStation = RuleStations.Where(w => w.StationID == model.Station).Select(s => s.RuleStationID).FirstOrDefault();
                    model.StationSEQ = RuleStations.Where(w => w.StationID == model.Station).Select(s => s.Sequence).FirstOrDefault();
                }
                // 判斷是否有$符號,代表有不良代碼
                if (model.Inputs.Where(w => w.Input.Contains("$")).Any())
                {
                    model.BarcodeNG = true;
                    // 判斷是否為投入站,投入站不能刷不良
                    //if (model.StationSEQ == 1)
                    //{
                    //    Msg += "投入站不能刷不良代碼</br>";
                    //}

                    if (!string.IsNullOrWhiteSpace(Msg))
                    {
                        Success = false;
                        return Json(new Result() { success = Success, msg = Msg, data = Data });
                    }
                }

                // 取作業站的生產製程
                var stationUnit = string.Empty;
                var station = await _basApi.GetStations(model.Station);
                if (station.Count() != 0)
                {
                    stationUnit = station.FirstOrDefault().UnitNo;
                }
                var keyParts = new List<BarCodeCheckDto.inputItem>();

                // 先查詢已綁定組件數量
                var BarCodeItems = await _pcsApi.GetBarcodeItemByBarCode(model.Input);
                BarCodeItems = BarCodeItems.Where(w => w.S.UnitNo == stationUnit).ToList();

                //  WipKps - BarCodeItem 剩下未綁定的KpNo
                var ExceptWipKp = model.WipKps.ToList();
                foreach (var item in BarCodeItems)
                {
                    var ByItemWipKp = ExceptWipKp.Where(w => w.KpNo.Trim().ToUpper() == item.ItemNo.Trim().ToUpper()).FirstOrDefault();
                    if (ByItemWipKp != null)
                        ExceptWipKp.Remove(ByItemWipKp);
                }

                //  KeyParts代碼順序
                var SpecifyKeyPartsNo = model.KpItemName == null ? new List<string>() : model.KpItemName.Split(',').ToList();
                int KpItemQty = BarCodeItems.Count();
                int i = 0;

                // 判斷指定KeyParts代碼是否有刷足夠數
                if (SpecifyKeyPartsNo.Count() > model.Inputs.Where(w => !w.Input.StartsWith("$")).Count())
                {
                    Msg = "有指定KeyParts代號 刷入數量不足,請在確認!";
                    return Json(new Result() { success = false, msg = Msg, data = Data });
                }

                foreach (var KeyPartItem in model.Inputs)
                {
                    // 判斷是組件先+1
                    if (!KeyPartItem.Input.StartsWith("$"))
                        i += 1;

                    // 當刷入組組件+已紀錄組件數量 大於 設定組件數量
                    if (i + KpItemQty > model.WipKps.Count())
                    {
                        Msg = "已刷超過組件數量";
                        Success = false;
                        return Json(new Result() { success = Success, msg = Msg, data = Data });
                    }

                    // NG代碼
                    if (KeyPartItem.Input.StartsWith("$"))
                    {
                        keyParts.Add(new BarCodeCheckDto.inputItem
                        {
                            inputType = "NG",
                            inputData = KeyPartItem.Input,
                            oldInputData = KeyPartItem.InputNo,
                            kpItemNo = ""
                        });
                    }
                    else // KeaParts
                    {
                        // 判斷是否有輸入KeyParts代碼順序
                        // 有指定KeyParts順序
                        if (i <= SpecifyKeyPartsNo.Count())
                        {
                            var WipKp = ExceptWipKp.Where(w => w.KpNoName.ToUpper() == SpecifyKeyPartsNo[i - 1].ToUpper()).FirstOrDefault();
                            // 比對資料為空時
                            if (WipKp == null)
                            {
                                Msg = $"請確認KeyParts代號【{SpecifyKeyPartsNo[i - 1].ToUpper()}】是否數量全數已綁定?";
                                return Json(new Result() { success = false, msg = Msg, data = Data });
                            }

                            keyParts.Add(new BarCodeCheckDto.inputItem
                            {
                                inputType = WipKp.KpNo,
                                inputData = KeyPartItem.Input,
                                oldInputData = KeyPartItem.InputNo,
                                kpItemNo = WipKp.KpName
                            });
                        }
                        else
                        {
                            var WipKp = ExceptWipKp.Where(w => !SpecifyKeyPartsNo.Any(w1 => w1.ToUpper().Contains(w.KpNoName.ToUpper())))
                                                          .ToList();
                            // 排除有指定數量,其他按照WipKp順序取值
                            var k = i - 1 - SpecifyKeyPartsNo.Count();
                            keyParts.Add(new BarCodeCheckDto.inputItem
                            {
                                inputType = WipKp[k].KpNo,
                                inputData = KeyPartItem.Input,
                                oldInputData = KeyPartItem.InputNo,
                                kpItemNo = WipKp[k].KpName
                            });
                        }
                    }
                }

                // 治具
                var outfit = new List<BarCodeCheckDto.Outfit>();
                foreach (var outfitItem in model.wipOutfits)
                {
                    outfit.Add(new BarCodeCheckDto.Outfit
                    {
                        inputData = outfitItem.Inputs
                    });
                }

                var x = new BarCodeCheckDto
                {
                    wipNo = model.WipNO,
                    barcode = model.Input,
                    barcodeType = "M",
                    stationID = model.Station,
                    line = model.LineID,
                    unitNo = model.UnitNO,
                    inputItems = keyParts,
                    outfits = outfit,
                    userID = GetLogInUserID()
                };

                var barcode_result = await _pcsApi.PassIngByCheck(JsonConvert.SerializeObject(x));
                if (!barcode_result.Success)
                    return Json(new Result() { success = barcode_result.Success, msg = barcode_result.Msg, data = Data });
                // 過站判斷成功
                else
                {
                    Msg = barcode_result.Msg;
                    Data = string.Empty;
                }
                #endregion
            }
            else
            {
                // 組件資料
                var items = await _pcsApi.GetItems();
                items = items.Where(w => model.WipKps.Any(wi => wi.KpNo.Trim().ToUpper() == w.ItemNo.Trim().ToUpper())).ToList();
                // 判斷Input為指定KeyParts順序
                if (items.Any(a => a.ItemName.ToUpper() == Data.ToUpper()))
                {
                    if (model.KpItemName != null)
                    {
                        // 取得目前Input指定KP代碼的綁定數量
                        var KpItemNameByCount = model.KpItemName.Split(",").Where(w => w.ToUpper() == Data.ToUpper()).Count();
                        // WipKp的ByKpNo數量
                        var WipKpByCount = model.WipKps.Where(w1 => w1.KpNo == items.Where(w => w.ItemName.ToUpper() == Data.ToUpper())
                                                .Select(s => s.ItemNo).FirstOrDefault()).Count();
                        // 目前綁定KpNo 等於 WipKp ByKpNo 數量  
                        if (KpItemNameByCount == WipKpByCount)
                        {
                            Success = false;
                            Msg = $"指定KeyParts:{Data} 已超過資料設定數量</br>";
                            return Json(new Result() { success = Success, msg = Msg, data = Data });
                        }
                    }

                    return Json(new Result1() { success = Success, msg = Msg, data = "", data1 = Data });
                }
            }

            #region 判斷下一站為完工站
            var NextStopCloseStation = await _pcsApi.CheckNextStopCloseStation(model.WipNO, model.UnitNO, model.Station);
            #endregion

            #region 過站判斷正常 往下處理Table 移到API執行
            //    #region 當生產單位為SMT或DIP時,確認是否有綁Group,有綁連片一起過站
            //    List<int> GroupBarCodeID = new List<int>();
            //    if (model.UnitNO == "S" || model.UnitNO == "D")
            //    {
            //        var GroupID = await _pcsApi.GetBarcodeGroupByBarCodeID(model.BarCodeID);
            //        if (GroupID.Count != 0)
            //        {
            //            var BarCodeGroup = await _pcsApi.GetBarcodeGroupByGroupID(GroupID.FirstOrDefault().GroupID);
            //            GroupBarCodeID = BarCodeGroup.Where(w => w.BarcodeID != model.BarCodeID).Select(s => s.BarcodeID).ToList();
            //        }

            //        foreach (int id in GroupBarCodeID)
            //        {
            //            // 更新 BarCode_Info
            //            var barcodeGroupID = await _pcsApi.GetBarcodeInfoes(id);
            //            if (barcodeGroupID.Count() != 0)
            //            {
            //                barcodeGroupID[0].StatusNo = BarStatusNo;
            //                barcodeGroupID[0].RuleStationID = model.RuleStation;
            //                barcodeGroupID[0].RuleStatus = !model.BarcodeNG ? "P" : "F"; //F 不良 
            //                barcodeGroupID[0].WipID = model.WipID;
            //                barcodeGroupID[0].StatusID = NextStopCloseStation.Success ? -1 : 1;
            //                barcodeGroupID[0].UpdateDate = DateTime.Now;
            //                await _pcsApi.PutBarcodeInfoes(JsonConvert.SerializeObject(barcodeGroupID[0]));
            //            }
            //            // 新增 BarCodeStation
            //            barcodeStation.BarcodeID = id;
            //            await _pcsApi.PostBarcodeStation(JsonConvert.SerializeObject(barcodeStation));
            //            // 新增 BarCodeItem
            //            for (int i = 0; i < model.Inputs.Where(w => !w.StartsWith("$")).Count(); i++)
            //            {
            //                var barcodeItem = new BarcodeItem
            //                {
            //                    BarcodeID = id,
            //                    WipID = model.WipID,
            //                    RuleStationID = model.RuleStation,
            //                    ItemNo = model.MaterialKps[i].KpNo,
            //                    PartNo = Kp[i],
            //                    SysType = "S",
            //                    CreateUserID = 0,
            //                    CreateDate = DateTime.Now,
            //                    UpdateDate = DateTime.Now
            //                };
            //                await _pcsApi.PostBarcodeItem(JsonConvert.SerializeObject(barcodeItem));
            //            }
            //            // 新增 BarCodeWip 投入站新增 for 只有投入站才新增
            //            if (model.StationSEQ == 1)
            //            {
            //                BarcodeWip barcodeWip = new BarcodeWip
            //                {
            //                    BarcodeID = id,
            //                    WipID = model.WipID
            //                };
            //                await _pcsApi.PostBarcodeWip(JsonConvert.SerializeObject(barcodeWip));

            //                var wipInfo = await _pcsApi.GetWipInfo(model.WipID);
            //                wipInfo[0].CompleteQTY += 1;
            //                await _pcsApi.PutWipInfo(JsonConvert.SerializeObject(wipInfo[0]));

            //            }
            #endregion

            if (NextStopCloseStation.Success)
            {
                // 刪除 BarCodeGroup DIP完工後刪除
                if (model.UnitNO == "D")
                {
                    var GroupID = await _pcsApi.GetBarcodeGroupByBarCodeID(model.BarCodeID);
                    if (GroupID.Count != 0)
                    {
                        await _pcsApi.DeleteBarcodeGroupByGroupID(GroupID.FirstOrDefault().GroupID);
                    }
                }
            }

            return Json(new Result1() { success = Success, msg = Msg, data = Data, data1 = "" });
        }
        #endregion

        #region PCS022 條碼输入整批作業
        public async Task<IActionResult> PCS022()
        {
            await GetLineInfo();
            await GetFactoryUnit();
            return View();
        }

        /// <summary>
        /// PCS022 Query
        /// </summary>
        /// <param name="wipNo">工單號碼/param>
        /// <param name="productNo">料號</param>
        /// <param name="unit">生產單位/param>
        /// <param name="lineID">LineID</param>
        /// <param name="type">選擇查詢類型</param>
        /// <returns></returns>
        public async Task<IActionResult> PCS022QueryAsync(string wipNo, string productNo, string unit, string type, int lineID = 0, int page = 0, int limit = 10)
        {
            if (type == "W")
                productNo = string.Empty;
            else
                wipNo = string.Empty;

            IResultModel<BarcodeInfoDto> result = await _pcsApi.GetBarcodeInfoesByPCS022Query(wipNo: wipNo,
                itemNo: productNo, unit: unit, lineID, page: page, limit: limit);

            if (result.Data.Count() != 0)
            {
                return Json(new Table() { code = 0, msg = "", data = result.Data, count = result.DataTotal });
            }
            return Json(new Table() { count = 0, data = null });
        }

        [HttpGet]
        public IActionResult PCS022V(int wipID, int stationID)
        {
            ViewBag.WIP_ID = wipID;
            ViewBag.STATION_ID = stationID;
            return View();
        }

        [HttpGet]
        public async Task<IActionResult> PCS022VQuery(int wipID, int stationID, int page = 0, int limit = 10)
        {
            var result = await _pcsApi.GetWipStationBarcodeByPCS022(wipID, stationID, page, limit);

            if (result.DataTotal > 0)
            {
                return Json(new Table() { code = 0, msg = "", data = result.Data, count = result.DataTotal });
            }

            return Json(new Table() { count = 0, data = null });
        }

        [HttpPost]
        public async Task<IActionResult> PCS022U(int wipID, int StationID)
        {
            var result = await _pcsApi.GetBarcodeInfoesByWipID(wipID);
            result = result.Where(w => w.StationID == StationID && w.RuleStatus == "P").ToList();

            var FlowRule = result.FirstOrDefault().GetWipInfo.FlowRuleID;
            var result_RuleStation = await _basApi.GetRuleStationsByFlow(FlowRule, 0);
            // 只抓標準站 & 排除完工站
            result_RuleStation = result_RuleStation.Where(w => w.StationType == "M" && w.StationID != 1000).OrderBy(o => o.Sequence).ToList();
            // 當站
            var NowSequence = result_RuleStation.Where(w => w.StationID == StationID && w.FlowRuleID == FlowRule).FirstOrDefault().Sequence;
            var NextStationID = 0;
            // 排除當站為最後一站
            if (result_RuleStation.Count != NowSequence + 1)
                NextStationID = result_RuleStation.Where(w => w.Sequence == NowSequence + 1).FirstOrDefault().StationID;

            if (NextStationID != 0)
            {
                var resultMsg = string.Empty;
                foreach (var item in result)
                {
                    //自動過站
                    var barCode = new BarCodeCheckDto
                    {
                        wipNo = item.GetWipInfo.WipNO,
                        barcode = item.BarcodeNo,
                        barcodeType = "M",
                        stationID = NextStationID,
                        line = item.GetWipInfo.LineID ?? 0,
                        unitNo = item.GetWipInfo.UnitNO,
                        inputItems = null,
                        userID = GetLogInUserID()
                    };

                    try
                    {
                        var barcode_result = await _pcsApi.PassIngByCheck(JsonConvert.SerializeObject(barCode));


                        if (barcode_result.Success)
                        {
                            resultMsg += $"{item.BarcodeNo} 內部條碼:資料過站成功!!!" + "</br>";
                        }
                        else
                        {
                            resultMsg += $"{item.BarcodeNo} 內部條碼:資料過站失敗!!!原因:" + barcode_result.Msg + "</br>";
                        }
                        //return Json(new Result() { success = true, msg = resultMsg });
                    }
                    catch (Exception ex)
                    {
                        return Json(new Result() { success = false, msg = ex.Message });
                    }
                }
                return Json(new Result() { success = true, msg = resultMsg });
            }
            return Json(new Result() { success = true, msg = "該站為最後一站,無法執行過站" });
        }
        #endregion

        #region PCS023 條碼置換
        public ActionResult PCS023()
        {
            return View();
        }

        //頁面提交,id=0 添加,id>0 修改
        [HttpPost]
        public async Task<IActionResult> PCS023Async(PCS023ViewModel model)
        {
            var result_barcodeInfo = new List<BarcodeInfo>();
            // 內部條碼置換
            if (model.ChangeType == "P")
            {
                // 查內部條碼
                result_barcodeInfo = await _pcsApi.GetBarcodeInfoesByNo(model.BarCodeNoOld);

                if (result_barcodeInfo.Count == 0)
                {
                    ModelState.AddModelError("error", "找不到內部條碼【" + model.BarCodeNoOld + "】 ,請確認");
                    return View(model);
                }

                // 確認新條碼不再barcodeInfo 有資料
                var result_CheckbarcodeInfo = await _pcsApi.GetBarcodeInfoesByNo(model.BarCodeNoNew);
                if (result_CheckbarcodeInfo.Count != 0)
                {
                    ModelState.AddModelError("error", "新內部條碼【" + model.BarCodeNoNew + "】,已在使用中");
                    return View(model);
                }

                // 新條碼序號是否有置換紀錄
                var result_CheckBarcodeChange = await _pcsApi.GetBarcodeChangeByBarcodeNo(model.BarCodeNoNew);
                if (result_CheckBarcodeChange.Any(w => w.BarcodeNoOld == model.BarCodeNoNew && w.ChangeType == "P"))
                {
                    ModelState.AddModelError("error", "新內部條碼【" + model.BarCodeNoNew + "】,已有變更紀錄,無法再次變更");
                    return View(model);
                }
            }
            // 出貨序號置換
            else if (model.ChangeType == "E")
            {
                // 查出貨序號
                result_barcodeInfo = await _pcsApi.GetBarcodeInfoesByExtraNo(model.BarCodeNoOld);

                if (result_barcodeInfo.Count == 0)
                {
                    ModelState.AddModelError("error", "找不到出貨條碼【" + model.BarCodeNoOld + "】 ,請確認");
                    return View(model);
                }

                // 確認新條碼不再barcodeInfo 有資料
                var result_CheckbarcodeInfo = await _pcsApi.GetBarcodeInfoesByExtraNo(model.BarCodeNoNew);
                if (result_CheckbarcodeInfo.Count != 0)
                {
                    ModelState.AddModelError("error", "新出貨條碼【" + model.BarCodeNoNew + "】,已在使用中");
                    return View(model);
                }

                // 新條碼序號是否有置換紀錄
                var result_CheckBarcodeChange = await _pcsApi.GetBarcodeChangeByBarcodeNo(model.BarCodeNoNew);
                if (result_CheckBarcodeChange.Any(w => w.BarcodeNoOld == model.BarCodeNoNew && w.ChangeType == "E"))
                {
                    ModelState.AddModelError("error", "新出貨條碼【" + model.BarCodeNoNew + "】,已有變更紀錄,無法再次變更");
                    return View(model);
                }
            }

            var barcodeInfo = result_barcodeInfo.FirstOrDefault();
            // 新條碼置換
            if (model.ChangeType == "P")
                barcodeInfo.BarcodeNo = model.BarCodeNoNew;
            else
                barcodeInfo.ExtraBarcodeNo = model.BarCodeNoNew;

            BarcodeChange barcodeChange = new BarcodeChange
            {
                BarcodeID = barcodeInfo.BarcodeID,
                BarcodeNoOld = model.BarCodeNoOld,
                BarcodeNoNew = model.BarCodeNoNew,
                ChangeType = model.ChangeType,
                Memo = model.Memo,
                CreateUserID = GetLogInUserID()
            };

            var result = await _pcsApi.PostBarcodeChange(JsonConvert.SerializeObject(barcodeChange));
            if (result.Success)
            {
                await _pcsApi.PutBarcodeInfoes(JsonConvert.SerializeObject(barcodeInfo));
                ModelState.AddModelError("error", "變更成功!");
                return View();
            }
            else
            {
                ModelState.AddModelError("error", "變更失敗,錯誤原因:" + result.Msg);
                return View(model);
            }
        }

        #endregion

        #region PCS024條碼組件维护相关

        public async Task<IActionResult> PCS024(string id)
        {
            if (id != null)
            {
                await GetFactoryUnit(id);
                ViewBag.UnitNo = id;
            }
            else
            {
                await GetFactoryUnit();
            }
            //await GetFactoryUnit();
            return View();
        }
        //新增頁面
        public async Task<IActionResult> PCS024C(string id)
        {
            var result = await _pcsApi.GetBarcodeInfoesByNo(id);
            if (result.Count > 0)
            {
                var tt = result[0];
                ViewBag.BarcodeID = tt.BarcodeID;
                ViewBag.WipID = tt.WipID;
                ViewBag.BarcodeNo = id;

                await GetFactoryUnit();
                //await GetStations();
                await GetItems();
            }
            else
            {
                ViewBag.BarcodeNo = "查無序號請重新輸入";
            }
            return View();
        }

        //修改页面
        [HttpGet]
        public async Task<IActionResult> PCS024UAsync(int id)
        {
            await GetItems();

            var result = await _pcsApi.GetBarcodeItem(id);

            if (result.Count == 0)
            {
                return View();
            }
            return View(result[0]);
        }

        public async Task<IActionResult> PCS024DAsync(int id)
        {
            var result = await _pcsApi.DeleteBarcodeItem(id);
            return Json(new Result() { success = true, msg = "" });
        }

        [HttpGet]
        public async Task<IActionResult> GetBarcodeInfoesByNoAsync(string id)
        {
            var result = await _pcsApi.GetBarcodeInfoesByNo(id);

            if (result.Count > 0)
            {
                return Json(new Table() { code = 0, msg = "", data = result, count = 1 });
            }

            return Json(new Table() { count = 0, data = null });
        }


        //頁面提交,id=0 添加,id>0 修改
        [HttpPost]
        public async Task<IActionResult> PCS024CSaveAsync(BarcodeItem model)
        {

            var bNo = model.B.BarcodeNo;
            if (ModelState.IsValid)
            {
                IResultModel result;
                model.CreateUserID = GetLogInUserID();
                result = await _pcsApi.PostBarcodeItemAddnew(JsonConvert.SerializeObject(model));


                if (result.Success)
                {
                    var _msg = "新增成功!";
                    return RedirectToAction("Refresh", "Home", new { msg = _msg });
                }
                else
                {
                    //var BarcodeItem = await _pcsApi.GetBarcodeItem(model.BarcodeItemID);
                    //var tt = BarcodeItem[0];
                    //ViewBag.BarcodeID = model.BarcodeID;
                    //ViewBag.WipID = model.WipID;
                    //ViewBag.BarcodeNo = bNo;
                    var BarcodeInfoes = await _pcsApi.GetBarcodeInfoesByNo(bNo);
                    var tt = BarcodeInfoes[0];
                    ViewBag.BarcodeID = tt.BarcodeID;
                    ViewBag.WipID = tt.WipID;
                    ViewBag.BarcodeNo = bNo;
                    await GetFactoryUnit();
                    await GetItems();

                    ModelState.AddModelError("error", result.Msg);

                }
            }
            return View("PCS024C", model);

        }

        [ResponseCache(Duration = 0)]
        [HttpGet]
        public async Task<IActionResult> GetBarcodeItemsAsync()
        {
            var result = await _pcsApi.GetBarcodeItems();

            if (result.Count > 0)
            {
                return Json(new Table() { code = 0, msg = "", data = result, count = result.Count });
            }

            return Json(new Table() { count = 0, data = null });
        }

        [ResponseCache(Duration = 0)]
        [HttpGet]
        public async Task<IActionResult> GetBarcodeItemByUnit2Async(string ID)
        {
            string str, str1;
            var strA = ID.Split("=");
            str = strA[0];
            str1 = strA[1];

            if (ID is null)
                return Json(new Table() { count = 0, data = null });

            var result = await _pcsApi.GetBarcodeItemByStr(str, str1);
            //var result = await _pcsApi.GetBarcodeItemByUnit(ID);

            if (result.Count > 0)
            {
                return Json(new Table() { code = 0, msg = "", data = result, count = result.Count });
            }

            return Json(new Table() { count = 0, data = null });
        }

        [ResponseCache(Duration = 0)]
        [HttpGet]
        public async Task<IActionResult> GetBarcodeItemByUnitAsync(string unitId, string barcodeNo)
        {
            //string str, str1;
            //var strA = ID.Split("=");
            //str = strA[0];
            //str1 = strA[1];
            //WO0002A10001

            if (barcodeNo is null)
                return Json(new Table() { count = 0, data = null });

            var result = await _pcsApi.GetBarcodeItemByStr(unitId, barcodeNo);
            //var result = await _pcsApi.GetBarcodeItemByUnit(ID);

            if (result.Count > 0)
            {
                return Json(new Table() { code = 0, msg = "", data = result, count = result.Count });
            }

            return Json(new Table() { count = 0, data = null });
        }

        #endregion

        #region PCS027 組件資料整批刪除
        public async Task<IActionResult> PCS027()
        {
            await GetItemsList();
            return View();
        }

        [HttpPost]
        public JsonResult PCS027_Excel(IFormFile Uploader)
        {
            List<string> Print = new List<string>();
            //通過上傳檔案流初始化Mapper
            using (var workbook = new XLWorkbook(Uploader.OpenReadStream()))
            {
                try
                {
                    var worksheet = workbook.Worksheet(1);
                    // 定義資料起始/結束 Cell
                    var firstCell = worksheet.FirstCellUsed();
                    var lastCell = worksheet.LastCellUsed();

                    // 使用資料起始/結束 Cell,來定義出一個資料範圍
                    var data = worksheet.Range(firstCell.Address, lastCell.Address);
                    var rowCount = data.RowCount();
                    var columnCount = data.ColumnCount();
                    for (int i = 1; i <= rowCount; i++)
                    {
                        // 取得每一欄
                        if (data.Cell(i, 1).Value.ToString() != null)
                        {
                            Print.Add(data.Cell(i, 1).Value.ToString());
                        }
                    }
                }
                catch (Exception ex)
                {
                    return Json(new { data = ex.Message, success = false });
                }
            }

            //将数据Json化并传到前台视图
            return Json(new { data = string.Join(",", Print), success = true });
        }

        /// <summary>
        /// PCS027 Query
        /// </summary>
        /// <param name="wipNo">工單號料</param>
        /// <param name="barCode">內部條碼</param>
        /// <param name="KPItemNo">組件編號</param>
        /// <param name="BarCodeItem">內部條碼List</param>
        /// <param name="type">選擇查詢類型</param>
        /// <returns></returns>
        public async Task<IActionResult> PCS027QueryAsync(string wipNo, string barCode, string KPItemNo,
           string BarCodeItem, string type, int page = 0, int limit = 10)
        {
            try
            {
                // 初始執行不查詢
                if (type == null)
                {
                    return Json(new Table() { count = 0, data = null });
                }

                if (type == "W")
                {
                    barCode = string.Empty;
                    BarCodeItem = string.Empty;
                }
                else if (type == "B")
                {
                    wipNo = string.Empty;
                    BarCodeItem = string.Empty;
                }
                else if (type == "BS")
                {
                    wipNo = string.Empty;
                    barCode = string.Empty;
                }

                IResultModel<BarcodeItemDTO> result = await _pcsApi.GetBarcodeItemByPCS027Query(wipNO: wipNo,
                    barCode: barCode, KPItemNo: KPItemNo, BarCodeItem: BarCodeItem
                    , page: page, limit: limit);

                if (result.Data.Count() != 0)
                {
                    return Json(new Table() { code = 0, msg = "", data = result.Data, count = result.DataTotal });
                }

                // 有執行錯誤
                if (!result.Success)
                {
                    return Json(new Table() { code = 1, msg = "查詢錯誤:" + result.Msg, count = 0 });
                }

                return Json(new Table() { count = 0, data = null });
            }
            catch (Exception ex)
            {
                return Json(new Table() { code = 1, msg = "查詢錯誤:" + ex.Message, count = 0 });
            }
        }

        /// <summary>
        /// PCS027 組件批次刪除
        /// </summary>
        /// <param name="wipNo">工單號料</param>
        /// <param name="barCode">內部條碼</param>
        /// <param name="KPItemNo">組件編號</param>
        /// <param name="BarCodeItem">內部條碼List</param>
        /// <param name="type">選擇查詢類型</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> PCS027DAsync(string wipNo, string barCode, string KPItemNo,
           string BarCodeItem, string type)
        {
            IResultModel<BarcodeItemDTO> result = await _pcsApi.GetBarcodeItemByPCS027Query(wipNO: wipNo,
                  barCode: barCode, KPItemNo: KPItemNo, BarCodeItem: BarCodeItem);

            var barcodeItemOld = result.Data;
            foreach (var item in barcodeItemOld)
            {
                var barcodeItemChange = new BarcodeItemChange();
                barcodeItemChange.BarcodeItemChangeID = 0;
                barcodeItemChange.BarcodeID = item.BarcodeID;
                barcodeItemChange.PartNoOld = item.PartNo;
                barcodeItemChange.ChangeType = "DR";
                barcodeItemChange.ItemNo = item.ItemNo;
                barcodeItemChange.StationID = item.StationID;
                barcodeItemChange.WipID = item.WipID;
                barcodeItemChange.KpItemNo = item.KpItemNo;
                barcodeItemChange.CreateUserID = GetLogInUserID();
                barcodeItemChange.CreateDate = System.DateTime.Now;
                barcodeItemChange.UpdateDate = System.DateTime.Now;

                await _pcsApi.PostBarcodeItemChange(JsonConvert.SerializeObject(barcodeItemChange));
                await _pcsApi.DeleteBarcodeItem(item.BarcodeItemID);
            }
            return Json(new Result() { success = true, msg = "刪除成功" });
        }
        #endregion

        [ResponseCache(Duration = 0)]
        [HttpGet]
        public async Task<IActionResult> PCS030()
        {
            GetSOPTypeSelect();
            await GetFactoryUnit();
            return View();
        }

        /// <summary>
        /// PCS030 SOP文件查詢 Query
        /// </summary>
        /// <param name="itemNo">料號</param>
        /// <param name="unitNo">生產單位</param>
        /// <param name="sopType">SOP類型</param>
        /// <param name="date_str">建立日期起</param>
        /// <param name="date_end">建立日期迄</param>
        /// <returns></returns>
        public async Task<IActionResult> PCS030QueryAsync(string itemNo, string unitNo
            , string sopType, string date_str, string date_end)
        {
            IResultModel<MaterialSopDto> result = await _pcsApi.GetMaterialSopQuery(itemNo: itemNo, unitNo: unitNo
            , sopType: sopType, date_str: date_str, date_end: date_end);

            if (result.Data.Count() != 0)
            {
                return Json(new Table() { code = 0, msg = "", data = result.Data, count = 0 });
            }
            return Json(new Table() { count = 0, data = null });
        }

        [HttpGet]
        public async Task<IActionResult> PCS030C()
        {
            GetSOPTypeSelect();
            await GetFactoryUnit(false);
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> PCS030Async(MaterialSop model, IFormFile formFile)
        {
            //string FileName = string.Empty;
            //string NewName = string.Empty;
            //string FilePath = string.Empty;

            ////var fileProvider = _fileServerProvider.GetProvider("/aa");
            ////var fileInfo = fileProvider.GetFileInfo("/");
            //if (formFile != null)
            //{
            //    if (formFile.Length > 0)
            //    {
            //        //取得使用者上傳檔案的原始檔名
            //        FileName = Path.GetFileName(formFile.FileName);
            //        //取原始檔名中的副檔名
            //        var fileExt = Path.GetExtension(FileName);
            //        //為避免使用者上傳的檔案名稱發生重複,重新給一個亂數名稱
            //        NewName = Path.GetRandomFileName() + fileExt;
            //        //指定要寫入的路徑、檔名和副檔名
            //        FilePath = $"\\PDF\\";//本機目錄
            //        using (var stream = new FileStream(_env.WebRootPath + FilePath + NewName, FileMode.Create))
            //        {
            //            await formFile.CopyToAsync(stream);
            //        }

            //        var fileProvider = _fileServerProvider.GetProvider("/aa");
            //        //var fileInfo = fileProvider.GetFileInfo(formFile.FileName);
            //        //fileInfo = fileProvider.GetFileInfo(formFile.FileName);
            //        ////遠端目錄
            //        //using (var stream = new FileStream(fileInfo.PhysicalPath, FileMode.Create))
            //        //{
            //        //    await formFile.CopyToAsync(stream);
            //        //}



            //        IResultModel result;
            //        model.FileName = FileName;
            //        model.NewName = NewName;
            //        model.FilePath = FilePath;// fileInfo.PhysicalPath;

            //        result = await _pcsApi.PostMaterialSop(JsonConvert.SerializeObject(model));
            //        if (result.Success)
            //        {
            //            var _msg = model.MaterialSopID == 0 ? "新增成功!" : "修改成功!";
            //            return RedirectToAction("Refresh", "Home", new { msg = _msg });
            //        }
            //        else
            //        {
            //            ModelState.AddModelError("error", result.Msg);
            //        }
            //    }
            //}
            //else
            //{
            //    ModelState.AddModelError("error", "請選擇要上傳檔案");
            //}
            await GetFactoryUnit(false);
            GetSOPTypeSelect();

            if (ModelState.IsValid)
            {
                IResultModel result;
                if (model.MaterialSopID == 0)
                {
                    result = await _pcsApi.PostMaterialSop(JsonConvert.SerializeObject(model));
                }
                else
                {
                    result = await _pcsApi.PutMaterialSop(JsonConvert.SerializeObject(model));
                }

                if (result.Success)
                {
                    var _msg = model.MaterialSopID == 0 ? "新增成功!" : "修改成功!";
                    return RedirectToAction("Refresh", "Home", new { msg = _msg });
                }
                else
                {

                    ModelState.AddModelError("error", result.Msg);
                }
            }
            if (model.MaterialSopID == 0)
            {
                return View("PCS030C", model);
            }
            return View("PCS030U", model);


        }

        [HttpGet]
        public async Task<IActionResult> PCS030U(int id)
        {
            var result = await _pcsApi.GetMaterialSop(id);
            GetSOPTypeSelect();
            await GetFactoryUnit(false);
            return View(result);
        }

        public async Task<IActionResult> PCS030DAsync(int id)
        {
            var result = await _pcsApi.DeleteMaterialSop(id);
            return Json(new Result() { success = result.Success, msg = result.Msg });
        }

        #region PCS032 工單生產重新過站
        public ActionResult PCS032()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> PCS032Async(PCS032ViewModel model)
        {
            var BarCodeInterval = new List<string>();

            if (model.GoByStation == 0 || model.RetrueStation == 0)
            {
                ModelState.AddModelError("error", "請輸入正確資料");
                return View(model);
            }

            if (!string.IsNullOrWhiteSpace(model.BarCodeNoStr) || !string.IsNullOrWhiteSpace(model.BarCodeNoEnd))
            {
                if (string.IsNullOrWhiteSpace(model.BarCodeNoStr) || string.IsNullOrWhiteSpace(model.BarCodeNoEnd))
                {
                    ModelState.AddModelError("error", "請輸入條碼起訖");
                    return View(model);
                }
            }

            // 有設定條碼區間判斷
            if (!string.IsNullOrWhiteSpace(model.BarCodeNoStr) && !string.IsNullOrWhiteSpace(model.BarCodeNoEnd))
            {
                if (model.BarCodeNoStr.Length != model.BarCodeNoEnd.Length)
                {
                    ModelState.AddModelError("error", "條碼區間起訖長度不相同");
                    return View(model);
                }

                // 流水碼預設長度
                int NoLength = 4;
                if (model.BarCodeNoStr.Length <= NoLength || model.BarCodeNoEnd.Length <= NoLength)
                {
                    ModelState.AddModelError("error", "條碼區間號碼長度不能小於" + (NoLength + 1));
                    return View(model);
                }

                if (model.BarCodeNoStr.Substring(0, model.BarCodeNoStr.Length - NoLength) !=
                    model.BarCodeNoEnd.Substring(0, model.BarCodeNoEnd.Length - NoLength))
                {
                    ModelState.AddModelError("error", "條碼區間前置號碼不一樣");
                    return View(model);
                }


                if (!int.TryParse(model.BarCodeNoStr.Substring(model.BarCodeNoStr.Length - NoLength, NoLength), out _) ||
                    !int.TryParse(model.BarCodeNoEnd.Substring(model.BarCodeNoEnd.Length - NoLength, NoLength), out _))
                {
                    ModelState.AddModelError("error", "條碼區間流水碼格式錯誤");
                    return View(model);
                }

                var NoStr = int.Parse(model.BarCodeNoStr.Substring(model.BarCodeNoStr.Length - NoLength, NoLength));
                var NoEnd = int.Parse(model.BarCodeNoEnd.Substring(model.BarCodeNoEnd.Length - NoLength, NoLength));
                if (NoStr > NoEnd)
                {
                    ModelState.AddModelError("error", "條碼區間結束流水碼不可以小於條碼區間起始流水碼");
                    return View(model);
                }

                var BarCode = model.BarCodeNoEnd.Substring(0, model.BarCodeNoEnd.Length - NoLength);
                for (int i = NoStr; i <= NoEnd; i++)
                {
                    // 將條碼區間寫入List
                    var itemBarcodeNo = BarCode + i.ToString().PadLeft(NoLength, '0');
                    BarCodeInterval.Add(itemBarcodeNo.ToUpper());
                }
            }

            var result_Wip = await _pcsApi.GetWipInfoByWipNO(model.WipNo.Trim().ToUpper());
            var FlowRule = result_Wip.FirstOrDefault().FlowRuleID;
            var result_RuleStation = await _basApi.GetRuleStationsByFlow(FlowRule, 0);
            // 只抓標準站 & 排除完工站
            result_RuleStation = result_RuleStation.Where(w => w.StationType == "M" && w.StationID != 1000).OrderBy(o => o.Sequence).ToList();

            var goBySequence = result_RuleStation.Where(w => w.StationID == model.GoByStation).FirstOrDefault().Sequence;
            var retrueSequence = result_RuleStation.Where(w => w.StationID == model.RetrueStation).FirstOrDefault().Sequence;

            if (retrueSequence >= goBySequence)
            {
                var RuleStations = await _basApi.GetRuleStationsByFlow(FlowRule);
                RuleStations = RuleStations.Where(w => w.StationType == "M" && w.StationID != 1000).OrderBy(o => o.Sequence).ToList();
                var StationList = new List<SelectListItem>();
                for (int i = 0; i < RuleStations.Count; i++)
                {
                    StationList.Add(new SelectListItem(RuleStations[i].Sequence + "-" + RuleStations[i].StationDesc, RuleStations[i].StationID.ToString()));
                }

                if (RuleStations.Count == 0)
                {
                    StationList.Add(new SelectListItem("N/A", null));
                }

                ViewBag.GetStationList = StationList;
                ModelState.AddModelError("error", "設定失敗,無法指定通過站後續站別");
                return View(model);
            }

            // 判斷Type 單站還是通過後續
            var result_BarcodeInfo = await _pcsApi.GetBarcodeInfoesByWipNo(model.WipNo.Trim().ToUpper());
            if (model.Type == "P")
            {
                var put_BarcodeInfo = result_BarcodeInfo.Where(w => w.StationID == model.GoByStation && w.StatusID != -1).ToList();
                put_BarcodeInfo = put_BarcodeInfo.Select(s => { s.StationID = model.RetrueStation; return s; }).ToList();

                // 有設定條碼區間,在抓區間內條碼
                if (BarCodeInterval.Count() != 0)
                {
                    put_BarcodeInfo = put_BarcodeInfo.Where(w => BarCodeInterval.Contains(w.BarcodeNo)).ToList();
                }

                foreach (var item in put_BarcodeInfo)
                {
                    await _pcsApi.PutBarcodeInfoes(JsonConvert.SerializeObject(item));
                }

            }
            else
            {
                // 取通過後續的站別
                var goByStations = result_RuleStation.Where(w => w.Sequence >= goBySequence).Select(s => s.StationID).ToList();
                foreach (var Station in goByStations)
                {
                    var put_BarcodeInfo = result_BarcodeInfo.Where(w => w.StationID == Station && w.StatusID != -1).ToList();
                    put_BarcodeInfo = put_BarcodeInfo.Select(s => { s.StationID = model.RetrueStation; return s; }).ToList();

                    // 有設定條碼區間,在抓區間內條碼
                    if (BarCodeInterval.Count() != 0)
                    {
                        put_BarcodeInfo = put_BarcodeInfo.Where(w => BarCodeInterval.Contains(w.BarcodeNo)).ToList();
                    }

                    foreach (var item in put_BarcodeInfo)
                    {
                        await _pcsApi.PutBarcodeInfoes(JsonConvert.SerializeObject(item));
                    }
                }
            }

            WipReturn wipReturn = new WipReturn
            {
                WipNo = model.WipNo.Trim().ToUpper(),
                GoStationId = model.GoByStation,
                ReStationId = model.RetrueStation,
                Type = model.Type,
                Memo = model.Memo,
                CreateUserID = GetLogInUserID()
            };

            var result = await _pcsApi.PostWipReturn(JsonConvert.SerializeObject(wipReturn));
            if (result.Success)
            {
                ModelState.AddModelError("error", "新增成功!");
                return View();
            }

            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> PCS032Query(string wipNo)
        {
            var result = new ResultModel<SelectListItem>();
            var result_Wip = await _pcsApi.GetWipInfoByWipNO(wipNo.Trim().ToUpper());

            if (result_Wip.Count == 0)
            {
                result.Success = false;
                result.Msg = "找不到工單號碼【" + wipNo + "】建立資料";
            }
            else if (result_Wip.Count != 1)
            {
                result.Success = false;
                result.Msg = "工單號碼【" + wipNo + "】有開立多張工單維護資料,無法使用生產序號退回";
            }
            else
            {
                var FlowRule = result_Wip.FirstOrDefault().FlowRuleID;
                var result_RuleStation = await _basApi.GetRuleStationsByFlow(FlowRule, 0);
                //result_RuleStation = result_RuleStation.Where(w => w.StationType == "M").OrderBy(o => o.Sequence).ToList();
                //var Stations = new List<SelectListItem>();
                result_RuleStation = result_RuleStation.Where(w => w.StationType == "M" && w.StationID != 1000).OrderBy(o => o.Sequence).ToList();
                var RuleStations = new List<SelectListItem>();
                for (int i = 0; i < result_RuleStation.Count; i++)
                {
                    RuleStations.Add(new SelectListItem(result_RuleStation[i].Sequence + "-" + result_RuleStation[i].StationDesc, result_RuleStation[i].StationID.ToString()));
                }
                result.Data = RuleStations;
                result.Success = true;
            }
            return Json(result);
        }

        #endregion


        //修改页面
        [HttpGet]
        public async Task<IActionResult> BAS001UAsync(int id)
        {
            var result = await _basApi.GetFactoryInfo(id);
            result = await _basApi.GetFactoryInfoes();

            if (result.Count > 0)
            {
                //return Json(new Table() { code = 0, msg = "", data = result, count = result.Count });
            }

            // return Json(new Table() { count = 0, data = null });
            //if (result.Count == 0)
            //{
            //    return View();
            //}
            return PartialView("~/Views/Shared/PCS/_SOPPartial", Json(new Table() { code = 0, msg = "", data = result, count = result.Count }));
        }

        [HttpGet]
        public async Task<IActionResult> SOP()
        {
            var result = await _basApi.GetFactoryInfoes();

            if (result.Count > 0)
            {
                return Json(new Table() { code = 0, msg = "", data = result, count = result.Count });
            }

            //return Json(new Table() { count = 0, data = null });

            return PartialView("_SOPPartial", Json(new Table() { count = 0, data = null }));
        }

        #region PCS025組件资料维护相关

        public IActionResult PCS025()
        {
            return View();
        }

        //修改页面
        [HttpGet]
        public async Task<IActionResult> PCS025UAsync(int id)
        {
            await GetItems();

            var result = await _pcsApi.GetBarcodeItem(id);

            if (result.Count == 0)
            {
                return View();
            }
            var tt = result[0];
            ViewBag.BarcodeNo = tt.B.BarcodeNo;
            ViewBag.ItemName = tt.I.ItemName;
            result[0].PartNo = "";
            return View(result[0]);
        }

        //頁面提交,id=0 添加,id>0 修改
        [HttpPost]
        public async Task<IActionResult> PCS025USaveAsync(BarcodeItem model)
        {
            if (ModelState.IsValid)
            {
                IResultModel result;
                IResultModel result2;

                var barcodeItemOldList = await _pcsApi.GetBarcodeItem(model.BarcodeItemID);
                var barcodeItemOld = barcodeItemOldList[0];
                var barcodeItemChange = new BarcodeItemChange();
                barcodeItemChange.BarcodeItemChangeID = 0;
                barcodeItemChange.BarcodeID = barcodeItemOld.BarcodeID;
                barcodeItemChange.PartNoOld = barcodeItemOld.PartNo;
                barcodeItemChange.ChangeType = "NR";
                barcodeItemChange.ItemNo = barcodeItemOld.ItemNo;
                barcodeItemChange.StationID = barcodeItemOld.StationID;
                barcodeItemChange.WipID = barcodeItemOld.WipID;
                barcodeItemChange.KpItemNo = barcodeItemOld.KpItemNo;
                // barcodeItemChange.CreateUserID = barcodeItemOld.CreateUserID;  YIRU
                barcodeItemChange.CreateUserID = GetLogInUserID();
                barcodeItemChange.CreateDate = System.DateTime.Now;
                barcodeItemChange.UpdateDate = System.DateTime.Now;
                model.CreateUserID = GetLogInUserID();
                result = await _pcsApi.PutBarcodeItem(model.BarcodeItemID, JsonConvert.SerializeObject(model));

                result2 = await _pcsApi.PostBarcodeItemChange(JsonConvert.SerializeObject(barcodeItemChange));

                //result = await _pcsApi.PostBarcodeItem(JsonConvert.SerializeObject(model));


                if (result.Success)
                {
                    var _msg = "置換成功!";
                    return RedirectToAction("Refresh", "Home", new { msg = _msg });
                }
                else
                {
                    var BarcodeItem = await _pcsApi.GetBarcodeItem(model.BarcodeItemID);
                    var tt = BarcodeItem[0];
                    ViewBag.BarcodeNo = tt.B.BarcodeNo;
                    ViewBag.ItemName = tt.I.ItemName;
                    ModelState.AddModelError("error", result.Msg);
                }
            }

            return View("PCS025U", model);

        }

        public IActionResult PCS026()
        {
            return View();
        }
        public async Task<IActionResult> PCS026DAsync(int id)
        {

            var barcodeItemOldList = await _pcsApi.GetBarcodeItem(id);
            var barcodeItemOld = barcodeItemOldList[0];
            var barcodeItemChange = new BarcodeItemChange();
            barcodeItemChange.BarcodeItemChangeID = 0;
            barcodeItemChange.BarcodeID = barcodeItemOld.BarcodeID;
            barcodeItemChange.PartNoOld = barcodeItemOld.PartNo;
            barcodeItemChange.ChangeType = "DR";
            barcodeItemChange.ItemNo = barcodeItemOld.ItemNo;
            barcodeItemChange.StationID = barcodeItemOld.StationID;
            barcodeItemChange.WipID = barcodeItemOld.WipID;
            barcodeItemChange.KpItemNo = barcodeItemOld.KpItemNo;
            //  barcodeItemChange.CreateUserID = barcodeItemOld.CreateUserID; yiru
            barcodeItemChange.CreateUserID = GetLogInUserID();
            barcodeItemChange.CreateDate = System.DateTime.Now;
            barcodeItemChange.UpdateDate = System.DateTime.Now;

            IResultModel result;
            IResultModel result2;
            result2 = await _pcsApi.PostBarcodeItemChange(JsonConvert.SerializeObject(barcodeItemChange));

            if (result2.Success)
            {
                result = await _pcsApi.DeleteBarcodeItem(id);
                return Json(new Result() { success = (result.Success), msg = result.Msg });

            }
            else
            {
                return Json(new Result() { success = (result2.Success), msg = result2.Msg });

            }

        }
        #endregion

        //YIRU ADD  -------------------------------------------------------------------------------------------------------------------------------

        #region PCS031 完工入庫
        public IActionResult PCS031()
        {
            return View();
        }



        public async Task<IActionResult> PCS031QueryAsync(string barcodeNo, string wipNo
                , string boxNo, string inhouseNo, string date_str, string date_end
                , string status, int page = 0, int limit = 10)
        {
            //IResultModel<FqcInhouseMasterDto> result = await _fqcApi.GetFqcInhouseMasterQuery(barcodeNo: barcodeNo, wipNo: wipNo
            //, boxNo: boxNo, inhouseNo: inhouseNo, date_str: date_str, date_end: date_end
            //, status: status, page: page, limit: limit);
            IResultModel<FqcInhouseMaster_WareDto> result = await _pcsApi.GetFqcInhouseMasterMultiQuery(barcodeNo: barcodeNo, wipNo: wipNo
             , boxNo: boxNo, inhouseNo: inhouseNo, date_str: date_str, date_end: date_end
             , status: status, page: page, limit: limit);
            if (result.Data.Count() != 0)
            {
                // var Data = result.Data.Where(w => w.StatusName == "允收");
                var Data = result.Data;


                return Json(new Table() { code = 0, msg = "", data = Data, count = result.DataTotal });
            }
            return Json(new Table() { count = 0, data = null });
        }

        public async Task<IActionResult> PCS031sum(string[] ids)
        {

            string msg = "";
            if (ids.Length > 0)
            {
                var qty = 0;
                for (int i = 0; i < ids.Length; i++)
                {
                    qty += Convert.ToInt32(ids[i]);



                }

                return Json(new Result() { success = true, msg = qty.ToString() });
            }
            else
            {
                return Json(new Result() { success = false, msg = "NO Select Data" });
            }


        }
        public async Task<IActionResult> PCS031inhouse_allAsync(string[] ids)
        {
            string msg = "";
            if (ids.Length > 0)
            {
                for (int i = 0; i < ids.Length; i++)
                {
                    string InhouseNo = ids[i].Split(',')[0];
                    string boxNo = ids[i].Split(',')[1];
                    string seq = ids[i].Split(',')[2];
                    string recordNumber = ids[i].Split(',')[3];
                    string locationNo = ids[i].Split(',')[4];
                    var result = await PCS0311inhouse(InhouseNo, boxNo, Convert.ToInt16(seq), recordNumber, locationNo);

                    if (!result.success)
                    {
                        msg += result.msg + "<br>";
                    }

                }

                return Json(new Result() { success = true, msg = "批次入庫完成<br>" + msg });
            }
            else
            {
                return Json(new Result() { success = false, msg = "NO Select Data" });
            }

        }
        public async Task<IActionResult> PCS031inhouseAsync(string InhouseNo, string boxNo, int seq, string recordNumber, string locationNo)
        {
            var result = await PCS0311inhouse(InhouseNo, boxNo, seq, recordNumber, locationNo);
            return Json(new Result() { success = result.success, msg = result.msg });



        }


        private async Task<Result> PCS0311inhouse(string InhouseNo, string boxNo, int seq, string recordNumber, string locationNo)
        {
            /* 1.先查詢是否已入庫過
             * 2.依barcodeinfo 查詢 該箱號所屬序號
             * 3.查詢所有序號查詢該流程 是否為最後一個流程(入庫),即在可入庫狀態
             * 4.若有序號不可入庫 => 畫面顯示不可入之序號
             * 5.所有序號可入庫 = >
             */

            var result1 = await _pcsApi.GetWareHouseing(inhouseNo: InhouseNo, seq: seq);
            if (result1.Count() > 0)
            {
                result1 = result1.Where(w => w.SerialNo == boxNo).ToList();
                if (result1.Count() > 0)
                {
                    return new Result() { success = false, msg = "箱號:" + boxNo + "已有入庫資料" };
                }
            }

            var result = await _fqcApi.GetBarcodeInfoesByBoxNo(boxNo: boxNo);

            if (result.Count() != 0)
            {
                var _msg = string.Empty;
                try
                {
                    if (recordNumber == null || recordNumber == "") _msg = "箱號:" + boxNo + "請輸入recordNumber";
                    else if (AppSetting.Setting.Location == "9000" || AppSetting.Setting.Location == "0S08")
                    {

                        if (recordNumber.Length != 10)
                        {
                            _msg = "箱號:" + boxNo + " recordNumber 必須為10碼且為50000開頭,RecordNumber format error<br>";

                        }
                        else if (!recordNumber.StartsWith("50000"))
                        {
                            _msg = "箱號:" + boxNo + " recordNumber 必須為10碼且為50000開頭,RecordNumber format error<br>";

                        }

                    }
                    foreach (var item in result)
                    {
                        //因已到入庫階段有帶出箱號才會進到此判斷,因此判斷流程是否流結束改如下條件
                        if (item.RuleStatus != "P" || item.StatusID != -1)
                        {
                            _msg += "序號【" + item.BarcodeNo + "】,流程尚未完成,不可入庫!<br>";
                        }

                        //var FlowStation_result = await _basApi.GetRuleStation(item.StationID);
                        //if (FlowStation_result.Count() != 0)
                        //{
                        //    var FlowRule_result = await _basApi.GetRuleStationsByFlow(FlowStation_result.Select(s => s.FlowRuleID).First());
                        //    if (FlowRule_result.Count() != 0)
                        //    {
                        //        var LastStationID = FlowRule_result.Where(w => w.StationID != 1000).OrderBy(o => o.Sequence).Select(s => s.StationID).Last();

                        //        if (item.StationID != LastStationID || item.RuleStatus != "P" || item.StatusID != -1)
                        //        {
                        //            _msg += "序號【" + item.BarcodeNo + "】,流程尚未完成,不可入庫!<br>";
                        //        }
                        //    }
                        //    else
                        //    {
                        //        _msg = "查無序號" + item.BarcodeNo + "目前流程(flowID)";
                        //    }
                        //}

                        //else
                        //{
                        //    _msg = "查無序號" + item.BarcodeNo + "目前流程(rule_station_ID)";
                        //}
                    }
                    if (_msg == string.Empty)
                    {

                        var FlowRules_result = await _basApi.GetFlowRulesByUnit("W");
                        if (FlowRules_result.Count() != 0)
                        {
                            var FlowRuleID = FlowRules_result.Select(s => s.FlowRuleID).First();
                            var ruleStations_result = await GetRuleStationByFlowRuleID(FlowRuleID);
                            if (ruleStations_result.Count() != 0)
                            {
                                var StationID = ruleStations_result.Select(s => s.StationID).First();


                                var Wipinfo_result = await _pcsApi.GetWipInfo(result.Select(s => s.WipID).First());
                                var Wipinfo_LineID = Wipinfo_result.Select(s => s.LineID).First();  //lineid
                                var WipAtt_result = await _pcsApi.GetWipAtt(Wipinfo_result.Select(s => s.WipNO).First()); //料號
                                var Userinfo_result = await _sysApi.GetUserInfo(GetLogInUserID());

                                //修改FQC_inhouse_Master LocationNO
                                var fqcInhouseMaster = await _fqcApi.GetFqcInhouseMaster(InhouseNo, seq);
                                fqcInhouseMaster.LocationNo = locationNo;

                                var result_FQC = await _fqcApi.PutFqcInhouseMaster(JsonConvert.SerializeObject(fqcInhouseMaster));
                                if (!result_FQC.Success)
                                {
                                    _msg = result_FQC.Msg;
                                    return new Result() { success = false, msg = _msg };
                                }

                                List<PTD101AMESModel> PTD101AMESModels = new List<PTD101AMESModel>();
                                foreach (var item in result)
                                {

                                    BarcodeInfo barcodeInfo = new BarcodeInfo
                                    {
                                        BarcodeID = item.BarcodeID,
                                        BarcodeNo = item.BarcodeNo,
                                        StatusNo = item.StatusNo,
                                        ExtraBarcodeNo = item.ExtraBarcodeNo,
                                        StationID = StationID,
                                        RuleStatus = "P",//F 不良 
                                        BoxNo = item.BoxNo,
                                        WipID = item.WipID,
                                        StatusID = -1,
                                        CreateUserID = item.CreateUserID,
                                        CreateDate = item.CreateDate,
                                        UpdateDate = System.DateTime.Now


                                    };

                                    var resultPutBInfo = await _pcsApi.PutBarcodeInfoes(JsonConvert.SerializeObject(barcodeInfo));
                                    if (!resultPutBInfo.Success)
                                    {
                                        _msg = resultPutBInfo.Msg;
                                        return new Result() { success = false, msg = _msg };
                                    }

                                    var barcodeStations = new BarcodeStation
                                    {
                                        BarcodeID = item.BarcodeID,
                                        WipID = item.WipID,
                                        StationID = StationID,
                                        FlowRuleID = FlowRuleID,
                                        RuleStatus = "P",
                                        InputDate = DateTime.Now,
                                        LineId = (int)Wipinfo_LineID,
                                        CreateUserID = item.CreateUserID,
                                        GetRuleStation = new RuleStation
                                        {
                                            //RuleStationID = RuleStationID,
                                            //FlowRuleID = "",
                                            //StationID ="",
                                            //StationDescl
                                            //Sequence="",
                                            //StationType = "",
                                            //CreateUserId =item.CreateUserID,
                                            //CreateDate = DateTime.Now,
                                            //UpdateDate = DateTime.Now


                                        }
                                    };
                                    var resultPoutBStation = await _pcsApi.PostBarcodeStation(JsonConvert.SerializeObject(barcodeStations));
                                    if (!resultPoutBStation.Success)
                                    {
                                        _msg = resultPoutBStation.Msg;
                                        return new Result() { success = false, msg = _msg };
                                    }


                                    PTD101AMESModels.Add(new PTD101AMESModel
                                    {
                                        FQCID = InhouseNo,
                                        SSN = item.ExtraBarcodeNo,
                                        ISN = item.BarcodeNo,
                                        RecordNumber = recordNumber,
                                        PN = WipAtt_result.ItemNO,
                                        EmpID = Userinfo_result.Select(s => s.UserNo).FirstOrDefault(),
                                        Location = AppSetting.Setting.Location,
                                        Key = AppSetting.Setting.PTD101Key


                                    });


                                }

                                var Warehouseing = new WareHouseing
                                {
                                    InhouseNo = InhouseNo,
                                    SeqID = seq,
                                    SerialNo = boxNo,
                                    Serial_Type = "B",
                                    RecordNumber = recordNumber,
                                    Create_UserID = Userinfo_result.Select(s => s.UserID).FirstOrDefault(),
                                    Create_Date = DateTime.Now,
                                    LocationNo = locationNo
                                };

                                var resultPostWH = await _pcsApi.PostWareHouseing(JsonConvert.SerializeObject(Warehouseing));
                                if (!resultPostWH.Success)
                                {
                                    _msg = resultPostWH.Msg;
                                    return new Result() { success = false, msg = _msg };
                                }

                                await _pcsApi.PostPTD101AMES(JsonConvert.SerializeObject(PTD101AMESModels));


                            }
                            else
                            {
                                _msg = "入庫代碼(W)查無設定站別";
                            }

                        }
                        else
                        {
                            _msg = "查無入庫代碼(W)";
                        }

                        if (_msg == string.Empty)
                        {
                            //執行入庫作業
                            return new Result() { success = true, msg = "入庫完成" };
                        }
                        else
                        {
                            return new Result() { success = false, msg = _msg };
                        }
                    }
                    else
                    {
                        return new Result() { success = false, msg = _msg };
                    }
                }
                catch (Exception ex)
                {
                    _msg = ex.ToString();
                    return new Result() { success = false, msg = _msg };
                }

            }
            else
            {
                return new Result() { success = false, msg = "箱號:" + boxNo + "沒有序號資料" };
            }



        }


        #endregion

        #region PCS031V入庫單箱號查詢
        public async Task<IActionResult> PCS031V(string InhouseNo, int SeqID)
        {
            var model = new FqcDto();
            model.InhouseNo = InhouseNo;// "QWO0002A1001";
            model.SeqID = SeqID;
            IResultModel<FqcDto> result;
            result = await _fqcApi.GetFqcQuery(model.InhouseNo, model.SeqID);

            if (result.Data.Count() != 0)
            {
                model = result.Data.FirstOrDefault();
                model.h_InhouseNo = model.InhouseNo;
                model.h_SeqID = model.SeqID.ToString();
            }
            else
            {
                ModelState.AddModelError("error", "找不到入庫單號【" + model.InhouseNo + "】的資料");
                model.h_InhouseNo = "";
                model.h_SeqID = "";
            }

            return View("PCS031V", model);
            //  return View(model);
        }


        [HttpGet]
        public async Task<IActionResult> PCS031VAsync(FqcDto model)
        {
            if (string.IsNullOrWhiteSpace(model.InhouseNo))
            {
                ModelState.AddModelError("error", "請輸入入庫單號");
                return View("PCS031V", model);
            }

            IResultModel<FqcDto> result;

            result = await _fqcApi.GetFqcQuery(model.InhouseNo, model.SeqID);

            if (result.Data.Count() != 0)
            {
                model = result.Data.FirstOrDefault();
                model.h_InhouseNo = model.InhouseNo;
                model.h_SeqID = model.SeqID.ToString();
            }
            else
            {
                ModelState.AddModelError("error", "找不到入庫單號【" + model.InhouseNo + "】的資料");
                model.h_InhouseNo = "";
                model.h_SeqID = "";
            }

            return View("PCS031V", model);
        }


        #endregion

        #region PCS031Q入庫單箱號查詢
        // [HttpGet]
        public async Task<IActionResult> PCS031Q(string BoxNo)
        {


            var model = new BoxNO_SNDto();
            model.BoxNo = BoxNo;
            return View(model);

            //IResultModel<BoxNO_SNDto> result;

            //result = await _pcsApi.GetBarcodeInfoesByBoxNoPCS031Q(boxNo: model.BoxNo);


            //if (result.Data.Count() != 0)
            //{
            //    model = result.Data.FirstOrDefault();

            //    model.BoxNo = model.BoxNo;

            //}
            //else
            //{
            //    ModelState.AddModelError("error", "找不到箱號單號【" + model.BoxNo + "】的序號資料");
            //    model.BoxNo = "";

            //}
            ////// ViewBag.BoxNO = boxNo;
            //return View("PCS031Q", model);
        }
        [ResponseCache(Duration = 0)]
        [HttpGet]
        public async Task<IActionResult> PCS031QQueryAsync(string id, int page = 0, int limit = 10)
        {


            IResultModel<BoxNO_SNDto> result = await _pcsApi.GetBarcodeInfoesByBoxNoPCS031Q(boxNo: id, page: page, limit: limit);
            if (result.Data.Count() != 0)
            {

                return Json(new Table() { code = 0, msg = "", data = result.Data, count = result.Data.Count() });
            }
            return Json(new Table() { count = 0, data = null });
        }


        #endregion

        //YIRU End  -------------------------------------------------------------------------------------------------------------------------------

        /// <summary>
        /// 登入UserID
        /// </summary>
        /// <returns></returns>
        public int GetLogInUserID()
        {
            int user_id = 0;
            HttpContext.Request.Cookies.TryGetValue("UserID", out string userID);

            if (userID != null)
            {
                if (int.Parse(userID.ToString()) >= 0)
                {
                    user_id = int.Parse(userID.ToString());
                }
            }
            return user_id;
        }

        #region PCS033組件资料维护相关

        public IActionResult PCS033()
        {
            return View();
        }
        //新增頁面
        public async Task<IActionResult> PCS033C()
        {
            var id = GetLogInUserID();
            ViewBag.UserID = id;
            var result = await _sysApi.GetUserInfo(id);
            var name = result[0].UserName;
            ViewBag.UserName = name;
            return View();
        }

        //頁面提交,id=0 添加,id>0 修改
        [HttpPost]
        public async Task<IActionResult> PCS033CSaveAsync(SampleSipmentSN model)
        {

            if (ModelState.IsValid)
            {
                IResultModel result;
                IResultModel result2;

                result2 = await _pcsApi.GetSampleSerialRule(model.Qty);
                if (result2.Success)
                {
                    string str, str1;
                    var strA = result2.Msg.Split("-");
                    str = strA[0];
                    str1 = strA[1];
                    model.StartNo = str;
                    model.EndNo = str1;
                    result = await _pcsApi.PostSampleSipmentSN(JsonConvert.SerializeObject(model));
                    if (result.Success)
                    {
                        var _msg = "取得序號成功!,序號為[" + result2.Msg + "]";
                        return RedirectToAction("Refresh", "Home", new { msg = _msg });
                    }
                    else
                    {

                        ModelState.AddModelError("error", result.Msg);

                    }
                }
                else
                {

                    ModelState.AddModelError("error", "取得序號失敗");


                }
            }
            return View("PCS033C", model);

        }

        [ResponseCache(Duration = 0)]
        [HttpGet]
        public async Task<IActionResult> GetSampleSipmentSNsAsync()
        {

            var result = await _pcsApi.GetSampleSipmentSNs();

            if (result.Count > 0)
            {
                return Json(new Table() { code = 0, msg = "", data = result, count = result.Count });
            }

            return Json(new Table() { count = 0, data = null });
        }
        [ResponseCache(Duration = 0)]
        [HttpGet]
        public async Task<IActionResult> GetSampleSipmentSNsByQueryAsync(string itemNo, string wipNo, string userName, string Sdate, string Edate)
        {
            if (string.IsNullOrEmpty(wipNo))
                wipNo = "*";
            if (string.IsNullOrEmpty(itemNo))
                itemNo = "*";
            if (string.IsNullOrEmpty(userName))
                userName = "*";
            if (string.IsNullOrEmpty(Sdate))
                Sdate = "*";
            if (string.IsNullOrEmpty(Edate))
                Edate = "*";

            var result = await _pcsApi.GetSampleSipmentSNsByQurey(itemNo, wipNo, userName, Sdate, Edate);

            if (result.Count > 0)
            {
                return Json(new Table() { code = 0, msg = "", data = result, count = result.Count });
            }

            return Json(new Table() { count = 0, data = null });
        }

        #endregion

        #region PCS035 工單查詢-投產可修改
        public async Task<IActionResult> PCS035(string id)
        {
            if (id != null)
            {
                await GetFactoryUnit(id);
                ViewBag.UnitNo = id;
            }
            else
            {
                await GetFactoryUnit();
            }

            //await GetFactoryUnit();
            return View();
        }
        #endregion

        #region PCS036 條碼解除出貨序號及箱號
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public IActionResult PCS036()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> PCS036Async(PCS036ViewModel model, string select)
        {
            IResultModel result;
            var _msg = string.Empty;
            // 內部條碼
            if (select == "0")
            {
                if (string.IsNullOrWhiteSpace(model.BarCodeNo))
                {
                    ModelState.AddModelError("error", "請輸入內部條碼");
                    return View(model);
                }

                var q = await _pcsApi.GetBarcodeInfoesByNo(model.BarCodeNo);
                if (q.Count == 0)
                {
                    ModelState.AddModelError("error", "內部序號【" + model.BarCodeNo + "】,找不到");
                    return View(model);
                }

                BarcodeInfo barcodeInfo = q.FirstOrDefault();
                barcodeInfo.BoxNo = "";
                barcodeInfo.ExtraBarcodeNo = "";
                barcodeInfo.UpdateDate = DateTime.Now;
                result = await _pcsApi.PutBarcodeInfoes(JsonConvert.SerializeObject(barcodeInfo));
                if (result.Success)
                {
                    _msg += "內部序號【" + model.BarCodeNo + "】解除綁定成功!";
                }
                else
                {
                    _msg += "內部序號【" + model.BarCodeNo + "】解除綁定失敗!";
                }
            }

            // 條碼區間
            if (select == "1")
            {
                if (string.IsNullOrWhiteSpace(model.BarCodeNoStr) || string.IsNullOrWhiteSpace(model.BarCodeNoEnd))
                {
                    ModelState.AddModelError("error", "請確定都有輸入條碼區間");
                    return View(model);
                }

                if (model.BarCodeNoStr.Length != model.BarCodeNoEnd.Length)
                {
                    ModelState.AddModelError("error", "條碼區間起訖長度不相同");
                    return View(model);
                }

                // 流水碼預設長度
                int NoLength = 4;
                if (model.BarCodeNoStr.Length <= NoLength || model.BarCodeNoEnd.Length <= NoLength)
                {
                    ModelState.AddModelError("error", "條碼區間號碼長度不能小於" + NoLength + 1);
                    return View(model);
                }

                if (model.BarCodeNoStr.Substring(0, model.BarCodeNoStr.Length - NoLength) !=
                    model.BarCodeNoEnd.Substring(0, model.BarCodeNoEnd.Length - NoLength))
                {
                    ModelState.AddModelError("error", "條碼區間前置號碼不一樣");
                    return View(model);
                }


                if (!int.TryParse(model.BarCodeNoStr.Substring(model.BarCodeNoStr.Length - NoLength, NoLength), out _) ||
                    !int.TryParse(model.BarCodeNoEnd.Substring(model.BarCodeNoEnd.Length - NoLength, NoLength), out _))
                {
                    ModelState.AddModelError("error", "條碼區間流水碼格式錯誤");
                    return View(model);
                }

                var NoStr = int.Parse(model.BarCodeNoStr.Substring(model.BarCodeNoStr.Length - NoLength, NoLength));
                var NoEnd = int.Parse(model.BarCodeNoEnd.Substring(model.BarCodeNoEnd.Length - NoLength, NoLength));
                if (NoStr > NoEnd)
                {
                    ModelState.AddModelError("error", "條碼區間結束流水碼不可以小於條碼區間起始流水碼");
                    return View(model);
                }

                var BarCode = model.BarCodeNoEnd.Substring(0, model.BarCodeNoEnd.Length - NoLength);

                for (int i = NoStr; i <= NoEnd; i++)
                {
                    var itemBarcodeNo = BarCode + i.ToString().PadLeft(NoLength, '0');
                    var q_BarcodeInfo = await _pcsApi.GetBarcodeInfoesByNo(itemBarcodeNo);

                    if (q_BarcodeInfo.Count != 0)
                    {
                        BarcodeInfo barcodeInfo = q_BarcodeInfo.FirstOrDefault();
                        barcodeInfo.BoxNo = "";
                        barcodeInfo.ExtraBarcodeNo = "";
                        barcodeInfo.UpdateDate = DateTime.Now;
                        result = await _pcsApi.PutBarcodeInfoes(JsonConvert.SerializeObject(barcodeInfo));
                        //if (result.Success)
                        //{
                        //    _msg += "解除綁定成功";
                        //}
                        //else
                        //{
                        //    _msg += "解除綁定失敗";
                        //}
                    }
                }

                _msg = "條碼區間【" + model.BarCodeNoStr + "】 ~ 【" + model.BarCodeNoEnd + "】解除綁定成功";
            }

            // 新增Log
            var unbindExtraBarcode = new UnbindExtraBarcode
            {
                StartBarcodeNo = select == "0" ? model.BarCodeNo : model.BarCodeNoStr,
                EndBarcodeNo = select == "0" ? model.BarCodeNo : model.BarCodeNoEnd,
                UnbindReason = model.Remark,
                CreateUserID = GetLogInUserID()
            };
            await _pcsApi.PostUnbindExtraBarcode(JsonConvert.SerializeObject(unbindExtraBarcode));

            ModelState.AddModelError("error", _msg);
            return View(model);
        }
        #endregion

        #region 工單相關資料新增或更新
        /// <summary>
        /// 工單相關資料新增或更新
        /// </summary>
        /// <param name="model">WipDataViewModel Dto</param>
        /// <param name="formFile">檔案上傳</param>
        /// <returns>Msg:錯誤訊息 Model:工單資訊相關Model</returns>
        private async Task<(string Msg, WipDataViewModel model)> WipExecuteDB(WipDataViewModel model, IFormFile formFile)
        {
            string Msg = string.Empty;
            IResultModel result;
            // 登入UserID
            var UserID = GetLogInUserID();

            try
            {
                // 工單基本資料 WipInfo
                result = await _pcsApi.PutWipInfo(JsonConvert.SerializeObject(model.wipInfo));

                if (!result.Success)
                    Msg += result.Msg;
                else
                {
                    // 工單屬性 WipAtt
                    model.wipAtt.WipNO = model.wipInfo.WipNO;
                    result = await _pcsApi.PutWipAtt(JsonConvert.SerializeObject(model.wipAtt));
                    if (!result.Success)
                    {
                        Msg += result.Msg;
                    }

                    // 標籤 WipLabel
                    model.wipLabel.ApproveLogo = model.wipLabel.ApproveLogos == null ? null : string.Join(',', model.wipLabel.ApproveLogos);
                    model.wipLabel.WipNO = model.wipInfo.WipNO;
                    model.wipLabel.CreateUserID = UserID;
                    model.wipLabel.UpdateUserID = UserID;
                    result = await _pcsApi.PutWipLabel(JsonConvert.SerializeObject(model.wipLabel));
                    if (!result.Success)
                    {
                        Msg += result.Msg;
                    }

                    // 安勤統一執行WipSystem
                    if (ViewBag.WipSpecial == "Y")
                    {
                        // 測試備註空白 帶工單描述
                        if (string.IsNullOrWhiteSpace(model.wipSystem.TestMemo))
                        {
                            model.wipSystem.TestMemo = model.wipInfo.Description;
                        }

                        model.wipSystem.ItemNo = model.wipAtt.ItemNO;
                        model.wipSystem.WipNo = model.wipInfo.WipNO;
                        model.wipSystem.CreateUserID = UserID;
                        model.wipSystem.UpdateUserID = UserID;
                        result = await _pcsApi.PutWipSystem(JsonConvert.SerializeObject(model.wipSystem));
                        if (!result.Success)
                        {
                            Msg += result.Msg;
                        }
                    }
                    else
                    {
                        // 系統WipSystem
                        if (model.wipInfo.UnitNO == "B" || model.wipInfo.UnitNO == "P" || model.wipInfo.UnitNO == "T")
                        {
                            // 測試備註空白 帶工單描述
                            if (string.IsNullOrWhiteSpace(model.wipSystem.TestMemo))
                            {
                                model.wipSystem.TestMemo = model.wipInfo.Description;
                            }

                            model.wipSystem.ItemNo = model.wipAtt.ItemNO;
                            model.wipSystem.WipNo = model.wipInfo.WipNO;
                            model.wipSystem.CreateUserID = UserID;
                            model.wipSystem.UpdateUserID = UserID;
                            result = await _pcsApi.PutWipSystem(JsonConvert.SerializeObject(model.wipSystem));
                            if (!result.Success)
                            {
                                Msg += result.Msg;
                            }
                        }
                        else
                        // 板卡 WipBoard
                        {
                            model.wipBoard.Smd = model.wipBoard.SMDs == null ? null : string.Join(',', model.wipBoard.SMDs);
                            model.wipBoard.SmdSolderMask = model.wipBoard.SmdSolderMasks == null ? null : string.Join(',', model.wipBoard.SmdSolderMasks);
                            model.wipBoard.DipSide = model.wipBoard.DipSides == null ? null : string.Join(',', model.wipBoard.DipSides);
                            model.wipBoard.ItemNo = model.wipAtt.ItemNO;
                            model.wipBoard.WipNo = model.wipInfo.WipNO;
                            model.wipBoard.CreateUserID = UserID;
                            model.wipBoard.UpdateUserID = UserID;
                            result = await _pcsApi.PutWipBoard(JsonConvert.SerializeObject(model.wipBoard));
                            if (!result.Success)
                            {
                                Msg += result.Msg;
                            }
                        }
                    }

                    // 內部條碼 WipBaocode
                    if (!string.IsNullOrWhiteSpace(model.wipBarcode.Remarks))
                    {
                        model.wipBarcode.WipID = model.wipInfo.WipID;
                        model.wipBarcode.WipNO = model.wipInfo.WipNO;
                        model.wipBarcode.UnitNO = model.wipInfo.UnitNO;
                        model.wipBarcode.CreateUserID = UserID;
                        result = await _pcsApi.PutWipBarcode(JsonConvert.SerializeObject(model.wipBarcode));
                        if (!result.Success)
                        {
                            Msg += result.Msg;
                        }
                    }

                    // 工單MAC WipMAC
                    if (!string.IsNullOrWhiteSpace(model.wipMAC.StartNO) && !string.IsNullOrWhiteSpace(model.wipMAC.EndNO))
                    {
                        if (model.wipMAC.StartNO.Length == 12)
                        {
                            model.wipMAC.Title = model.wipMAC.StartNO.Substring(0, 6).ToUpper();
                            model.wipMAC.StartNO = model.wipMAC.StartNO.Substring(model.wipMAC.StartNO.Length - 6, 6).ToUpper();
                            model.wipMAC.EndNO = model.wipMAC.EndNO.Substring(model.wipMAC.EndNO.Length - 6, 6).ToUpper();

                            // 確認MAC Table是否有料號資料
                            var mACInfo = await _pcsApi.GetMACInfo(model.wipAtt.ItemNO);
                            if (mACInfo != null)
                            {
                                model.wipMAC.ClassGroup = mACInfo.ClassGroup;
                            }

                            if (!string.IsNullOrWhiteSpace(model.wipMAC.WipNO))
                                result = await _pcsApi.PutWipMAC(JsonConvert.SerializeObject(model.wipMAC));
                            else
                            {
                                model.wipMAC.WipNO = model.wipInfo.WipNO;
                                model.wipMAC.CreateUserID = UserID;
                                result = await _pcsApi.PostWipMAC(JsonConvert.SerializeObject(model.wipMAC));
                            }

                            if (!result.Success)
                            {
                                Msg += result.Msg;
                            }
                        }
                    }

                    // 工單 KeyParts WipKp 
                    // 判斷料號KP有資料 沒有資料時 一起新增到料號KP
                    // 2022.10.12 取消判斷 刪除料號KP,在逐一新增
                    var materialItem = await _pcsApi.GetMaterialItemByItemNO(model.wipAtt.ItemNO);
                    if (materialItem != null)
                    {
                        await _pcsApi.DeleteMaterialKpByItem(materialItem.ItemID);
                    }

                    // 先比對新舊ID 當舊ID有 新的沒有代表已刪除
                    var resultOld_WipKp = await _pcsApi.GetWipKpByWipNo(model.wipInfo.WipNO);
                    var delete_WipKpID = resultOld_WipKp.Select(s => s.WipKpID).Except(model.WipKps.Select(s => s.WipKpID));
                    foreach (var id in delete_WipKpID)
                    {
                        await _pcsApi.DeleteWipKp(id);
                    }

                    foreach (var item in model.WipKps.Where(w => w.WipKpID != -1))
                    {
                        item.WipNo = model.wipInfo.WipNO;
                        item.ItemNo = model.wipAtt.ItemNO;
                        item.CreateUserID = UserID;
                        item.UpdateUserID = UserID;
                        if (item.WipKpID == 0)
                            result = await _pcsApi.PostWipKp(JsonConvert.SerializeObject(item));
                        else
                            result = await _pcsApi.PutWipKp(JsonConvert.SerializeObject(item));

                        if (!result.Success)
                        {
                            Msg += result.Msg;
                        }

                        // 新增到料號KP檔 MaterialKp
                        result = await _pcsApi.PostMaterialKp(JsonConvert.SerializeObject(new MaterialKp
                        {
                            ItemID = materialItem.ItemID,
                            KpName = item.KpName,
                            KpNo = item.KpNo,
                            KpSeq = Convert.ToInt32(item.KpSeq),
                            Length = item.Length,
                            StationType = item.UnitNo,
                            IsRepeat = "N",
                            Title = item.Title,
                            CreateUserID = UserID,
                            UpdateUserID = UserID
                        }));
                        if (!result.Success)
                        {
                            Msg += result.Msg;
                        }
                    }
                    model.WipKps = model.WipKps.Where(w => w.WipKpID != -1).ToList();

                    // 工單 治具 WipOutfit
                    // 先比對新舊ID 當舊ID有 新的沒有代表已刪除
                    var resultOld_WipOutfit = await _pcsApi.GetWipOutfitByWipNo(model.wipInfo.WipNO);
                    var delete_WipOutfit = resultOld_WipOutfit.Select(s => s.WipOutfitID).Except(model.WipOutfits.Select(s => s.WipOutfitID));
                    foreach (var id in delete_WipOutfit)
                    {
                        await _pcsApi.DeleteWipOutfit(id);
                    }
                    foreach (var item in model.WipOutfits.Where(w => w.WipOutfitID != -1))
                    {
                        item.WipNo = model.wipInfo.WipNO;
                        item.ItemNo = model.wipAtt.ItemNO;
                        item.UpdateUserID = UserID;
                        item.CreateUserID = UserID;
                        item.OutfitNo = ".";
                        if (item.WipOutfitID == 0)
                            result = await _pcsApi.PostWipOutfit(JsonConvert.SerializeObject(item));
                        else
                            result = await _pcsApi.PutWipOutfit(JsonConvert.SerializeObject(item));

                        if (!result.Success)
                        {
                            Msg += result.Msg;
                        }
                    }
                    model.WipOutfits = model.WipOutfits.Where(w => w.WipOutfitID != -1);

                    // SOP
                    // 先比對新舊ID 當舊ID有 新的沒有代表已刪除
                    var resultOld_WipSop = await _pcsApi.GetWipSopByWipNo(model.wipInfo.WipNO);
                    var delete_WipSop = resultOld_WipSop.Select(s => s.WipSOPID).Except(model.WipSops.Select(s => s.WipSOPID));
                    foreach (var id in delete_WipSop)
                    {
                        await _pcsApi.DeleteWipSop(id);
                    }
                    foreach (var item in model.WipSops.Where(w => w.WipSOPID != -1))
                    {
                        item.WipNo = model.wipInfo.WipNO;
                        item.ItemNo = model.wipAtt.ItemNO;
                        item.CreateUserID = UserID;
                        item.UpdateUserID = UserID;
                        if (item.WipSOPID == 0)
                            result = await _pcsApi.PostWipSop(JsonConvert.SerializeObject(item));
                        else
                            result = await _pcsApi.PutWipSop(JsonConvert.SerializeObject(item));

                        if (!result.Success)
                        {
                            Msg += result.Msg;
                        }
                    }
                    model.WipSops = model.WipSops.Where(w => w.WipSOPID != -1);

                    // 檔案上傳
                    string FileName = string.Empty;
                    string NewName = string.Empty;
                    string FilePath = string.Empty;

                    if (formFile != null)
                    {
                        if (formFile.Length > 0)
                        {
                            //取得使用者上傳檔案的原始檔名
                            FileName = Path.GetFileName(formFile.FileName);
                            //取原始檔名中的副檔名
                            //var fileExt = Path.GetExtension(FileName);
                            //為避免使用者上傳的檔案名稱發生重複,重新給一個亂數名稱
                            //NewName = Path.GetRandomFileName() + fileExt;
                            //指定要寫入的路徑、檔名和副檔名
                            FilePath = $@"{_env.WebRootPath}\UploadFolder\{model.wipInfo.WipNO}";
                            var path = $@"{FilePath}\{FileName}";

                            if (!System.IO.Directory.Exists(FilePath))
                            {
                                System.IO.Directory.CreateDirectory(FilePath);
                            }

                            using (var stream = new FileStream(path, FileMode.Create))
                            {
                                await formFile.CopyToAsync(stream);
                            }

                            model.wipInfoBlob.WipNo = model.wipInfo.WipNO;
                            model.wipInfoBlob.ImageName = FileName;
                            model.wipInfoBlob.Filepath = $@"\UploadFolder\{model.wipInfo.WipNO}\";
                            model.wipInfoBlob.CreateUserID = UserID;
                            model.wipInfoBlob.UpdateUserID = UserID;
                            result = await _pcsApi.PostWipInfoBlob(JsonConvert.SerializeObject(model.wipInfoBlob));
                            if (!result.Success)
                            {
                                Msg += result.Msg;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Msg += $"Exception:{ex.Message}";
            }
            return (Msg, model);
        }
        #endregion
    }
   
    public static class ObjectExtension
    {
        public static T GetAttributeFrom<T>(this object instance, string propertyName) where T : Attribute
        {
            var attributeType = typeof(T);
            var property = instance.GetType().GetProperty(propertyName);
            if (property == null) return default(T);
            return (T)property.GetCustomAttributes(attributeType, false).FirstOrDefault();
        }
    }
   


}