<template>
  <div class="app-container">
    <div class="app-container">
      <div class="filter-container">
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="form_add"> 新增 </el-button>
      </div>
      <el-table
        v-loading="listLoading"
        element-loading-text="给我一点时间"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        :row-style="rowStyle"
        :cell-style="cellStyle"
        class="elTable"
        row-key="id"
        default-expand-all
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        @sort-change="tableSort"
      >
        <el-table-column label="角色名称" header-align="center" min-width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="顺序" sortable prop="sort" min-width="80px" header-align="center" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.sort }}</span>
          </template>
        </el-table-column>
        <el-table-column label="启用" min-width="80px" header-align="center" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.enable" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" @change="handleEnableChange(scope.$index, scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" header-align="center" align="center" width="330" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{row}">
            <el-button type="warning" size="mini" @click="handleMenu(row)">菜单</el-button>
            <el-button type="warning" size="mini" style="width:70px" @click="handleDataRole(row)">数据权限</el-button>
            <el-button type="primary" size="mini" @click="form_edit(row)">编辑</el-button>
            <el-button v-if="row.status!='已删'" size="mini" type="danger" @click="form_delete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="getdataListParm.offset" :limit.sync="getdataListParm.pagecount" @pagination="getList" />

      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
        <el-form ref="dataForm" :rules="rules" :model="dataform" label-position="left" label-width="100px" style="width: 600px; margin-left:50px;">
          <el-form-item label="角色名称" prop="name">
            <el-input ref="name" v-model="dataform.name" />
          </el-form-item>
          <el-form-item label="顺序" prop="sort">
            <el-input ref="sort" v-model="dataform.sort" />
          </el-form-item>
          <el-form-item label="EAS信息接收" prop="easInformationReception">
            <el-switch ref="easInformationReception" v-model="dataform.easInformationReception" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" />
          </el-form-item>
          <el-form-item label="启用" prop="enable">
            <el-switch ref="enable" v-model="dataform.enable" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button v-if="dialogStatus==='create'" type="success" @click="add_dialog_save_again()"> 确认新增 </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?add_dialog_save():edit_dialog_save()"> 确认 </el-button>
          <el-button @click="dialogFormVisible = false;getList();"> 关闭 </el-button>
        </div>
      </el-dialog>

      <el-dialog :title="textMap['dataRole']" :visible.sync="dialogDataRoleVisible" :close-on-click-modal="false">
        <el-form ref="dataRoleTemp" :rules="rules" label-position="left" :model="dataRoleTemp" label-width="100px" style="width: 600px; margin-left:50px;">
          <el-form-item label="数据权限" prop="datarole">
            <el-radio-group v-model="dataRoleTemp.datarole">
              <el-radio :label="3">全部数据</el-radio>
              <el-radio :label="2">牧场数据</el-radio>
              <el-radio :label="1">部门数据</el-radio>
              <el-radio :label="0">个人数据</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="dataRoleTemp.datarole == 1" label="部门" prop="deptNameList">
            <el-select v-model="dataRoleTemp.deptNameList" style="width:500px;" multiple placeholder="部门">
              <el-option v-for="item in findAllDepart" :key="item.id" :label="item.name" :value="item.name" />
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="edit_dialog_saveRole()"> 确认 </el-button>
          <el-button @click="dialogDataRoleVisible = false;getList()"> 关闭 </el-button>
        </div>
      </el-dialog>
      <el-dialog :title="textMap['menu']" :visible.sync="dialogMenuVisible" :close-on-click-modal="false">
        <el-form :rules="rules" label-position="left" label-width="100px" style="width: 600px; margin-left:50px;">
          <el-form-item label="菜单" prop="menuname">
            <tree-select
              :disabled="disabled"
              :height="280"
              :width="200"
              size="small"
              multiple
              :data="parentMenu"
              :default-props="defaultProps"
              collapse-tags
              check-strictly
              :node-key="nodeKey"
              :checked-keys="defaultCheckedKeys"
              @popoverHide="popoverHide"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button :disabled="isokDisable" type="primary" @click="updateMenu()"> 确认 </el-button>
          <el-button @click="dialogMenuVisible = false;getList()"> 关闭 </el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import TreeSelect from '@/components/TreeSelect'
