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 Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using AMESCoreStudio.WebApi.Enum;

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 IFileServerProvider _fileServerProvider;
        private readonly IWebHostEnvironment _env;

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

        #region Funcion BLL


        /// <summary>
        /// 工單建立時判斷是否都有資料
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string CheckWipInfoInsert(WipDataViewModel model)
        {
            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 + ",";

            // 序號編碼sheet


            // 系統
            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;
        }

        public string CheckWipInfoInsert_WipSystem(WipSystem model)
        {
            string Msg = string.Empty;

            // 判斷預設值是否更改過,如果有就判斷必填欄位
            if (!string.IsNullOrWhiteSpace(model.BiTemperature) ||
                !string.IsNullOrWhiteSpace(model.BiTime) ||
                !string.IsNullOrWhiteSpace(model.BiMemo) ||
                !string.IsNullOrWhiteSpace(model.Checksum) ||
                !string.IsNullOrWhiteSpace(model.Bios))
            {
                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.BiTime))
                    Msg += model.GetAttributeFrom<DisplayAttribute>(nameof(model.BiMemo)).Name + ",";

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

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

            }

            return Msg;
        }

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

            // 判斷預設值是否更改過,如果有就判斷必填欄位
            if (model.BiRatio != 0 ||
                model.BiosVer != 0 ||
                model.PartsBakeTime != 0 ||
                model.PcbBake != 0 ||
                !string.IsNullOrWhiteSpace(model.BiTemperature) ||
                !string.IsNullOrWhiteSpace(model.BiTime) ||
                !string.IsNullOrWhiteSpace(model.Checksum) ||
                !string.IsNullOrWhiteSpace(model.BurnLocation))
            {
                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();

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

            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>
        /// <returns></returns>
        private async Task GetFactoryUnit()
        {
            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));
            }

            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>RuleStationID</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].StationDesc, 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",
                }
            };

            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>
        /// 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.Contains(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 != null)
            {
                values = SelectedValue.Split(',').ToList();
            }
            else
                values.Add("F"); //預設
            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 != null)
            {
                values = SelectedValue.Split(',').ToList();
            }
            else
                values.Add("F"); //預設
            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 = null)
        {
            List<string> values = new List<string>();
            if (SelectedValue != null)
            {
                values = SelectedValue.Split(',').ToList();
            }
            else
                values.Add("A"); //預設
            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 WipNp
        /// </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 == null)
                return Json(new { data = "" });
            else

                return Json(new { data = result.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, rulestationID);

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

        /// <summary>
        /// 用工單號碼查詢綁定作業站
        /// </summary>
        /// <returns>RuleStation </returns>
        [HttpPost]
        public async Task<JsonResult> GetRuleStationByWipNoUnitNoJson(string wipNo)
        {

            var result_wipNo = await _pcsApi.GetWipInfoByWipNO(wipNo);

            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
                };
                var result = await _pcsApi.GetRuleStationByFlow(flowRuleID);

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

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

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

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



        /// <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 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();
            //var result = new WipAllViewModel();
            //return View(result);

            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.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.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)
        {

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

                //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;
                    }
                }

                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);
            }
            await GetItemsList();
            await GetProductType();
            await GetFactoryInfo();
            await GetFactoryUnit();
            await GetLineInfo();
            await GetMFGType();
            await GetProcessTypes();
            await GetMaterialFlowRuleJson(model.wipAtt.ItemNO, model.wipInfo.UnitNO);
            await GetOutfitCommodityInfoJson();
            await GetFactoryUnitByWipNoJson(model.wipInfo.WipNO);
            await GetRuleStationByWipNoUnitNoJson(model.wipInfo.WipNO);
            GetWipSEQType();
            GetBurnType();
            GetPartsBakeType();
            GetPCBBakeTypeSelect();
            GetPCBProcessingTypeSelect();
            GetSolderPasteSelect();
            GetWipType();
            GetWipSystemTypeSelect();
            GetWipSystemPMTypeSelect();
            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)
        {
            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 });
                }

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

                //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;
                    }
                }

                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);
            }
            await GetItemsList();
            await GetProductType();
            await GetFactoryInfo();
            await GetFactoryUnit();
            await GetLineInfo();
            await GetMFGType();
            await GetProcessTypes();
            await GetMaterialFlowRuleJson(model.wipAtt.ItemNO, model.wipInfo.UnitNO);
            await GetOutfitCommodityInfoJson();
            await GetFactoryUnitByWipNoJson(model.wipInfo.WipNO);
            await GetRuleStationByWipNoUnitNoJson(model.wipInfo.WipNO);
            GetWipSEQType();
            GetBurnType();
            GetPartsBakeType();
            GetPCBBakeTypeSelect();
            GetPCBProcessingTypeSelect();
            GetSolderPasteSelect();
            GetWipType();
            GetWipSystemTypeSelect();
            GetWipSystemPMTypeSelect();
            GetSOPTypeSelect();
            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);
        }
        [HttpPost]
        public async Task<IActionResult> PCS003Async(WipDataViewModel model, string action, IFormFile formFile)
        {



            #region 選單
            await GetItemsList();
            await GetProductType();
            await GetFactoryInfo();
            await GetFactoryUnit();
            await GetLineInfo();
            await GetMFGType();
            await GetProcessTypes();
            await GetFlowRuleList();
            await GetFactoryUnitByWipNoJson(model.wipInfo.WipNO);
            await GetMaterialFlowRuleJson(model.wipAtt.ItemNO, model.wipInfo.UnitNO);
            await GetOutfitCommodityInfoJson();
            await GetRuleStationByWipNoUnitNoJson(model.wipInfo.WipNO);
            GetWipSEQType();
            GetBurnType();
            GetPartsBakeType();
            GetPCBBakeTypeSelect();
            GetPCBProcessingTypeSelect();
            GetSolderPasteSelect();
            GetWipType();
            GetWipSystemTypeSelect();
            GetSOPTypeSelect();
            GetCheckboxApproveLogo();
            GetCheckboxCompanyLogo();
            GetCheckboxPrintMode();
            GetCheckboxWipAttr();
            GetCheckboxDIP();
            GetCheckboxSMD();
            GetWipSystemPMTypeSelect();

            #endregion

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

            IResultModel result;
            // 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.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);

            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.wipBoard.DipCarrier = model.wipBoard.DipCarrier == "Y" ? "true" : "false";
                //model.wipBoard.DipTape = model.wipBoard.DipTape == "Y" ? "true" : "false";
                //model.wipBoard.Burn = model.wipBoard.Burn == "Y" ? "true" : "false";
                ////系統
                //model.wipSystem.FinePackage = model.wipSystem.FinePackage == "Y" ? "true" : "false";
                ModelState.AddModelError("error", Msg);

                return View("PCS003", model);
            }

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

                return View("PCS003", model);
            }

            // 判斷MAC是否正確
            var CheckMACMsg = CheckMACData(model);
            if (!string.IsNullOrWhiteSpace(CheckMACMsg))
            {
                ModelState.AddModelError("error", CheckMACMsg);
                return View("PCS003", model);
            }

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

                    if (!RuleStation.Where(w => Outfits.RuleStationID == w.RuleStationID).Any())
                    {
                        ModelState.AddModelError("error", "治具組合中生產單位與作業站不匹配");
                        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;
                await _pcsApi.PutWipLabel(JsonConvert.SerializeObject(model.wipLabel));

                // 系統
                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;
                            await _pcsApi.PutWipSystem(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.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;
                            await _pcsApi.PutWipBoard(JsonConvert.SerializeObject(model.wipBoard));
                        }
                    }
                }

                //// 工單對應SOP
                //var q = await _pcsApi.GetMaterialSopQuery(itemNo: model.wipAtt.ItemNO, unitNo: model.wipInfo.UnitNO, state: "Y");
                //if (q.Data.Count() != 0)
                //{
                //    model.wipSop.MaterialSopID = q.Data.FirstOrDefault().MaterialSopID;
                //    await _pcsApi.PostWipSop(JsonConvert.SerializeObject(model.wipSop));
                //}

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

                }

                // 出貨序號
                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;
                        if (model.wipBarcodeOther.OtherID != 0)
                            result = await _pcsApi.PutWipBarcodeOther(JsonConvert.SerializeObject(model.wipBarcodeOther));
                        else
                            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;
                            result = await _pcsApi.PostWipMAC(JsonConvert.SerializeObject(model.wipMAC));
                        }
                    }
                }
                // 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;
                    if (item.WipKpID == 0)
                        await _pcsApi.PostWipKp(JsonConvert.SerializeObject(item));
                    else
                        await _pcsApi.PutWipKp(JsonConvert.SerializeObject(item));
                }

                // 治具
                // 先比對新舊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;
                    if (item.WipOutfitID == 0)
                        await _pcsApi.PostWipOutfit(JsonConvert.SerializeObject(item));
                    else
                        await _pcsApi.PutWipOutfit(JsonConvert.SerializeObject(item));
                }

                // 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;
                    if (item.WipSOPID == 0)
                        await _pcsApi.PostWipSop(JsonConvert.SerializeObject(item));
                    else
                        await _pcsApi.PutWipSop(JsonConvert.SerializeObject(item));
                }

                // 檔案上傳
                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 + FileName, FileMode.Create))
                        {
                            await formFile.CopyToAsync(stream);
                        }

                        model.wipInfoBlob.WipNo = model.wipInfo.WipNO;
                        model.wipInfoBlob.ImageName = FileName;
                        model.wipInfoBlob.Filepath = FilePath;
                        result = await _pcsApi.PostWipInfoBlob(JsonConvert.SerializeObject(model.wipInfoBlob));
                    }
                }
            }


            WipCheck wipCheck = new WipCheck
            {
                WipNo = model.wipInfo.WipNO
            };
            if (action == "生管確認")
            {
                await _pcsApi.PutWipCheckByPMC(JsonConvert.SerializeObject(wipCheck));
            }
            else if (action == "工程確認")
            {
                await _pcsApi.PutWipCheckByPE(JsonConvert.SerializeObject(wipCheck));
            }
            else if (action == "製造確認")
            {
                await _pcsApi.PutWipCheckByMF(JsonConvert.SerializeObject(wipCheck));
            }

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

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

                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對應" });
        }
        #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();
            // 流水碼預設長度
            int NoLength = 4;
            string _msg = string.Empty;
            int WipQty = model.WipInfo.PlanQTY;
            string InputStartNo = model.WipBarcode.StartNO.Trim();
            string InputEndNo = model.WipBarcode.EndNO.Trim();
            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("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.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.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()
        {
            await GetFactoryUnit();
            return View();
        }

        /// <summary>
        /// PCS005 Query
        /// </summary>
        /// <param name="unitno">生產單位</param>
        /// <param name="wipno">工單號碼</param>
        /// <param name="itemNo">料號</param>
        /// <returns></returns>
        public async Task<IActionResult> PCS005QueryAsync(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);

            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()
        {
            await GetFactoryUnit();
            return View();
        }

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

        [ResponseCache(Duration = 0)]
        [HttpGet]
        public async Task<IActionResult> PCS006QueryAsync(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 = 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);
                }
            }

            await _pcsApi.PostWipLog(JsonConvert.SerializeObject(wipLog));
            await _pcsApi.PutWipinfoToStatusNO(wipID, statusNO);
            //if (result.)
            //{
            //    var msg = "修改失敗!";
            //    return Json(msg);
            //}
            var _msg = "修改成功!";
            return Json(_msg);
        }

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

        #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();
                model.BarCodeNo = result_barcodeinfo.BarcodeNo;
            }

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

            if (result_barcodeinfo == null)
            {
                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.WipNO,
                        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.CreateUserID.ToString(),
                    InputDate = barcodestation.CreateDate.ToString()
                });
            }

            // 組件清單
            var barcodeitems = await _pcsApi.GetBarcodeItemByBarCodeID(result_barcodeinfo.BarcodeID);
            foreach (var barcodeitem in barcodeitems.OrderBy(o => o.CreateDate))
            {
                result.BarCodeKPs.Add(new BarCodeKP
                {
                    Station = barcodeitem.S.StationDesc,
                    KPPartNo = barcodeitem.PartNo,
                    KPItemNo = barcodeitem.KpItemNo,
                    InputDate = barcodeitem.CreateDate.ToString()
                });
            }

            // 治具清單
            var barcodeoutfits = await _pcsApi.GetBarcodeOutfitByBarcodeNo(model.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()
                });
            }

            // 組件變更
            var barcodeitemchanges = await _pcsApi.GetBarcodeItemChangesByBarCodeID(result_barcodeinfo.BarcodeID);
            foreach (var barcodeitemchange in barcodeitemchanges.OrderBy(o => o.CreateDate))
            {
                result.KPChanges.Add(new KPChange
                {
                    KPPartNo = barcodeitemchange.PartNoOld,
                    KPItemNo = barcodeitemchange.ItemNo,
                    ChangeType = barcodeitemchange.ChangeType,
                    Date = barcodeitemchange.CreateDate.ToString(),
                    User = barcodeitemchange.CreateUserID.ToString()
                });
            }


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

        //[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> PCS011Async(WipLock model)
        {
            IResultModel result;

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

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

                // 流水碼預設長度
                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).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 PCS021 條碼輸入作業
        [ResponseCache(Duration = 0)]
        [HttpGet]
        public async Task<IActionResult> PCS021()
        {
            var model = new PCS021ViewModel();
            await GetFactoryUnit();
            //await GetLineInfo();
            //await GetStation();
            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> PCS021_GetWip(PCS021ViewModel model)
        {
            await GetFactoryUnit();
            await GetItemsList();
            //await GetLineInfo();

            if (string.IsNullOrWhiteSpace(model.WipNO))
            {
                ModelState.AddModelError("error", "請輸入工單號碼");
            }

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

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

            //if (model.RolwStation == 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);
                if (model.Station != 0)
                {
                    model.RuleStation = ruleStations.Where(w => w.StationID == model.Station).FirstOrDefault().RuleStationID;
                    model.StationTypeNo = ruleStations.Where(w => w.StationID == model.Station).FirstOrDefault().Station.TypeNo;
                }
                else
                {
                    model.RuleStation = ruleStations.FirstOrDefault().RuleStationID;
                    model.StationTypeNo = ruleStations.FirstOrDefault().Station.TypeNo;
                }

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

                // 工單KeyParts
                model.WipKps = await _pcsApi.GetWipKpByWipNo(model.WipNO);
                model.WipKps = model.WipKps.Where(w => w.UnitNo == model.UnitNO).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.RuleStationID == model.RuleStation).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.RuleStationID == null) ||
                                       (w.UnitNo == model.UnitNO && w.RuleStationID == model.RuleStation)).ToList();
                    model.wipOutfits.Clear();
                    foreach (var item in q1)
                    {
                        model.wipOutfits.Add(new WipOutfitDtos
                        {
                            OutfitNo = item.OutfitNo,
                            PartNo = item.PartNo,
                            StationName = item.StationName,
                            UnitNoName = item.UnitNoName
                        }
                       );
                    }
                }

                //var wipsop = await _pcsApi.GetWipSop(q.FirstOrDefault().WipID);
                //if (wipsop != null)
                //{
                //    ////model.SopPath = wipsop.GetMaterialSop.FilePath + wipsop.GetMaterialSop.NewName;
                //}

            }

            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;

            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 Kp = model.Inputs.Where(w => !w.Input.Contains("$")).ToList(); // 撈非不良代碼 = 組件序號
            var q = await _pcsApi.GetBarCodeFromWip(model.Input);
            // 判斷是否用內部序號有對應到工單號碼,沒對應到視為組件或不良代碼
            if (q.Success)
            {
                #region 確認序號的狀態
                // 比對內序號的工單號碼與過站工單號碼是否一致
                if (q.Msg == model.WipNO)
                {
                    // Input為內部序號
                    model.Barcode = true;

                    //// 確認內部序號是否報廢
                    //var BarCodeScrapped = await _pcsApi.CheckBarCodeScrapped(Data);
                    //if (!BarCodeScrapped.Success)
                    //    return Json(new Result() { success = BarCodeScrapped.Success, msg = BarCodeScrapped.Msg, data = Data });

                    //// 確認內部序號是否鎖定
                    //var BarCodeLock = await _pcsApi.CheckBarCodeLock(Data);
                    //if (!BarCodeLock.Success)
                    //    return Json(new Result() { success = BarCodeLock.Success, msg = BarCodeLock.Msg, data = Data });

                    // 取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 BarCodeFlow = await _pcsApi.CheckBarCodeFlow(model.WipNO, model.Input, model.UnitNO, model.Station);
                    //if (!BarCodeFlow.Success)
                    //    return Json(new Result() { success = BarCodeFlow.Success, msg = BarCodeFlow.Msg, data = Data });


                    // 下一個作業站是完工站時再判斷是否都有刷組件
                    // 判斷組件是否都有輸入
                    //if (Kp.Count() != 0)
                    //{
                    //    var CheckBarCodeKP = await _pcsApi.CheckBarCodeKP(model.WipNO, model.Input, model.UnitNO, Kp);
                    //    if (!CheckBarCodeKP.Success)
                    //        return Json(new Result() { success = CheckBarCodeKP.Success, msg = CheckBarCodeKP.Msg, data = Data });

                    //    if (CheckBarCodeKP.Data != null)
                    //        ExtNo = CheckBarCodeKP.Data.FirstOrDefault();
                    //}

                    var keyParts = new List<BarCodeCheckDto.inputItem>();
                    // 先查詢已綁定組件數量
                    var BarCodeItems = await _pcsApi.GetBarcodeItemByBarCode(model.Input);
                    int KpItemQty = BarCodeItems.Count();
                    int i = 0;
                    foreach (var KeyPartItem in model.Inputs)
                    {
                        // 判斷是組件先+1
                        if (!KeyPartItem.Input.Contains("$"))
                            i += 1;

                        // 當刷入組組件+已紀錄組件數量 大於 設定組件數量
                        if (i + KpItemQty > model.WipKps.Count())
                        {
                            Msg = "已刷超過組件數量";
                            Success = false;
                            return Json(new Result() { success = Success, msg = Msg, data = Data });
                        }
                        keyParts.Add(new BarCodeCheckDto.inputItem
                        {
                            inputType = KeyPartItem.Input.Contains("$") ? "NG" : model.WipKps[i - 1 + KpItemQty].KpNo,
                            inputData = KeyPartItem.Input,
                            oldInputData = KeyPartItem.InputNo
                        });
                    }

                    // 治具
                    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",
                        station = model.Station,
                        line = model.LineID,
                        unitNo = model.UnitNO,
                        inputItems = keyParts,
                        outfits = outfit
                    };

                    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 = "內部序號【" + Data + "】 過站完成!";
                        Data = string.Empty;
                    }
                }
                else
                {
                    Msg += "內部序號工單號碼與過站工單不相同</br>";
                }
                #endregion
            }


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

            #region 過站判斷正常 往下處理Table 移到API執行

            //if (model.Barcode)
            //{
            //    #region 內部序號輸入後新增 or 更新
            //    string BarStatusNo = _basApi.GetFactoryUnit(model.UnitNO).InvokeAsync().Result.FirstOrDefault().UnitCode;

            //    // 新增or更新 BarCode_Info
            //    var barcodeInfos = await _pcsApi.GetBarcodeInfoesByNo(model.Input);
            //    if (barcodeInfos.Count() != 0)
            //    {
            //        model.BarCodeID = barcodeInfos[0].BarcodeID;

            //        barcodeInfos[0].StatusNo = BarStatusNo;
            //        barcodeInfos[0].ExtraBarcodeNo = ExtNo;
            //        barcodeInfos[0].RuleStationID = model.RuleStation;
            //        barcodeInfos[0].RuleStatus = !model.BarcodeNG ? "P" : "F"; //F 不良 
            //        barcodeInfos[0].WipID = model.WipID;
            //        barcodeInfos[0].StatusID = NextStopCloseStation.Success ? -1 : 1;
            //        barcodeInfos[0].UpdateDate = DateTime.Now;
            //        await _pcsApi.PutBarcodeInfoes(JsonConvert.SerializeObject(barcodeInfos[0]));
            //    }
            //    else
            //    {
            //        BarcodeInfo barcodeInfo = new BarcodeInfo
            //        {
            //            BarcodeNo = model.Input,
            //            StatusNo = BarStatusNo,
            //            RuleStationID = model.RuleStation,
            //            RuleStatus = !model.BarcodeNG ? "P" : "F",//F 不良 
            //            WipID = model.WipID,
            //            StatusID = NextStopCloseStation.Success ? -1 : 1,
            //            CreateUserID = 1
            //        };
            //        var resultBarCodeInfo = await _pcsApi.PostBarcodeInfoes(JsonConvert.SerializeObject(barcodeInfo));
            //        if (resultBarCodeInfo.Success)
            //            model.BarCodeID = (int)resultBarCodeInfo.Data.Select(s => s.BarcodeID).FirstOrDefault();
            //    }

            //    // 新增 BarCodeStation
            //    BarcodeStation barcodeStation = new BarcodeStation
            //    {
            //        BarcodeID = model.BarCodeID,
            //        WipID = model.WipID,
            //        RuleStationID = model.RuleStation,
            //        RuleStatus = !model.BarcodeNG ? "P" : "F", //F 不良 
            //        InputDate = DateTime.Now,
            //        LineId = model.LineID
            //    };
            //    await _pcsApi.PostBarcodeStation(JsonConvert.SerializeObject(barcodeStation));

            //    // 新增 BarCodeItem
            //    // 先查詢已綁定組件數量
            //    var BarCodeItems = await _pcsApi.GetBarcodeItemByBarCodeID(model.BarCodeID);
            //    int KpItemQty = BarCodeItems.Count();

            //    for (int i = 0; i < Kp.Count(); i++)
            //    {
            //        // 
            //        if (ExtNo == Kp[i])
            //            continue;

            //        var barcodeItem = new BarcodeItem
            //        {
            //            BarcodeID = model.BarCodeID,
            //            WipID = model.WipID,
            //            RuleStationID = model.RuleStation,
            //            ItemNo = model.MaterialKps[i + KpItemQty].KpNo,
            //            PartNo = Kp[i],
            //            SysType = "S",
            //            CreateUserID = 0,
            //            CreateDate = DateTime.Now,
            //            UpdateDate = DateTime.Now
            //        };
            //        await _pcsApi.PostBarcodeItem(JsonConvert.SerializeObject(barcodeItem));
            //    }
            //    #endregion

            //    // 新增 BarCodeWip 投入站新增 for 只有投入站才新增
            //    if (model.StationSEQ == 1)
            //    {
            //        BarcodeWip barcodeWip = new BarcodeWip
            //        {
            //            BarcodeID = model.BarCodeID,
            //            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]));

            //    }

            //    // 判斷有不良代碼 新增 NgInfo NgComponent  
            //    if (model.BarcodeNG)
            //    {
            //        foreach (var NGNo in model.Inputs.Where(w => w.Contains("$")))
            //        {
            //            var FixtureNo = string.Join(",", model.MaterialOutfits.Select(s => s.Inputs).ToArray());
            //            NgInfo ngInfo = new NgInfo
            //            {

            //                TypeNo = model.StationTestType,
            //                OperatorID = 0,
            //                FixtureNo = string.IsNullOrWhiteSpace(FixtureNo) ? "-1" : FixtureNo,
            //                BarcodeID = model.BarCodeID,
            //                ReasonNo = NGNo,
            //                ProgramNo = "N/A",
            //                MachineNo = "N/A",
            //                StationId = model.Station,
            //                WipId = model.WipID
            //            };
            //            var resultNgInfo = await _pcsApi.PostNgInfo(JsonConvert.SerializeObject(ngInfo));
            //            if (resultNgInfo.Success)
            //            {
            //                NgComponent ngComponent = new NgComponent
            //                {
            //                    NgID = resultNgInfo.Data.FirstOrDefault().NgID,
            //                    LocationNo = "N/A",
            //                    NgNo = NGNo
            //                };
            //                await _pcsApi.PostNgComponent(JsonConvert.SerializeObject(ngComponent));
            //            }
            //        }
            //    }

            //    #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]));

            //            }

            //            // 新增 NgInfo 不良時新增 判斷有不良代碼
            //            if (model.BarcodeNG)
            //            {
            //                foreach (var NGNo in model.Inputs.Where(w => w.Contains("$")))
            //                {
            //                    var FixtureNo = string.Join(",", model.MaterialOutfits.Select(s => s.Inputs).ToArray());
            //                    NgInfo ngInfo = new NgInfo
            //                    {

            //                        TypeNo = model.StationTestType,
            //                        OperatorID = 0,
            //                        FixtureNo = string.IsNullOrWhiteSpace(FixtureNo) ? "-1" : FixtureNo,
            //                        BarcodeID = model.BarCodeID,
            //                        ReasonNo = NGNo,
            //                        ProgramNo = "N/A",
            //                        MachineNo = "N/A",
            //                        StationId = model.Station,
            //                        WipId = model.WipID
            //                    };
            //                    var resultNgInfo = await _pcsApi.PostNgInfo(JsonConvert.SerializeObject(ngInfo));
            //                    if (resultNgInfo.Success)
            //                    {
            //                        NgComponent ngComponent = new NgComponent
            //                        {
            //                            NgID = resultNgInfo.Data.FirstOrDefault().NgID,
            //                            LocationNo = "N/A",
            //                            NgNo = NGNo
            //                        };
            //                        await _pcsApi.PostNgComponent(JsonConvert.SerializeObject(ngComponent));
            //                    }
            //                }
            //            }
            //        }
            //    }
            //    #endregion

            //    Msg = "內部序號【" + Data + "】 過站完成!";
            //    Data = string.Empty;

            //}
            #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);
                    }
                }

                // 確認完工數是否等於工單數
                // await _pcsApi.CheckWipNoBarCodeAllClost(model.WipNO, model.UnitNO, model.RuleStation);
            }

            return Json(new Result() { success = Success, msg = Msg, data = Data + "@" + model.InputNo }); // 刷入條碼+異常欄位
        }
        #endregion

        #region PCS024條碼組件维护相关

        public async Task<IActionResult> PCS024()
        {
            await GetFactoryUnit();
            return View();
        }
        //新增頁面
        public async Task<IActionResult> PCS024C(string id)
        {
            var result = await _pcsApi.GetBarcodeInfoesByNo(id);
            var tt = result[0];
            ViewBag.BarcodeID = tt.BarcodeID;
            ViewBag.WipID = tt.WipID;
            ViewBag.BarcodeNo = id;
            await GetFactoryUnit();
            //await GetStations();
            await GetItems();
            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 = "" });
        }

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

            var bNo = model.B.BarcodeNo;
            if (ModelState.IsValid)
            {
                IResultModel result;
                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.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> GetBarcodeItemByUnitAsync(string ID)
        {
            string str, str1;
            var strA = ID.Split("=");
            str = strA[0];
            str1 = strA[1];
            //WO0002A10001

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

            var result = await _pcsApi.GetBItemByStr(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 });
        }

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

        [HttpPost]
        public JsonResult TestFunc(string number)
        {
            string hashNumber = number;
            string name = "";

            if (number == "A12345")
            {
                name = "Annie";
            };

            return Json(name);
        }

        //修改页面
        [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.RuleStationID = barcodeItemOld.RuleStationID;
                barcodeItemChange.WipID = barcodeItemOld.WipID;
                barcodeItemChange.KpItemNo = barcodeItemOld.KpItemNo;
                barcodeItemChange.CreateUserID = barcodeItemOld.CreateUserID;
                barcodeItemChange.CreateDate = System.DateTime.Now;
                barcodeItemChange.UpdateDate = System.DateTime.Now;

                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.RuleStationID = barcodeItemOld.RuleStationID;
            barcodeItemChange.WipID = barcodeItemOld.WipID;
            barcodeItemChange.KpItemNo = barcodeItemOld.KpItemNo;
            barcodeItemChange.CreateUserID = barcodeItemOld.CreateUserID;
            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 });

            }

        }

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

        [HttpPost]
        public async Task<IActionResult> PCS027CAsync(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();
            return View(model);
        }

        #endregion

        public async Task<IActionResult> PCS999()
        {
            return View();
        }

        //頁面提交,id=0 添加,id>0 修改
        [HttpPost]
        public async Task<IActionResult> PCS999Async(MaterialKpDtos model)
        {
            var aa = "string";
            return View(model);
        }

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


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