<template>
  <div class="custom-tree-container jfgz" style="height:400px; padding:0 40px;">
    <div class="block category_list_tree">


      <el-scrollbar wrap-class="column-wrapper scrollable-items-container" :native="false" style="height: 350px;">
      <el-tree
        :data="categoryTree"
        node-key="id"
        :expand-on-click-node="false"
        :render-content="renderContent">
      </el-tree>
      </el-scrollbar>



      <el-dialog
        title="新增分类"
        width="600px"
        :visible.sync="dialogCreateCategoryVisible"
        :close-on-click-modal="false"
        @close="onDismissCreateCategoryDialog" append-to-body>
        <el-form ref="newCategoryForm" :model="newCategoryForm" :rules="rules" @submit.native.prevent
                 style="padding-right:20px;">
          <el-form-item label="分类名称" prop="name" label-width="100px">
            <el-input v-model="newCategoryForm.name" auto-complete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogCreateCategoryVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitCreateCategoryForm('newCategoryForm')">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog
        title="编辑分类"
        width="600px"
        :visible.sync="dialogEditCategoryVisible"
        :close-on-click-modal="false"
        @close="onDismissEditCategoryDialog" append-to-body>
        <el-form ref="categoryForm" :model="categoryForm" :rules="rules" @submit.native.prevent style="padding-right:20px;">
          <el-form-item label="分类名称" prop="name" label-width="100px">
            <el-input v-model="categoryForm.name" auto-complete="off"></el-input>
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">

          <el-button @click="dialogEditCategoryVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitEditCategoryForm('categoryForm')">确 定</el-button>
        </div>
      </el-dialog>








    </div>
  </div>
</template>
<script>
  let id = 1000

