using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProductionControl
{
    public partial class FrmUserInfo : Form
    {
        Service.UserService service = new Service.UserService();
        Models.User model = new Models.User();
        public FrmUserInfo(Models.User m = null)
        {
            InitializeComponent();
            if (m != null)
            {
                model = m;
                this.txtCode.Enabled = false;
                if (model.Code == "admin") 
                    this.txtName.Enabled=cobRoleId.Enabled = false; 
            }
        }
        private void initDataView()
        {
            this.cobRoleId.DisplayMember = "Name";
            this.cobRoleId.ValueMember = "Id";  
            this.cobRoleId.DataSource = service.GetRoleItems();

            //
            this.txtCode.Text = model.Code;
            this.txtName.Text = model.Name; 
            this.txtNote.Text = model.Note; 
            this.cobRoleId.SelectedValue = model.RoleId;
        }
        private void FrmUserInfo_Load(object sender, EventArgs e)
        {
            initDataView();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string szCode = this.txtCode.Text.Trim();
                string szName = this.txtName.Text.Trim();
                string szNote = this.txtNote.Text.Trim();
                int roleId = (int)this.cobRoleId.SelectedValue;
                
                if (szCode == "" || szName == "")
                    throw new Exception("请填写帐号和名称！"); 

                model.Code = szCode;
                model.Name = szName;
                model.RoleId = roleId;
                model.Note = szNote;
  
                model.ModifyUserCode = Config.loginUser.Code; 
                bool result;
                if (model.Id == 0)
                {
                    model.Password = Utils.Util.GetMD5("");
                    model.CreateUserCode = Config.loginUser.Code; 
                    result = service.Insert(model);
                }
                else
                    result = service.Update(model);
                if (!result)
                    throw new Exception("保存失败！");

                MessageBox.Show("保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.DialogResult= DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