import waves from '@/directive/waves' // waves directive
import { isIntegerZero } from '@/utils/validate'
import { PostDataByName, GetDataByName, UpdateDataRelation, ExecDataByConfig, getRecuData, failproccess } from '@/api/common'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { MessageBox } from 'element-ui'
import Cookies from 'js-cookie'
import { sortChange } from '@/utils/index.js'
export default {
  name: 'Role',
  components: { Pagination, TreeSelect },
  directives: { waves },
  data() {
    return {
      disabled: false,
      tableKey: 0,
      list: [{ 'sqlname': '', 'id': 0, 'sqlstr': '' }],
      parentMenu: [],
      total: 0,
      listLoading: true,
      requestParam: {
        name: 'createRole', offset: 0, pagecount: 0, params: []
      },
      UpdateDataRelationParam: {
        name: '', dataname: '', datavalue: '', valuename: '', values: ''
      },
      dataform: {
        id: '', name: '', selectMenus: [], sort: '', enable: '', easInformationReception: ''
      },
      getdataListParm: { name: 'getRoleall',
        offset: 1, pagecount: 10, returntype: 'Map',
        parammaps: { pastureId: Cookies.get('pastureid') }},
      getMenuParm: { name: 'getMenuandButtonRecuRule', idname: 'id', params: [-1] },
      rules: {
        name: [{ type: 'string', required: true, message: '名称必填', trigger: 'change' }],
        sort: [{ validator: isIntegerZero, trigger: 'blur' }],
        datarole: [{ required: true, message: '必填', trigger: 'blur' }]
      },
      dialogFormVisible: false,
      dialogMenuVisible: false,
      dialogDataRoleVisible: false,
      selectedMenu: '',
      dialogStatus: '',
      textMap: { update: '编辑', create: '新增', menu: '授权菜单', dataRole: '数据权限' },
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      defaultProps: { children: 'children', label: 'title' },
      nodeKey: 'id',
      defaultCheckedKeys: [],
      getDataRoleListParm: {
        name: 'getDataRole', offset: 1, pagecount: '', returntype: 'Map', parammaps: {}
      },
      getEchoDeptParm: {
        name: 'getRoleDepartmentName', offset: 1, pagecount: '', returntype: 'Map', parammaps: {}
      },
      isokDisable: false,
      dataRoleTemp: {},
      dataRolelist: [],
      deptList: [],
      findAllDepart: [],
      getDepartParam: { name: 'getDepatmentOnlyName', offset: 0, pagecount: 0 },
      requestParam2: {},
      requestParam3: {}
    }
  },
  created() {
    this.getList()
    this.getDepartDownList()
  },
  methods: {
    tableSort(column) {
      sortChange(column, this.list)
    },
    popoverHide(checkedIds, checkedData) {
      this.dataform.selectMenus = checkedIds
      this.selectedMenu = checkedIds
      this.UpdateDataRelationParam.values = checkedIds
    },
    getMenuList() {
      getRecuData(this.getMenuParm).then(response => {
        this.parentMenu = response.data
      })
    },
    getDepartDownList() {
      GetDataByName(this.getDepartParam).then(response => {
        this.findAllDepart = response.data.list
      })
    },
    getList() {
      this.listLoading = true
      GetDataByName(this.getdataListParm).then(response => {
        if (response.data.list !== null) {
          for (var i = 0; i < response.data.list.length; i++) {
            response.data.list[i].enable = parseInt(response.data.list[i].enable)
          }
          this.list = response.data.list
        }
        if (response.data.total) {
          this.total = response.data.total
        }
        this.getMenuList()
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0.5 * 1000)
      })
    },
    resetRequestParam() {
      this.dataform.id = ''
      this.dataform.name = ''
      this.dataform.sort = '0'
      this.dataform.enable = 1
      this.dataform.easInformationReception = 0
    },
    form_add() {
      this.resetRequestParam()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.$refs.name.focus()
      })
    },
    add_dialog_save() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.requestParam.name = 'createRole'
          this.requestParam.params = []
          this.requestParam.params[0] = this.dataform.name
          this.requestParam.params[1] = this.dataform.sort
          this.requestParam.params[2] = this.dataform.enable
          this.requestParam.params[3] = this.dataform.easInformationReception
          PostDataByName(this.requestParam).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '新增成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    add_dialog_save_again() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.requestParam.name = 'createRole'
          this.requestParam.params = []
          this.requestParam.params[0] = this.dataform.name
          this.requestParam.params[1] = this.dataform.sort
          this.requestParam.params[2] = this.dataform.enable
          this.requestParam.params[3] = this.dataform.easInformationReception
          PostDataByName(this.requestParam).then(() => {
            this.$nextTick(() => {
              this.$refs['name'].focus()
            })
            this.getList()
            this.resetRequestParam()
            this.$notify({
              title: '成功',
              message: '新增成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleMenu(row) {
      this.requestParam.name = 'getMenuByRole'
      this.requestParam.params = []
      this.requestParam.params[0] = row.id
      this.requestParam.pagecount = 0
      this.requestParam.returntype = 'list'
      this.dataform.id = row.id
      this.dialogMenuVisible = true

      console.log("this.requestParam",this.requestParam)
      GetDataByName(this.requestParam).then(response => {
        this.selectedMenu = response.data.lists.menu_id
        this.defaultCheckedKeys = this.selectedMenu
        this.UpdateDataRelationParam.values = this.defaultCheckedKeys
      })
    },
    updateMenu() {
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.UpdateDataRelationParam.name = 'role_menu'
      this.UpdateDataRelationParam.dataname = 'role_id'
      this.UpdateDataRelationParam.datavalue = this.dataform.id
      this.UpdateDataRelationParam.valuename = 'menu_id'
      this.UpdateDataRelationParam.values = this.selectedMenu

      UpdateDataRelation(this.UpdateDataRelationParam).then(() => {
        this.dialogMenuVisible = false
        this.$notify({
          title: '成功',
          message: '修改成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    form_edit(row) {
      console.log(row, '=====')
      this.dataform.id = row.id
      this.dataform.name = row.name
      this.dataform.sort = row.sort
      this.dataform.enable = row.enable
      this.dataform.easInformationReception = row.easInformationReception
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.$refs.name.focus()
      })
    },
    edit_dialog_save() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.requestParam.name = 'updateRole'
          this.requestParam.params = []
          this.requestParam.params[0] = this.dataform.name
          this.requestParam.params[1] = this.dataform.sort
          this.requestParam.params[2] = this.dataform.enable
          this.requestParam.params[3] = this.dataform.easInformationReception
          this.requestParam.params[4] = this.dataform.id
          PostDataByName(this.requestParam).then(() => {
            this.getList()
            this.resetRequestParam()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleEnableChange(index, row) {
      this.requestParam.name = 'updateRole'
      this.requestParam.params = []
      this.requestParam.params[0] = row.name
      this.requestParam.params[1] = row.sort
      this.requestParam.params[2] = row.enable
      this.requestParam.params[3] = row.id
      PostDataByName(this.requestParam).then(() => {
        this.$notify({
          title: '成功',
          message: '修改成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    form_delete(row) {
      MessageBox.confirm('名称：' + row.name, '确认删除？', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.requestParam.name = 'deleteRole'
        this.requestParam.params = []
        this.requestParam.params[0] = row.id
        PostDataByName(this.requestParam).then(() => {
          this.getList()
          this.resetRequestParam()
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        })
      })
    },
    handleDataRole(row) {
      if (row.deptNameList == undefined) {
        this.$set(row, 'deptNameList', [])
      }
      this.dataRoleTemp = Object.assign({}, row)
      this.$set(this.dataRoleTemp, 'datarole', 0)
      this.dialogDataRoleVisible = true
      this.getDataRoleListParm.parammaps.id = row.id
      GetDataByName(this.getDataRoleListParm).then(response => {
        this.dataRolelist = response.data.list
        this.$set(this.dataRoleTemp, 'datarole', response.data.list[0].datarole)
        if (this.dataRoleTemp.datarole == 1) {
          this.getEchoDeptParm.parammaps = {}
          this.getEchoDeptParm.parammaps.role_id = row.id
          GetDataByName(this.getEchoDeptParm).then(response => {
            var deptNameArr = []
            for (let i = 0; i < response.data.list.length; i++) {
              deptNameArr.push(response.data.list[i].name)
            }
            this.$set(this.dataRoleTemp, 'deptNameList', deptNameArr)
            this.$forceUpdate()
            console.log(this.dataRoleTemp.deptNameList)
          })
        }
      })
    },

    edit_dialog_saveRole() {
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.$refs['dataRoleTemp'].validate((valid) => {
        if (valid) {
          if (this.dataRoleTemp.datarole == 1) {
            console.log('quanbu', this.dataRoleTemp.deptNameList)
            if (this.dataRoleTemp.deptNameList == undefined || this.dataRoleTemp.deptNameList.length == 0) {
              this.$message({ type: 'warning', message: '请选择部门' })
              return false
            }
            this.requestParam2 = {}
            this.requestParam2.common = { 'returnmap': '0' }
            this.requestParam2.data = []
            for (let i = 0; i < this.dataRoleTemp.deptNameList.length; i++) {
              this.requestParam2.data.push({ 'name': 'getDepartmentId', 'type': 'sm', 'parammaps': { 'name': this.dataRoleTemp.deptNameList[i] }})
            }
            ExecDataByConfig(this.requestParam2).then(response => {
              console.log('新增保存发送参数', this.requestParam2)
              if (response.msg == 'fail') {
                this.$notify({ title: '保存失败', message: response.data, type: 'warning', duration: 2000 })
              } else {
                var arr = []
                for (let i = 0; i < response.data.length; i++) {
                  for (let j = 0; j < response.data[i].resultmaps.length; j++) {
                    arr.push(response.data[i].resultmaps[j].id)
                  }
                }
                this.requestParam3.name = 'role_department'
                this.requestParam3.dataname = 'role_id'
                this.requestParam3.datavalue = this.dataRoleTemp.id
                this.requestParam3.valuename = 'department_id'
                this.requestParam3.values = arr
                UpdateDataRelation(this.requestParam3).then(response => {
                  if (response.msg == 'fail') {
                    this.$notify({ title: '保存失败', message: response.data, type: 'warning', duration: 2000 })
                  } else {
                    this.requestParam.name = 'setDataRole'
                    this.requestParam.parammaps = {}
                    this.requestParam.parammaps.id = this.dataRoleTemp.id
                    this.requestParam.parammaps.datarole = this.dataRoleTemp.datarole
                    PostDataByName(this.requestParam).then(response => {
                      console.log('设置数据权限保存发送参数', this.requestParam)
                      if (response.msg !== 'fail') {
                        this.getList()
                        this.dialogDataRoleVisible = false
                        this.$notify({ title: '成功', message: '设置成功', type: 'success', duration: 2000 })
                      } else {
                        failproccess(response, this.$notify)
                      }
                    })
                  }
                })
              }
            })
          } else {
            this.requestParam.name = 'setDataRole'
            this.requestParam.parammaps = {}
            this.requestParam.parammaps.id = this.dataRoleTemp.id
            this.requestParam.parammaps.datarole = this.dataRoleTemp.datarole
            PostDataByName(this.requestParam).then(response => {
              console.log('设置数据权限保存发送参数', this.requestParam)
              if (response.msg !== 'fail') {
                this.getList()
                this.dialogDataRoleVisible = false
                this.$notify({ title: '成功', message: '设置成功', type: 'success', duration: 2000 })
              } else {
                failproccess(response, this.$notify)
              }
            })
          }
        }
      })
    }
  }
}
</script>
