<template>
  <div class="flex-column">
    <sticky :className="'sub-navbar'">
      <div class="filter-container">
        <el-input @keyup.enter.native="handleFilter" size="mini" prefix-icon="el-icon-search" style="width: 200px;margin-bottom: 0;" class="filter-item" :placeholder="'关键字'"
          v-model="listQuery.key">
        </el-input>
        <permission-btn moduleName='modulemanager' :size="'mini'" v-on:btn-event="onBtnClicked"></permission-btn>
      </div>
    </sticky>
    <div class="app-container flex-item">
			<div class="bg-white fh">
        <el-row :gutter="12" style="width:100%;height:100%;">
          <el-col :span="4" style="padding:12px;">
             <el-tree :data="cateTree" :props="defaultProps" @node-click="handleNodeClick" :default-expand-all="true"></el-tree>
          </el-col>
          <el-col :span="20" style="height:100%;">
            <el-table ref="mainTable" :key='tableKey' :data="tableData" v-loading="listLoading" border fit
              highlight-current-row style="width: 100%;" height="calc(100% - 112px)" @row-click="rowClick" @selection-change="handleSelectionChange">
              <el-table-column type="selection" align="center" width="55">
              </el-table-column>

              <el-table-column :label="'Id'" v-if="showDescription" min-width="120px">
                <template slot-scope="scope">
                  <span>{{scope.row.id}}</span>
                </template>
              </el-table-column>
 

              <el-table-column prop="name" label="分类名称" show-overflow-tooltip>
              </el-table-column>

              <el-table-column prop="createtime" label="创建时间" show-overflow-tooltip>
              </el-table-column>

              <!-- <el-table-column :label="'操作'" style="text-align:center;" width="240px"  show-overflow-tooltip>
                <template  slot-scope="scope">
                  <el-button type="primary" size="mini">查看</el-button>
                  <el-button type="success" size="mini" @click="applyPass(scope.row)">审批</el-button>
                  <el-button type="danger" size="mini" >拒绝</el-button>
                </template>
              </el-table-column> -->
            </el-table>
            <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="handleCurrentChange" />
          </el-col>
        </el-row>
			</div>
    </div>

    <el-dialog width="400px" height="200px" top="80px"
                class="dialog-mini body-small addWindow"
                v-el-drag-dialog
                :title="'添加'"
                :close-on-click-modal="false"
                :close-on-press-escape="false"
                :visible.sync="addServiceVisible"
                >
      <el-container style="width:400px;height:200px;overflow-y:hidden;">
        <el-container v-if="addServiceVisible">
          <AddForm @close="addSuccess"></AddForm>
        </el-container>
      </el-container>
    </el-dialog>

    <el-dialog width="400px" height="200px" top="80px"
                class="dialog-mini body-small addWindow"
                v-el-drag-dialog
                :title="'添加'"
                :close-on-click-modal="false"
                :close-on-press-escape="false"
                :visible.sync="editServiceVisible"
                >
      <el-container style="width:400px;height:200px;overflow-y:hidden;">
        <el-container v-if="editServiceVisible">
          <EditForm @close="editSuccess" :id="editForm.id"></EditForm>
        </el-container>
      </el-container>
    </el-dialog>

   


     <el-dialog width="620px" height="100px" top="160px"
                class="dialog-mini body-small addWindow"
                v-el-drag-dialog
                :title="'审批'"
                :close-on-click-modal="false"
                :close-on-press-escape="false"
                :visible.sync="approvalVisible"
                >
      <el-container style="width:600px;height:200px;overflow-y:hidden;">
        <el-container v-if="approvalVisible">
         <div>
            <el-checkbox-group v-model="selectedRoles">
              <el-checkbox v-for="(item,index) in roles" :key="index" :label="item.name" :name="item.id" />
              <!-- <el-checkbox label="selected and disabled" disabled /> -->
            </el-checkbox-group>
         </div>
        
         <div style="position:absolute;bottom:12px;width:90%;text-align:right;">
            <el-button type="primary" size="mini" @click="submit">通过</el-button>
         </div>
        </el-container>
      </el-container>
    </el-dialog>


  </div>

</template>

<script>
import Pagination from '@/components/Pagination'
import { listToTreeSelect} from '@/utils'
import extend from "@/extensions/delRows.js"
import * as modules from '@/api/modules'
import * as login from '@/api/login'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import waves from '@/directive/waves' // 水波纹指令
import Sticky from '@/components/Sticky'
import permissionBtn from '@/components/PermissionBtn'
import elDragDialog from '@/directive/el-dragDialog'
import iconData from '@/assets/public/css/comIconfont/iconfont/iconfont.json'
import {getMethodCommon,postMethodCommon } from "@/api/common";
import AddForm from './widget/AddForm.vue'
import EditForm from './widget/EditForm.vue'

