<template>
  <ifbp-page>
    <ifbp-breadcrumb name="消息模板"></ifbp-breadcrumb>
    <!--search-->
    <ifbp-button-area id="search-container">
      <el-button type="primary" v-if="!isAdd" class="fl" @click="add">新增</el-button>
      <el-button type="primary" class="fl" v-if="!isEdit" @click="edit">修改</el-button>
      <el-button type="primary"  class="fl" v-if="showBtn" @click="save">保存</el-button>
      <el-button type="primary"  class="fl" v-if="showBtn" @click="cancel">取消</el-button>
      <el-button type="text" class="fr" v-if="!isAdd" @click="showSearch">
        高级搜索
        <i class="el-icon-arrow-down" v-if="this.isHide"></i>
        <i class="el-icon-arrow-up" v-if="!this.isHide"></i>
      </el-button>
      <el-button v-if="!isEdit" type="primary" class="fr" @click="goBackInfo">返回</el-button>
    </ifbp-button-area>

    <div id="advanced-search" :class="{hide: isHide}">
      <el-row>
        <el-col :span="2"><span class="search-label">编码:</span></el-col>
        <el-col :span="3">
          <el-input type="text" v-model="search_data.templateCode" placeholder="请输入编码"></el-input>
        </el-col>
        <el-col :span="2"><span class="search-label"> 名称:</span></el-col>
        <el-col :span="3">
          <el-input type="text" v-model="search_data.templateName" placeholder="请输入名称"></el-input>
        </el-col>
        <el-col :span="2"><span class="search-label"> 启用状态:</span></el-col>
        <el-col :span="4">
          <el-select id="s-state" v-model="search_data.templateStatus">
            <el-option
              v-for="item in search_enablestate"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-col>
        <div class="fr">
          <el-button @click="search">搜索</el-button>
        </div>
      </el-row>
    </div>

    <div id="staff-detail" style="font-size: 0px;" v-show="!isAdd">
      <div id="app-container">
        <el-tree
          style="height: 400px;overflow: auto;"
          accordion
          :props="defaultProps"
          :load="loadNode"
          lazy
          :highlight-current="true"
          @current-change="handleAppChange"
        >
        </el-tree>
      </div>
      <div id="tpl-container" style="height: 400px; position:relative;">
        <el-table
        :max-height="400"
        :data="tableData"
        border
        class="message-template-table"
        style="width: 100%">
          <el-table-column
            v-for="column in tableColumn"
            :prop="column.prop"
            :label="column.title"
            v-if="column.display"
            ></el-table-column>
          <el-table-column
            prop="templateDescription_name"
            label="模型视图"
            :filters="pubsceneFilters"
            :filter-method="filterPubscene"
            filter-placement="bottom-end">
            <template scope="scope">
            {{scope.row.templateDescription_name}}
            </template>
          </el-table-column>
          <el-table-column
            v-for="column in tableColumn1"
            :prop="column.prop"
            :label="column.title"
            v-if="column.display"
            ></el-table-column>
          <el-table-column
            label="操作"
            className="operate-column"
            width="144"
            >
            <template scope="scope">
              <el-tooltip class="item" effect="dark" placement="top-start" content="设计">
                <i class="el-icon-setting" type="primary" @click="designerTpl(scope)"></i>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" placement="top-start" content="启用状态">
                <i class="el-icon-pt-tuichu" type="primary" @click="enabledTpl(scope)"></i>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" placement="top-start" content="查看">
                <i class="el-icon-search" type="primary" @click="checkTpl(scope)"></i>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" placement="top-start" content="删除">
                <i class="el-icon-delete" type="primary" @click="deleteTpl(scope)"></i>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="currentTotal">
      </el-pagination>
      </div>
    </div>
    <div id="edit-container" v-if="showTemplate">
      <div id="form-container">
        <el-form
          :model="currentTpl"
          label-width="100px"
          ref="currentTplForm"
          :rules="rules">
          <el-form-item label="业务类型：">
            <el-button v-model="currentTpl.code" type="text" v-if="!isEdit">{{currentTpl.templateScene}}</el-button>
            <el-button v-model="currentTpl.code" type="text" v-else>{{currentApp.name}}</el-button>
          </el-form-item>
          <el-form-item label="编码："
            prop="templateCode">
            <el-button type="text" v-model="currentTpl.templateCode" v-if="!isEdit">{{currentTpl.templateCode}}</el-button>
            <el-input v-model="currentTpl.templateCode" v-if="showTemplateCode">{{currentTpl.templateCode}}</el-input>
          </el-form-item>
          <el-form-item label="名称："
            prop="templateName">
            <el-button type="text" v-model="currentTpl.templateName" v-if="!isEdit">{{currentTpl.templateName}}</el-button>
            <el-input v-model="currentTpl.templateName" v-else>{{currentTpl.templateName}}</el-input>
          </el-form-item>
          <el-form-item label="模型视图："
            prop="templateDescription">
            <el-button type="text" v-model="currentTpl.templateDescription_name" v-if="!isEdit">{{currentTpl.templateDescription_name}}</el-button>
            <el-ref 
                    v-else
                    :is-muti-select="false"
                    :ref-code="'pubscence_ref'"
                    :field="'templateDescription'"
                    :template-value="currentTpl"
                    :query-params="queryParams"
                    width="300px"
                    :is-edit="true">
            </el-ref>
          </el-form-item>
        </el-form>
      </div>
    </div>
