<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;margin:0px 12px;" class="filter-item" :placeholder="'站点名称'"
          v-model="listQuery.key">
        </el-input> -->

        <el-autocomplete
          size="mini"
          v-model="siteName"
          style="margin-right:12px;"
          :fetch-suggestions="querySearchAsync"
          placeholder="防火站点"
          :value-key="'name'"
          @select="handleSelect"
          clearable
        ></el-autocomplete>

         <el-date-picker
          v-model="startEndTime"
          style="position:relative;top:1px;"
          size="mini"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="dateTimeChange"
          >
        </el-date-picker>
        <!-- 人员名称 -->
        <el-input @keyup.enter.native="handleFilter" clearable size="mini" prefix-icon="el-icon-search" style="width: 200px;margin-bottom: 0;margin:0px 12px;" class="filter-item" :placeholder="'人员姓名'"
          v-model="listQuery.userName">
        </el-input>
        <!-- 身份证号 -->
        <el-input @keyup.enter.native="handleFilter" clearable size="mini" prefix-icon="el-icon-search" style="width: 200px;margin-bottom: 0;margin-right:12px;" class="filter-item" :placeholder="'身份证号'"
          v-model="listQuery.cardNo">
        </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="bg-white fh">
        <el-table ref="mainTable" :key='tableKey' :data="tableData" v-loading="listLoading" size="mini" border fit
          highlight-current-row style="width: 100%;" height="calc(100vh - 182px)" @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="userName" label="人员姓名" show-overflow-tooltip>
          </el-table-column>

          <el-table-column  prop="cardNo" label="身份证号" show-overflow-tooltip>
          </el-table-column>

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

          <el-table-column  prop="inTime" label="进山时间" show-overflow-tooltip>
          </el-table-column>

          <el-table-column  prop="siteName" label="防火站点" show-overflow-tooltip>
          </el-table-column>

          <el-table-column  prop="inTypeName" label="登记方式" show-overflow-tooltip>
          </el-table-column>

          <el-table-column :label="'操作'" style="text-align:center;" width="120px">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" icon="el-icon-document" @click="getDetail(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="750px" height="400px" top=" calc( 50vh - 200px)"
                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:750px;height:400px;overflow-y:hidden;">
        <el-container v-if="addServiceVisible">
          <AddForm :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 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';
import AddForm from './widget/Examine';
import EditForm from './widget/EditForm';
import SelectRoles from './widget/SelectRoles'

export default {
  name: 'module',
  components: {
    Sticky,
    permissionBtn,
    Pagination,
    AddForm,
    EditForm,
    SelectRoles
    // elDragDialog
  },
  mixins: [extend],
  directives: {
    waves,
    elDragDialog
  },
  data() {
    return {
      siteName:null,
      startEndTime:[new Date("2023-01-01"),new Date()],
      lngLat:[117.92214891969796,35.26152309532066],
      states:[
        {
          value:1,
          label:"应急",
        },{
          value:0,
          label:"防火",
        }
      ],
      tableData:[
        {
          name:"徐景良",
          phone:"17861857725",
          time:"2023-04-19 10:00:00",
          site:"塔山防火站",
          method:"本人登记",
          user:"徐景良",
        },{
          name:"张斌",
          phone:"17861857725",
          time:"2023-04-19 10:00:00",
          site:"塔山防火站",
          method:"管理员登记",
          user:"张斌",
        }
      ],
      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,
        startTime:null,
        endTime:null,
        cardNo: null,
        userName:null,
        siteId: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.listQuery.startTime = this.formatTime(this.startEndTime[0]);
    this.listQuery.endTime = this.formatTime(this.startEndTime[1]);
    this.getList();
  },
  mounted() {

  },
  methods: {
    resetListQuery(){
      this.listQuery.userName = null;
      this.listQuery.cardNo = null;
      this.listQuery.siteId = null;
      this.siteName = null;
      this.getList();
    },
    querySearchAsync(e,cb){
      if(e == "" || e==null || e == " "){
        return;
      }
      getMethodCommon("/FireCodePC/LoadAllSite",{pageIndex:1,pageSize:10,siteName:e,state:3}).then(res=>{
        if(res.code == 200){
          if(res.data.length>0){
            let list = [
              // {
              //   name:"全部",
              //   value:null
              // }
            ];
            res.data.forEach((item,index)=>{
              let it = {
                name:item.siteName,
                value:item.id
              }
              list.push(it);
            })
            if(list.length>0){
              cb(list);
            }else{
              return null;
            }
          }
        }
      })
      
    },
    handleSelect(e){
      this.listQuery.siteId = e.value;
      this.getList();
    },
    formatTime(dateParam){
      var date = new Date(dateParam);
      var year = date.getFullYear();    //  返回的是年份
      var month = date.getMonth() + 1;  //  返回的月份上个月的月份，记得+1才是当月
      var dates = date.getDate(); 
      var hour = date.getHours();
      var minute = date.getMinutes();
      var seconds = date.getSeconds();
      if(month<10)month="0"+month;
      if(date<10)date="0"+date;
      if(hour<10)hour = "0"+hour;
      if(minute<10)minute = "0"+minute;
      if(seconds<10)seconds = "0"+seconds
      var time=year + "-" + month + "-" + dates + " "+ hour+":"+minute+":"+seconds
      return time;
    },
    dateTimeChange(e){
      this.listQuery.startTime = this.formatTime(e[0]);
      this.listQuery.endTime = this.formatTime(e[1]);
      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.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("/FireCodeApp/LoadInUser",this.listQuery).then(res=>{
        if(res.code == 200){
          this.tableData = res.data
          this.total = res.count
          this.listLoading = false
        }
      })
    },

    handleFilter() {
      this.listQuery.pageIndexIndex = 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;
    },
    getDetail(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">
.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>
