<template>
  <div v-if="pageLoading"
       class="resi-container">
    <el-card class="resi-card-table">
      <div class="resi-row-btn">
        <el-button class="diy-button--add"
                   size="small"
                   @click="handleAdd('1', 'add')">添加积分类别</el-button>
      </div>

      <el-table :data="tableData"
                row-key="id"
                v-loading="tableLoading"
                border
                :height="tableHeight"
                style="width: 100%"
                class="resi-table">
        <el-table-column v-for="item in tableHeader"
                         :key="item.columnName"
                         :prop="item.columnName"
                         :label="item.label"
                         :align="item.align">
        </el-table-column>
        <el-table-column label="操作"
                         align="center"
                         width="200">
          <template slot-scope="scope">
            <el-button v-if="scope.row.pid == 0"
                       @click="handleAdd('2', 'add', scope.row.id)"
                       type="text"
                       size="small"
                       class="btn-color-1j">添加二级分类</el-button>
            <el-button v-if="scope.row.pid != 0 && scope.row.categoryName"
                       @click="handleAdd('3', 'add', scope.row.id, scope.row.pid, scope.row.categoryName)"
                       type="text"
                       size="small"
                       class="btn-color-2j">添加积分规则</el-button>
            <el-button v-if="scope.row.pid != 0"
                       @click="handleEdit(scope.row, 'edit', scope.row.categoryName ? '4' :  scope.row.ruleName ? '5' : '1')"
                       type="text"
                       size="small"
                       class="btn-color-edit">修改</el-button>
            <el-button v-if="scope.row.pid != 0"
                       @click="handleDel(scope.row)"
                       type="text"
                       size="small"
                       class="btn-color-del">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog title="添加积分分类"
               :visible.sync="dialogVisible"
               width="40%"
               append-to-body
               :close-on-click-modal="false"
               :before-close="handlerCancle">
      <el-form label-width="100px"
               :model="form"
               :rules="rules"
               ref="ruleForm">
        <el-form-item label="分类"
                      prop="pid">
          <el-select class="item_width_1"
                      v-model="form.pid"
                      placeholder="请选择"
                      size="small"
                      style="width: 180px;"
                      :disabled="addLevel == '2' || addLevel == '3' || addLevel == '4' ? true : false"
                      clearable>
            <el-option v-for="item in typeList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
            </el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="类别名称"
                      prop="categoryName">
          <el-input :disabled="addLevel == '3' || addLevel == '5' ? true : false" v-model="form.categoryName"
                    size="small"
                    style="width: 180px;"></el-input>
        </el-form-item>
        <el-form-item v-if="addLevel == '3'  || addLevel == '5'" label="规则名称"
                      prop="ruleName">
          <el-input v-model="form.ruleName"
                    size="small"
                    style="width: 180px;"></el-input>
        </el-form-item>
        <el-form-item v-if="addLevel == '3' || addLevel == '5'"
                      label="加减分值"
                      prop="pointValue">
          <el-input-number v-model="form.pointValue"
                           size="small"
                           label="描述文字"></el-input-number>
          (减分请输入负数)
        </el-form-item>
        <el-form-item v-if="addLevel == '3' || addLevel == '5'"
                      label="居民端积分申请"
                      prop="applyFlag"
                      label-width="200px">
            <el-radio v-model="form.applyFlag" label="0">允许申请</el-radio>
            <el-radio v-model="form.applyFlag" label="1">不允许申请</el-radio>
        </el-form-item>
      </el-form>
      <div class="resi-btns">
        <el-button size="small"
                   @click="handlerCancle">取消</el-button>
        <el-button type="primary"
                   size="small"
                   :loading="btnLoading"
                   @click="handleSUbmit">提交</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  data () {
    return {
      tableLoading: false,
      btnLoading: false,
      pageLoading: false,
      dialogVisible: false,
      tableData: [],
      sHeight: 0,
      addLevel: '1',
      addType: 'add',
      tableHeader: [
        {
          label: '积分类别',
          align: 'left',
          columnName: 'categoryName'
        }, {
          label: '积分规则',
          columnName: 'ruleName',
          align: 'center'
        }
      ],
      typeList: [], //类别
      form: { // 新增修改相关
        categoryName: '', // 类别名称
        pid: '', // 上级类别ID
        newPid: '', // 添加积分规则用到的pid
        ruleName: '', // 积分规则名称
        pointValue: '', // 加减积分
        applyFlag: '0' // 允许申请0，不允许申请1
      },
      rules: {
        pid: [{ required: true, message: '请选择分类', trigger: 'blur' }],
        categoryName: [{ required: true, message: '类别名称不能为空', trigger: 'blur' }],
        ruleName: [{ required: true, message: '规则名称不能为空', trigger: 'blur' }],
        pointValue: [{ required: true, message: '加减分值不能为空', trigger: 'blur' }],
        applyFlag: [{ required: true, message: '请选择积分申请', trigger: 'blur' }]
      }
    }
  },
  computed: {
    tableHeight () {
      const h = this.clientHeight - this.sHeight + this.iframeHeigh
      const _h = this.clientHeight - this.sHeight
      return this.$store.state.inIframe ? h : _h
    },

    ...mapGetters(['clientHeight', 'iframeHeight'])
  },
  async created () {
    this.getTableData()
    this.pageLoading = true
  },
  mounted () {
    this.$nextTick(() => {
      this.sHeight = 210
    })
  },
  methods: {
    // 列表添加相关
    handleAdd (type, addType, id, pid, categoryName) {
      this.addLevel = type
      this.addType = addType
      if (type == '2') {
        this.form.pid = id
      }

      if  (type == '3') {
        this.form.pid = pid
        this.form.newPid = id
        this.form.categoryName = categoryName
      }
      this.dialogVisible = true
    },
    handlerCancle () {
      this.dialogVisible = false
    },
    // 列表修改点击事件
    async handleEdit (row, addType, level) {
      let url = ''
      if (level === '4') {
        url = `/point/additiverule/categorydetail/${row.id}`
      } else if(level === '5') {
        url = `/point/additiverule/ruledetail/${row.id}`
      }
      this.addLevel = level
      this.addType = addType
      this.dialogVisible = true
      await this.$http.post(url).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        } else {
          this.form = { ...res.data }
        }
      })
    },
    // 添加积分类别
    async addLevelFirst () {
      const _form = {
        pid: this.form.pid, // 上级类别ID
        categoryName: this.form.categoryName // 类别名称
      }
      await this.$http
        .post('/point/additiverule/addcategory', _form)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            this.dialogVisible = false
            this.getTableData()
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
      this.btnLoading = false
    },
    // 添加积分规则
    async addLevelChild () {
      const _form = {
        ruleName: this.form.ruleName,
        pid: this.form.newPid,
        pointValue: this.form.pointValue,
        applyFlag: this.form.applyFlag
      }
      await this.$http
        .post('/point/additiverule/addrule', _form)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            this.dialogVisible = false
            this.getTableData()
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
      this.btnLoading = false
    },
    // 提交按钮
    handleSUbmit () {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.btnLoading = true
          if (this.addType == 'add') {
            if (this.addLevel == '1' || this.addLevel == '2') this.addLevelFirst()
            else this.addLevelChild()
          } else this.editCate()

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 修改提交  ---------------这里还没做
    async editCate () {
      const _form = {
        categoryName: this.form.categoryName,
        level: this.form.level,
        pointValue: this.form.pointValue
      }
      await this.$http
        .post('/heart/icresidemanddict/update', _form)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            this.dialogVisible = false
            this.getTableData()
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
      this.btnLoading = false
    },
    // 删除
    handleDel (row) {
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let params = [row.id]
      console.log('row1', row)
        this.$http.post('/point/additiverule/delete', params)
          .then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            } else {
              console.log('row3', row)
              this.$message.success('删除成功')
              this.getTableData()
            }
          })
          .catch((err) => {
            console.log('row4', err)
            return this.$message.error('网络错误')
          })
      }).catch(err => {
          console.log(err)
      });
    },
    // 查询积分类别规则列表
    async getTableData () {
      this.tableLoading = true
      let params = {}
      await this.$http.post('/point/additiverule/list4tree', params).then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            } else {
              let list = []
              if (res.data.length > 0) {
                res.data.forEach(element => { // 一级循环
                  if (element.pid === '0') {
                    element.children = []
                    list.push(element)
                    this.typeList.push({ //类别
                      value: element.id,
                      label: element.categoryName
                    })
                  }
                });
              }
              if (list.length > 0) { // 二级循环
                res.data.forEach(element => {
                  if (element.pid) {
                    list.forEach((item, index) => {
                      if (element.pid === item.id) {
                        element.children = []
                        list[index].children.push(element)
                      }
                    });
                  }
                });
              }
              if (list.length > 0) {  // 三级循环
                res.data.forEach(element => {
                  if (element.pid) {
                    list.forEach((item, index) => {
                      if (item.children.length > 0 ) {
                        item.children.forEach((itemC, indexC) => {
                           if (element.pid === itemC.id) {
                              list[index].children[indexC].children.push(element)
                           }
                        });
                      }
                    });
                  }
                });
              }
              this.tableData = list.map((item, index) => {
                return {
                  ...item,
                  index: index + 1,
                  children: item.children.map(n => {
                    return {
                      ...n
                    }
                  })
                }
              })
            }
          })
        this.tableLoading = false
    }
  }
}
</script>

