<template>
  <div class="app-container">
    <div class="search">
      <el-input v-model="tab2.table.getdataListParm.parammaps.pastureName" placeholder="牧场名称" style="width: 180px;" class="filter-item" clearable />
      <el-select v-model="tab2.table.getdataListParm.parammaps.enable" placeholder="状态" class="filter-item" style="width: 120px;" clearable>
        <el-option v-for="item in stateList" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-select v-model="tab2.table.getdataListParm.parammaps.statue" placeholder="是否归属集团" class="filter-item" style="width: 120px;" clearable>
        <el-option v-for="item in isBelongGroupList" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-button class="successBorder" @click="form_search">{{$t('common.query')}}</el-button>
      <el-button class="successBorder" @click="handleRefresh">{{$t('common.reset')}}</el-button>
    </div>
    <div class="operation">
      <el-button v-if="isRoleEdit" class="success" icon="el-icon-plus" @click="handleCreate">新增</el-button>
    </div>
    <div class="table">
      <el-table
        :key="tab2.table.tableKey"
        v-loading="tab2.table.listLoading"
        element-loading-text="给我一点时间"
        :data="tab2.table.list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        :row-style="rowStyle"
        :cell-style="cellStyle"
        class="elTable table-fixed"
      >
        <el-table-column label="序号" align="center" type="index" width="50px">
          <template slot-scope="scope">
            <span>{{ scope.$index + (tab2.table.pageNum-1) * tab2.table.pageSize + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="牧场ID" min-width="130px" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.NoEdit">{{ scope.row.pasturecode }}</span>
            <el-input v-if="scope.row.Edit" v-model="scope.row.pasturecode" 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.pasturename }}</span>
            <el-input v-if="scope.row.Edit" v-model="scope.row.pasturename" 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.user }}</span>
            <el-input v-if="scope.row.Edit" v-model="scope.row.user" 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="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="权限归属" min-width="130px" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.NoEdit">{{ scope.row.groupsname }}</span>
            <el-select v-if="scope.row.Edit" v-model="scope.row.groupsid" :clearable="false" filterable placeholder="权限归属" class="filter-item" style="width: 120px;" clearable>
              <el-option v-for="item in belongGroupList" :key="item.id" :label="item.groupsname" :value="item.id" />
            </el-select>
          </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.note }}</span>
            <el-input v-if="scope.row.Edit" v-model="scope.row.note" type="textarea" :autosize="{ minRows: 1.3, maxRows: 4}" maxlength="32" style="width:95%;padding:10px 0;" />
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{row}">
            <!-- 页面权限 -->
            <a v-if="row.NoEdit && isRoleEdit" class="correcting" @click="handlePageConfiguration(row)">页面配置</a>

            <!-- 新增 -->
            <el-button v-if="row.isCreate && isRoleEdit" class="miniSuccess" icon="el-icon-folder-checked" :disabled="isokDisable" @click="createData(row)" />
            <span v-if="row.isCreate && isRoleEdit" class="centerSpan">|</span>
            <el-button v-if="row.isCreate && isRoleEdit" class="minCancel" icon="el-icon-close" @click="createCancel(row)" />
            <!-- 编辑 -->
            <span v-if="row.isUpdate && isRoleEdit" class="centerSpan">|</span>
            <el-button v-if="row.isUpdate && isRoleEdit" class="miniSuccess" icon="el-icon-edit-outline" @click="handleUpdate(row)" />
            <!-- 编辑保存 -->
            <el-button v-if="row.isUpdateSave && isRoleEdit" class="miniSuccess" icon="el-icon-folder-checked" :disabled="isokDisable" @click="updateData(row)" />
            <span v-if="row.isUpdateSave && isRoleEdit" class="centerSpan">|</span>
            <el-button v-if="row.isUpdateSave && isRoleEdit" class="minCancel" icon="el-icon-close" @click="updateCancel(row)" />
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="tab2.table.total>=0" :total="tab2.table.total" :page.sync="tab2.table.getdataListParm.offset" :limit.sync="tab2.table.getdataListParm.pagecount" @pagination="getList" />
    </div>

    <!-- 页面配置 -->
    <el-dialog :title="textMap[tab1.pageConfiguration.dialogStatus]" :visible.sync="tab1.pageConfiguration.dialogFormVisible" :close-on-click-modal="false" width="25%">
      <div style="height: 400px;overflow-y: auto;">
        <el-tree
          ref="tree"
          v-loading="tab1.pageConfiguration.listLoading"
          show-checkbox
          node-key="id"
          :default-expand-all="true"
          :data="tab1.pageConfiguration.data"
          :props="tab1.pageConfiguration.defaultProps"
          :default-checked-keys="tab1.pageConfiguration.defaultCheckedKeys"
          @check-change="handelCheckChange"
        />
      </div>
      <div slot="footer" class="dialog-footer" style="bottom:10px">
        <el-button class="cancelClose" @click="tab1.pageConfiguration.dialogFormVisible = false;getList(); ">取消</el-button>
        <el-button class="save" :disabled="isokDisable" @click="pageConfigurationData()">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { GetDataByName, GetDataByNames, failproccess, transData, ExecDataByConfig, checkButtons } from '@/api/common'
