<template lang="pug">
    el-container(style="padding:0px;height:77.6vh;")
        el-aside( width="333px" style="z-index:1000;box-shadow: 2px 0 8px 0 rgba(0, 0, 0, 0.2);")
            el-card.treeCard(style='background:#f4f4f4;box-sizing:border-box;height:100%' :body-style="{ 'overflow-x': 'hidden', 'overflow-y': 'auto' }")
                div.title-bold(slot='header' style='padding-right:150px;margin-left:10px;z-index:1001;') 数据字典维护
                el-tree.dic_tree(style='background:#f4f4f4;' :data="data" node-key='id' :highlight-current='true' :props="defaultProps" :default-expand-all='true' @node-click="handleNodeClick" ref = "tree")
                    //- div(class="custom-tree-node" slot-scope="{ node, data }" )
                    span(class="custom-tree-node" style='width:90%;line-height: 18px;' slot-scope="{ node, data }")
                        div(v-if="data.children&&data.children.length>0" style='background:#f4f4f4;')
                          div.dic_tree_header( ) 数据字典项
                        span( v-else)
                            div.tree_point
                            span &nbsp; {{ node.label }}
        el-container()
            el-header(style='height:42px;line-height:42px;background: #f4f4f4;z-index:1001;border: 1px solid rgba(196, 196, 196, 1);')
                span.title-bold.title-left-color(v-if="listTitle") {{listTitle}}
                span.title-bold.title-left-color(v-else) 数据字典项
                el-popover( placement="bottom" width="150")
                        el-button( slot="reference" size='mini' type="primary" icon="el-icon-s-tools" style='float:right;transform:translateY(6px)')  筛选
                        el-checkbox-group( v-model="checkList")
                            el-col( :span="24")
                                el-checkbox( v-for="(item,index) in tableHeader" :label="item" :key="index" )
                                  span {{item.label}}
                el-button(v-if="isAuth('sys:dic:save')",type='primary' size='mini' icon='el-icon-plus',style='float:right;transform:translateY(6px);margin-right:20px;' :disabled="flag" @click='addOrUpdateHandle()') 新增
            el-main.box_main
                el-card.tableCard
                    drag-table( :data="dataList" :header="checkList" :isToLine='true' :option="tableOption"  @getDataList="getDataList" v-loading="dataListLoading"  :operationNum="4"  :isShowOperate="true")
                      //- -- 插槽
                      el-table-column(slot="fixed"  fixed  prop=""  label="序号" width="80"  header-align="center" align="center")
                          template( slot-scope="scope")
                            span   {{scope.$index+(pageIndex - 1) * pageSize + 1}}
                      //- 操作项
                      template( slot-scope="scope" )
                          el-button(type="text"  v-if="isAuth('sys:dic:update')"  @click="addOrUpdateHandle(scope.row)") 编辑
                          el-button(type="text"  v-if="isAuth('sys:dic:delete')"  @click="deleteHandle(scope.row)") 删除
            el-footer.box_footer
                el-pagination(@size-change='sizeChangeHandle' background  @current-change='currentChangeHandle' :current-page='pageIndex', :page-sizes='[10, 20, 50, 100]', :page-size='pageSize', :total='totalPage', layout='total, sizes, prev, pager, next, jumper')
                el-dialog(width="40%",:append-to-body='true' :visible.sync='visible' :modal-append-to-body='false' @close="closeForm('ruleForm')")
                    div.title-bold(slot='title') {{!ruleForm.id ? '新增字典项': '编辑字典项'}}
                    el-form(:model="ruleForm", :inline="false" :rules="rules" ref="ruleForm", label-width="100px", @submit.native.prevent)
                        el-card(shadow="never")
                            el-row(:span='24')
                                el-col(:span='24')
                                    el-form-item(label="上级字典项ID:" prop="parentId" v-if='false')
                                        el-input(v-model='ruleForm.parentId' placeholder=""  clearable v-if='false')
                                el-col(:span='24')
                                    el-form-item(label="字典项名称:" prop="name")
                                        el-input(v-model='ruleForm.name' placeholder="请输入字典项名称"  clearable )
                                el-col(:span='12')
                                    el-form-item(label="字典项值:" prop="value")
                                        el-input(v-model='ruleForm.value' placeholder="请输字典项值"  clearable )
                                el-col(:span='12')
                                    el-form-item(label="排序值:" prop="sortValue")
                                        el-input(v-model.number='ruleForm.sortValue' placeholder="请输入字典项排序" clearable)

                    div(slot="footer" style=' text-align: center;')
                        el-button(type='primary' size='medium' @click="cancel") 取 消
                        el-button(type='primary' size='medium' @click="addsave" v-prevent-re-click) 保 存
