using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Siger.Middlelayer.Common.Extensions;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Request;

namespace Siger.ApiConfig.Controller
{

    public class BussineseUserController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerProjectBussineseUserRepository _bussineseUserRepository;
        private readonly Isiger_wms_bussinese_contactsRepository _BussineseContactsRepository;
        public BussineseUserController(IUnitOfWork unitOfWork, ISigerProjectBussineseUserRepository bussineseUserRepository,
            Isiger_wms_bussinese_contactsRepository BussineseContactsRepository)
        {
            _unitOfWork = unitOfWork;
            _bussineseUserRepository = bussineseUserRepository;
            _BussineseContactsRepository = BussineseContactsRepository;
        }

        [HttpGet]
        public IActionResult GetList(string bussineseid, string userid, int page, int pagesize)
        {
            var data = _bussineseUserRepository.GetPagedList(bussineseid.ToInt(), userid.ToInt(), ProjectId, page, pagesize);

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

        [HttpPost]
        public IActionResult Add([FromBody]RequestBussineseUser req)
        {
            if (req.bussineseid <= 0 || req.userid <= 0)
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }

            var data = _bussineseUserRepository.Get(t => t.projectid == ProjectId && t.status == (int)RowState.Valid &&
                t.userid == req.userid && t.bussineseid == req.bussineseid);
            if (data != null)
            {
                throw new BadRequestException(CommonEnum.RecordExits);
            }

            var entity = new siger_project_bussinese_user
            {
                bussineseid = req.bussineseid,
                userid = req.userid,
                projectid = ProjectId,
                updator = UserId,
                updatetime = DateTime.Now
            };

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

        [HttpPost]
        public IActionResult Update([FromBody]RequestUpdateBussineseUser req)
        {
            if (req.bussineseid <= 0 || req.userid <= 0 || req.id <= 0)
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }

            var entity = _bussineseUserRepository.Get(t => t.projectid == ProjectId && t.status == (int)RowState.Valid &&
                t.id == req.id);
            if (entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            var data = _bussineseUserRepository.Get(t => t.projectid == ProjectId && t.status == (int)RowState.Valid &&
                t.userid == req.userid && t.bussineseid == req.bussineseid && t.id != req.id);
            if (data != null)
            {
                throw new BadRequestException(CommonEnum.RecordExits);
            }

            entity.bussineseid = req.bussineseid;
            entity.userid = req.userid;
            entity.updator = UserId;
            entity.updatetime = DateTime.Now;

            _bussineseUserRepository.Update(entity);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            else
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
        }

        [HttpPost]
        public IActionResult Delete([FromBody]RequestDeleteEntities req)
        {
            if (req.ids == null || !req.ids.Any())
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }
            var models = _bussineseUserRepository.GetList(t =>
                req.ids.Contains(t.id) && t.projectid == ProjectId && t.status == (int)RowState.Valid).ToList();
            if (!models.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            foreach (var model in models)
            {
                model.status = (int)RowState.Invalid;
                _bussineseUserRepository.Update(model);
            }

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

        [HttpGet]
        public IActionResult GetSupplierDunsByUser()
        {
            var data = _bussineseUserRepository.GetPagedList(0, UserId, ProjectId, 1, 10000000);
            var dataList = data.Data.Where(t => !string.IsNullOrEmpty(t.duns));
            if (dataList.Any())
            {
                return new ObjectResult(dataList.Select(t => new
                {
                    t.id,
                    name = t.duns,
                    username = t.name
                }).Distinct().ToList());
            }

            var result = _BussineseContactsRepository.GetList(f => f.status == (int)RowState.Valid &&
                f.projectid == ProjectId && !string.IsNullOrEmpty(f.duns) && f.supply_type == 1).Select(f => new
                {
                    f.id,
                    name = f.duns,
                    username = f.name
                }).ToList();

            return new ObjectResult(result);
        }


    }
}