import Cookies from 'js-cookie'
import Pagination from '@/components/Pagination'
export default {
  name: 'OperationManagement',
  components: { Pagination },
  data() {
    return {
      requestParams: [
        { name: 'getGroupsAllList', offset: 0, pagecount: 0, parammaps: {}}
      ],
      isRoleEdit: [],
      stateList: [{ id: 1, name: '启用' }, { id: 0, name: '禁止' }], // 状态
      isBelongGroupList: [{ id: 1, name: '是' }, { id: 0, name: '否' }], // 是否归属集团
      belongGroupList: [], // 权限归属
      tab1: {
        // 页面配置
        pageConfiguration: {
          dialogFormVisible: false,
          dialogStatus: '',
          temp: {},
          listLoading: true,
          getdataListParm: {
            name: 'getMenuandButtonlistMC'
          },
          parentType: [],
          defaultProps: {
            children: 'children',
            label: 'name'
          },
          defaultCheckedKeys: [],
          arrList: []
        }
      },
      tab2: {
        table: {
          getdataListParm: {
            name: 'groupsrelationlistMCAll',
            page: 1,
            offset: 1,
            pagecount: 10,
            returntype: 'Map',
            parammaps: {
              pastureName: '',
              enable: '',
              statue: ''
            }
          },
          tableKey: 0,
          list: [],
          total: 0,
          listLoading: true,
          temp: {}
        },
        // 页面配置
        pageConfiguration: {
          temp: {}
        }
      },
      requestParam: {},
      rules: {},
      isokDisable: false,
      textMap: {
        pageConfiguration: '页面配置',
        relation: '关联'
      },
      rowStyle: { maxHeight: 30 + 'px', height: 30 + 'px' },
      cellStyle: { padding: 0 + 'px' }

    }
  },

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

  methods: {
    getButtons() {
      const Edit = 'Role'
      const isRoleEdit = checkButtons(JSON.parse(sessionStorage.getItem('buttons')), Edit)
      this.isRoleEdit = isRoleEdit
    },
    getDownList() {
      GetDataByNames(this.requestParams).then(response => {
        this.belongGroupList = response.data.getGroupsAllList.list
      })
    },
    handleEnableChange() {
      console.log('点击了是否启用')
    },
    form_search() {
      console.log('点击了查询')
      this.tab2.table.getdataListParm.offset = 1
      this.getList()
    },
    handleRefresh() {
      console.log('点击了重置')
      this.tab2.table.getdataListParm.parammaps.pastureName = ''
      this.tab2.table.getdataListParm.parammaps.statue = ''
      this.tab2.table.getdataListParm.parammaps.enable = ''
      this.tab2.table.getdataListParm.offset = 1
      this.getList()
    },

    createCancel(row) {
      console.log('点击了牧场新增取消')
      for (let i = 0; i < this.tab2.table.list.length; i++) {
        if (row.myId === this.tab2.table.list[i].myId) {
          var listIndex2 = this.tab2.table.list.indexOf(this.tab2.table.list[i])
        }
        if (listIndex2 > -1) {
          this.tab2.table.list.splice(listIndex2, 1)
          return
        }
      }
    },
    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()
    },

    getPageConfigurationList() {
      this.tab1.pageConfiguration.getdataListParm.parammaps = {}
      this.tab1.pageConfiguration.getdataListParm.parammaps.pastureid = this.tab2.pageConfiguration.temp.pastureid
      this.tab1.pageConfiguration.getdataListParm.parammaps.id = this.tab1.pageConfiguration.temp.id
      this.tab1.pageConfiguration.listLoading = true
      this.tab1.pageConfiguration.defaultCheckedKeys = []
      GetDataByName(this.tab1.pageConfiguration.getdataListParm).then(response => {
        if (response.data.list !== null) {
          for (let i = 0; i < response.data.list.length; i++) {
            if (parseFloat(response.data.list[i].seebutton) > 0 && response.data.list[i].pid !== -1) {
              this.tab1.pageConfiguration.defaultCheckedKeys.push(String(response.data.list[i].menu_id))
            }
            if (parseFloat(response.data.list[i].seebutton) > 0) {
              this.tab1.pageConfiguration.arrList.push(String(response.data.list[i].menu_id))
            }
          }
          this.tab1.pageConfiguration.data = transData(response.data.list, 'id', 'pid', 'children')
          console.log(this.tab1.pageConfiguration.data)
          console.log(response.data.list)
        } else {
          this.tab1.pageConfiguration.data = []
        }
        setTimeout(() => {
          this.tab1.pageConfiguration.listLoading = false
        }, 1000)
      })
    },
    handelCheckChange(id) {
      // this.tab1.pageConfiguration.defaultCheckedKeys = this.$refs.tree.getCheckedKeys()
      var checkedKeys = this.$refs.tree.getCheckedKeys()
      var options = checkedKeys.map((item) => {
        var node = this.$refs.tree.getNode(item) // 所有被选中的节点对应的node
        const tmpMap = {}
        console.log(node, 'node')
        tmpMap.pid = node.parent.key
        tmpMap.value = node.key
        return tmpMap
      })
      var selectedData = options.map((item) => {
        console.log(item)
        return item
      })
      console.log(selectedData)
      var arr = []
      for (let i = 0; i < selectedData.length; i++) {
        if (selectedData[i].pid !== undefined) {
          arr.push(selectedData[i].pid, selectedData[i].value)
        } else {
          arr.push(selectedData[i].value)
        }
      }
      this.tab1.pageConfiguration.arrList = this.unique(arr)
      // this.tab1.pageConfiguration.defaultCheckedKeys = this.unique(arr)
    },
    unique(arr) {
      return Array.from(new Set(arr))
    },
    handlePageConfiguration(row) {
      this.tab2.pageConfiguration.temp = Object.assign({}, row)
      console.log('点击了行内页面配置')
      this.tab1.pageConfiguration.dialogStatus = 'pageConfiguration'
      this.tab1.pageConfiguration.dialogFormVisible = true
      this.tab1.pageConfiguration.defaultCheckedKeys = []
      this.getPageConfigurationList()
    },
    pageConfigurationData() {
      console.log('牧场页面配置保存')
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.requestParam = {}
      this.requestParam.common = { 'returnmap': '0' }
      this.requestParam.data = []
      this.requestParam.data[0] = { 'name': 'deletemenuPastureMC', 'type': 'e', 'parammaps': {
        'id': this.tab2.pageConfiguration.temp.id
      }}
      var list = []
      for (let i = 0; i < this.tab1.pageConfiguration.arrList.length; i++) {
        list.push({ 'id': this.tab1.pageConfiguration.arrList[i] })
      }
      this.requestParam.data[1] = { 'name': 'insertSpotList', 'resultmaps': { 'list': list }}
      this.requestParam.data[1].children = []
      this.requestParam.data[1].children[0] = { 'name': 'insertRolepastureMC', 'type': 'e', 'parammaps': {
        menuid: '@insertSpotList.id',
        id: this.tab2.pageConfiguration.temp.id
      }}
      ExecDataByConfig(this.requestParam).then(response => {
        console.log('页面配置保存发送参数', this.requestParam)
        if (response.msg !== 'fail') {
          this.tab1.pageConfiguration.dialogFormVisible = false
          this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
          this.getList()
        } else {
          this.$notify({ title: '保存失败', message: response.data, type: 'warning', duration: 2000 })
        }
      })
    },
    getList() {
      this.tab2.table.listLoading = true
      GetDataByName(this.tab2.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.tab2.table.list = response.data.list
          this.tab2.table.pageNum = response.data.pageNum
          this.tab2.table.pageSize = response.data.pageSize
          this.tab2.table.total = response.data.total
        } else {
          this.tab2.table.list = []
        }
        setTimeout(() => {
          this.tab2.table.listLoading = false
        }, 100)
      })
    },
    handleCreate() {
      console.log('点击了牧场新增')
      // 编辑true/不可编辑false
      // 新增操true,编辑false，编辑保存false
      for (let i = 0; i < this.tab2.table.list.length; i++) {
        if (this.tab2.table.list[i].Edit == true) {
          this.$message({ type: 'error', message: '当前内容未保存，请点击取消或保存继续进行操作', duration: 2000 })
          return false
        }
      }
      this.tab2.table.list.unshift({ 'myId': (new Date()).valueOf(), 'Edit': true, 'NoEdit': false, 'isCreate': true, 'isUpdate': false, 'isUpdateSave': false, 'enable': 1, 'pasturecode': '', 'phone': '', 'contact': '', 'address': '', 'pasturename': '', 'group': '', 'groupsid': '', 'pasturecode': '' })
    },

    createData(row) {
      console.log('点击了牧场新增保存', row)
      // 检验牧场ID/牧场名称是否为空
      if (row.pasturecode == '' && row.pasturename == '' && row.user == '') {
        this.$message({ type: 'error', message: '牧场ID/牧场名称/管理员用户名不能为空', duration: 2000 })
        return false
      } else if (row.pasturename == '' && row.user == '') {
        this.$message({ type: 'error', message: '牧场名称/管理员用户名不能为空', duration: 2000 })
        return false
      } else if (row.pasturecode == '') {
        this.$message({ type: 'error', message: '牧场ID不能为空', duration: 2000 })
        return false
      } else if (row.pasturename == '') {
        this.$message({ type: 'error', message: '牧场名称不能为空', duration: 2000 })
        return false
      } else if (row.user == '') {
        this.$message({ type: 'error', message: '管理员用户名不能为空', duration: 2000 })
        return false
      }
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.requestParam = {}
      this.requestParam.common = { 'returnmap': '0' }
      this.requestParam.data = []
      this.requestParam.data[0] = { 'name': 'checkuser', 'type': 'v', 'parammaps': {
        'user': row.user
      }}
      this.requestParam.data[1] = { 'name': 'insertPasture', 'type': 'e', 'parammaps': {
        'pasturecode': row.pasturecode,
        'pasturename': row.pasturename,
        'groupsid': row.groupsid,
        'user': row.user,
        'note': row.note,
        'enable': row.enable,
        'emp': row.emp,
        'phone': row.phone,
        'address': row.address
      }}
      this.requestParam.data[2] = { 'name': 'createNewPasture', 'type': 'e', 'parammaps': {
        'user': row.user,
        'pastureid': '@insertPasture.LastInsertId',
        'type': '0'
      }}
      ExecDataByConfig(this.requestParam).then(response => {
        console.log('新增保存发送参数', this.requestParam)
        if (response.msg !== 'fail') {
          this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
          this.getList()
        } else {
          const tId = new RegExp("column 'id'")
          if (tId.test(response.data)) {
            this.$notify({ title: '保存失败', message: '集团已存在，不可重复生成', type: 'warning', duration: 2000 })
          } else {
            this.$notify({ title: '保存失败', message: response.data, type: 'warning', duration: 2000 })
          }
        }
      })
    },
    handleUpdate(row) {
      console.log('点击了牧场编辑', row)
      for (let i = 0; i < this.tab2.table.list.length; i++) {
        if (this.tab2.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
      if (row.groupsid !== undefined) {
        row.groupsid = String(row.groupsid)
      }
    },
    updateData(row) {
      console.log('点击了牧场编辑保存')
      // 检验牧场ID/牧场名称是否为空
      if (row.pasturecode == '' && row.pasturename == '' && row.user == '') {
        this.$message({ type: 'error', message: '牧场ID/牧场名称/管理员用户名不能为空', duration: 2000 })
        return false
      } else if (row.pasturename == '' && row.user == '') {
        this.$message({ type: 'error', message: '牧场名称/管理员用户名不能为空', duration: 2000 })
        return false
      } else if (row.pasturecode == '') {
        this.$message({ type: 'error', message: '牧场ID不能为空', duration: 2000 })
        return false
      } else if (row.pasturename == '') {
        this.$message({ type: 'error', message: '牧场名称不能为空', duration: 2000 })
        return false
      } else if (row.user == '') {
        this.$message({ type: 'error', message: '管理员用户名不能为空', duration: 2000 })
        return false
      }
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.requestParam = {}
      this.requestParam.common = { 'returnmap': '0' }
      this.requestParam.data = []
      this.requestParam.data[0] = { 'name': 'updatePasture', 'type': 'e', 'parammaps': {
        'id': row.id,
        'pasturecode': row.pasturecode,
        'pasturename': row.pasturename,
        'groupsid': row.groupsid,
        'user': row.user,
        'note': row.note,
        'enable': row.enable,
        'emp': row.emp,
        'phone': row.phone,
        'address': row.address
      }}
      this.requestParam.data[1] = { 'name': 'updateUserName', 'type': 'e', 'parammaps': {
        'id': row.id,
        'userold': row.userold,
        'user': row.user
      }}
      ExecDataByConfig(this.requestParam).then(response => {
        console.log('编辑保存发送参数', this.requestParam)
        if (response.msg !== 'fail') {
          this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
          this.getList()
        } else {
          const tId = new RegExp("column 'id'")
          if (tId.test(response.data)) {
            this.$notify({ title: '保存失败', message: '集团已存在，不可重复生成', type: 'warning', duration: 2000 })
          } else {
            this.$notify({ title: '保存失败', message: response.data, type: 'warning', duration: 2000 })
          }
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  
  .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>
