<template>
<div style="padding: 10px;" id="sys-setting">
  <el-tabs v-model="activeName" @tab-click="handleClick">
    <el-tab-pane label="安全设置" name="first">
      <el-form :model="security" ref='security' label-width="100px" style="max-width: 500px; margin: 10px auto;">
        <el-form-item label="旧密码" prop='oldPwd' required>
          <el-input auto-complete="off" type="password" v-model="security.oldPwd"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop='newPwd' required>
          <el-input auto-complete="off" type="password" v-model="security.newPwd"></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop='reNewPwd' required>
          <el-input auto-complete="off" type="password" v-model="security.reNewPwd"></el-input>
        </el-form-item>
          <el-form-item >
          	<div style="float:right;">
	          	<el-button type="default" @click="cancel">取消</el-button>
              <el-button type="primary" @click="confirmPas('security')">保存</el-button>
          	</div>

        </el-form-item>
      </el-form>
    </el-tab-pane>
    <el-tab-pane label="偏好设置" name="second">
      <div style="margin-top: 7px;">
        <ifbp-panel-group :navbar="true" :scrollDom="scrollDom">
            <ifbp-panel title="导航模式">
              <p class="desc">设置导航菜单展示方式：左侧导航是鼠标移到左上角图标区域从左侧滑出菜单，顶部导航是点击header中间的title区域在下方弹出菜单面板</p>
              <div class="setting-form">
                  <div :class="['setting-form-item', {'selected': settings.navPosition === 'left'}]" @click="checkItemClick('navPosition', 'left')">
                    <img class="nav preview-img" src="../../assets/images/settings/nav-left.jpg" alt="左侧导航">
                    <el-radio class="radio" v-model="settings.navPosition" label="left">左侧导航</el-radio>
                  </div>
                  <div :class="['setting-form-item', {'selected': settings.navPosition === 'top'}]" @click="checkItemClick('navPosition', 'top')">
                    <img class="nav preview-img" src="../../assets/images/settings/nav-top.jpg" alt="顶部导航">
                    <el-radio class="radio" v-model="settings.navPosition" label="top">顶部导航</el-radio>
                  </div>
              </div>
            </ifbp-panel>

            <ifbp-panel title="页签">
                <p class="desc">设置是否展示多页签：选中单页签后不显示多页签，选中多页签后打开过的应用以页签的形式展示在顶部</p>
                <div class="setting-form">
                  <div :class="['setting-form-item', {'selected': settings.showTabs === false}]" @click="checkItemClick('showTabs', false)">
                    <img class="tab preview-img" src="../../assets/images/settings/show-tabs-no.png" alt="左侧导航">
                    <el-radio class="radio" v-model="settings.showTabs" :label="false">单页签</el-radio>
                  </div>
                  <div :class="['setting-form-item', {'selected': settings.showTabs === true}]" @click="checkItemClick('showTabs', true)">
                    <img class="tab preview-img" src="../../assets/images/settings/show-tabs-yes.jpg" alt="顶部导航">
                    <el-radio class="radio" v-model="settings.showTabs" :label="true">多页签</el-radio>
                  </div>
                </div>
            </ifbp-panel>

            <ifbp-panel title="主题设置">
                <div class="theme-setting">
                  <el-form label-width="150px" :model="settings">
                    <el-form-item label="系统颜色" inline-label="true">
                      <el-select v-model="settings.themeCode" placeholder="请选择颜色" style="width:100%;" @change="handleThemeChange">
                        <el-option v-for="item in themeArray" :label="item.name" :value="item.code" :key="item.code"></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="banner区域背景色" inline-label="true">
                      <el-select v-model="settings.bannerColor" placeholder="请选择颜色" style="width:100%;">
                        <el-option v-for="item in bannerArray" :label="item.name" :value="item.code" :key="item.code"></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="显示类型" inline-label="true">
                      <el-select v-model="settings.showtype" placeholder="请选择类型" style="width:100%;">
                        <el-option v-for="item in showtypeArray" :label="item.name" :value="item.code" :key="item.code"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-form>
                </div>
            </ifbp-panel>
        </ifbp-panel-group>
      </div>
    </el-tab-pane>
  </el-tabs>
  <ifbp-footer v-show = 'this.activeName != "first"'>
    <el-button type="default" @click="cancel">取消</el-button>
    <el-button class="fr" type="primary" @click="confirm">保存</el-button>
  </ifbp-footer>
