<template>
  <div class="site-content">

    <sticky :className="'sub-navbar'">
      <div class="filter-container">
        <el-select v-model="listQuery.state" clearable placeholder="审核状态" size="mini" @change="stateChange">
          <el-option v-for="item in states" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>

        <el-input @keyup.enter.native="handleFilter" size="mini" prefix-icon="el-icon-search"
          style="width: 200px;margin-bottom: 0;margin:0px 12px;" class="filter-item" :placeholder="'站点名称'"
          v-model="listQuery.siteName">
        </el-input>

        <el-button type="default" size="mini" @click="resetListQuery">重置</el-button>
        <el-button type="primary" size="mini" @click="getList()">搜索</el-button>

        <permission-btn moduleName='modulemanager' :size="'mini'" v-on:btn-event="onBtnClicked"></permission-btn>

      </div>
    </sticky>
    <div class="app-container flex-item">
      <div class="fh">
        <el-table ref="mainTable" :key='tableKey' :data="tableData" v-loading="listLoading" border fit
          highlight-current-row style="width: 100%;" height="calc(100% - 54px)" @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="siteName" label="站点名称" show-overflow-tooltip>
          </el-table-column>

          <el-table-column prop="siteAddress" label="站点地址" show-overflow-tooltip>
          </el-table-column>

          <el-table-column prop="state" label="审核状态" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-tag :type="scope.row.state == '未审核'? 'warning': (scope.row.state == '审核通过' ? 'success':'danger')"
                size="mini">{{scope.row.state}}</el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="director" label="负责人" show-overflow-tooltip>
          </el-table-column>

          <el-table-column prop="phone" label="负责人电话" show-overflow-tooltip>
          </el-table-column>

          <el-table-column :label="'操作'" style="text-align:center;" width="180px">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" icon="" @click="signelEdit(scope.row)">详情</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageIndex" :limit.sync="listQuery.pageSize"
          @pagination="handleCurrentChange" />
      </div>
    </div>

    <el-dialog width="1066px" height="690px" top=" calc(50vh - 340px)" 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:1050px;height:690px;overflow-y:hidden;">
        <el-container v-if="addServiceVisible">
          <AddForm @addSuccess="addSuccess" :detailInfo="detailInfo" @close="addServiceVisible = false"></AddForm>
        </el-container>
      </el-container>
    </el-dialog>

    <el-dialog width="1066px" height="690px" top="60px" 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:1050px;height:690px;overflow-y:hidden;">
        <el-container v-if="editServiceVisible">
          <EditForm @editSuccess="editSuccess" @close="editServiceVisible = false" :id="editForm.id"></EditForm>
        </el-container>
      </el-container>
    </el-dialog>

    <el-dialog width="800px" height="690px" top="60px" class="dialog-mini body-small addWindow" v-el-drag-dialog
      :title="'编辑服务'" :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="selectRolesVisible">
      <el-container style="width:800px;height:690px;overflow-y:hidden;">
        <el-container v-if="selectRolesVisible">
          <!-- <EditForm @editSuccess="editSuccess" :id="editForm.id"></EditForm> -->
          <!-- <select-roles :roles="selectRoles" :isUnLoadGroupList="true" :userNames="selectRoleNames" v-on:roles-change="rolesChange"></select-roles> -->
          <select-roles :serviceId="serviceId" @serviceSuccess="serviceSuccess"></select-roles>
        </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 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';
  import AddForm from './widget/Examine';
  import EditForm from './widget/EditForm';
  import SelectRoles from './widget/SelectRoles'
  import Sticky from '@/components/Sticky'

  export default {
    name: 'module',
    components: {
      permissionBtn,
      Pagination,
      AddForm,
      EditForm,
      SelectRoles,
      Sticky
      // elDragDialog
    },
    mixins: [extend],
    directives: {
      waves,
      elDragDialog
    },
    data() {
      return {
        states: [
          {
            value: 0,
            label: "未审核",
          }, {
            value: 1,
            label: "审核通过",
          }, {
            value: 2,
            label: "未通过",
          }, {
            value: 3,
            label: "全部",
          }
        ],
        tableData: [],
        addServiceVisible: false,
        editServiceVisible: false,
        selectRolesVisible: 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: {
          // 查询条件
          pageIndex: 1,
          pageSize: 20,
          state: 3,
          siteName: null,
        },
        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,
        selectRoles: [], // 用户分配的角色
        selectRoleNames: '',
        serviceId: null,

      }
    },
    computed: {

    },
    filters: {

    },
    created() {
      this.getList()
    },
    mounted() {

    },
    methods: {
      goBack() {
        this.$router.push({ 'path': '/gridman' })
      },
      resetListQuery() {
        this.listQuery.state = 3;
        this.listQuery.siteName = null;
        this.getList();
      },
      stateChange(e) {
        this.listQuery.state = e;
        this.getList();
      },
      serviceSuccess() {
        this.selectRolesVisible = false;
      },
      rolesChange(type, val) {
        if (type === 'Texts') {
          this.selectRoleNames = val
          return
        }
        this.selectRoles = val
      },
      selectRole(id) {
        this.serviceId = id;
        this.selectRolesVisible = true;
      },
      addSuccess() {
        this.addServiceVisible = false;
        this.$message({
          type: "success",
          message: "审核成功！"
        })
        this.getList();
      },
      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
        getMethodCommon("/FireCodePC/LoadAllSite", this.listQuery).then(res => {
          if (res.code == 200) {
            this.tableData = res.data
            this.tableData.forEach((item, index) => {
              switch (item.state) {
                case 0: this.tableData[index].state = "未审核";
                  break;
                case 1: this.tableData[index].state = "审核通过";
                  break;
                case 2: this.tableData[index].state = "未通过";
                  break;
                case 3: this.tableData[index].state = "全部";
                  break;
              }
            })
            this.total = res.count
            this.listLoading = false
          }
        })
      },
      handleFilter() {
        this.listQuery.pageIndex = 1
        this.getList()
      },
      handleSizeChange(val) {
        this.listQuery.pageSize = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.pageIndex = val.page
        this.listQuery.pageSize = 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;
      },
      signelEdit(row) {
        this.detailInfo = row;
        this.addServiceVisible = 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(() => {
          let idsStr = [];
          this.multipleSelection.forEach((item, index) => {
            idsStr.push(item.id);
          })
          postMethodCommon("/CimService/Delete", idsStr).then(res => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: "删除成功",
              })
            }
            this.getList();
          })
        }).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
    }
  }