</ifbp-page>
</template>

<script>

export default {
  watch:{
    isAdd:function(){
      if(this.isAdd === true){
        this.showTemplateCode = true;
      } else {
        this.showTemplateCode = false;
      }
    },
    isEdit: function(){
      if(this.isEdit === false){
        this.showTemplateCode = false;
      } else {
        this.showTemplateCode = true;
      }
    }
  },
  data(){
    return {
      queryParams:{
        busitypecode: ''
      },
      currentTotal:0,
      currentValue:'',      
      currentPage:1,
      pageSize: 10,
      total:'',
      editTemplate: false,
      showTemplate: false,
      showTemplateCode: true,
      currentScope: '',
      currentRowScope:'',
      pubsceneFilters:[],
      appClickData: '',//选中节点的数据
      treeData: [],
      tableData: [],
      tplTree: [],
      isHide: true,
      showBtn: false,
      isAdd: false,
      isEdit: true,
      search_data:{
        templateCode: '',
        templateName: '',
        templateStatus: '',
      },
      search_enablestate:[
        {
          label: '全部',
          value: ''
        },
        {
          label:'已启用',
          value:'2',
        },{
          label:'未启用',
          value:'3',
        }
      ],
      currentTpl: {
        code: '',
        templateCode: '',
        templateName: '',
        templateScene: '',
        templateDescription: '',
        templateDescription_name: ''
      },
      defaultProps: {
        children: 'children',
        label: 'name',
        isLeaf: 'leaf'
      },
      currentApp: '', //选中节点的数据
      tableColumn: [{
        title: '编码',
        prop: 'templateCode',
        display: true
      },{
        title: '名称',
        prop: 'templateName',
        display: true
      }],
      tableColumn1: [{
        title: '启用状态',
        prop: 'templateStatus',
        display: true
      },{
        title: '创建时间',
        prop: 'createTimeForDisplay',
        display: true
      },{
        title: '创建人',
        prop: 'createby',
        display: true
      },{
        title: '修改时间',
        prop: 'modifyTimeForDisplay',
        display: true
      },{
        title: '修改人',
        prop: 'modifiedby',
        display: true
      }],
      rules:{
        templateCode:[
          { required: true, message: '请输入模板编码', trigger: 'blur' }
        ],
        templateName:[
          { required: true, message: '请输入模板名称', trigger: 'blur'}
        ],
        pk_pubscene:[
          { required: true, message: '请选择模型视图', trigger: 'change'}
        ]
      }
    };
  },
  methods:{
   handleCurrentChange(currentPage){
     this.currentPage = currentPage;
     this.handleAppChange(this.currentValue,this.pageSize,this.currentPage);
   },
   handleSizeChange(pageSize){
     this.pageSize = pageSize;
     this.handleAppChange(this.currentValue,this.pageSize,this.currentPage);
   },
    // 高级搜索
    showSearch() {
      this.isHide = !this.isHide;
    },
    search(){
      const self = this;
      var search_data = self.search_data;
      this.$http({
            url:'/ifbp-msg/msg/fuzzySearch?templateName='+ search_data.templateName + '&templateCode=' + search_data.templateCode + '&templateStatus='+ search_data.templateStatus + '&templateScene=',
            method:'get'
          }).then((res) => {
            if(res.data.success === true && res.data.data.length !== 0){
              self.addType(res.data.data);
              self.tableData = res.data.data;
              self.currentTotal = res.data.data.length;
            } else if(res.data.success === true && res.data.data.length === 0){
              self.$message('未查询到相关数据');
              self.tableData = res.data.data;
            }
          }).catch((res) => {
            self.$message.error("请求失败");
          });
    },
    filterPubscene(value,row){
      return row.templateDescription_name === value;
    },
    getPubscence(){
      var protocol = window.location.protocol;
      var host = window.location.host;
      const self = this;
        this.$http({
          url: '/uitemplate_web/iref_ctr/commonRefsearch',
          method:'post',
          // data:'refModelUrl=http://dev-ap.iservice.imfbp.com/ifbp-app-sm-infoset-web/infoset/pubscence_ref/'
          data:'refModelUrl=' + protocol+'//' + host +'/ifbp-app-sm-infoset-web/infoset/pubscence_ref/'
        }).then((res) => {
          if(res.data.data) {
            var data = JSON.parse(JSON.stringify(res.data.data));
            data.forEach((value) => {
              self.$set(value,'text',value.refname);
              self.$set(value,'value',value.refname);
            });
            this.pubsceneFilters = JSON.parse(JSON.stringify(data));

          } else {
            this.$message.error('获取模型视图失败');
          }
          this.search();
        }).catch(() => {
          this.$message.error('请求出错');
        });
    },
    loadNode(node, resolve){
      if(node.level === 0) {
        this.$http({
          url: '/ifbp-app-sm/buz/products'
        }).then((res) => {
          if(res.data.success === true) {
            resolve(res.data.data);
          } else {
            this.$message.error('请求失败');
          }
        }).catch(() => {
          this.$message.error('请求出错');
        });
      } else if(node.level === 1) {
        this.$http({
          url: '/ifbp-app-sm/buz/product/' + node.data.pid + '/models'
        }).then((res) => {
          if(res.data.success === true) {
            resolve(res.data.data);
          } else {
            this.$message.error('请求失败');
          }
        }).catch(() => {
          this.$message.error('请求出错');
        });
      } else if(node.level === 2) {
        this.$http({
          url: '/ifbp-app-sm/buz/product/' + node.data.pid + '/model/' + node.data.mid + '/buzitypes'
        }).then((res) => {
          if(res.data.success === true) {
            for(var i=0;i<res.data.data.length;i++) {
              res.data.data[i].leaf = true;
            }
            resolve(res.data.data);
          } else {
            this.$message.error('请求失败');
          }
        }).catch(() => {
          this.$message.error('请求出错');
        });
      }
    },
    handleAppChange(currentValue) {
      const self = this;
      this.currentValue = currentValue;
      var value = currentValue;
      var page = this.currentPage;
      var rows = this.pageSize;
      if(value.leaf) {
        this.currentApp = value;
        this.currentTpl.code = value.code;
        this.$http({
          url: '/ifbp-msg/msg/listByScene?page='+ page +'&rows='+ rows +'&templateScene=' + value.code,
          method: 'get'
        }).then((res) => {
          if(res.data.success === true) {
            self.addType(res.data.data);
            self.tableData = res.data.data;
            self.currentTotal = res.data.data.length;
          }
        }).catch(() => {
          self.$message({
            type: 'error',
            message: '请求失败'
          });
        });
      } else {
        self.currentApp = '';
      }
    },
    // 时间戳转换为日期格式
    changeData(value){
      var date = new Date(value);
      var Y,M,D,h,m,s;
      Y = date.getFullYear() + '-';
      M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
      D = date.getDate() + ' ';
      h = date.getHours() + ':';
      m = date.getMinutes() + ':';
      s = date.getSeconds();
      return Y+M+D+h+m+s;
    },
    //转换时间启用状态
    addType(data) {
      data.forEach((v) => {
        if (v.createtime) {
          this.$set(v, 'createTimeForDisplay', this.changeData(v.createtime));
        }
        // var pubsceneFilters = JSON.parse(JSON.stringify(this.pubsceneFilters));
        this.pubsceneFilters.forEach((value) => {
          if(v.templateDescription === value.id){
            this.$set(v,'templateDescription_name',value.value);
          }
        });
        if(v.templateStatus === '3'){
          this.$set(v,'templateStatus','未启用');
        } else if(v.templateStatus === '2'){
          this.$set(v,'templateStatus','已启用');
        }
        if (v.modifiedtime) {
          this.$set(v, 'modifyTimeForDisplay', this.changeData(v.modifiedtime));
        }
      });
    },
    handleTplChange(value) {
      if(!value.forms) {
        this.currentTpl = value;
      } else {
        this.currentTpl = '';
      }
    },
    backInfo() {
      this.showTemplate = false;
      this.showBtn = false;
      this.isAdd = false;
      this.isEdit = true;
      this.showTemplateCode = false;
      this.$router.push('/appArea');
    },
    goBackInfo(){
      this.showTemplate = false;
      this.showBtn = false;
      this.isAdd = false;
      this.isEdit = true;
      this.showTemplateCode = false;
      this.currentTpl = {
                  code: '',
                  templateCode: '',
                  templateName: '',
                  templateScene: '',
                  templateDescription: ''
                };
      this.$router.push('/messageTemplate');
      this.editTemplate === false;
    },
    save() {
      const self = this;
      var submitData = {};
      this.$refs.currentTplForm.validate((valid) => {
        var addTemplate = {
            templateCode: self.currentTpl.templateCode,
            templateName: self.currentTpl.templateName,
            templateScene: self.currentTpl.code,
            templateDescription: self.currentTpl.templateDescription,
            pkMsgTemplate: "",
            templateStatus: "3",
            parentPkMsgTemplate: "",
            createby: "",
            createtime: "",
            modifiedby: "",
            modifiedtime: "",
            version: 0,
            parentCodeMsgTemplate: "",
            isdefault: "0",
            templateContent: null
        };
        var editTemplate = {
            pkMsgTemplate: self.currentRowScope.pkMsgTemplate,
            templateCode: self.currentTpl.templateCode,
            templateName: self.currentTpl.templateName,
            templateScene: self.currentTpl.code,
            templateDescription: self.currentTpl.templateDescription,
            templateStatus: null,
            parentPkMsgTemplate: "",
            createby: "",
            createtime: "",
            modifiedby: "",
            modifiedtime: "",
            version: 0,
            parentCodeMsgTemplate: "",
            isdefault: "0",
            templateContent: null
        };
        if(valid){
          if(self.editTemplate === false){
            this.$http({
              url:'/ifbp-msg/msg/create',
              method:'post',
              data: addTemplate
            }).then((res) => {
              if(res.data.success === true){
                self.isAdd = false;
                self.showBtn = false;
                self.showTemplate = false;
                self.currentTpl = {
                  code: '',
                  templateCode: '',
                  templateName: '',
                  templateScene: '',
                  templateDescription: ''
                };
                self.tableData.push(res.data.data);
                self.addType(self.tableData);
                self.$message({
                  type: 'success',
                  message: '保存成功'
                });
              }else{
                self.$message({
                  type:'error',
                  message: res.data.error.errorMessage
                });
              }
            }).catch((res) => {
              this.$message({
                type: 'error',
                message: '请求失败'
              });
            });
          } else if(self.editTemplate === true){
            this.$http({
              url:'/ifbp-msg/msg/updata',
              method:'post',
              data: editTemplate
            }).then((res) => {
              if(res.data.success === true){
                self.isAdd = false;
                self.showBtn = false;
                self.showTemplate = false;
                self.currentTpl = '';
                self.editTemplate = false;
                self.$set(self.tableData,self.currentScope.$index,res.data.data);
                self.addType(self.tableData);
                self.$message({
                  type:'success',
                  message: '修改成功'
                });
              }else{
                self.$message({
                  type:'error',
                  message: '修改失败'
                });
              }
            }).catch((res) => {
              this.$message({
                type: 'error',
                message: '请求失败'
              });
            });
          }
          
        }
      })
    },
    add() {
      if(this.currentApp === '') {
        this.$message('请选择有效的业务类型');
      } else {
        this.queryParams.busitypecode = this.currentApp.code;
        this.isAdd = true;
        this.showBtn = true;
        this.isHide = true;
        this.showTemplateCode = true;
        this.showTemplate = true;
        this.editTemplate === false;
      }
    },
    edit() {
      this.isEdit = true;
      this.showBtn = true;
      this.showTemplateCode = false;
      this.editTemplate = true;
    },
    designerTpl(scope){
      this.$router.push('/messageTemplate/messageDesigner');
      window.localStorage.setItem('currentTpl',JSON.stringify(scope.row));
    },
    checkTpl(scope){
      this.queryParams.busitypecode = scope.row.templateScene;
      this.isEdit = false;
      this.isHide = true;
      this.isAdd = true;
      this.showTemplateCode = false;
      this.showTemplate = true;
      this.currentScope = scope;
      var beanMap = {
        "templateDescription_ref": {}
      };
      beanMap.templateDescription_ref[scope.row.templateDescription] = {
        name: scope.row.templateDescription_name,
        id: scope.row.templateDescription
      };
      this.currentRowScope = JSON.parse(JSON.stringify(scope.row));
      this.currentTpl = JSON.parse(JSON.stringify(scope.row));
      this.$set(this.currentTpl,'beanMap',beanMap);
      var app = JSON.parse(JSON.stringify(scope.row));
      app.name = app.templateScene;
      if(!this.currentApp){
        this.currentApp = app;
      }
    },
    enabledTpl(scope){
      const self = this;
      var templateStatus;
      var rowData = JSON.parse(JSON.stringify(scope.row));
        if(rowData.templateStatus === '未启用'){
          templateStatus='3';
        }
        if(rowData.templateStatus === '已启用'){
          templateStatus='2';
        }
      var template = {
          pkMsgTemplate: rowData.pkMsgTemplate,
          templateStatus: templateStatus,
          templateDescription: rowData.templateDescription
      };
      this.$http({
        url: '/ifbp-msg/msg/upStatus',
        method:'post',
        data: template
      }).then((res) => {
        if(res.data.success === true) {
          if(templateStatus === '3'){
            self.$set(scope.row,'templateStatus','已启用');
          }
          if(templateStatus === '2'){
            self.$set(scope.row,'templateStatus','未启用');
          }
        } else{
          self.$message.error(res.data.errorMsg);
        }
      }).catch(() => {
        self.$message.error('请求出错');
      });
    },
    deleteTpl(scope){
      const self = this;
      this.$http({
        url: '/ifbp-msg/msg/delete/' + scope.row.pkMsgTemplate,
        method:'get'
      }).then((res) => {
        if(res.data.success === true) {
           this.$message({
            type: 'success',
            message: '删除成功'
          });
          self.tableData.splice(scope.$index,1);
        }
      }).catch(() => {
          self.$message({
            type: 'error',
            message: '删除失败'
          });
      });
    },
    requestTplTree() {
      this.$http({
        url: '/uitemplate_web/uitemplate_ctr/uitemplate_design_ctr/queryUITemplateList',
        method: 'post',
        contentType: 'application/x-www-form-urlencoded',
        data: 'data=' + encodeURIComponent('{"tenant_id":"","type":"sys"}')
      }).then((res) => {
        this.tplTree = res.data.formCategories;
      }).catch(() => {
        this.$message.error('请求失败');
      });
    },
    deleteRow(row) {
      console.log(row);
      this.$confirm('确定删除关联?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: '/wbalone/uitemplatenexusbase/delete/' + row.pkNexus,
            method: 'post'
          }).then((res) => {
            this.tableData.splice(this.tableData.indexOf(row), 1);
            if(res.data.status === 1) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
            } else {
              this.$message({
                type: 'error',
                message: res.data.msg
              });
            }
          }).catch(() => {
            this.$message({
              type: 'error',
              message: '删除失败!'
            });
          });

        });
    },
    closeDialog() {
      console.log('close dialog');
    },
    confirm() {
      if (this.currentTpl.code === '') {
        this.$message('请选择有效的业务类型');
      } else {
        this.$http({
          url: '/wbalone/uitemplatenexusbase/create',
          method: 'post',
          data: {
            pkTemp: this.currentTpl.id,
            nexuskey: this.dialogForm.nexuskey,
            funnode: this.currentApp.code
          }
        }).then((res) => {
          console.log(res);
          if(res.data.status === 1) {
            console.log(res);
            this.dialogVisible = false;
            res.data.data.type = 'UI模板';
            this.tableData.push(res.data.data);
          } else {
            this.$message.error(res.data.message);
          }
        }).catch(() => {
          this.$message.error('请求失败');
        });
      }
    },
    cancel() {
      if(this.editTemplate === true){
        this.isEdit = false;
        this.showBtn = false;
      } else{
        this.isAdd = false;
        this.isEdit = true;
        this.showBtn = false;
        this.showTemplateCode = false;
        this.showTemplate = false;
        this.editTemplate = false;
        this.resetForm();
      }
      
    },
    resetForm() {
      Object.keys(this.currentTpl).forEach((key) => {
        this.currentTpl[key] = '';
      });
    },
  },
  created(){
    
    this.getPubscence();
    // this.request();
  }
};
</script>