<style lang="scss" scoped>
.resi-container .resi-card-table {
  ::v-deep .el-table {
    th {
      color: #fff;
      background-color: rgba(33, 149, 254, 1);
    }

    .cell {
      span:nth-of-type(3) {
        display: inline-block;
        width: 90%;
        word-break: break-all;
      }
    }
  }
}
.resi-table {
  ::v-deep .el-button--text {
    text-decoration: underline;
  }
  ::v-deep .btn-color-del {
    margin-left: 10px;
    color: rgba(213, 16, 16, 1);
  }
  ::v-deep .btn-color-2j {
    margin-left: 10px;
    color: #fdaf30;
  }
  ::v-deep .btn-color-1j {
    margin-left: 10px;
    color: #3cb357;
  }
  ::v-deep .btn-color-edit {
    color: rgba(0, 167, 169, 1);
  }
}
</style>

<style lang="scss" scoped>
.resi-row-btn {
  display: flex;
  margin-bottom: 13px;
  ::v-deep .el-button {
    // margin-left: 10px;
    border: 0;
  }
  ::v-deep .el-select {
    margin-right: 10px;
  }
  .el-button--success {
    background: rgba(34, 193, 195, 1);
  }
}
.avatar-uploader {
  ::v-deep .el-upload {
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .el-upload:hover {
    border-color: #409eff;
  }
  .avatar {
    width: 70px;
    height: 70px;
    display: block;
  }
  .avatar-uploader-icon {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    font-size: 28px;
    color: #8c939d;
    width: 70px;
    height: 70px;
    line-height: 70px;
    text-align: center;
  }
}

.resi-btns {
  margin-top: 20px;
  text-align: center;
}
</style>
