<template>
  <div class="app-container">
    <div class="search">
      <el-input v-model="table.getdataListParm.parammaps.rolename" placeholder="角色名称" style="width: 180px;" class="filter-item" clearable />
      <el-input v-model="table.getdataListParm.parammaps.createmp" placeholder="创建人" style="width: 180px;" class="filter-item" clearable />
      <el-select v-model="table.getdataListParm.parammaps.enable" placeholder="是否启用" class="filter-item" style="width: 120px;" clearable>
        <el-option v-for="item in enableList" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-date-picker ref="inputDatetime" v-model="table.getdataListParm.parammaps.inputDatetime" class="inputDatetime filter-item" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 250px;" />
      <el-button class="successBorder" @click="handleSearch">查询</el-button>
      <el-button class="successBorder" @click="handleRefresh">重置</el-button>
    </div>
    <div class="operation">
      <el-button v-if="isRoleEdit" icon="el-icon-plus" class="success" @click="handleCreate">新增</el-button>
      <el-button v-if="isRoleEdit" icon="el-icon-delete" class="danger" @click="handleDelete">删除</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"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="center" width="50" />
        <el-table-column label="序号" align="center" type="index" width="50px">
          <template slot-scope="scope">
            <span>{{ scope.$index + (table.pageNum-1) * table.pageSize + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="角色名称" min-width="130px" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.NoEdit">{{ scope.row.rolename }}</span>
            <el-input v-if="scope.row.Edit" v-model="scope.row.rolename" type="textarea" :autosize="{ minRows: 1.3, maxRows: 4}" maxlength="32" style="width:95%;padding:10px 0;" />
          </template>
        </el-table-column>
        <el-table-column label="备注" min-width="130px" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.NoEdit">{{ scope.row.remark }}</span>
            <el-input v-if="scope.row.Edit" v-model="scope.row.remark" type="textarea" :autosize="{ minRows: 1.3, maxRows: 4}" maxlength="32" style="width:95%;padding:10px 0;" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.createdtime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建人" min-width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.createmp }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否启用" min-width="110px" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.enable" :disabled="scope.row.NoEdit==true" 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="操作" align="center" width="180" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{row}">
            <!-- 页面权限 -->
            <a v-if="row.NoEdit && isRoleEdit" class="correcting" @click="handleRole(row)">页面权限</a>
            <span v-if="row.NoEdit && isRoleEdit" class="centerSpan">|</span>
            <!-- 新增 -->
            <el-button v-if="row.isCreate && isRoleEdit" icon="el-icon-folder-checked" class="miniSuccess" :disabled="isokDisable" @click="createData(row)" />
            <span v-if="row.isCreate && isRoleEdit" class="centerSpan">|</span>
            <el-button v-if="row.isCreate && isRoleEdit" icon="el-icon-close" class="minCancel" @click="createCancel(row)" />
            <!-- 编辑 -->
            <el-button v-if="row.isUpdate && isRoleEdit" icon="el-icon-edit-outline" class="miniSuccess" @click="handleUpdate(row)" />
            <span v-if="row.isUpdate && isRoleEdit" class="centerSpan">|</span>
            <el-button v-if="row.isUpdate && isRoleEdit" icon="el-icon-delete" class="miniDanger" @click="handleRowDelete(row)" />
            <!-- 编辑保存 -->
            <el-button v-if="row.isUpdateSave && isRoleEdit" icon="el-icon-folder-checked" class="miniSuccess" :disabled="isokDisable" @click="updateData(row)" />
            <span v-if="row.isUpdateSave && isRoleEdit" class="centerSpan">|</span>
            <el-button v-if="row.isUpdateSave && isRoleEdit" icon="el-icon-close" class="minCancel" @click="updateCancel(row)" />
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="table.total>=0" :total="table.total" :page.sync="table.getdataListParm.offset" :limit.sync="table.getdataListParm.pagecount" @pagination="getList" />
    </div>

    <el-dialog :fullscreen="dialogFull" :visible.sync="role.dialogFormVisible" :close-on-click-modal="false" width="70%">
      <template slot="title">
        <div class="avue-crud__dialog__header">
          <span class="el-dialog__title">
            <span style="display:inline-block;width:3px;height:20px;margin-right:5px; float: left;margin-top:2px" />
            {{ textMap[role.dialogStatus] }}
          </span>
          <div class="avue-crud__dialog__menu" @click="dialogFull? dialogFull=false: dialogFull=true">
            <svg-icon v-if="dialogFull" icon-class="exit-fullscreen" />
            <svg-icon v-else icon-class="fullscreen" />
          </div>
        </div>
      </template>
      <div class="role-details inside-base">
        <div class="inside-base-main clearfix">
          <div class="inside-base-cont">
            <div class="role-cont clearfix">
              <div>
                <el-table
                  ref="table"
                  :data="tableData"
                  style="width: 100%;margin-bottom: 20px;"
                  row-key="id"
                  border
                  :indent="10"
                  :select-on-indeterminate="true"
                  :default-expand-all="false"
                  show-checkbox
                  :checked-keys="defaultCheckedKeys"
                  :tree-props="{children: 'childList', hasChildren: 'hasChildren'}"
                >
                  <el-table-column header-align="center" prop="name" label="页面" />
                  <el-table-column header-align="center" label="查看" :render-header="renderSeeHeader">
                    <template slot-scope="scope">
                      <el-checkbox v-model="scope.row.fnCheck.seebutton" :indeterminate="scope.row.indeterminate.seebutton" label="查看" @change="fnCheckEv(scope, 'seebutton')" />
                    </template>
                  </el-table-column>
                  <el-table-column header-align="center" label="编辑" :render-header="renderEditHeader">
                    <template slot-scope="scope">
                      <el-checkbox v-model="scope.row.fnCheck.editbutton" :indeterminate="scope.row.indeterminate.editbutton" label="编辑" @change="fnCheckEv(scope, 'editbutton')" />
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
        </div>
        <div slot="footer" class="dialog-footer" style="right:30px;position:absolute;bottom:10px">
          <el-button class="cancelClose" @click="role.dialogFormVisible = false;getList(); ">取消</el-button>
          <el-button v-if="role.dialogStatus==='role'" class="save" :disabled="isokDisable" @click="roleData()">确认</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { GetDataByName, PostDataByName, failproccess, transData, ExecDataByConfig, 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'
export default {
  name: 'Role',
  components: { Pagination },
  data() {
    return {
      dialogFull: false,
      isRoleEdit: [],
      enableList: [{ id: 1, name: '是' }, { id: 0, name: '否' }], // 是否启用

      table: {
        getdataListParm: {
          name: 'getRoleList',
          page: 1,
          offset: 1,
          pagecount: parseInt(Cookies.get('pageCount')),
          returntype: 'Map',
          parammaps: {
            pastureid: Cookies.get('pastureid'),
            rolename: '',
            createmp: '',
            enable: '',
            startTime: '',
            stopTime: '',
            inputDatetime: ''
          }
        },
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: true,
        temp: {}
      },
      requestParam: {},
      selectList: [],
      role: {
        dialogFormVisible: false,
        dialogStatus: '',
        temp: {}
      },
      // parentType: [],
      getRecuListParm: {
        name: 'getMenuByRole',
        parammaps: {
          pastureid: Cookies.get('pastureid')
        }
      },
      tableData: [],
      defaultCheckedKeys: [],
      // tableData: [
      //   {
      //     id: 1, page: '配方计划', pageCheck: false,
      //     fnList: ['查看', '编辑'],
      //     fnCheck: { see: false, edit: false },
      //     childList: [
      //       { p_id: 1, id: 31, page: '配方模板', pageCheck: false, fnList: ['查看', '编辑'], fnCheck: { see: false, edit: false }},
      //       { p_id: 1, id: 32, page: '栏舍配方', pageCheck: false, fnList: ['查看', '编辑'], fnCheck: { see: false, edit: false }}
      //     ]
      //   }, {
      //     id: 2, page: '栏舍生产', pageCheck: false,
      //     fnList: ['查看', '编辑'],
      //     fnCheck: { see: false, edit: false },
      //     childList: [
      //       { p_id: 2, id: 33, page: '栏舍产奶量', pageCheck: false, fnList: ['查看', '编辑'], fnCheck: { see: false, edit: false }},
      //       { p_id: 2, id: 34, page: '栏舍剩料量', pageCheck: false, fnList: ['查看', '编辑'], fnCheck: { see: false, edit: false }}
      //     ]
      //   }
      // ],
      isokDisable: false,
      textMap: {
        role: '权限管理'
      },
      rowStyle: { maxHeight: 30 + 'px', height: 30 + 'px' },
      cellStyle: { padding: 0 + 'px' }

    }
  },

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

  methods: {
    getButtons() {
      const Edit = 'Role'
      const isRoleEdit = checkButtons(JSON.parse(sessionStorage.getItem('buttons')), Edit)
      this.isRoleEdit = isRoleEdit
    },
    getList() {
      this.table.listLoading = true
      GetDataByName(this.table.getdataListParm).then(response => {
        console.log('table数据', response.data.list)
        if (response.data.list !== null) {
          for (let i = 0; i < response.data.list.length; i++) {
            this.$set(response.data.list[i], 'Edit', false) // 编辑
            this.$set(response.data.list[i], 'NoEdit', true) // 不可编辑/输入
            this.$set(response.data.list[i], 'isCreate', false) // 新增操作
            this.$set(response.data.list[i], 'isUpdate', true) // 编辑操作
            this.$set(response.data.list[i], 'isUpdateSave', false) // 编辑保存
          }
          this.table.list = response.data.list
          this.table.pageNum = response.data.pageNum
          this.table.pageSize = response.data.pageSize
        } else {
          this.table.list = []
        }
        this.table.total = response.data.total
        setTimeout(() => {
          this.table.listLoading = false
        }, 100)
      })
    },
    handleEnableChange() {
      console.log('点击了是否启用')
    },
    handleConfirmStartChange() {
      console.log('点击了确认开始')
    },
    handleSearch() {
      console.log('点击了查询')
      if (this.table.getdataListParm.parammaps.inputDatetime !== '' && this.table.getdataListParm.parammaps.inputDatetime !== null) {
        this.table.getdataListParm.parammaps.startTime = parseTime(this.table.getdataListParm.parammaps.inputDatetime[0], '{y}-{m}-{d}')
        this.table.getdataListParm.parammaps.stopTime = parseTime(this.table.getdataListParm.parammaps.inputDatetime[1], '{y}-{m}-{d}')
      } else {
        this.table.getdataListParm.parammaps.inputDatetime = ''
        this.table.getdataListParm.parammaps.startTime = ''
        this.table.getdataListParm.parammaps.stopTime = ''
      }
      this.table.getdataListParm.offset = 1
      this.getList()
    },
    handleRefresh() {
      console.log('点击了重置')
      this.table.getdataListParm.parammaps.rolename = ''
      this.table.getdataListParm.parammaps.createmp = ''
      this.table.getdataListParm.parammaps.enable = ''
      this.table.getdataListParm.parammaps.startTime = ''
      this.table.getdataListParm.parammaps.stopTime = ''
      this.table.getdataListParm.parammaps.inputDatetime = ''
      this.table.getdataListParm.offset = 1
      this.getList()
    },

    handleCreate() {
      console.log('点击了新增')
      // 编辑true/不可编辑false
      // 新增操true,编辑false，编辑保存false
      for (let i = 0; i < this.table.list.length; i++) {
        if (this.table.list[i].Edit == true) {
          this.$message({ type: 'error', message: '当前内容未保存，请点击取消或保存继续进行操作', duration: 2000 })
          return false
        }
      }
      this.table.list.unshift({ 'myId': (new Date()).valueOf(), 'Edit': true, 'NoEdit': false, 'isCreate': true, 'isUpdate': false, 'isUpdateSave': false, 'enable': 1, 'confirmStart': 1, 'createdtime': parseTime(new Date(), '{y}-{m}-{d}'), 'createmp': Cookies.get('employename'), 'rolename': '' })
    },
    createData(row) {
      console.log('点击了新增保存', row)
      this.table.temp.pastureid = Cookies.get('pastureid')
      this.table.temp.empname = row.empname
      this.table.temp.rolename = row.rolename
      this.table.temp.enable = row.enable
      this.table.temp.remark = row.remark
      this.table.temp.createmp = row.createmp
      // 检验角色名称/角色是否为空
      if (this.table.temp.rolename == '') {
        this.$message({ type: 'error', message: '角色名称不能为空', duration: 2000 })
        return false
      }
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 3000)
      this.requestParam.name = 'createRole'
      this.requestParam.parammaps = this.table.temp
      PostDataByName(this.requestParam).then(response => {
        console.log('新增保存发送参数', this.requestParam)
        if (response.msg !== 'fail') {
          this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
          this.getList()
        } else {
          const isRepeat = new RegExp('Duplicate entry')
          if (isRepeat.test(response.data)) {
            this.$message({ type: 'error', message: '角色名称不可重复', duration: 2000 })
          } else {
            this.$notify({ title: '保存失败', message: response.data, type: 'warning', duration: 2000 })
          }
        }
      })
    },
    createCancel(row) {
      console.log('点击了新增取消')
      for (let i = 0; i < this.table.list.length; i++) {
        if (row.myId === this.table.list[i].myId) {
          var listIndex = this.table.list.indexOf(this.table.list[i])
        }
        if (listIndex > -1) {
          this.table.list.splice(listIndex, 1)
          return
        }
      }
    },
    handleUpdate(row) {
      console.log('点击了编辑')
      for (let i = 0; i < this.table.list.length; i++) {
        if (this.table.list[i].Edit == true) {
          this.$message({ type: 'error', message: '当前内容未保存，请点击取消或保存继续进行操作', duration: 2000 })
          return false
        }
      }
      // 编辑true,不可编辑false
      row.Edit = true
      row.NoEdit = false
      // 新增false,编辑false,编辑保存true
      row.isCreate = false
      row.isUpdate = false
      row.isUpdateSave = true
    },
    updateData(row) {
      console.log('点击了编辑保存', row)
      this.table.temp.pastureid = Cookies.get('pastureid')
      this.table.temp.id = row.id
      this.table.temp.empname = row.empname
      this.table.temp.rolename = row.rolename
      this.table.temp.enable = row.enable
      this.table.temp.remark = row.remark
      // 检验角色名称/角色是否为空
      if (this.table.temp.rolename == '') {
        this.$message({ type: 'error', message: '角色名称不能为空', duration: 2000 })
        return false
      }
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 3000)
      this.requestParam.name = 'updateRole'
      this.requestParam.parammaps = this.table.temp
      PostDataByName(this.requestParam).then(response => {
        console.log('新增保存发送参数', this.requestParam)
        if (response.msg !== 'fail') {
          this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
          this.getList()
        } else {
          this.$notify({ title: '保存失败', message: response.data, type: 'warning', duration: 2000 })
        }
      })
    },
    updateCancel(row) {
      console.log('点击了编辑取消')
      // 编辑false,不可编辑true
      row.Edit = false
      row.NoEdit = true
      // 新增false,编辑true,编辑保存false
      row.isCreate = false
      row.isUpdate = true
      row.isUpdateSave = false
      this.getList()
    },
    handleRowDelete(row) {
      console.log('点击了行内删除')
      MessageBox.confirm('是否确认删除此信息?', {
        confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        console.log(this.selectList)
        this.selectList = []
        this.requestParam = {}
        this.requestParam.common = { 'returnmap': '0' }
        this.requestParam.data = []
        this.requestParam.data[0] = { 'name': 'checkDeleteRole', 'type': 'v', 'parammaps': {
          'pastureid': row.pastureid,
          'id': row.id
        }}
        this.requestParam.data[1] = { 'name': 'deleteRole', 'type': 'e', 'parammaps': {
          'pastureid': row.pastureid,
          'id': row.id
        }}
        ExecDataByConfig(this.requestParam).then(response => {
          console.log('删除保存发送参数', this.requestParam)
          if (response.msg === 'fail') {
            this.$notify({ title: '删除失败', message: response.data, type: 'warning', duration: 2000 })
          } else {
            this.$notify({ title: '', message: '删除成功', type: 'success', duration: 2000 })
            this.getList()
          }
        })
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' })
      })
    },
    handleSelectionChange(val) {
      console.log('勾选数据', val)
      this.selectList = val
    },
    handleDelete() {
      console.log('点击了删除')
      if (this.selectList.length == 0) {
        this.$message({ type: 'error', message: '请选择角色信息', duration: 2000 })
      } else {
        MessageBox.confirm('是否确认删除此信息?', {
          confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning'
        }).then(() => {
          console.log(this.selectList)
          this.requestParam.common = { 'returnmap': '0' }
          this.requestParam.data = []
          for (let i = 0; i < this.selectList.length; i++) {
            this.requestParam.data[i] = { 'name': 'checkDeleteRole', 'type': 'v', 'parammaps': {
              'pastureid': this.selectList[i].pastureid,
              'id': this.selectList[i].id
            }}
          }
          this.requestParam.data[this.selectList.length] = { 'name': 'insertSpotList', 'resultmaps': { 'list': this.selectList }}
          this.requestParam.data[this.selectList.length].children = []
          this.requestParam.data[this.selectList.length].children[0] = { 'name': 'deleteRole', 'type': 'e', 'parammaps': {
            'pastureid': '@insertSpotList.pastureid',
            'id': '@insertSpotList.id'
          }}
          ExecDataByConfig(this.requestParam).then(response => {
            console.log('删除保存发送参数', this.requestParam)
            if (response.msg === 'fail') {
              this.$notify({ title: '删除失败', message: response.data, type: 'warning', duration: 2000 })
            } else {
              this.$notify({ title: '', message: '删除成功', type: 'success', duration: 2000 })
              this.getList()
            }
          })
        })
      }
    },
    handleRole(row) {
      this.role.temp = Object.assign({}, row)
      console.log('点击了行内页面权限')
      this.dialogFull = false
      this.role.dialogStatus = 'role'
      this.role.dialogFormVisible = true
      this.tableData = []
      this.getRecuListParm.parammaps.roleid = row.id
      this.getRoleList()
    },
    getRoleList() {
      GetDataByName(this.getRecuListParm).then(response => {
        if (response.data.list !== null) {
          this.tableData = transData(response.data.list, 'id', 'pid', 'children')
          console.log(this.tableData)
          this.tableData.forEach((item, i) => {
            item.childList = item.children
            this.$set(item, 'fnCheck', {})
            this.$set(item, 'indeterminate', { 'seebutton': false, 'editbutton': false })
            if (item.seebutton == 1) { this.$set(item.fnCheck, 'seebutton', true) } else if (item.seebutton == 0) { this.$set(item.fnCheck, 'seebutton', false) } else if (item.seebutton == 2) { this.$set(item.indeterminate, 'seebutton', true) } else if (item.seebutton == 3) { this.$set(item.indeterminate, 'seebutton', false) }
            if (item.editbutton == 1) { this.$set(item.fnCheck, 'editbutton', true) } else if (item.editbutton == 0) { this.$set(item.fnCheck, 'editbutton', false) } else if (item.seebutton == 2) { this.$set(item.indeterminate, 'editbutton', true) } else if (item.seebutton == 3) { this.$set(item.indeterminate, 'editbutton', false) }
            if (item.seebutton == 2) { this.$set(item.indeterminate, 'seebutton', true) } else if (item.seebutton == 0) { this.$set(item.indeterminate, 'seebutton', false) }
            if (item.editbutton == 3) { this.$set(item.indeterminate, 'editbutton', true) } else if (item.editbutton == 0) { this.$set(item.indeterminate, 'editbutton', false) }
            if (item.childList !== undefined && item.childList.length > 0) {
              item.childList.forEach((item, i) => {
                this.$set(item, 'fnCheck', {})
                this.$set(item, 'indeterminate', { 'seebutton': false, 'editbutton': false })
                if (item.seebutton == 1) { this.$set(item.fnCheck, 'seebutton', true) } else if (item.seebutton == 0) { this.$set(item.fnCheck, 'seebutton', false) }
                if (item.editbutton == 1) { this.$set(item.fnCheck, 'editbutton', true) } else if (item.editbutton == 0) { this.$set(item.fnCheck, 'editbutton', false) }
              })
            }
          })
          console.log(this.tableData)
        }
      })
    },
    // 查找父级函数
    getParent(data2, nodeId2) {
      var arrRes = []
      if (data2.length === 0) {
        if (nodeId2) {
          arrRes.push(data2)
        }
        return arrRes
      }
      const rev = (data, nodeId) => {
        for (var i = 0, length = data.length; i < length; i++) {
          const node = data[i]
          if (node.id === nodeId) {
            arrRes.push(node)
            rev(data2, node.pid)
            break
          } else {
            if (node.childList) {
              rev(node.childList, nodeId)
            }
          }
        }
        return arrRes
      }
      arrRes = rev(data2, nodeId2)
      return arrRes
    },

    /**
    * 功能选择
    */
    // 子选框事件
    fnCheckEv(scope, type) {
      // 如果有子项，则子项的选框选择跟当前一致
      if (scope.row.childList) {
        console.log(scope.row)
        this.handleFnAll(scope.row, scope.row.fnCheck[type], scope.row.indeterminate[type], type)
      }
      // 查找父级选框
      this.getParent(this.tableData, scope.row.id).forEach((item, i) => {
        // console.log(item)
        if (type == 'seebutton') {
          if (!item.childList) {
            console.log(item)
            item.fnCheck[type] = scope.row.fnCheck[type]
          } else {
            let num = 0
            item.childList.forEach((item, i) => {
              if (item.fnCheck[type] === true) {
                num += 1
              }
            })
            if (num === item.childList.length) {
              console.log(item)
              item.fnCheck[type] = true
              item.indeterminate[type] = false
            } else {
              item.fnCheck[type] = false
              item.fnCheck['editbutton'] = false
              const childListArr = []
              const childEditListArr = []
              console.log(item.childList)
              item.childList.forEach((item, index) => {
                console.log(item) // d打印正常
                console.log(item.fnCheck) // d打印正常
                // console.log(item.fnCheck['editbutton'])//错误？
                console.log(item.fnCheck.editbutton)// 错误？
                childListArr.push(item.fnCheck[type])
                childEditListArr.push(item.fnCheck['editbutton'])
              })

              console.log(childEditListArr)
              if (childListArr.includes(true)) {
                item.indeterminate[type] = true
                item.fnCheck['editbutton'] = false
                console.log(childEditListArr)
                if (childEditListArr.includes(true)) { // 判断编辑子级是否有true
                  item.indeterminate['editbutton'] = true
                } else {
                  item.indeterminate['editbutton'] = false
                }
                if (item.childList.length > 0) {
                  item.childList.forEach((item, i) => {
                    if (item.fnCheck['editbutton'] === false) {
                      item.fnCheck['editbutton'] = false
                    } else {
                      item.fnCheck['editbutton'] = item.fnCheck[type]
                    }
                  })
                }
              } else {
                item.indeterminate[type] = false
                console.log(item)
                // item.indeterminate['editbutton'] = false
                const editArr = []
                if (item.childList.length > 0) {
                  item.childList.forEach((item, i) => {
                    item.fnCheck['editbutton'] = item.fnCheck[type]
                    editArr.push(item.fnCheck['editbutton'])
                  })
                }
                if (editArr.includes(true)) { // 判断编辑子级是否有true
                  item.indeterminate['editbutton'] = true
                } else {
                  item.indeterminate['editbutton'] = false
                }
              }
            }
          }
        } else if (type == 'editbutton') {
          if (!item.childList) {
            item.fnCheck[type] = scope.row.fnCheck[type]
          } else {
            let num = 0
            item.childList.forEach((item, i) => {
              if (item.fnCheck[type] === true) {
                num += 1
              }
            })
            if (num === item.childList.length) {
              item.fnCheck[type] = true
              item.fnCheck['seebutton'] = true
              item.indeterminate[type] = false
              item.indeterminate['seebutton'] = false
              item.childList.forEach((item, i) => { // 编辑时，选中编辑的同时，选中查看
                console.log(item)
                if (item.fnCheck['seebutton'] === false) { // 查看未选中时，选中编辑可控制查看
                  item.fnCheck['seebutton'] = item.fnCheck['editbutton']
                }
              })
              console.log(item)
            } else {
              console.log(item)
              item.fnCheck[type] = false
              console.log(item.fnCheck['seebutton'])
              if (item.fnCheck['seebutton'] === false) { // 查看未选中时，选中编辑可控制查看
                item.fnCheck['seebutton'] = false
              }
              const childListArr = []
              for (let i = 0; i < item.childList.length; i++) {
                childListArr.push(item.childList[i].fnCheck[type])
              }
              childListArr.includes(true)
              if (childListArr.includes(true)) {
                if (item.fnCheck['seebutton'] === false) {
                  item.indeterminate['seebutton'] = true
                }
                item.indeterminate[type] = true
              } else {
                // if (item.fnCheck['seebutton'] === false) {
                //    item.indeterminate['seebutton'] = false
                // }

                item.indeterminate[type] = false
              }
              // item.indeterminate[type] = true
              item.childList.forEach((item, i) => { // 编辑时，选中编辑的同时，选中查看
                if (item.fnCheck['seebutton'] === false) {
                  item.fnCheck['seebutton'] = item.fnCheck['editbutton']
                }
              })
              console.log(item)
            }
          }
        }
      })
    },
    handleFnAll(row, fnCheck, indeterminate, type) {
      console.log(row, fnCheck, indeterminate, type)
      row.fnCheck[type] = fnCheck
      if (row.childList) {
        const that = this
        row.childList.forEach((element, i) => {
          row.indeterminate[type] = false
          console.log(fnCheck, indeterminate)
          // console.log(element, row.childList[i], fnCheck, indeterminate, type)
          that.handleFnAll(row.childList[i], fnCheck, indeterminate, type)
        })
      }
    },
    /**
    * 权限选择
    */
    // 权限：全部、自己
    // 子选框事件
    dataCheckEv(scope, type) {
      console.log(scope)
      const temp = scope.row.dataCheck[type]
      console.log(scope, type)
      for (const x in scope.row.dataCheck) {
        scope.row.dataCheck[x] = false
      }
      scope.row.dataCheck[type] = temp
      // 如果有子项，则子项的选框选择跟当前一致
      if (scope.row.childList) {
        this.handleDataAll(scope.row, scope.row.dataCheck[type], type)
      }
      // 查找父级选框
      this.getParent(this.tableData, scope.row.id).forEach((item, i) => {
        console.log(item, '==============674')
        for (const x in item.dataCheck) {
          item.dataCheck[x] = false
        }
        if (!item.childList) {
          console.log(item, '==============679')
          item.dataCheck[type] = temp
        } else {
          var num = 0
          item.childList.forEach((item, i) => {
            if (item.dataCheck[type] === true) {
              num += 1
            }
          })
          if (num === item.childList.length) {
            console.log(item, '==============689')
            item.dataCheck[type] = true
          } else {
            console.log(item, '==============691')
            item.dataCheck[type] = false
          }
        }
      })
    },
    handleDataAll(row, dataCheck, type) {
      for (const x in row.dataCheck) {
        row.dataCheck[x] = false
      }
      row.dataCheck[type] = dataCheck
      if (row.childList) {
        console.log(row, dataCheck, type)
        const that = this
        row.childList.forEach((element, i) => {
          that.handleDataAll(row.childList[i], dataCheck, type)
        })
      } else {
        console.log(row, dataCheck, type)
      }
    },
    renderSeeHeader(h, { column }) {
      return h(
        'div',
        [
          h('span', column.label),
          h('el-checkbox', {
            style: 'display:inline-flex;margin-left:5px;',
            on: {
              change: ($event, column) => this.selectSee($event, column, 'see') // 选中事件 $event, column，这里$event=true,column是input的dom当在select里打印的时候
            }
          })
        ]
      )
    },
    renderEditHeader(h, { column }) {
      return h(
        'div',
        [
          h('span', column.label),
          h('el-checkbox', {
            style: 'display:inline-flex;margin-left:5px;',
            on: {
              change: ($event, column) => this.selectEdit($event, column, 'edit') // 选中事件 $event, column，这里$event=true,column是input的dom当在select里打印的时候
            }
          })
        ]
      )
    },
    selectSee(obj, $event = this.targetEv, title) {
      const _this = this
      if ($event) {
        this.targetEv = $event // 这里是获取当前点击的input的dom元素赋值给this.targetEv，方便提交后初始化使用
      }
      if (obj === true) {
        this.flag = false
      } else {
        this.flag = true
      }
      this.targetEv.target.checked = obj
      this.targetEv.target.parentNode.className = obj ? 'el-checkbox__input is-checked' : 'el-checkbox__input'
      _this.tableData.forEach((item, index) => {
        _this.$set(_this.tableData[index], 'check', obj.toString())
        if (title === 'see') {
          if (obj === true) {
            item.fnCheck['seebutton'] = true
            if (item.childList.length > 0) {
              item.childList.forEach((item, index) => {
                item.fnCheck['seebutton'] = true
              })
            }
          } else {
            item.fnCheck['seebutton'] = false
            if (item.childList.length > 0) {
              item.childList.forEach((item, index) => {
                item.fnCheck['seebutton'] = false
              })
            }
          }
        }
      })
    },
    selectEdit(obj, $event = this.targetEv, title) {
      const _this = this
      if ($event) {
        this.targetEv = $event // 这里是获取当前点击的input的dom元素赋值给this.targetEv，方便提交后初始化使用
      }
      console.log('进来就错了', obj)
      if (obj === true) {
        this.flag = false
      } else {
        this.flag = true
      }
      this.targetEv.target.checked = obj
      this.targetEv.target.parentNode.className = obj ? 'el-checkbox__input is-checked' : 'el-checkbox__input'
      _this.tableData.forEach((item, index) => {
        _this.$set(_this.tableData[index], 'check', obj.toString())
        if (title === 'edit') {
          if (obj === true) {
            item.fnCheck['editbutton'] = true
            if (item.fnCheck['seebutton'] === false) {
              item.fnCheck['seebutton'] = true
            }
            if (item.childList.length > 0) {
              item.childList.forEach((item, index) => {
                item.fnCheck['editbutton'] = true
                if (item.fnCheck['seebutton'] === false) {
                  item.fnCheck['seebutton'] = true
                }
              })
            }
          } else {
            item.fnCheck['editbutton'] = false
            if (item.childList.length > 0) {
              item.childList.forEach((item, index) => {
                item.fnCheck['editbutton'] = false
              })
            }
          }
        }
      })
    },
    roleData(row) {
      console.log('点击了权限确认', this.tableData)
      // console.log('点击了权限确认', JSON.stringify(this.tableData))
      const dataAll = []
      const dataArr = []
      const dataArr2 = []
      this.tableData.forEach((item, index) => {
        if (item.fnCheck.seebutton === true) { item.seebutton = 1 } else { item.seebutton = 0 }
        if (item.fnCheck.editbutton === true) { item.editbutton = 1 } else { item.editbutton = 0 }
        if (item.indeterminate.seebutton === true) { item.seebutton = 2 }
        if (item.indeterminate.editbutton === true) { item.editbutton = 3 }
        if (item.childList.length > 0) {
          item.childList.forEach((item, index) => {
            if (item.fnCheck.seebutton === true) { item.seebutton = 1 } else { item.seebutton = 0 }
            if (item.fnCheck.editbutton === true) { item.editbutton = 1 } else { item.editbutton = 0 }
            dataArr2.push({ 'menuid': item.menu_id, 'seebutton': item.seebutton, 'editbutton': item.editbutton })
          })
        }
        dataArr.push({ 'menuid': item.menu_id, 'seebutton': item.seebutton, 'editbutton': item.editbutton })
      })
      dataArr.forEach((item, index) => {
        dataAll.push({ 'menuid': item.menuid, 'seebutton': item.seebutton, 'editbutton': item.editbutton })
      })
      dataArr2.forEach((item, index) => {
        dataAll.push({ 'menuid': item.menuid, 'seebutton': item.seebutton, 'editbutton': item.editbutton })
      })

      this.requestParam.common = { 'returnmap': '0' }
      this.requestParam.data = []
      this.requestParam.data[0] = { 'name': 'insertSpotList', 'resultmaps': { 'list': dataAll }}
      this.requestParam.data[0].children = []
      this.requestParam.data[0].children[0] = { 'name': 'insertRolemenu', 'type': 'e', 'parammaps': {
        pastureid: this.role.temp.pastureid,
        roleid: this.role.temp.id,
        menuid: '@insertSpotList.menuid',
        seebutton: '@insertSpotList.seebutton',
        editbutton: '@insertSpotList.editbutton'
      }}
      console.log(JSON.stringify(this.requestParam),'this.requestParam')
      ExecDataByConfig(this.requestParam).then(response => {
        console.log('权限菜单保存发送参数', this.requestParam)
        if (response.msg === 'fail') {
          this.$notify({ title: '保存失败', message: response.data, type: 'warning', duration: 2000 })
        } else {
          this.$notify({ title: '', message: '保存成功', type: 'success', duration: 2000 })
          this.role.dialogFormVisible = false
          this.getList()
        }
      })
    }

  }
}
</script>
<style lang="scss" scoped>
  .search{margin-top:10px;}
  
  .inside-base {
    position: relative;
  }

  .inside-base-main {
    width: 100%;
    background: #ffffff;
    // box-shadow: 0px 0px 10px 0px rgba(231,232,238,1);
    border-radius: 4px;
    margin-bottom: 30px;
  }

  // 中间内容
  .inside-base-cont {
    margin: 0 20px;
  }

  .role-cont {
    position: relative;
    font-size: 16px;
    color: #333333;
    line-height: 40px;
    > span {
      width: 90px;
      height: 40px;
      text-align: right;
      float: left;
      margin-right: 10px;
      margin-bottom: 20px;
    }
    > div {
      position: relative;
      width: 100%;
      float: left;
      margin-bottom: 20px;
      >>> .el-input__inner {
        width: 320px;
      }
    }
  }
  .check-page-all {
    position: absolute;
    top: 13px;
    left: 11px;
    z-index: 99;
  }

  /* element-ui css */
  .inside-base {
    >>> .el-input__inner {
      font-size: 16px;
      color: #333333;
    }
  }
</style>
