using System;
using System.Collections;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using Siger.Middlelayer.Common;
using System.Web;
using System.Threading.Tasks;
using System.IO;
using System.Reflection;
using Newtonsoft.Json;
using Siger.ApiCommon.Result;
using Siger.ApiDNC.Utility;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.DncRepository.Repositories.Interface;
using Siger.Middlelayer.DncRepository.Request;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.DncRepository.Entities;
using Siger.Middlelayer.DncRepository.Response;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Repository.Paged;
using SharpCompress.Compressors.Xz;
using NPOI.HPSF;

namespace Siger.ApiDNC.Controllers
{
    public class DncPgCreateController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerProjectDncUserPowerRepository _sigerProjectDncUserPowerRepository;
        private readonly ISigerProjectDncProgramRepository _sigerProjectDncProgramRepository;
        private readonly ISigerProjectProductRepository _sigerProjectProduct;
        private readonly ISigerProjectMachineRepository _machineRepository;

        public DncPgCreateController(IUnitOfWork unitOfWork, ISigerProjectDncUserPowerRepository sigerProjectDncUserPowerRepository, 
            ISigerProjectDncProgramRepository sigerProjectDncProgramRepository, ISigerProjectProductRepository sigerProjectProduct,
            ISigerProjectMachineRepository machineRepository)
        {
            _unitOfWork = unitOfWork;
            _sigerProjectDncUserPowerRepository = sigerProjectDncUserPowerRepository;
            _sigerProjectDncProgramRepository = sigerProjectDncProgramRepository;
            _sigerProjectProduct = sigerProjectProduct;
            _machineRepository = machineRepository;
        }

        /// <summary>
        /// 根据权限获取按钮
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetCheckbuttons()
        {
            return new ObjectResult(_sigerProjectDncUserPowerRepository.GetCheckbuttons(UserId));
        }

        /// <summary>
        /// 获取审核人员
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetCheckUsers()
        {
            return new ObjectResult(_sigerProjectDncUserPowerRepository.GetCheckUsers(ProjectId));
        }

        /// <summary>
        /// //获取产品名称
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetProducts()
        {
            return new ObjectResult(_sigerProjectDncUserPowerRepository.GetProducts(ProjectId));
        }

        /// <summary>
        /// 获取部门信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetsectionLists()
        {
            return new ObjectResult(_sigerProjectDncUserPowerRepository.GetsectionLists(ProjectId));
        }

        /// <summary>
        /// 程序创建->权限设置->添加->GetUsers
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        //参数为null查询所有数据
        public IActionResult GetUsers(int? sectionID)
        {
            return new ObjectResult(_sigerProjectDncUserPowerRepository.GetUsers(ProjectId, sectionID));
        }

        /// <summary>
        /// 添加权限
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddPower(RequestAddPower req)
        {
            //未选择任何权限
            if (req.add_power == (int)PowerStatu.OFF && req.del_power == (int)PowerStatu.OFF
                                                     && req.check_power == (int)PowerStatu.OFF && req.all_power == (int)PowerStatu.OFF)
            {
                throw new BadRequestException(RequestEnum.SelectNoPower);
            }

            //存在配置数据不允许保存
            var power = _sigerProjectDncUserPowerRepository.Get(f => f.mid == req.mid && f.status == (int)RowState.Valid);
            if (power != null)
            {
                throw new BadRequestException(RequestEnum.DataExist);
            }

            var result = _sigerProjectDncUserPowerRepository.AddPower(ProjectId, UserId, req.mid, req.add_power, req.del_power, req.check_power, req.all_power, req.remark);
            if (!result)
            {
                throw new BadRequestException(RequestEnum.NoPermission);
            }
            return new ObjectResult(CommonEnum.Succefull);
        }

        /// <summary>
        /// 获取人员权限信息
        /// </summary>
        /// <param name="powerid"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetPowerUserInfo(int powerid)
        {
            return new ObjectResult(_sigerProjectDncUserPowerRepository.GetPowerUserInfo(ProjectId, powerid));
        }

        /// <summary>
        /// 修改权限
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult EditPower(RequestEditPower req)
        {
            var result = _sigerProjectDncUserPowerRepository.EditPower(UserId, req.powerid, req.add_power, req.del_power, req.check_power, req.all_power, req.remark, ProjectId);
            if (!result)
            {
                throw new BadRequestException(RequestEnum.NoPermission);
            }
            return new ObjectResult(CommonEnum.Succefull);
        }

        /// <summary>
        /// 删除人员
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult DelPower(RequestDelPower req)
        {
            var result = _sigerProjectDncUserPowerRepository.DelPower(UserId, req.powerid);
            if (!result)
            {
                throw new BadRequestException(RequestEnum.NoPermission);
            }
            return new ObjectResult(CommonEnum.Succefull);
        }

        /// <summary>
        /// 权限设置列表
        /// </summary>
        /// <param name="sectionID"></param>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetPowerLists(int? sectionID, int page = 1, int pagesize = 10)
        {
            var data = _sigerProjectDncUserPowerRepository.GetPowerLists(ProjectId, sectionID, page, pagesize, out int totalCount);
            return new PagedObjectResult(data, totalCount, page, pagesize);
        }