</div>
</template>
<script>
import commonUtils from "../../util/commonUtils.js";
export default {
  data() {
    return {
      //固定写法
      scrollDom: document.getElementsByClassName('view')[0],
      activeName: "first",
      themeCodeOriginal: '',
      security: {
        oldPwd: '',
        newPwd: '',
        reNewPwd: '',
      },
      // settings 表中的主要字段
      settings: {
        themeCode: '',
        themeName: '',
        userId: '',
        themeId: '',
        showTabs: true, // 是否展示多页签：true or false
        navPosition: 'left', // 导航菜单位置："left" or "top"
        bannerColor: '', // banner区域背景色
        showtype: '',//显示类型
      },
      themeArray: [
        {
          code: 'default',
          name: '默认'
        },
        {
          code: 'red',
          name: '红色'
        }
      ],
      bannerArray: [
        {
          code: 'default',
          name: '默认'
        },
        {
          code: 'red',
          name: '红色'
        }
      ],
      showtypeArray: [
        {
          code: 'table',
          name: '表格'
        },
        {
          code: 'form',
          name: '表单'
        }
      ]
    };
  },
  created() {
    this.getSettingsData();
  },
  methods: {

    checkItemClick(key, value) {
      this.settings[key] = value;
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    //保存密码 
    confirmPas(formName){  
    	let promise1 = null;
    	this.$refs[formName].validate((valid) => {
          if (valid) {
            promise1 = this.checkPwd();
            promise1.then(res=>{
	        	if(res){
		        		this.loginOut();
		        	}       	
		        });
            
          } else {
            console.log('error submit!!');
            return false;
          }
        });
    },
    //保存系统设置
    confirm() {
      const promise2 = this.saveSettingsData();
      promise2.then((val2) => { // 保存系统风格设置成功
        if(val2) { // 未修改密码 && 保存系统风格成功，返回并刷新
          // window.history.go(-1);
          setTimeout(() => { // 延迟1s重新加载,页面设置生效
         	 window.location.reload();
        	}, 1000);
        }        
      });  
    },
    // 取消
    cancel() {
      window.history.go(-1);
    },
    // 获取系统设置的数据
    getSettingsData() {
      this.$http({
        url: '/wbalone/wbTheme/getPresentUserTheme',
        method: 'get',
      }).then((res) => {
        if(res.data.status === 1) {
          var data = res.data.wbTheme || {};
          Object.keys(this.settings).forEach(key => {
            this.$set(this.settings, key, data[key] === undefined ? '' : data[key]);
          });
          this.settings.themeId = res.data.themeId;
          this.themeCodeOriginal = data.themeCode;
        }
      }).catch((e) => {
        console.log("获取系统设置数据失败, " + e);
      });
    },
    handleThemeChange(val) {
      var item = this.themeArray.filter(v => {
        return v.code === val;
      })[0];
      this.$set(this.settings, 'themeName', item.name || '');
    },
    // 保存系统偏好设置
    saveSettingsData(settings) {
      commonUtils.setCookie('ifbp-theme', this.settings.themeCode);
      this.$set(this.settings, 'userId', commonUtils.getCookie('_A_P_id') || '');

      const promise = new Promise((resolve, reject) => {
        var data = {
          isDefault: this.settings.themeCode === 'default' ? "Y" : "N",
          themeCode: this.settings.themeCode,
          themeName: this.settings.themeName,
          userId: this.settings.userId,
          themeId: this.settings.themeId,
          jsonTheme: this.settings,
          showtype: this.settings.showtype,
        };
        var url = '/wbalone/wbTheme/upDataTheme';
        return this.$http({
          url: url,
          method: 'post',
          data: data,
        }).then(res => {
          if(res.data.status === 1) {
            console.log('success:' + res);
            this.$message({
              message: "保存系统设置数据成功！",
              type: "success",
            });
            resolve(true);
          } else {
            reject();
          }
        }).catch((e) => {
          this.$message({
            message: "保存系统设置数据失败！",
            type: "error",
          });
          reject();
          console.log("保存系统设置数据失败, " + e);
        });
      });
      return promise;
    },
    // 检查密码正确性
    checkPwd() {
      const promise = new Promise((resolve, reject) => {
        if (this.security.oldPwd === this.security.newPwd) {
          this.$message({
            message: '新旧密码不能相同！',
            type: 'error'
          });
          reject();
          this.activeName = "first";
        } else if (this.security.newPwd !== this.security.reNewPwd) {
          this.$message({
            message: '两次输入的新密码不一致！',
            type: 'error'
          });
          reject();
          this.activeName = "first";
        } else {
          this.changePwd(resolve, reject);
        }
      });
      return promise;
    },
    // 保存密码
    changePwd(resolve, reject) {
      this.$http({
//        url: '/ifbp-app-sm/sm/user/resetPwd?id=' + commonUtils.getCookie('_A_P_id') + '&oldPwd=' + this.security.oldPwd + '&newPwd=' + this.security.newPwd,
        url: '/riart/sfbase/sm/user/resetPwd?id=' + commonUtils.getCookie('_A_P_id') + '&oldPwd=' + this.security.oldPwd + '&newPwd=' + this.security.newPwd,
        method: 'get'
      }).then((res) => {
        if (res.data.success) {
          this.$message({
            message: '密码修改成功',
            type: 'success'
          });
          resolve(true);
        } else {
          this.$message({
            message: res.data.error.errorMessage,
            type: 'error'
          });
          this.activeName = "first";
          reject();
        }
      }).catch(() => {
        this.$message({
          message: '密码修改失败，请重试',
          type: 'error'
        });
        reject();
      });
    },
    // 登出系统
    loginOut() {
      localStorage.removeItem('wbalone_isLogin');
      var protocol = window.location.protocol; // 协议
      var host = window.location.host; // ip+端口
      var currentUrl = protocol + '//' + host  + window.ctxs.ap + '/'; // 当前URL
      var logoutUrl = this.getCookie("_A_P_logoutUrl") || ''; // 需要跳转的URL
      var serviceUrl = logoutUrl.replace(/"/g, '') + '?service=' + currentUrl;
      // var serviceUrl = window.location.href;
      window.location.href = window.ctxs.ap + '/logout?service=' + encodeURIComponent(serviceUrl);
    },
  }
};
</script>
<style scoped>
#sys-setting {
  padding: 0 10px !important;
}
#sys-setting .setting-form {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  margin-top: 15px;
}
#sys-setting .ifbp-panel-body p.desc {
  width: 30%;
  float: left;
  line-height: 22px;
  font-size: 14px;
  color: #666;
  padding: 6px 0;
  box-sizing: border-box;
}

#sys-setting .setting-form-item img.preview-img {
  width: 300px;
  border: 2px solid #d4d4d9;
  cursor: pointer;
}
#sys-setting .setting-form-item:hover img,
#sys-setting .setting-form-item.selected img {
  border-color: #5CB0E6;
}
#sys-setting .setting-form img.preview-img.nav {
  height: 178px;
}
#sys-setting .setting-form img.preview-img.tab {
  height: 82px;
}
#sys-setting .setting-form-item {
  margin: 10px;
}
#sys-setting .setting-form-item label.el-radio {
  display: block;
  text-align: center;
  margin-top: 15px;
}
#sys-setting .theme-setting{
  text-align: center;
}
#sys-setting .theme-setting .el-form-item {
  max-width: 500px;
  margin: 20px auto;
}

@media screen and (max-width: 520px){
  #sys-setting .ifbp-panel-body p.desc {
    width: 100%;
    float: none;
  }
  #sys-setting .theme-setting .el-form-item {
    margin-right: 0;
    width: 100%;
  }
}
</style>
<style>
#sys-setting .setting-form-item:hover .el-radio .el-radio__inner {
  border-color: #5CB0E6;
}
#sys-setting .el-tabs__header {
  margin-bottom: 0px;
}
</style>