export default {

    data() {
      const validateName = (rule, value, callback) => {
        var validValue = value ? value.replace(/\s/g, '').replace(/&nbsp;/ig, '') : value
        if (!validValue) {
          return callback(new Error('请填写积分分类名称'))
        } else {
          callback()
        }
      }
      return {
        profile: this.$store.getters.user_info,
        categoryTree: [],
        dialogCreateCategoryVisible: false,
        dialogEditCategoryVisible: false,
        categoryForm: {
          id: '',
          name: ''
        },
        filter: {
          keywords: '',
          category_id: []
        },
        parentCategoryTree: [],
        rules: {
          name: [
            { validator: validateName, trigger: 'blur' }
          ]
        },
        accessEnabled: {
          add: 0,
          delete: 0,
          excel_import: 0,
          edit: 0
        },
        newCategoryForm: {
          name: '',
          pid: []
        },
        rules: {

        }
      }
    },

    methods: {

      edit(row) {
        this.dialogEditCategoryVisible = true
        this.loadCurrentCategoryInfo(row.value)
      },

      loadCurrentCategoryInfo(categoryId) {
        var self = this
        this.$http('get','/integral.php/performance_work/task_category_info',{id: categoryId}).then(function(response) {
          if (response.status == 200) {
            var jsonData = response.data
            try {
              self.categoryForm.id = jsonData.data.id
              self.categoryForm.name = jsonData.data.name
              self.dialogEditCategoryVisible = true
            } catch (err) {
              console.log(err)
            }
          }
        })
      },

      submitEditCategoryForm: function(formName) {
        var form = this.$refs[formName]
        var self = this
        form.validate((valid) => {
          if (valid) {
            if (form) {
              self.submitEditCategoryForm2(form)
            }
          } else {
            return false
          }
        })
      },

      submitEditCategoryForm2: function() {
        const dataObj = this.categoryForm
        const formData = {}
        for (const item in dataObj) {
          if (item == 'pid') {
            const length = dataObj[item].length
            formData[item] = length == 0 ? 0 : dataObj[item][length - 1]
          } else {
            if (!dataObj[item]) {
              continue
            }
            formData[item] = dataObj[item]
          }
        }
        var self = this
        this.$http('post','/integral.php/performance_work/task_category_update',formData,'','',
          {transformRequest: [(data) => {
            const paramArray = new Array()
            for (const it in data) {
              paramArray.push(encodeURIComponent(it) + '=' + encodeURIComponent(data[it]))
            }
            return paramArray.join('&')
          }]},
          // headers: {
          //   'Content-Type': 'application/x-www-form-urlencoded'
          // }
        ).then(function(response) {
           const data = response.data
          self.$message({
            message: data.msg,
            type: data.code == 1000 ? 'success' : 'error'
          })
          if (data.code == 1000) {
            self.loadCategoryTree()
            self.dialogEditCategoryVisible = false
          }
        })
      },

      onDismissEditCategoryDialog: function() {
        var form = this.$refs['categoryForm']
        form.clearValidate()
        this.categoryForm = {
          id: '',
          name: '',
          pid: []
        }
      },

      addto: function(row) {
        this.newCategoryForm.pid.push(row.value)
        this.dialogCreateCategoryVisible = true

        // this.dialogCreateCategoryVisible=true
      },

      onDismissCreateCategoryDialog: function() {
        var form = this.$refs['newCategoryForm']
        form.clearValidate()
        this.newCategoryForm = {
          name: '',
          pid: []
        }
      },

      submitCreateCategoryForm: function(formName) {
        var form = this.$refs[formName]
        var self = this
        form.validate((valid) => {
          if (valid) {
            if (form) {
              self.sendCreateCategoryRequest()
            }
          } else {
            // console.log('验证未通过');
            return false
          }
        })
      },
      sendCreateCategoryRequest: function() {
        const dataObj = this.newCategoryForm
        const formData = {}
        for (const item in dataObj) {
          if (item == 'pid') {
            const length = dataObj[item].length
            formData[item] = length == 0 ? 0 : dataObj[item][length - 1]
          } else {
            if (!dataObj[item]) {
              continue
            }
            formData[item] = dataObj[item]
          }
        }
        formData['site_id'] = this.profile.site_id
        var self = this
        this.$http('post','/integral.php/performance_work/task_category_add',formData,'','',
          {transformRequest: [(data) => {
            const paramArray = new Array()
            for (const it in data) {
              paramArray.push(encodeURIComponent(it) + '=' + encodeURIComponent(data[it]))
            }
            return paramArray.join('&')
          }]},
          // headers: {
          //   'Content-Type': 'application/x-www-form-urlencoded'
          // }
        ).then(function(response) {
          let message = ''
            const data = response.data
            message = data.msg
          self.$message({
            message: message,
            type: data.code == 1000 ? 'success' : 'error'
          })
          if (data.code == 1000) {
            self.loadCategoryTree()
            self.dialogCreateCategoryVisible = false
          }
        })
      },
      loadCategoryTree: function() {
        var self = this
        this.$http('get','/integral.php/performance_work/task_category_tree').then(function(response) {
          if (response.status == 200) {
            const jsonData = response.data
            try {
              self.categoryTree = jsonData.data
            } catch (err) {
              console.log(err)
            }
          }
        })
      },

      delete(row) {
        const _row = row
        this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const params = {
            id: _row.value
          }
          var self = this
          this.$http('get','/integral.php/performance_work/task_category_del',params).then(function(response) {
              var data = response.data
            self.$message({
              message: data.msg,
              type: data.code == 1000 ? 'success' : 'error'
            })
            if (data.code == 1000) {
              self.loadCategoryTree()
              self.dialogEditCategoryVisible = false
            }
          })
        })
      },

      append(data) {
        const newChild = { id: id++, label: 'testtest', children: [] }
        if (!data.children) {
          this.$set(data, 'children', [])
        }
        data.children.push(newChild)
      },

      remove(node, data) {
        const parent = node.parent
        const children = parent.data.children || parent.data
        const index = children.findIndex(d => d.id === data.id)
        children.splice(index, 1)
      },

      renderContent(h, { node, data, store }) {
        return (
          <span class= 'custom-tree-node' ><span> {node.label}</span>
            <span>
              <el-button on-click={() => this.addto(data)}type = 'text' > 添加子分类 < /el-button>
              <el-button on-click={() => this.edit(data)}
                type = 'text' > 修改分类 </el-button>
              <el-button on-click = {() => this.delete(data)}
                type = 'text' > 删除分类 </el-button>
            </span>
          </span>)
      }
    },
    created() {
      this.loadCategoryTree()
    }
  }
</script>
<style>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }

  .jfgz .el-tree-node__content{ height:40px;}
  .category_list_tree .el-tree-node{
    border-bottom:1px solid #eee;
  }
</style>
