<template>
  <div class="app-container">
    <div class="search">
      <el-input v-model="table.parammaps.name" placeholder="请输入角色名称搜索" style="width: 180px;" class="filter-item"
        clearable />
      <el-button class="successBorder" @click="handleSearch">查询</el-button>
      <el-button class="successBorder" @click="handleRefresh">重置</el-button>
    </div>
    <div class="operation">
      <el-button v-if="isAdd" icon="el-icon-plus" class="success" @click="handleCreate">新增</el-button>
    </div>
    <div class="table">
      <el-table :key="table.tableKey" v-loading="table.listLoading" element-loading-text="给我一点时间" :data="table.list"
        border fit highlight-current-row style="width: 100%;" :row-style="rowStyle" :cell-style="cellStyle"
        class="elTable table-fixed">
        <el-table-column type="selection" align="center" width="50" />
        <el-table-column label="序号" min-width="130px" align="center" prop="id" />
        <el-table-column label="角色名称" min-width="130px" align="center" prop="name" />
        <el-table-column label="描述" min-width="130px" align="center" prop="remarks" />
        <el-table-column label="负责牧场" min-width="150px" align="center">
          <template slot-scope="{row}">
            <span>{{row.pasture_list.toString()}}</span>
          </template>
        </el-table-column>
        <el-table-column label="权限配置" min-width="150px" align="center">
          <template slot-scope="{row}">
            <span>{{row.menu_list.toString()}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{row}">
            <el-button v-if="isEdit" icon="el-icon-edit-outline" class="miniSuccess" @click="handleUpdate(row)" />
            <span v-if="isDelete" class="centerSpan">|</span>
            <el-button v-if="isDelete" icon="el-icon-delete" class="miniDanger" @click="handleRowDelete(row)" />
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="table.total>=0" :total="table.total" :page.sync="table.page" :limit.sync="table.page_size" @pagination="getList" />
    </div>
    <!-- 新增/编辑 -->
    <el-dialog :title="textMap[edit.dialogStatus]" :visible.sync="edit.dialogFormVisible" :close-on-click-modal="false"
      width="50%">
      <div class="edit">
        <el-form ref="editTemp" :rules="rules" :model="edit" label-position="right" label-width="115px"
          style="width: 100%;margin:0 auto 30px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="角色名称:" prop="name">
                <el-input ref="name" v-model="edit.name" placeholder="请输入角色名称" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="描述:" prop="remarks">
                <el-input ref="remarks" v-model="edit.remarks" placeholder="请输入描述" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="负责牧场:" prop="checkedPasture">
                <el-checkbox :indeterminate="edit.isIndeterminatePasture" v-model="edit.checkAllPasture"
                  @change="handlePastureCheckAllChange">全选</el-checkbox>
                <el-checkbox-group v-model="edit.checkedPasture" @change="handleCheckedPastureChange">
                  <el-checkbox v-for="(item,index) in edit.pastureList" :label="item.id"
                    :key="index">{{item.name}}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="后台权限:" prop="backgroundData">
                <el-checkbox v-model="edit.checkAllBackground"
                  @change="handleBackgroundCheckAllChange">全选</el-checkbox>
                <el-tree
                  :default-expand-all="true"
                  :data="edit.backgroundData"
                  highlight-current
                  show-checkbox
                  node-key="id"
                  :props="edit.backgroundDefaultProps"
                  :default-checked-keys="edit.backgroundCheckedkeys"
                  ref="backgroundTree">
                </el-tree>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="移动端权限:" prop="checkAllMobileData">
                <el-checkbox v-model="edit.checkAllMobile" @change="handleMobileCheckAllChange">全选</el-checkbox>
                <el-tree
                  :default-expand-all="true"
                  :data="edit.mobileData"
                  highlight-current
                  show-checkbox
                  node-key="id"
                  :props="edit.mobileDefaultProps"
                  :default-checked-keys="edit.mobileCheckedkeys"
                  ref="mobileTree">
                </el-tree>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer" style="right:30px;position:absolute;bottom: 40px;">
          <el-button class="cancelClose cancelClose" @click="edit.dialogFormVisible = false;getList(); ">关闭</el-button>
          <el-button class="save" :disabled="isokDisable"
            @click="edit.dialogStatus == 'add' ? createData():updateData()">确认</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { postJson, getJson, delJson,checkButtons } from '@/api/common'
  import Cookies from 'js-cookie'
  import { parseTime } from '@/utils/index.js'
  import { MessageBox } from 'element-ui'
  import Pagination from '@/components/Pagination'
  import TreeSelect from '@/components/TreeSelect'
  export default {
    name: 'Role',
    components: {
      Pagination,TreeSelect
    },
    data() {
      var validatePass = (rule, value, callback) => {
        let arr = this.$refs.backgroundTree.getCheckedKeys() // 在此获取选中的树形数据
        if (arr.length == 0 || !arr) {
          callback(new Error("请至少选择一个后台权限"));
        } else {
          callback();
        }
      };
      return {
        table: {
          page: 1,
          page_size: parseInt(Cookies.get('pageCount')),
          tableKey: 0,
          list: [],
          total: 0,
          listLoading: true,
          parammaps: {
            name: ''
          }
        },
        edit: {
          dialogStatus: '',
          dialogFormVisible: false,
          name:'',
          remarks:'',
          // 牧场
          pastureOptions: [],
          checkAllPasture: false,
          checkedPasture: [],
          pastureList: [],
          isIndeterminatePasture: false,
          // 后台权限
          checkAllBackground: false,
          backgroundData: [],
          backgroundDefaultProps: {
            children: 'children',
            label: 'name'
          },
          backgrounddefaultCheckedKeys: [],
          backgroundCheckedkeys: [],
          backgroundLength: 0,
          // 移动端权限
          checkAllMobile: false,
          mobileData: [],
          mobileDefaultProps: {
            children: 'children',
            label: 'name'
          },
          mobiledefaultCheckedKeys: [],
          mobileCheckedkeys: [],
          mobileLength: 0,
        },
        rules: {
          name: [{
            required: true,
            message: '必填',
            trigger: 'blur'
          }],
          checkedPasture: [
            { type: 'array', required: true, message: '请至少选择一个牧场', trigger: 'change' }
          ],
          backgroundData: [
            { type: 'array',validator: validatePass, required: true, trigger: 'change' }
          ],
        },
        textMap: {
          add: '新增',
          update: '编辑'
        },
        isokDisable: false,
        rowStyle: {
          maxHeight: 30 + 'px',
          height: 30 + 'px'
        },
        cellStyle: {
          padding: 0 + 'px'
        },
        isAdd:'',isEdit:'',isDelete:'',
      }
    },

    created() {
      this.getButton()
      this.getList()
      this.getPastureList()
      this.getBackgroundList()
      this.getMobileList()
    },
    methods: {
      getButton(){
        const add = 'systemManagement:role:add'
        this.isAdd = checkButtons(add)
        const edit = 'systemManagement:role:edit'
        this.isEdit = checkButtons(edit)
        const del = 'systemManagement:role:delete'
        this.isDelete = checkButtons(del)
      },
      getList() {
        // console.log(process.env.VUE_APP_BASE_API)
        this.table.listLoading = true
        let page = this.table.page
        let page_size = this.table.page_size
        let url = 'api/v1/system/role/list' + '?page=' + page + '&page_size=' + page_size
        let data = {
          name: this.table.parammaps.name
        }
        postJson(url, data).then(response => {
          if (response.code == 200) {
            this.table.list = response.data.list
            this.table.total = response.data.total
            this.table.pageNum = response.data.page
            this.table.pageSize = response.data.page_size
            console.log( this.table.list,'====')
          } else {
            this.table.list = []
          }
          setTimeout(() => {
            this.table.listLoading = false
          }, 1000)
        })
      },

      handleSearch() {
        console.log('点击了查询')
        this.table.page = 1
        this.getList()
      },
      handleRefresh() {
        console.log('点击了重置')
        this.table.parammaps.name = ''
        this.table.page = 1
        this.getList()
      },

      handleCreate() {
        console.log('点击了新增')
        this.edit.dialogStatus = 'add'
        this.edit.dialogFormVisible = true
        this.edit.isIndeterminatePasture = false
        this.edit.name = ''
        this.edit.remarks = ''
        this.edit.checkedPasture = []
        var myId = ''
        this.edit.mobileData.forEach(item => {
          if(item.name == '我的'){
            myId = item.id
          }
        })
        this.$nextTick(() => {
          this.$refs.backgroundTree.setCheckedKeys([]);
          this.$refs.mobileTree.setCheckedKeys([myId]);
        });
        // this.edit.mobileCheckedkeys = [4]
        this.edit.backgroundLength = 0
        this.edit.mobileLength = 0
        this.edit.isIndeterminatePasture = false
        this.edit.checkAllPasture = false
        this.edit.checkAllBackground = false
        this.edit.checkAllMobile = false
      },
      // 牧场
      getPastureList() {
        let page = 1
        let page_size = 100
        let url = 'api/v1/ops/pasture/list' + '?page=' + page + '&page_size=' + page_size
        let data = {}
        postJson(url, data).then(response => {
          if (response.code == 200) {
            this.edit.pastureOptions = []
            for (let i = 0; i < response.data.list.length; i++) {
              this.edit.pastureOptions.push(response.data.list[i].id)
            }
            this.edit.pastureList = response.data.list
          } else {
            this.edit.pastureOptions = []
            this.edit.pastureList = this.edit.pastureOptions
          }
        })
      },
      handlePastureCheckAllChange(val) {
        this.edit.checkedPasture = val ? this.edit.pastureOptions : [];
        this.edit.isIndeterminatePasture = false;
      },
      handleCheckedPastureChange(value) {
        let checkedCount = value.length;
        this.edit.checkAllPasture = checkedCount === this.edit.pastureList.length;
        this.edit.isIndeterminatePasture = checkedCount > 0 && checkedCount < this.edit.pastureList.length;
      },
      // 后台权限
      getBackgroundList() {
        let page = 1
        let page_size = 100
        let url = 'api/v1/system/menu/list' + '?page=' + page + '&page_size=' + page_size
        let data = {}
        postJson(url, data).then(response => {
          if (response.code == 200) {
            this.edit.backgroundLength = response.data.total
            this.edit.backgroundData = response.data.list
          } else {
            this.edit.backgroundLength = 0
            this.edit.backgroundData = []
          }
        })
      },
      handleBackgroundCheckAllChange(val) {
        if (this.edit.checkAllBackground) {
          this.$nextTick(() => {
            this.$refs.backgroundTree.setCheckedNodes(this.edit.backgroundData);
          });
        } else {
          this.$nextTick(() => {
            this.$refs.backgroundTree.setCheckedKeys([]);
          });
        }
        this.$nextTick(() => {
          let select_box = [];
          this.$refs.backgroundTree.getCheckedNodes().forEach((item) => {
            select_box.push(item.id);
          });
          this.edit.backgrounddefaultCheckedKeys = select_box
        });
      },
      // 移动端权限
      getMobileList() {
        let url = 'api/v1/system/mobile/list'
        let data = {}
        postJson(url, data).then(response => {
          if (response.code == 200) {
            this.edit.mobileLength = response.data.total
            this.edit.mobileData = response.data.list
          } else {
            this.edit.mobileLength = 0
            this.edit.mobileData = []
          }
        })
      },
      handleMobileCheckAllChange(val) {
        if (this.edit.checkAllMobile) {
          this.$nextTick(() => {
            this.$refs.mobileTree.setCheckedNodes(this.edit.mobileData);
          });
        } else {
          this.$nextTick(() => {
            this.$refs.mobileTree.setCheckedKeys([]);
          });
        }
        this.$nextTick(() => {
          let select_box = [];
          this.$refs.mobileTree.getCheckedNodes().forEach((item) => {
            select_box.push(item.id);
          });
          this.edit.mobiledefaultCheckedKeys = select_box
          console.log(select_box, 'select_box888');
        });
      },
      createData() {
        this.$refs['editTemp'].validate((valid) => {
          if (valid) {
            this.isokDisable = true
            setTimeout(() => {
              this.isokDisable = false
            }, 1000)
            let url = 'api/v1/system/role/add'
            let data = {
              'name': this.edit.name,
              "remarks": this.edit.remarks,
              "pasture_id": this.edit.checkedPasture,
              "menu_id": this.$refs.backgroundTree.getCheckedKeys().concat(this.edit.backgroundParentId),
              "mobile_id": this.$refs.mobileTree.getCheckedKeys(),
              "create_user": Cookies.get('username')
            }
            postJson(url, data).then(response => {
              if (response.code == 200) {
                this.$notify({
                  title: '',
                  message: '成功',
                  type: 'success',
                  duration: 2000
                })
                this.edit.dialogFormVisible = false
                this.getList()
              }
            })
          }
        })
      },

      handleUpdate(row) {
        this.edit.dialogStatus = 'update'
        this.edit.id = row.id
        this.edit.name = row.name
        this.edit.remarks = row.remarks
        this.edit.checkedPasture = []
        this.edit.backgroundCheckedkeys = []
        this.edit.mobileCheckedkeys = []
        this.getBackgroundList()
        this.getMobileList()
        this.getRolesList()
      },
      getRolesList() {
        let url = 'api/v1/system/role/permissions/'
        let data = this.edit.id
        getJson(url, data).then(response => {
          if (response.code == 200) {
            var menu_list = response.data.menu_list; //后台权限
            var new_menu_list = [];
            var item = '';
            menu_list.forEach(item=>{
              this.checked(item,this.edit.backgroundData,new_menu_list)
            })
            this.edit.backgroundCheckedkeys = new_menu_list
            var mobile_list = response.data.mobile_list; //移动端权限
            var new_mobile_list = [];
            var item = '';
            mobile_list.forEach(item=>{
              this.checked(item,this.edit.mobileData,new_mobile_list)
            })
            this.edit.mobileCheckedkeys = new_mobile_list
            this.edit.checkedPasture = response.data.pasture_list
          } else {
            this.edit.checkedPasture = []
            this.edit.backgroundCheckedkeys = []
            this.edit.mobileCheckedkeys = []
          }
          if (this.edit.checkedPasture.length == this.edit.pastureList.length) {
            this.edit.isIndeterminatePasture = false
            this.edit.checkAllPasture = true
          } else {
            this.edit.isIndeterminatePasture = true
            this.edit.checkAllPasture = false
          }

          this.edit.dialogFormVisible = true
        })
      },
      checked(id,data,newArr) {
        data.forEach(item => {
          if(item.id == id){
              if(item.children.length == 0 ){
                newArr.push(item.id)
              }
          }else{
            if( item.children.length !=0 ){
              this.checked(id,item.children,newArr)
            }
          }
        });
      },
      updateData(row) {
        let menu_id_list = this.$refs.backgroundTree.getCheckedKeys().concat(this.$refs.backgroundTree.getHalfCheckedKeys())
        let mobile_id_list = this.$refs.mobileTree.getCheckedKeys().concat(this.$refs.mobileTree.getHalfCheckedKeys())
        console.log(menu_id_list,'menu_id_list')
        this.$refs['editTemp'].validate((valid) => {
          if (valid) {
            this.isokDisable = true
            setTimeout(() => {
              this.isokDisable = false
            }, 1000)
            let url = 'api/v1/system/role/edit'
            let data = {
              "id": this.edit.id,
              'name': this.edit.name,
              "remarks": this.edit.remarks,
              "pasture_id": this.edit.checkedPasture,
              "menu_id": menu_id_list,
              "mobile_id": mobile_id_list,
              "create_user": Cookies.get('username')
            }
            console.log(data)
            postJson(url, data).then(response => {
              if (response.code == 200) {
                this.$notify({
                  title: '',
                  message: '成功',
                  type: 'success',
                  duration: 2000
                })
                this.edit.dialogFormVisible = false
                this.getList()
              }
            })
          }
        })
      },
      handleRowDelete(row) {
        console.log('点击了行内删除')
        MessageBox.confirm('是否确认删除此信息?', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let url = 'api/v1/system/role/'
          let data = row.id
          delJson(url, data).then(response => {
            if (response.code == 200) {
              this.$notify({
                title: '',
                message: '成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            }
          })
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .search {
    margin-top: 10px;
  }
</style>
