<template>
  <div class="table-form">
    <Form :model="model" :ref="action" :rules="rules" :label-width="labelWidth">
      <Row :gutter="10">
        <Col span="24">
         <Form-item label="角色代码" prop="code" v-validate:code.required.maxInputLength="rules">
            <Input v-model="model.code" maxlength="10"  placeholder="请输1~10位字符" :disabled="model.if"></Input>
          </Form-item>
          <Form-item label="角色名称" prop="name" v-validate:name.required.maxInputLength="rules">
            <Input v-model="model.name" maxlength="32"  placeholder="请输入1~32位字符" :disabled="disabled"></Input>
          </Form-item>
           <Form-item label="角色描述" prop="description" >
           <Input v-model="model.description"  type="textarea"  maxlength="200"  :autosize="true" placeholder="请输入0~200位字符" :disabled="disabled"></Input>
           </Form-item>
           <Form-item label="角色菜单" prop="roleMenus" >
           <div id="app">
               <treeselect v-model="model.roleMenus" :searchable="false" :multiple="true" :options="options" placeholder="请至少选择一项菜单"/>
            </div>
           </Form-item>
        </Col>
      </Row>

      <Row class="buttonDiv">
        <Button :loading="loading"
          @click="submitForm(action)"
          type="primary"
          v-if="!(action == 'detail')"
        >确&nbsp;&nbsp;定</Button>
        <Button @click="cancel">关&nbsp;&nbsp;闭</Button>
      </Row>
    </Form>
  </div>
</template>
<script lang="ts">
import { Component, Prop, Vue, Emit } from "vue-property-decorator";
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
@Component({
  components: {
    Treeselect
  }
})
// @Component
export default class RoleForm extends Vue {

    @Prop() private model!:any;
    @Prop(String) private action!:string;
    @Prop() private tableInfo!:any;
    @Prop() private tableVm!:any;

    loading : boolean = false;
    labelWidth:number =120;
    rules:any={};
    orignalOptions: Array<any> = [];
    options: Array<any> = [];
    menuList: Array<any> = [];
    uniqueMenuList: Array<any> = [];


    created(){
      this.getOptions();
    }
    getOptions(){
       this.getApiData('post',this.$msPrefix.base+'/api/v1/data/list/menu?size=1000&page=0','',res=>{
            if (res.rtnCode == 0) {
                this.menuList = res.data.content;
                res.data.content.forEach(element => {
                   if(this.isEmpty(element.parentId)){
                      this.orignalOptions.push(element);
                   }
                });
                 console.log("当前查到的顶级菜单结果：",  this.orignalOptions);
               //遍历顶级菜单，寻找子菜单
               this.orignalOptions.forEach(e =>{
                  var children = this.optionsFun(res.data.content,e.id);
                  if(children.length>0){
                     var pool :any ={
                            id:'',
                            label:'',
                            children:{}
                      }
                       pool.id = e.id;
                       pool.label = e.name;
                       pool.children = children;
                       this.options.push(pool);
                  }else{
                      var pool :any= {
                            id:'',
                            label:''
                      }
                       pool.id = e.id;
                       pool.label = e.name;
                       this.options.push(pool);
                  }
               });
              console.log('当前查到的全部菜单：',this.options);
            }
        },err=>{
        });

    }
//递归获取层级菜单
    optionsFun(data,selectid){
          var children : Array<any> = [];
          data.forEach(element => {
            if(element.parentId == selectid ){
               var mychildren = this.optionsFun(data,element.id);
                if(mychildren.length > 0){
                  var child: any = {
                        id:'',
                        label:'',
                        children:{}
                  };
                  child.id = element.id;
                  child.label = element.name;
                  child.children = mychildren;
                   children.push(child);
                }else{
                  var child: any = {
                        id:'',
                        label:''
                  };
                  child.id = element.id;
                  child.label = element.name;
                   children.push(child);
                }
            }

           });
      return children;
    }

    isEmpty(obj){
      	return (typeof obj === 'undefined' || obj === null || obj === "" || obj.length ==0);
    }

    data(){
       var validateRoles = (rule, value, callback) => {
            if (this.isEmpty(value)) {
              callback(new Error("请至少选择一个菜单"));
            } else {
              callback();
            }
      };
      return {
         rules: {
           roleMenus: [
                {
                  required: true,
                  validator: validateRoles,
                  trigger: "blur"
                }
            ]
         },
        // define the default value
        value: null,
        // define options
      }
    }

    mounted(){

    }
    addDistinctAllMenu(arr){
      this.uniqueMenuList = [];
        arr.forEach(element => {
           this.uniqueMenuList.push(element);
           this.menuList.forEach(e=>{
                if(element == e.id){
                   this.getAllParentMenu(e,this.uniqueMenuList);
                   this.getAllChildrenMenu(e,this.uniqueMenuList);
                }
           });
        });
        this.uniqueArr(this.uniqueMenuList);
    }
    uniqueArr(ary){
      ary.sort(function(a,b){return a-b;});
      for(var i=0;i<ary.length;i++){
        if(ary[i]===ary[i+1]){
            ary.splice(i,1);
            i--;
        }
      }
    }
    getAllParentMenu(menu,arr){
        if(menu.parentId){
           arr.push(menu.parentId);
           this.menuList.forEach(e=>{
             if(e.id == menu.parentId){
               this.getAllParentMenu(e,arr);
             }
           });
        }
    }
    getAllChildrenMenu(menu,arr){
        if(!this.isEmpty(menu.children)){
           menu.children.forEach(element => {     
            //  if(element.name != '分组管理')  {
                arr.push(element.id);
                this.getAllChildrenMenu(element,arr);  
            //  }                                  
           });
        }
    }
    save(){
       console.log('本次添加的初始数据为',this.model.roleMenus);
       var saveRes:any={id:'', code:'', name:'',description:'', roleMenus:[]};
        if(!this.isEmpty(this.model.roleMenus)){
          //循环获取添加父ID，并去重
          this.addDistinctAllMenu(this.model.roleMenus);
           console.log('本次添加的数据为',this.uniqueMenuList);
            this.uniqueMenuList.forEach(e=>{
                var roleMenuAction = { id:{menu:{id:e}}  }
                saveRes.roleMenus.push(roleMenuAction);
            });
        }
        saveRes.code = this.model.code;
        saveRes.id = this.model.id;
        saveRes.name = this.model.name;
        saveRes.description = this.model.description;
        //  this.model = null;
        console.log('本次添加的最终数据为',saveRes);
        this.getApiData('post',this.$msPrefix.base+'/api/v1/data/save/role',saveRes,res=>{
            this.loading=!1;
            if (res.rtnCode == 0) {
              this.tableVm.getData();
              this.cancel();
              this.$tools.message('success',(this.action == 'update'?'修改':'新增')+'成功！')
            }
        },err=>{
           this.loading=!1;
        });

    }

    /*提交*/
      submitForm (action) {

        (this.$refs[action] as any).validate((valid) => {
          if (valid) {
            console.log('最后一步校验',this.loading)
          	if(!this.loading){
                this.loading=!0;
                this.save()
            }
          } else {
            this.$tools.message('info',"请完善必填项!")

          }
        });
      }

    @Emit('closeModal') close(){}
    cancel() {
        this.close();
        // this.model = null;
        (this.$refs[this.action] as any).resetFields();
      }

      get disabled(){
        return this.action=='detail'
      }
}
</script>