export default {
  name: 'module',
  components: {
    Sticky,
    permissionBtn,
    Pagination,
    AddForm,
    EditForm
    // elDragDialog
  },
  mixins: [extend],
  directives: {
    waves,
    elDragDialog
  },
  data() {
    return {
      cateTree:[],
      defaultProps: {
        children: 'child',
        label: 'name'
      },
      tableData:[],
      addServiceVisible:false,
      editServiceVisible:false,
      approvalVisible:false,
      iconData: iconData,
      normalizer(node) {
        // treeselect定义字段
        return {
          label: node.name,
          id: node.id,
          children: node.children,
         
        }
      },
      columns: [
        // treetable的列名
        {
          text: '模块名称',
          value: 'name'
        },
        {
          text: '模块标识',
          value: 'code'
        },
        {
          text: 'URL',
          value: 'url'
        }
      ],
      selectMenus: [], // 菜单列表选中的值
      tableKey: 0,
      list: [], // 菜单列表
      total: 0,
      currentModule: null, // 左边模块treetable当前选中的项
      listLoading:false,
      listQuery: {
        // 查询条件
        page: 1,
        limit: 20,
        key: undefined
      },
      apps: [],

      showDescription: false,
      modules: [], // 用户可访问到的模块列表
      modulesTree: [], // 用户可访问到的所有模块组成的树
      temp: {
        // 模块临时值
        id: undefined,
        cascadeId: '',
        url: '',
        code: '',
        sortNo: 0,
        iconName: '',
        parentId: null,
        name: '',
        status: 0,
        isSys: false
      },
      menuTemp: {
        // 菜单临时值
        id: undefined,
        url: '',
        icon: '',
        code: '',
        moduleId: null,
        name: '',
        status: 0,
        sort: 0
      },
      dialogFormVisible: false, // 模块编辑框
      dialogStatus: '',
      dialogMenuVisible: false, // 菜单编辑框
      dialogMenuStatus: '',

      chkRoot: false, // 根节点是否选中
      treeDisabled: false, // 树选择框时候可用
      textMap: {
        update: '编辑',
        create: '添加'
      },
      rules: {
        name: [
          {
            required: true,
            message: '名称不能为空',
            trigger: 'blur'
          }
        ]
      },
      downloadLoading: false,
      multipleSelection:[],
      editForm:null,
      roles:[],
      selectedRoles:[],
      passFormData:null,
    }
  },
  computed: {

  },
  filters: {
    
  },
  created() {
    this.getCateTree();
    this.getList()
  },
  mounted() {

  },
  methods: {
    handleNodeClick(){

    },
    getCateTree(){
      postMethodCommon("/CimApiDescCategory/LoadTree").then(res=>{
        if(res.code == 200){
          this.cateTree = res.data;
        }
      })
    },
    applyPass(row){
      // let arr = [];
      // let obj = {
      //   id:row.id,
      //   status:1,
      //   marker:"",
      // }
      // arr.push(obj);
      // postMethodCommon("/CimServiceApply/AnditServiceApply",arr).then(res=>{
      //   this.$message({
      //     type:"success",
      //     message:"操作成功",
      //   })
      //   this.getList();
      // })
      getMethodCommon("/CimServiceApply/GetAnditServiceApply",{id:row.id}).then(res=>{
        if(res.code == 200){
          this.passFormData = res.result;
          this.roles = res.result.roleList;
          this.approvalVisible = true;

        }
      })
    },
    addSuccess(){
      this.addServiceVisible = false;
      this.getList();
      this.getCateTree();
    },
    editSuccess(){
      this.editServiceVisible = false;
      this.getList();
    },
    rowClick(row) {
      this.$refs.mainTable.clearSelection()
      this.$refs.mainTable.toggleRowSelection(row)
    },
    
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    onBtnClicked: function(domId) {
      console.log('you click:' + domId)
      switch (domId) {
        case 'btnAdd':
          this.addServiceVisible = true;
          break
        case 'btnEdit':
          if (this.multipleSelection.length != 1) {
            this.$message({
              message: '只能选中一个进行编辑',
              type: 'error'
            })
            return
          }
          this.handleUpdate()
          break
        case 'btnDel':
          if (this.multipleSelection.length != 1) {
            this.$message({
              message: '只能选中一个进行删除',
              type: 'error'
            })
            return
          }
          this.handleDelete()
          break
        case 'btnAddMenu':
          this.handleAddMenu()
          break
        case 'btnEditMenu':
          if (this.selectMenus.length !== 1) {
            this.$message({
              message: '只能选中一个进行编辑',
              type: 'error'
            })
            return
          }
          this.handleEditMenu(this.selectMenus[0])
          break
        case 'btnDelMenu':
          if (this.selectMenus.length < 1) {
            this.$message({
              message: '至少删除一个',
              type: 'error'
            })
            return
          }
          this.handleDelMenus(this.selectMenus)
          break
        default:
          break
      }
    },
    getList() {
      this.listLoading = true
       postMethodCommon("/CimApiDescCategory/Load",this.listQuery).then(res=>{
        if(res.code == 200){
          this.tableData = res.data
          this.total = res.count
          this.listLoading = false
        }
      })

    },

    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val.page
      this.listQuery.limit = val.limit
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        cascadeId: '',
        url: '',
        iconName: '',
        code: '',
        parentId: null,
        name: '',
        status: 0
      }
    },


    // #region 模块管理
    handleCreate() {
      // 弹出添加框
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.dpSelectModule = null
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      // 保存提交
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if(this.temp.url.indexOf('http') > -1 && !this.temp.code){
            this.$message.error('请输入模块标识')
            return
          }
          modules.add(this.temp).then(response => {
            // 需要回填数据库生成的数据
            this.temp.id = response.result.id
            this.temp.cascadeId = response.result.cascadeId
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this.getModulesTree()
          })
        }
      })
    },
    handleUpdate() {
      this.editForm = this.multipleSelection[0];
      this.editServiceVisible = true;
    },
    updateData() {
      // 更新提交
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          if(tempData.url.indexOf('http') > -1 && !tempData.code){
            this.$message.error('请输入模块标识')
            return
          }
          modules.update(tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })

            this.getModulesTree()
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
          })
        }
      })
    },
    handleDelete() {
      this.$confirm('确定删除所选数据?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
       
        // this.multipleSelection.forEach((item,index)=>{
        //   idsStr.push(item.id);
        // })
        let id = this.multipleSelection[0].id;

        postMethodCommon("/CimApiDescCategory/Delete?id="+id).then(res=>{
          if(res.code == 200){
            this.$message({
              type:"success",
              message:"删除成功",
            })
          }
          this.getList();
          this.getCateTree();
        })
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消删除'
				});          
			});
      
    },
    // #end region

    // #region 菜单管理
    handleAddMenu() {
      // 弹出添加框
      this.resetMenuTemp()
      this.dialogMenuStatus = 'create'
      this.dialogMenuVisible = true
      this.$nextTick(() => {
        this.$refs['menuForm'].clearValidate()
      })
    },
    addMenu() {
      // 保存提交
      this.$refs['menuForm'].validate(valid => {
        if (valid) {
          modules.addMenu(this.menuTemp).then(response => {
            // 需要回填数据库生成的数据
            this.menuTemp.id = response.result.id
            this.list.unshift(this.menuTemp)
            this.dialogMenuVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleEditMenu(row) {
      // 弹出编辑框
      this.menuTemp = Object.assign({}, row) // copy obj
      this.dialogMenuStatus = 'update'
      this.dialogMenuVisible = true
      this.$nextTick(() => {
        this.$refs['menuForm'].clearValidate()
      })
    },
    updateMenu() {
      // 更新提交
      this.$refs['menuForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.menuTemp)
          modules.updateMenu(tempData).then(() => {
            this.dialogMenuVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })

            for (const v of this.list) {
              if (v.id === this.menuTemp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.menuTemp)
                break
              }
            }
          })
        }
      })
    },
    handleDelMenus(rows) {
      // 多行删除
      modules.delMenu(rows.map(u => u.id)).then(() => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        rows.forEach(row => {
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
        })
      })
    },
    // #end region
    submit(){
      let arr = [];
      this.selectedRoles.forEach((item)=>{
        let obj = this.roles.find((row)=>{
          return row.name == item;
        })
        
        arr.push(obj.id);
      })

      // this.passFormData.roleList = arr;
      this.passFormData.roles = arr;
      this.passFormData.status = 1;
      postMethodCommon("/CimServiceApply/AnditServiceApply",this.passFormData).then(res=>{
        if(res.code == 200){
          this.$message({
            type:"success",
            message:"审批成功",
          })
          this.approvalVisible = false;

        }
      })

    }
  }
}
</script>

<style lang="scss">
.text {
    font-size: 14px;
}

.item {
    margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
    display: table;
    content: '';
}

.clearfix:after {
    clear: both;
}

.el-card__header {
    padding: 12px 20px;
}
.selectIcon-box{
  text-align: center;
  border: 1px solid #eeeeee;
  border-right: 0;
  border-bottom: 0;
  .el-col{
    padding: 10px 0;
    border-right: 1px solid #eeeeee;
    border-bottom: 1px solid #eeeeee;
    &.active{
      .iconfont{
        color: #409EFF;
      }
    }
  }
  .iconfont{
    cursor: pointer;
    font-size: 20px;
  }
}
.custom-icon-input::before{
  font-size: 18px;
  position: absolute;
  right: 10px;
  top: 0;
}
</style>