<style scoped>
.printTemplate{
  padding: 20px;
}

#edit-container {
  margin-top: 20px;
  background: #ffffff;
  position: relative;
  padding: 0 20px;
  height: 400px;
}
#appTplAuth-container {
  padding: 15px;
  font-size: 0px;
}

#form-container {
  width: 40%;
  margin-left: 30%;
  padding-top: 50px;
}

#app-container {
  display: inline-block;
  width: calc(20% - 20px);
  font-size: 14px;
  vertical-align: top;
  margin-top: 20px;
  margin-right: 20px;
}

#tpl-container {
  display: inline-block;
  width: 80%;
  font-size: 14px;
  height: 400px;
  background-color: white;
  vertical-align: top;
  margin-top: 20px;
}

#authApp-tpl-tree {
  display: inline-block;
  width: calc(30% - 2px);
  font-size: 14px;
  vertical-align: top;
}

#authApp-dialog-form {
  display: inline-block;
  width: calc(70% - 2px);
  font-size: 14px;
  vertical-align: top;
}
.operate-column .item {
  padding: 0 8px;
  color: #20a0ff;
  float: left;
}
</style>
<style>
.el-table .cell{
  padding:0 10px;
}
.pagination{
  margin-top:20px;
}
.message-template-table .operate-column .cell {
  padding-left: 8px;
  padding-right: 0;
}
</style>