</template>

<script>
import dragTable from '../../components/tab'
export default {
  data() {
    let validateNumber = (rule, value, callback) => {
      if (value < 0) {
        callback(new Error('只能输入正整数'))
      } else if (value > 10000) {
        callback(new Error('排序值超出范围'))
      } else {
        callback()
      }
    }
    return {
      checkList: [], //筛选数据
      tableHeader: [
        { label: '字典项名称', prop: 'name' },
        { label: '字典项值', prop: 'value' },
        { label: '排序值', prop: 'sortValue' },
      ],
      tableOption: {
        border: false, //是否边框
        maxHeight: 500, //高度
      },
      listTitle: '',
      flag: true,
      clickFlag: false,
      word: '', //查询
      dataList: [], //列表
      dataListLoading: false,
      logTimeout: null,
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      stationId: localStorage.getItem('stationId'),
      sort: 'sort_value',
      order: 'asc',
      addOrUpdateVisible: false,
      ruleForm: {},
      visible: false,
      dicInfo: {},
      dicId: '',
      rules: {
        //添加规则
        name: [
          { required: true, message: '字典项名称不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 30,
            message: '长度在 1 到 30 个字符',
            trigger: 'blur',
          },
        ],
        value: [
          {
            min: 1,
            max: 20,
            message: '长度在 1 到 20 个字符',
            trigger: 'blur',
          },
        ],
        sortValue: [
          { required: true, message: '排序值不能为空' },
          // { min: 1, max: 10, message: '排序值超出范围', trigger: 'blur' },
          { type: 'number', message: '排序值必须为数字' },
          { validator: validateNumber, trigger: ['blur', 'change'] },
          // { pattern: /^[1-9]\d*$/, message: '只能输入正整数', trigger: 'change' }
        ],
      },
      data: [],
      defaultProps: {
        children: 'children',
        label: 'name',
        id: 'id',
      },
    }
  },
  components: {
    dragTable,
  },
  watch: {
    totalPage() {
      //注意这个函数的名字必须和你监听data中的属性的名字一样，这样才能当你data中的属性发生变化时，触发这个函数
      let pages = Math.ceil(this.totalPage / this.pageSize) //新数据总页数
      //总页数小于当前页数则重新加载列表数据
      if (pages < this.pageIndex) {
        this.pageIndex = pages || 1
        this.getDataList() //获取表格数据的方法
      }
    },
  },
  created() {
    this.getList()
    this.dicInfo = this.data[0]
    this.checkList = [...this.tableHeader]
  },
  methods: {
    getList() {
      this.$http({
        url: this.$http.adornUrl('/sysDictionary/dictionaryAllList'),
        method: 'GET',
        params: {
          stationId: this.stationId,
        },
      }).then((data) => {
        if (data) {
          this.data = data.list
        }
      })
    },
    sortChange(column) {
      if (column.order === 'descending') {
        this.order = 'desc'
      } else {
        this.order = 'asc'
      }
      if (column.column.columnKey) {
        this.sort = column.column.columnKey
      } else {
        this.sort = column.prop
      }
      this.getDataList()
    },
    handleNodeClick(data) {
      console.log(data, '--------')
      this.listTitle = data.name
      if (data.parentId != '-1') {
        this.flag = false
      } else {
        this.flag = true
      }
      this.ruleForm.parentId = data.id
      this.dicId = data.id
      this.dicInfo = data
      this.getDataList()
    },
    getDataList(sort, order) {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/sysDictionary/dictionaryList'),
        method: 'post',
        data: {
          page: this.pageIndex,
          rows: this.pageSize,
          parentId: this.dicId,
          sort: sort || 'sort_value',
          order,
          stationId: this.stationId,
        },
      }).then((data) => {
        if (data) {
          this.dataList = data.page.rows
          this.totalPage = data.page.total
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    // 删除
    deleteHandle(row) {
      this.$confirm(`确认删除该字典项?`, '删除字典项', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false,
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/sysDictionary/deleteById'),
          method: 'post',
          data: row,
        }).then((res) => {
          if (res && res.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              },
            })
          } else {
            this.$message.error(res.msg)
          }
        })
      })
    },
    //添加或修改事件
    addOrUpdateHandle(row, flagType) {
      this.clickFlag = false
      this.visible = true
      if (row) {
        this.ruleForm = JSON.parse(JSON.stringify(row))
      } else {
        this.ruleForm = {}
        if (this.dicInfo) {
          this.ruleForm.parentId = this.dicInfo.id
          this.ruleForm.stationId = this.stationId
        }
      }
    },
    // 提交
    addsave() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.clickFlag = true
          this.ruleForm.stationId = this.stationId
          this.$http({
            url: this.$http.adornUrl(
              `/sysDictionary/${!this.ruleForm.id ? 'save' : 'update'}`
            ),
            method: 'post',
            data: this.ruleForm,
          }).then((data) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.getDataList()
                  //如果左边菜单栏点击的是最上层则不刷新
                  if (
                    this.ruleForm.parentId ===
                    '6070da6f5d9b40121359d993f9791b09'
                  ) {
                    this.getList()
                  }
                },
              })
            } else {
              this.clickFlag = false
              this.$message.error(data.msg)
            }
          })
        }
      })
    },
    closeForm(formRule) {
      this.ruleForm = {}
      this.$refs[formRule].resetFields()
      this.visible = false
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },
    //取消
    cancel() {
      this.$confirm(
        '确认取消?',
        `${!this.ruleForm.id ? '新增字典项' : '编辑字典项'}`,
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          this.closeForm('ruleForm')
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消退出',
          })
        })
    },
  },
}
</script>
<style lang="scss" scoped>
.dic_tree_header {
  width: 330px;
  height: 30px;
  line-height: 30px;
  text-indent: 20px;
  // background: white !important;
  background: white;
  border-radius: 15px 0 0 15px;
  box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.05);
  font-size: 14px;
  font-family: Microsoft YaHei;
  font-weight: bold;
  color: rgba(0, 0, 0, 1);
}

.tree_point {
  width: 6px;
  height: 6px;
  display: inline-block;
  transform: translateY(-3px);
  background: rgba(23, 41, 71, 1);
  opacity: 0.3;
  border-radius: 50%;
  margin-left: 7px;
}

.dic_tree /deep/ .el-tree-node__children {
  font-size: 14px;
  font-family: Microsoft YaHei;
  font-weight: bold;
  color: rgba(0, 0, 0, 1);
}

.dic_tree /deep/ .el-tree-node__expand-icon.expanded {
  position: absolute !important;
  left: 100px !important;
}

.dic_tree /deep/ .el-tree-node__content > .el-tree-node__expand-icon {
  position: absolute !important;
  left: 100px !important;
}
</style>
<style lang="scss">
.el-tree--highlight-current
  .el-tree-node.is-current
  > .el-tree-node__content
  .custom-tree-node {
  background-color: #33b0f6 !important;
  color: aliceblue;
}
.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background-color: transparent;
}
</style>
