<template>
  <div class="resform">
    <div class="demo-split" style="height:450px">
      <Split v-model="split1">
        <!--左面板-->
        <template #left>
        <div class="demo-split-pane">
          <Input placeholder="请输入关键字搜索..." id="keyword1" name="keyword1"></Input>
          <div class="area-tree-div" style="height: 300px;overflow-y: auto;overflow-x: hidden">
            <ul id="res-list-tree" class="ztree"></ul>
          </div>
        </div>
        </template>
        <!--右面板-->
        <template #right>
        <div class="demo-split-pane">
          <Button @click="add" style="margin: 10px 10px 10px 50px;" type="primary" size="small" :disabled="addDisable">
            添加资源
          </Button>
          <Button @click="edit" style="margin: 10px 10px;" type="success" size="small" :disabled="editDisable">编辑资源
          </Button>
          <Button @click="remove" style="margin: 10px 10px;" type="error" size="small" :disabled="removeDisable">删除资源
          </Button>
          <i-form label-position="right" :label-width="80" ref="resForm" :model="nowRes" :rules="rules" inline>
            <Row>
              <i-col :span="12">
                <Form-item label="名称：" prop="name" class="ivu-form-item-search">
                  <Input v-model="nowRes.name" placeholder="请输入名称" style="width: 100%" :disabled="disabled"></Input>
                </Form-item>
              </i-col>
              <i-col :span="12">
                <Form-item label="图标：" prop="micon" class="ivu-form-item-search">
                  <Input v-model="nowRes.micon" placeholder="请输入图标" style="width: 100%" :disabled="disabled"></Input>
                </Form-item>
              </i-col>
            </Row>
            <Row>
              <i-col :span="12">
                <Form-item label="链接：" class="ivu-form-item-search">
                  <Input v-model="nowRes.href" placeholder="请输入链接" style="width: 100%" :disabled="disabled"></Input>
                </Form-item>
              </i-col>
              <i-col :span="12">
                <Form-item label="排序：" class="ivu-form-item-search">
                  <InputNumber v-model="nowRes.sortNo" placeholder="请输入排序" style="width: 100%"
                               :disabled="disabled"></InputNumber>
                </Form-item>
              </i-col>
            </Row>
            <Row>
              <i-col :span="12">
                <FormItem label="类型：" prop="type" class="ivu-form-item-search">
                  <i-select v-model="nowRes.type" style="width: 100%" :disabled="disabled" filterable clearable>
                    <!--<Option v-for="item in systems" :value="item.id" :key="item.id">{{item.name}}</Option>-->
                    <Option :value="2" :key="2">菜单</Option>
                    <Option :value="1" :key="1">栏目</Option>
                    <Option :value="0" :key="0">应用</Option>
                    <Option :value="3" :key="3">外部链接</Option>
                    <Option :value="4" :key="4">外部通用组件</Option>
                  </i-select>
                </FormItem>
              </i-col>
              <i-col :span="12">
                <FormItem label="状态：" class="ivu-form-item-search">
                  <i-select v-model="nowRes.state" style="width: 100%" :disabled="disabled" filterable clearable>
                    <!--<Option v-for="item in systems" :value="item.id" :key="item.id">{{item.name}}</Option>-->
                    <Option :value="1" :key="1">启用</Option>
                    <Option :value="0" :key="0">停用</Option>
                  </i-select>
                </FormItem>
              </i-col>
            </Row>
            <Row>
              <i-col :span="12">
                <Form-item label="编码：" prop="code" class="ivu-form-item-search">
                  <Input v-model="nowRes.code" placeholder="请输入编码" style="width: 100%" :disabled="disabled"></Input>
                </Form-item>
              </i-col>
              <i-col :span="12">
                <Form-item label="上级：" class="ivu-form-item-search">
                  <Input v-model="nowRes.pname" placeholder="请选择上级" style="width: 100%" :disabled="disabled" search
                         @click.stop.native="showResTree"></Input>
                </Form-item>
              </i-col>
            </Row>
            <Row>
              <i-col :span="24">
                <Form-item label="备注：" class="ivu-form-item-search">
                  <Input v-model="nowRes.remark" type="textarea" :autosize="{minRows: 2,maxRows: 5}"
                         :disabled="disabled"
                         placeholder="请输入备注内容" style="width: 100%"></Input>
                </Form-item>
              </i-col>
            </Row>
             <Row v-if="!disabled">
              <i-col span="8" offset="8">
                <Button size="large" @click="cancel" style="margin: 0px 10px 0px 0px;">取消</Button>
                <Button type="primary" size="large" :loading="saveLoading" @click="ok('resForm')">保存</Button>
              </i-col>
            </Row>
          </i-form>
        </div>
        </template>
      </Split>
    </div>

    <resTree :resTreeShow.sync="showResTreeModal" :resParams="modalParams" @choseRes="choseRes"
             :openCheck="false"></resTree>
    <div class="demo-split" style="height: 600px;margin-top:20px">
      <Split v-model="split2">
        <template #left>
          <roleTable ref="res-role-table" searchable search-place="top" :nowObj="nowRes" type="res" stripe size="small"
                     title="拥有对象列表"></roleTable>
        </template>
        <template #right>
          <functionPage ref="function-table" searchable search-place="top" :nowObj="nowRes" stripe
                        title="拥有功能列表"></functionPage>
        </template>
      </Split>
    </div>
  </div>
</template>