</script>

<style lang="scss" scoped>
   .el-table {
    ::v-deep .el-table__body-wrapper::-webkit-scrollbar {
      width: 10px;
      /*滚动条宽度*/
      height: 10px;
      /*滚动条高度*/
    }

    /*定义滚动条轨道 内阴影+圆角*/
    ::v-deep .el-table__body-wrapper::-webkit-scrollbar-track {
      box-shadow: 0px 1px 3px #071e4a inset;
      /*滚动条的背景区域的内阴影*/
      border-radius: 10px;
      /*滚动条的背景区域的圆角*/
      background-color: rgba(0, 9, 34, 1);
      /*滚动条的背景颜色*/
    }

    /*定义滑块 内阴影+圆角*/
    ::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
      box-shadow: 0px 1px 3px #00a0e9 inset;
      /*滚动条的内阴影*/
      border-radius: 10px;
      /*滚动条的圆角*/
      background-color: rgba(0, 9, 34, 1);

      /*滚动条的背景颜色*/
    }
  }
    ::v-deep .el-pagination__jump{
    color: #fff;
  }
  ::v-deep .sticky{
    background: rgba(0, 9, 34, 0.6);
  }
  ::v-deep .dialog-mini .el-dialog__header {
    background: rgba(10,39,78, 1);
  }

  ::v-deep .dialog-mini .el-dialog__header .el-dialog__title {
    color: #fff;

  }

  ::v-deep .el-descriptions__body {
    background: rgba(0, 9, 34, 1);
    color: #fff;
  }

  ::v-deep .el-descriptions-item__label.is-bordered-label {
    background: rgba(0, 9, 34, 0.6);
    color: #fff;
  }

  ::v-deep .el-input__inner {
    background: rgba(0, 9, 34, 1);
    color: #fff;
  }

  ::v-deep .el-dialog {
    background: rgba(10,39,78, 1);

  }

  ::v-deep .el-loading-mask {
    background: rgba(0, 9, 34, 0.9);

  }

  .filter-container {
    text-align: right;
  }

  .site-container {
    width: 100%;
    height: 100%;
    background-image: url(/img/gridman/bg.png);
    background-size: 100% 100%;
  }

  .site-header {
    width: 100%;
    height: 99px;
    background-image: url(/img/gridman/header.png);
    background-size: 100% 100%;
    text-align: center;
    color: #fff;
    line-height: 90px;
    font-size: 36px;
    letter-spacing: 5px;
  }

  .header-btn {
    width: 100px;
    height: 50px;
    position: absolute;
    top: 4%;
    left: 2%;
  }

  .site-content {
    width: 100%;
    height: 94%;
    background: rgba(0, 9, 34, 0.6);
  }

  .app-container {
    height: 100%;
    background: rgba(0, 9, 34, 0.6);
  }

  ::v-deep .el-table {
    background: rgba(0, 9, 34, 0.6);
    border-left: 1px solid #00EDE8;
  }

  ::v-deep .el-table .el-table__body tr:hover td {
    background: rgba(24, 77, 143, 0.4) !important;
    cursor: pointer;
  }

  ::v-deep .el-table .el-table__body tr.current-row td {
    cursor: pointer;
    background: rgba(24, 77, 143, 0.4) !important;
  }

  ::v-deep .el-table tr {
    background: rgba(0, 9, 34, 0.6);
    border: none;
    color: #fff;

  }

  ::v-deep .el-table th.el-table__cell {
    background: rgba(0, 9, 34, 0.6);
    color: #fff;
    border: 1px solid #00EDE8;

  }

  ::v-deep .el-pagination__total,
  .el-pagination__jump {
    color: #fff;
  }

  ::v-deep .el-table td.el-table__cell,
  .el-table th.el-table__cell.is-leaf {
    border-bottom: 1px solid #00EDE8;
  }

  ::v-deep .el-table--border .el-table__cell,
  .el-table__body-wrapper .el-table--border.is-scrolling-left~.el-table__fixed {
    border-right: 1px solid #00EDE8;
  }

  ::v-deep .pagination-container {
    background: rgba(0, 9, 34, 0.6) !important;
    border: none;
  }

  .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>