        /// <summary>
        /// 验证程序号--是否有重复程序号
        /// </summary>
        /// <param name="programcode">程序号</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult CheckProgramCode(string programcode)
        {
            var data = _sigerProjectDncProgramRepository.Get(f => f.program_code == programcode && f.projectid == ProjectId && f.status == (int)RowState.Valid);
            if (data == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            return new ObjectResult(CommonEnum.Succefull);
        }

        /// <summary>
        /// 查询程序号是否已存在
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult programCodePost(RequestAddProgram req)
        {
            var data = _sigerProjectDncProgramRepository.Get(f => f.program_code == req.programcode && f.projectid == ProjectId && f.status == (int)RowState.Valid);
            if (data == null)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }

            throw new BadRequestException(RequestEnum.ProgramIsExist);
        }

        /// <summary>
        /// 主程序号是否重复
        /// </summary>
        /// <param name="programcode"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult CheckprogramCodeMainPost(string programcode)
        {
            var data = _sigerProjectDncProgramRepository.Get(f => f.program_code == programcode && f.projectid == ProjectId && f.status == (int)RowState.Valid
            && f.program_type == (int)progromType.Main);
            if (data == null)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }

            throw new BadRequestException(RequestEnum.ProgramIsExist);
        }

        /// <summary>
        /// 审核页面判断是否有重复程序号
        /// </summary>
        /// <param name="programcode"></param>
        /// <param name="programId"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult CheckprogramCodeMain(string programcode, int programId)
        {
            var data = _sigerProjectDncProgramRepository.Get(f => f.program_code == programcode && f.projectid == ProjectId && f.status == (int)RowState.Valid
            && f.program_type == (int)progromType.Main && f.id != programId);
            if (data == null)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }

            throw new BadRequestException(RequestEnum.ProGramCheckIsExist);
        }


        /// <summary>
        /// 添加程序
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddProgramPost(RequestAddProgram req)
        {
            if (string.IsNullOrEmpty(req.file_url) || string.IsNullOrEmpty(req.programcode) || req.productid == 0 || req.checkmid == 0)
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }
            var program = new siger_project_dnc_program
            {
                checkstatus = (int)CheckState.Waiting,
                program_code = req.programcode,
                productid = req.productid,
                checkmid = req.checkmid,
                create_remark = req.createremark,
                createmid = UserId,
                projectid = ProjectId,
                createtime = UnixTimeHelper.GetNow(),
                file_url = req.file_url,
                file_name = req.file_name,
                file_size = req.file_size
            };

            _sigerProjectDncProgramRepository.Insert(program);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }
        /// <summary>
        /// 添加主程序子程序
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddProgramPosts([FromBody] RequestAddProgramAll req)
        {
            var detail = new List<siger_project_dnc_program>();
            var guidCode = Guid.NewGuid().ToString();
            var version = string.Empty;

            foreach (var data in req.programs)
            {
                if (string.IsNullOrEmpty(data.file_url) || string.IsNullOrEmpty(data.programcode) || req.productid == 0 || req.checkmid == 0 || string.IsNullOrEmpty(req.process_code))
                {
                    throw new BadRequestException(RequestEnum.ParameterMiss);
                }
                var versionData = _sigerProjectDncProgramRepository.GetList(f => f.program_code == data.programcode && f.projectid == ProjectId
            && f.program_type == (int)progromType.Main).OrderByDescending(s=>s.createtime).FirstOrDefault();

                if (versionData != null)
                {
                    version = "V" + (versionData.program_version.Split('V')[1].ToInt() + 1).ToStr();
                }
                else
                {
                    version = "V1";
                }

                var programs = new siger_project_dnc_program()
                {
                    guid_code = guidCode,
                    checkstatus = (int)CheckState.Waiting,
                    program_code = data.programcode,
                    productid = req.productid,
                    checkmid = req.checkmid,
                    create_remark = req.createremark,
                    createmid = UserId,
                    projectid = ProjectId,
                    createtime = UnixTimeHelper.GetNow(),
                    program_type = data.program_type,
                    file_url = data.file_url,
                    file_name = data.file_name,
                    file_size = data.file_size,
                    process_code = req.process_code,
                    program_number = data.program_type == (int)progromType.Main ? req.programs.Count - 1 : 0,
                    program_version = data.program_type == (int)progromType.Main ? version : ""
                };
                detail.Add(programs);
            }

            _sigerProjectDncProgramRepository.Insert(detail);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 获取程序列表
        /// </summary>
        /// <param name="programcode"></param>
        /// <param name="product_name"></param>
        /// <param name="checkstatus"></param>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetProgramLists(string programcode, string product_name, int checkstatus, int page = 1, int pagesize = 10)
        {
            var data = _sigerProjectDncUserPowerRepository.GetProgramLists(ProjectId, UserId, programcode, product_name, checkstatus, page, pagesize, out int totalCount);

            if (!data.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            foreach (var item in data)
            {
                item.program_code = HttpUtility.HtmlEncode(item.program_code);
            }
            return new PagedObjectResult(data, totalCount, page, pagesize);
        }
        /// <summary>
        /// 获取主程序列表
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="processCode"></param>
        /// <param name="programCode"></param>
        /// <param name="checkStatus"></param>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetProgramsLists(string productId, string processCode, string programCode, int checkStatus, int page=1, int pagesize=10)
        {
            var data = _sigerProjectDncUserPowerRepository.GetMainProgramLists(ProjectId, UserId, productId, processCode, programCode, checkStatus, page, pagesize);

            return new PagedObjectResult(data.Data, data.Total,page,pagesize); 
        }


        /// <summary>
        /// 程序调用列表根据产品ID和工序ID筛选程序
        /// </summary>
        /// <param name="keywords"></param>
        /// <param name="createBy"></param>
        /// <param name="checkBy"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetProgramsCheckedList(string keywords, string createBy, string checkBy, int startDate, int endDate, int product_id, int route_id, int page=1, int pagesize=10)
        {
            var data = _sigerProjectDncUserPowerRepository.GetMainProgramList(ProjectId, UserId, keywords, createBy, checkBy, startDate, endDate, product_id, route_id, page, pagesize);

            return new PagedObjectResult(data.Data, data.Total, page, pagesize);
        }
        /// <summary>
        /// 获取已审核数据
        /// </summary>
        /// <param name="keywords"></param>
        /// <param name="createBy"></param>
        /// <param name="checkBy"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetProgramsCheckedLists(string keywords, string createBy, string checkBy, int startDate, int endDate, int page = 1, int pagesize = 10)
        {
            var data = _sigerProjectDncUserPowerRepository.GetMainProgramListChecked(ProjectId, UserId, keywords, createBy, checkBy, startDate, endDate, page, pagesize);

            return new PagedObjectResult(data.Data, data.Total, page, pagesize);
        }
        /// <summary>
        /// 版本记录
        /// </summary>
        /// <param name="programCode"></param>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetProgramVersionRecord(string programCode,int page=1,int pagesize=10)
        {
            if(string.IsNullOrEmpty(programCode))
            {
                throw new BadRequestException(RequestEnum.ProgramNoNotNull);
            }
            var query = _sigerProjectDncProgramRepository.Get(s => s.program_code == programCode && s.checkstatus == (int)CheckState.Checked && s.status == (int)RowState.Valid);

            var data = _sigerProjectDncUserPowerRepository.GetProgramVersionInfo(programCode, UserId, ProjectId, page, pagesize);

            foreach(var item in data.Data)
            {
                if(query!=null)
                {
                    if(item.id==query.id)
                    {
                        item.isUse = true;
                    }
                }
            }
            return new PagedObjectResult(data.Data, data.Total, page, pagesize);
        }
        /// <summary>
        /// 版本切换
        /// </summary>
        /// <param name="programCode"></param>
        /// <param name="programId"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult ProgramVersionSwitch(string programCode,int programId)
        {
            if (string.IsNullOrEmpty(programCode))
            {
                throw new BadRequestException(RequestEnum.ProgramNoNotNull);
            }

            var versionNew = _sigerProjectDncProgramRepository.Get(f => f.program_code == programCode && f.projectid == ProjectId && f.id == programId
            && f.program_type == (int)progromType.Main);

            if (versionNew == null)
            {
                throw new BadRequestException(RequestEnum.ProgramNotFind);
            }
            var programsNew = _sigerProjectDncProgramRepository.GetList(g => g.guid_code == versionNew.guid_code).ToList();
            foreach (var item in programsNew)
            {
                var programUse = _sigerProjectDncProgramRepository.Get(item.id);
                if (programUse == null)
                {
                    throw new BadRequestException(CommonEnum.RecordNotFound);
                }
                programUse.status = (int)RowState.Valid;
                programUse.checkstatus = (int)CheckState.Waiting;
                _sigerProjectDncProgramRepository.Update(programUse);
            }
            if (_unitOfWork.Commit() <= 0)
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
            return new ObjectResult(CommonEnum.Succefull);
        }

        /// <summary>
        /// 获取程序信息
        /// </summary>
        /// <param name="programid"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetProgramInfo(int programid)
        {
            var data = _sigerProjectDncProgramRepository.GetProgramInfo(ProjectId, programid);
            if (data == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var filesize = string.IsNullOrEmpty(data.file_size) ? "" : FileUtility.GetFileSize(data.file_size.ToInt());
            var productname = string.IsNullOrEmpty(data.productname) ? "" : HttpUtility.HtmlDecode(data.productname);
            data.file_size = filesize;
            data.productname = productname;
            return new ObjectResult(data);
        }

        /// <summary>
        /// 获取主子程序信息
        /// </summary>
        /// <param name="programid"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMainProgramInfo(int programid)
        {
            var data = _sigerProjectDncProgramRepository.GetProgramInfos(ProjectId, programid);
            //var data = _sigerProjectDncProgramRepository.Get(s => s.projectid == ProjectId && s.id == programid);

            var response = new List<ResponseMainSonInfo>();
            var programsList = new List<ReponsePrograms>();
            if (data == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var dataList = _sigerProjectDncProgramRepository.GetList(s => s.guid_code == data.guidcode);
            foreach (var item in dataList)
            {
                programsList.Add(new ReponsePrograms
                {
                    file_name = item.file_name,
                    file_size = item.file_size,
                    file_url = item.file_url,
                    programcode = item.program_code,
                    programid = item.id,
                    program_type = item.program_type
                });
            }
            response.Add(new ResponseMainSonInfo
            {
                checkmid = data.checkmid,
                productid = data.productid,
                processid = data.processid,
                createremark = data.create_remark,
                process_name = data.processname,
                productname = data.productname,
                programs = programsList
            });
            return new ObjectResult(response);
        }
        /// <summary>
        /// 修改主子程序
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult EditProgram([FromBody] RequestAddProgramAll req)
        {
            var version = string.Empty;
            var detail = new List<siger_project_dnc_program>();
            var guid = Guid.NewGuid().ToStr();
            if (!_sigerProjectDncUserPowerRepository.HasEditPower(UserId))
            {
                throw new BadRequestException(RequestEnum.NoPermission);
            }

            var versionDataById = _sigerProjectDncProgramRepository.Get(f => f.id == req.programid && f.projectid == ProjectId && f.status == (int)RowState.Valid
            && f.program_type == (int)progromType.Main);
            var programList = _sigerProjectDncProgramRepository.GetList(s => s.guid_code == versionDataById.guid_code).ToList();

            foreach(var program in programList)
            {
                var programLists = _sigerProjectDncProgramRepository.Get(program.id);
                if(programLists==null)
                {
                    throw new BadRequestException(CommonEnum.RecordNotFound);
                }
                programLists.status = (int)RowState.Invalid;
                _sigerProjectDncProgramRepository.Update(programLists);
            }

            foreach (var item in req.programs)
            {
                if (string.IsNullOrEmpty(item.file_url) || string.IsNullOrEmpty(item.programcode) || req.productid == 0 || req.checkmid == 0 || string.IsNullOrEmpty(req.process_code))
                {
                    throw new BadRequestException(RequestEnum.ParameterMiss);
                }
                var versionData = _sigerProjectDncProgramRepository.GetList(f => f.program_code == item.programcode && f.projectid == ProjectId
            && f.program_type == (int)progromType.Main).OrderByDescending(s => s.createtime).FirstOrDefault();

                if (versionData != null)
                {
                    version = "V" + (versionData.program_version.Split('V')[1].ToInt() + 1).ToStr();
                }
                else
                {
                    version = "V1";
                }

                var programs = new siger_project_dnc_program()
                {
                    guid_code = guid,
                    checkstatus = (int)CheckState.Waiting,
                    program_code = item.programcode,
                    productid = req.productid,
                    checkmid = req.checkmid,
                    create_remark = req.createremark,
                    createmid = UserId,
                    projectid = ProjectId,
                    createtime = UnixTimeHelper.GetNow(),
                    program_type = item.program_type,
                    file_url = item.file_url,
                    file_name = item.file_name,
                    file_size = item.file_size,
                    process_code = req.process_code,
                    program_number = item.program_type == (int)progromType.Main ? req.programs.Count - 1 : 0,
                    program_version = item.program_type == (int)progromType.Main ? version : ""
                };
                detail.Add(programs);
            }
            _sigerProjectDncProgramRepository.Insert(detail);

            if (_unitOfWork.Commit() <= 0)
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
            return new ObjectResult(CommonEnum.Succefull);
        }

        /// <summary>
        /// 修改主子程序
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult EditMainSonProgram([FromBody] RequestEditProgram req)
        {
            if (!_sigerProjectDncUserPowerRepository.HasEditPower(UserId))
            {
                throw new BadRequestException(RequestEnum.NoPermission);
            }
            _sigerProjectDncProgramRepository.EditProgram(req.programid, req.file_url,
                                                         req.file_name, req.file_size,
                                                         req.productid, req.checkmid,
                                                         req.createremark, req.programcode);
            return new ObjectResult(CommonEnum.Succefull);
        }

        /// <summary>
        /// 删除程序
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult DelProgram([FromBody] RequestDelProgram req)
        {
            if (!_sigerProjectDncUserPowerRepository.HasDeletePower(UserId))
            {
                throw new BadRequestException(RequestEnum.NoPermission);
            }
            var entities = _sigerProjectDncProgramRepository.GetList(f => f.projectid == ProjectId && f.status != 0 && req.programid.Contains(f.id));
            foreach (var item in entities)
            {
                _sigerProjectDncProgramRepository.Delete(item);
            }
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }

            throw new BadRequestException(CommonEnum.DeleteFaild);
        }

        /// <summary>
        /// 删除主子程序
        /// </summary>
        /// <param name="programid"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult DelAllProgram(int programid)
        {
            if (!_sigerProjectDncUserPowerRepository.HasDeletePower(UserId))
            {
                throw new BadRequestException(RequestEnum.NoPermission);
            }
            var entities = _sigerProjectDncProgramRepository.Get(f => f.projectid == ProjectId && f.status == (int)RowState.Valid && f.id == programid);
            var program = _sigerProjectDncProgramRepository.GetList(g => g.guid_code == entities.guid_code).ToList();
            foreach (var item in program)
            {
                var programList = _sigerProjectDncProgramRepository.Get(item.id);
                programList.status = (int)RowState.Invalid;
                _sigerProjectDncProgramRepository.Update(programList);
            }
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }

            throw new BadRequestException(CommonEnum.DeleteFaild);
        }



        [HttpPost]
        public IActionResult DeletePrograms([FromBody] RequestDelPrograms req)
        {
            if (!_sigerProjectDncUserPowerRepository.HasDeletePower(UserId))
            {
                throw new BadRequestException(RequestEnum.NoPermission);
            }
            if (req.programids == null || !req.programids.Any())
            {
                throw new BadRequestException(RequestEnum.ParameterError);
            }

            foreach (var programid in req.programids)
            {
                _sigerProjectDncProgramRepository.Delete(programid);
            }
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }

            throw new BadRequestException(CommonEnum.DeleteFaild);
        }

        /// <summary>
        /// 获取程序审核页面的按钮
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetCheckbtns()
        {
            return new ObjectResult(_sigerProjectDncUserPowerRepository.GetCheckbuttons(UserId));
        }

        /// <summary>
        /// 获取程序审核页面列表
        /// </summary>
        /// <param name="programcode"></param>
        /// <param name="product_name"></param>
        /// <param name="checkstatus"></param>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetProgramCheckLists(string programcode, string product_name, int checkstatus, int page = 1, int pagesize = 10)
        {
            var data = _sigerProjectDncUserPowerRepository.GetProgramLists(ProjectId, UserId, programcode, product_name, checkstatus, page, pagesize, out int totalCount);
            return new PagedObjectResult(data, totalCount, page, pagesize);
        }

        /// <summary>
        /// 验证程序号--是否有已审核的重复程序号
        /// </summary>
        /// <param name="programcode"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult CheckProgramCodetwo(string programcode = "")
        {
            if (_sigerProjectDncProgramRepository.IsExist(f => f.program_code == programcode && f.checkstatus == (int)CheckState.Checked))
            {
                return new ObjectResult(CommonEnum.Succefull);
            }

            throw new BadRequestException(CommonEnum.RecordNotFound);
        }

        [HttpPost]
        public IActionResult CheckProgramPost([FromBody] RequestCheckProgramPost req)
        {
            if (!_sigerProjectDncUserPowerRepository.HasApprovalPower(UserId))
            {
                throw new BadRequestException(RequestEnum.NoPermission);
            }
            _sigerProjectDncProgramRepository.CheckProgramPost(ProjectId, UserId, req.programid,
                                                              req.check_remark ?? "", req.num, req.programcode ?? "");
            return new ObjectResult(CommonEnum.CheckSuccess);
        }

        [HttpPost]
        public IActionResult CheckProgramPosts([FromBody] RequestCheckProgramPosts req)
        {
            if (!_sigerProjectDncUserPowerRepository.HasApprovalPower(UserId))
            {
                throw new BadRequestException(RequestEnum.NoPermission);
            }

            if (req.programids == null || !req.programids.Any())
            {
                throw new BadRequestException(RequestEnum.ParameterError);
            }

            foreach (var program in req.programids)
            {
                _sigerProjectDncProgramRepository.CheckProgramPost(ProjectId, UserId, program.programid,
                    req.check_remark ?? "", req.num, program.programcode ?? "");
            }

            return new ObjectResult(CommonEnum.CheckSuccess);
        }
        /// <summary>
        /// 审核程序
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult CheckMainProgram([FromBody] RequestCheckProgramsNew req)
        {
            if (!_sigerProjectDncUserPowerRepository.HasApprovalPower(UserId))
            {
                throw new BadRequestException(RequestEnum.NoPermission);
            }

            if (req.programids==0)
            {
                throw new BadRequestException(RequestEnum.ParameterError);
            }

            var program = _sigerProjectDncProgramRepository.Get(req.programids);
            if (program.guid_code==null)
            {
                program.checkmid = UserId;
                program.checktime = UnixTimeHelper.GetNow();
                program.check_remark = req.check_remark ?? "";
                program.checkinfo = (req.num == (int)CheckInfo.OK) ? ((int)CheckInfo.OK) : ((int)CheckInfo.NOK);//1通过，2不通过
                program.checkstatus = (req.num == (int)CheckState.Waiting) ? ((int)CheckState.Checked) : ((int)CheckState.Reject);//1待审核，2已审核，3被拒绝

                _sigerProjectDncProgramRepository.Update(program);
                if (_unitOfWork.Commit() <= 0)
                {
                    throw new BadRequestException(CommonEnum.Fail);
                }

                return new ObjectResult(CommonEnum.CheckSuccess);
            }
            var programList = _sigerProjectDncProgramRepository.GetList(s => s.guid_code == program.guid_code).ToList();

            

            if (req.num != (int)CheckInfo.NOK)
            {
                var data = _sigerProjectDncProgramRepository.GetList(p => p.program_code == program.program_code && p.id != req.programids
                 && p.projectid == ProjectId && p.status == (int)RowState.Valid).ToList();

                if (data.Any())
                {
                    foreach (var old in data)
                    {
                        var oldProgramList = _sigerProjectDncProgramRepository.GetList(s => s.guid_code == old.guid_code).ToList();
                        foreach (var p in oldProgramList)
                        {
                            var son = _sigerProjectDncProgramRepository.Get(p.id);
                            son.status = (int)RowState.Invalid;
                            _sigerProjectDncProgramRepository.Update(son);
                        }
                    }
                }
            }

            foreach (var item in programList)
            {             
                var checkData = _sigerProjectDncProgramRepository.Get(item.id);
                checkData.checkmid = UserId;
                checkData.checktime = UnixTimeHelper.GetNow();
                checkData.check_remark = req.check_remark??"";
                checkData.checkinfo = (req.num == (int)CheckInfo.OK) ? ((int)CheckInfo.OK) : ((int)CheckInfo.NOK);//1通过，2不通过
                checkData.checkstatus = (req.num == (int)CheckState.Waiting) ? ((int)CheckState.Checked) : ((int)CheckState.Reject);//1待审核，2已审核，3被拒绝

                _sigerProjectDncProgramRepository.Update(checkData);
            }
            if (_unitOfWork.Commit() <= 0)
            {
                throw new BadRequestException(CommonEnum.Fail);
            }

            return new ObjectResult(CommonEnum.CheckSuccess);
        }

        /// <summary>
        /// 获取已审核的程序
        /// </summary>
        /// <param name="createmid">创建人</param>
        /// <param name="checkmid">审核人</param>
        /// <param name="product">产品名称及图纸号</param>
        /// <param name="starttime"></param>
        /// <param name="endtime"></param>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetProgramChecked(string createmid, string checkmid, string product, string starttime, string endtime,
                                               int page = 1, int pagesize = 10)
        {
            var start = (int)UnixTimeHelper.ConvertDataTimeLong(starttime);
            var end = (int)UnixTimeHelper.ConvertDataTimeLong(endtime.ToDateTime().AddDays(1).AddSeconds(-1).ToString());
            var data = _sigerProjectDncUserPowerRepository.GetProgramLists(ProjectId, UserId, createmid.ToStr(), checkmid.ToStr(), product.ToStr(),
                page, pagesize, start, end);
            return new PagedObjectResult(data.Data, data.Total, page, pagesize);
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Upload()
        {
            var files = Request.Form.Files;

            //同时只能上传一个文件
            if (1 != files.Count)
            {
                //只允许上传单个文件
                throw new BadRequestException(RequestEnum.ErrorFileCount);
            }

            var formFile = files.First();
            var allowTypes = new ArrayList { ".txt", ".eia", ".mpf", ".min", ".spf", ".zip", ".cnc", ".nc", ".prg", ".dwg", ".jpg", ".eng" };
            var fileType = Path.GetExtension(formFile.FileName).ToLower();
            if (!allowTypes.Contains(fileType))
            {
                //文件类型错误
                throw new BadRequestException(RequestEnum.ErrorFileType);
            }
            var physicaPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, CommonConst.UploadProgramFilePath);
            if (!Directory.Exists(physicaPath))
            {
                Directory.CreateDirectory(physicaPath);
            }

            try
            {
                var filePath = Path.Combine(physicaPath, Guid.NewGuid() + fileType);
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await formFile.CopyToAsync(stream);
                }

                return new ObjectResult(new { file_url = FileUtility.GetDisplayPath(filePath), name = formFile.FileName, size = formFile.Length });
            }
            catch (Exception e)
            {
                Logger.WriteLineError($"upload {formFile} failed, error:" + e.Message);
                throw new BadRequestException(RequestEnum.ImportFailed);
            }
        }

        /// <summary>
        /// 获取文件内容
        /// </summary>
        /// <param name="file_url"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetContent(string file_url)//,int type)
        {
            if (string.IsNullOrEmpty(file_url))
            {
                throw new BadRequestException(RequestEnum.ErrorFilePath);
            }
            if (file_url.ToLower().EndsWith(".zip") || file_url.ToLower().EndsWith(".dwg") || file_url.ToLower().EndsWith(".jpg") || file_url.ToLower().EndsWith(".eng"))
            {
                return new ObjectResult(new { content = "无法预览" });
            }
            var path = FileUtility.GetTruePath(file_url);
            if (!System.IO.File.Exists(path))
            {
                Logger.WriteLineError($"program getContent from:{path} failed");
                throw new BadRequestException(RequestEnum.ErrorFilePath);
            }
            var data = System.IO.File.ReadAllLines(path);

            return new ObjectResult(new { data.Length, content = FileUtility.GetText(path) });
        }
        /// <summary>
        /// 预览主程序子程序接口
        /// </summary>
        /// <param name="programId"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetAllContent(int programId)
        {
            var path = string.Empty;
            var programInfo = string.Empty;
            var programInfoList = new List<ResponsePrograms>();

            if (programId == 0)
            {
                throw new BadRequestException(RequestEnum.IdIsEmpty);
            }
            var programList = new List<siger_project_dnc_program>();
            var dataList = _sigerProjectDncProgramRepository.GetList(s => s.id == programId && s.status == (int)RowState.Valid && s.projectid == ProjectId);
            if (dataList.Any())
            {
                if (dataList.FirstOrDefault().guid_code != null)
                {
                    programList = _sigerProjectDncProgramRepository.GetList(s => s.guid_code == dataList.FirstOrDefault().guid_code && s.projectid == ProjectId).OrderBy(s => s.program_type).ToList();
                }
                else
                {
                    programList = dataList.ToList();
                }
            }

            foreach (var data in programList)
            {
                if (string.IsNullOrEmpty(data.file_url))
                {
                    throw new BadRequestException(RequestEnum.ErrorFilePath);
                }
                if (data.file_url.ToLower().EndsWith(".zip") || data.file_url.ToLower().EndsWith(".dwg") || data.file_url.ToLower().EndsWith(".jpg") || data.file_url.ToLower().EndsWith(".eng"))
                {
                    return new ObjectResult(new { content = "无法预览" });
                }
                path = FileUtility.GetTruePath(data.file_url);
                if (!System.IO.File.Exists(path))
                {
                    Logger.WriteLineError($"program getContent from:{path} failed");
                    throw new BadRequestException(RequestEnum.ErrorFilePath);
                }
                programInfo = FileUtility.GetText(path);
                var programLists = new ResponsePrograms
                {
                    programid=data.id,
                    file_content = programInfo,
                    file_name = data.file_name,
                    program_code = data.program_code,
                    program_type = data.program_type
                };
                programInfoList.Add(programLists);
            }
            return new ObjectResult(programInfoList);
        }

        [HttpGet]
        public IActionResult GetContentDownload(string file_url, string filename)
        {
            if (string.IsNullOrEmpty(file_url))
            {
                throw new BadRequestException(RequestEnum.ErrorFilePath);
            }
            var data = DNCHttpUtility.ZipResults(file_url, filename);
            return new ObjectResult(data);
        }

        [HttpPost]
        public IActionResult UpdateProgramContent([FromBody] RequestUpdateContent request)
        {
            var program = _sigerProjectDncProgramRepository.Get(request.id);
            if (program == null || program.status != (int)RowState.Valid)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            if (string.IsNullOrEmpty(program.file_url))
            {
                throw new BadRequestException(RequestEnum.ErrorFilePath);
            }
            var path = FileUtility.GetTruePath(program.file_url);
            if (!System.IO.File.Exists(path))
            {
                throw new BadRequestException(RequestEnum.ErrorFilePath);
            }

            try
            {

                System.IO.File.WriteAllText(path, request.content);

                program.checkstatus = 1;
                program.createtime = UnixTimeHelper.GetNow();
                _sigerProjectDncProgramRepository.Update(program);
                if (_unitOfWork.Commit() > 0)
                {
                    return new ObjectResult(CommonEnum.Succefull);
                }
                throw new BadRequestException(CommonEnum.Fail);
            }
            catch (Exception e)
            {
                Logger.WriteLineError($"UpdateProgramContent failed, error:" + e.Message);
                throw new BadRequestException(CommonEnum.Fail);
            }
        }
        /// <summary>
        /// 编辑主程序子程序内容
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UpdateProgramAllContent([FromBody] RequestUpdateAllContent request)
        {
            foreach(var item in request.allcontent)
            {
                var program = _sigerProjectDncProgramRepository.Get(item.id);
                if (program == null || program.status != (int)RowState.Valid)
                {
                    throw new BadRequestException(CommonEnum.RecordNotFound);
                }
                if (string.IsNullOrEmpty(program.file_url))
                {
                    throw new BadRequestException(RequestEnum.ErrorFilePath);
                }
                var path = FileUtility.GetTruePath(program.file_url);
                if (!System.IO.File.Exists(path))
                {
                    throw new BadRequestException(RequestEnum.ErrorFilePath);
                }
                try
                {
                    System.IO.File.WriteAllText(path, item.content);

                    program.checkstatus = 1;
                    program.createtime = UnixTimeHelper.GetNow();
                    _sigerProjectDncProgramRepository.Update(program);
                }
                catch (Exception e)
                {
                    Logger.WriteLineError($"UpdateProgramContent failed, error:" + e.Message);
                    throw new BadRequestException(CommonEnum.Fail);
                }
            }
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 回传程序
        /// </summary>
        /// <param name="program"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ReturnProgram([FromBody] RequestReturnProgram program)
        {
            var list = DownloadProgram(program.sectionid, program.data);
            var file_name = "";
            var file_url = "";
            var file_size = "";
            if (list != null)
            {
                file_name = list[0];
                var programPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "upload/dnc/programs/", file_name);
                var newName = Guid.NewGuid() + file_name;
                var newPathh = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "upload/dnc/programs/", newName);
                if (System.IO.File.Exists(programPath))
                {
                    System.IO.File.Move(programPath, newPathh);
                    file_url = FileUtility.GetDisplayPath(newPathh);
                    FileInfo files = new FileInfo(newPathh);
                    file_size = files.Length.ToString();//文件大小。byte
                }
            }
            //if (_sigerProjectDncProgramRepository.IsExist(f=>f.projectid==ProjectId && f.program_code==program.program && f.toll_gate_code==program.gateNo))
            //    throw new BadRequestException(CommonEnum.RecordExits);
            var code = _sigerProjectDncProgramRepository.GetList(f => f.projectid == ProjectId && f.toll_gate_code == program.gateNo && f.status == (int)RowState.Valid).FirstOrDefault();
            if (code.program_code != program.program)
            {
                throw new BadRequestException(RequestEnum.ProgramTollGateCodeExsit);
            }
            var product = _sigerProjectProduct.Get(f => f.projectid == ProjectId && f.drawingcode == program.productName);
            var process_code = _sigerProjectDncProgramRepository.GetList(q => q.toll_gate_code == program.gateNo && q.status == (int)RowState.Valid).FirstOrDefault();
            _sigerProjectDncProgramRepository.Insert(new siger_project_dnc_program
            {
                program_code = program.program,
                toll_gate_code = program.gateNo,
                projectid = ProjectId,
                create_remark = "回传程序",
                file_name = file_name,
                productid = product != null ? product.id : 0,
                file_url = file_url,
                file_size = file_size,
                createtime = UnixTimeHelper.GetNow(),
                createmid = UserId,
                checkstatus = (int)CheckState.Waiting,
                check_remark = "",
                machine_code = process_code != null ? process_code.machine_code : "",
                process_code = process_code != null ? process_code.process_code : "",
                program_version = "V1",
            });
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 回传程序
        /// </summary>
        /// <param name="program"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ReturnPrograms([FromBody] RequestReturnPrograms program)
        {
            var machine = _machineRepository.Get(q => q.id == program.machine_id && q.projectid == ProjectId && q.status == (int)RowState.Valid);
            var list = DownloadPrograms(program.sectionid, program.program);
            var file_name = "";
            var file_url = "";
            var file_size = "";
            if (list != null)
            {
                file_name = list.FirstOrDefault();
                var programPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "upload/dnc/programs/", file_name);
                var newName = Guid.NewGuid() + file_name;
                var newPathh = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "upload/dnc/programs/", newName);
                if (System.IO.File.Exists(programPath))
                {
                    System.IO.File.Move(programPath, newPathh);
                    file_url = FileUtility.GetDisplayPath(newPathh);
                    FileInfo files = new FileInfo(newPathh);
                    file_size = files.Length.ToString();//文件大小。byte
                }
            }
            var product = _sigerProjectProduct.Get(f => f.projectid == ProjectId && f.drawingcode == program.productName);
            _sigerProjectDncProgramRepository.Insert(new siger_project_dnc_program
            {
                program_code = program.program,
                projectid = ProjectId,
                create_remark = "回传程序",
                file_name = file_name,
                productid = program.product_id,
                file_url = file_url,
                file_size = file_size,
                createtime = UnixTimeHelper.GetNow(),
                createmid = UserId,
                checkmid= UserId,
                checkstatus = (int)CheckState.Waiting,
                check_remark = "",
                machine_code = machine != null ? machine.code : "",
                process_code =  program.route_id.ToString(),
                program_version = "V1",
                program_type=(int)progromType.Main
            });
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }
        private List<string> DownloadPrograms(int sectionid, string data)
        {
            var machine = _sigerProjectDncProgramRepository.GetSectionMachine(ProjectId, sectionid);
            var dicts = new Dictionary<string, string>();
            var extion = "txt";
            dicts.Add(data, extion);
            var result = DNCHttpUtility.HCPrograFile(CompanyId, ProjectId, machine.id, dicts);
            return result;
        }
        private List<string> DownloadProgram(int sectionid, List<string> data)
        {
            var machine = _sigerProjectDncProgramRepository.GetSectionMachine(ProjectId, sectionid);
            //获取程序后缀名
            var programs = _sigerProjectDncProgramRepository.GetList(q =>
                q.status == (int)RowState.Valid && q.projectid == ProjectId && data.Contains(q.program_code)).ToList();

            var dicts = new Dictionary<string, string>();
            foreach (var program in data)
            {
                var extion = "txt";
                var pro = programs.FirstOrDefault(q => q.program_code == program);
                if (!string.IsNullOrWhiteSpace(pro?.file_name))
                {
                    extion = pro.file_name.Substring(pro.file_name.LastIndexOf(".") + 1, (pro.file_name.Length - pro.file_name.LastIndexOf(".") - 1));
                }
                dicts.Add(program, extion);
            }
            var result = DNCHttpUtility.HCPrograFile(CompanyId, ProjectId, machine.id, dicts);
            return result;
        }

        /// <summary>
        /// 根据版本号下载压缩文件
        /// </summary>
        /// <param name="programCode"></param>
        /// <param name="programVersion"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult DownloadProgramToZip(string programCode,string programVersion)
        {
            var programs = _sigerProjectDncProgramRepository.Get(q => q.projectid == ProjectId && q.program_version == programVersion && q.program_code == programCode);
            var programsAll = _sigerProjectDncProgramRepository.GetList(s => s.guid_code == programs.guid_code);

            var dicts = new Dictionary<string, string>();
            foreach (var program in programsAll)
            {
                dicts.Add(program.file_name, program.file_url);
            }

            var result = DNCHttpUtility.DownloadPrograFile(dicts);
            return new ObjectResult(result);
        }
        /// <summary>
        /// 根据版本号下载Zip文件
        /// </summary>
        /// <param name="programId"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult DownloadZipById(int programId)
        {
            //获取程序后缀名
            var programs = _sigerProjectDncProgramRepository.Get(q => q.projectid == ProjectId && q.id == programId);
            var programsAll = _sigerProjectDncProgramRepository.GetList(s => s.guid_code == programs.guid_code).ToList();
            //List<string> programList = new List<string>();

            List<ResponseProgramFileList> programList = new List<ResponseProgramFileList>();

            //var dicts = new Dictionary<string, string>();
            foreach (var program in programsAll)
            {
                var manSonProgram = _sigerProjectDncProgramRepository.Get(program.id);
                programList.Add(new ResponseProgramFileList
                {
                    file_name = manSonProgram.file_name,
                    file_url = manSonProgram.file_url
                });
            }
            var result = DNCHttpUtility.DownloadZip(programList);
            return new ObjectResult(result);
        }
    }
}