<script>
  import { getTree, addRes, editRes, removeRes, getRes } from '../../../../api/rbac/res-manage'
  import page from '_c/page'
  import roleTable from '../role/role-table.vue'
  import functionPage from '../function/function-list.vue'
  import resTree from '../res/res-tree.vue'
  import 'ztree/js/jquery.ztree.exhide'
  import { fuzzySearch } from '../../../bc-ztree/ztreeSearch'

  let $this
  export default {
    name: 'res_list',
    components: {
      page,
      roleTable,
      functionPage,
      resTree
    },
    data () {
      return {
        split1: 0.5,//分割面板的百分比
        split2: 0.5,//分割面板的百分比
        resId: '',//当前资源id
        nowRes: {},//当前资源对象,新增或编辑时会变化
        /*nowPres:{},*/
        lastRes: {},//上一次选择的资源对象
        disabled: true,
        addDisable: false,//添加按钮状态
        editDisable: false,//编辑按钮状态
        removeDisable: false,//删除按钮状态
        saveLoading: false,
        showResTreeModal: false,
        modalParams: {},
        setting: {//ztree树初始化设置
          view: {
            showLine: false,
            selectedMulti: false,
            // showIcon: false
          },
          data: {
            simpleData: {
              enable: true,
              idKey: 'id',
              pIdKey: 'pid',
              rootPId: null
            }
          },
          callback: {
            onClick: this.view
          }
          /*,
          check:{
            enable: true,
            chkboxType: { "Y": "ps", "N": "ps" }
          }*/
        },
        rules: {
          name: [
            { required: true, message: '名称不能为空!', trigger: 'blur' },
          ],
          micon: [
                { required: true, message: '图标不能为空!', trigger: 'blur' },
          ],
          type: [
                { required: true, type: 'number', message: '类型不能为空!', trigger: 'change' },
          ],
          code: [
            { required: true, message: '编码不能为空!', trigger: 'blur' },
          ]
        },
      }
    },
    methods: {
      view (event, treeId, treeNode, clickFlag) {//点击树节点触发查看事件
        this.nowRes = Object.assign({}, treeNode)
        this.nowRes.name = treeNode.ename//由于模糊搜索将name给改成了带html的字.所以需要将bean的name还原一下
        this.resId = treeId
        this.disabled = true
        this.editDisable = false
        this.addDisable = false
        this.removeDisable = false
      },
      add () {
        this.disabled = false
        this.editDisable = true
        this.removeDisable = true
        this.lastRes = Object.assign({}, this.nowRes)
        this.nowRes = { pid: this.lastRes.id, pname: this.lastRes.name, state: 1 }
      },
      edit (params) {
        this.disabled = false
        this.addDisable = true
        this.removeDisable = true
        this.lastRes = Object.assign({}, this.nowRes)
        //this.nowRes = {pid: this.lastRes.id, pname: this.lastRes.name};
      },
      remove (params) {
        if (!this.nowRes.id) {
          this.$Message.warning('请选择待操作节点')
          return
        }
        this.$Modal.confirm({
          title: '风险操作',
          content: '确定删除？',
          width: 300,
          closable: true,
          onOk () {
            removeRes($this.nowRes.id).then(data => {
              this.$Message.success('操作成功！')
              $this.saveLoading = false
              $this.reloadData()
              $this.nowRes = {}
            }).catch(err => {
              this.$Message.error('操作失败！')
              console.log(err)
              this.saveLoading = false
            })
          },
        })
      },
      showResTree () {
        if (!this.disabled) {
          this.showResTreeModal = true
          this.modalParams = { title: '选择上级', flag: '2', resId: this.nowRes.id }
        }
      },
      choseRes (pres) {
        this.nowRes.pname = pres.name
        this.nowRes.pid = pres.id
      },
      ok (name) {
        this.$refs[name].validate((valid) => {
          if (!valid) {
            return
          }//表单校验失败则返回
          this.saveLoading = true
          if (this.nowRes.id) {//有id就是编辑操作
            let params = this.nowRes
            delete params['createTime']
            delete params['modifyTime']
            //执行修改操作
            editRes(params).then(data => {
              this.$Message.success('操作成功！')
              this.saveLoading = false
              this.disabled = true
              this.reloadData()
              $this.nowRes = {}
            }).catch(err => {
              this.$Message.error('操作失败！')
              console.log(err)
              this.saveLoading = false
            })
          } else {
            //执行添加操作
            addRes(this.nowRes).then(data => {
              this.$Message.success('操作成功！')
              this.saveLoading = false
              this.disabled = true
              this.reloadData()
              $this.nowRes = {}
            }).catch(err => {
              this.$Message.error('操作失败！')
              console.log(err)
              this.saveLoading = false
            })
          }
        })

      },
      cancel () {//取消编辑后将数据还原
        this.disabled = true
        this.editDisable = false
        this.addDisable = false
        this.removeDisable = false
        this.nowRes = Object.assign({}, this.lastRes)
      },
      reloadData () {
        getTree().then(res => {
          //循环将name备份到ename属性中,避免受到模糊搜索的影响
          res.result.forEach(n => {
            n.ename = n.name
          })
          $.fn.zTree.init($('#res-list-tree'), this.setting, res.result)
          fuzzySearch('res-list-tree', 'keyword1', null, false)//搜索功能
        })
      }/*,
    onCurrentChange (currentRow,oldCurrentRow) {
      this.nowRes = currentRow;
      view();
    }*/
    },
    mounted () {
      $this = this
      this.reloadData()
    }
  }
</script>

<style>
  .demo-split {
    height: 400px;
    border: 1px solid #dcdee2;
  }
 .resform .ivu-form-inline .ivu-form-item{
    width:100%;
  }
  .demo-split-pane {
    padding: 10px;
  }
</style>
