<template>
  <div v-if="pageLoading" class="resi-container">
    <el-card class="resi-card-table">
      <div class="resi-row-btn">
        <el-form :inline="true" :model="form" class="demo-form-inline">
          <el-form-item label="需求分类">
            <el-select v-model="form.firstCategoryCode" filterable placeholder="请选择" clearable>
              <el-option
                v-for="item in demandOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="resi-row-btn">
        <el-button type="success" @click="handleAdd('1', 'add')">新增分类</el-button>
      </div>
      
      <el-table
        :data="tableData"
        row-key="categoryId"
        v-loading="tableLoading"
        border
        max-height="800"
        style="width: 100%"
        class="resi-table"
      >
        <el-table-column label="序号" type="index" align="center" width="50">
          <template slot-scope="scope">{{ scope.row.index }}</template>
        </el-table-column>
        <el-table-column
          v-for="item in tableHeader"
          :key="item.columnName"
          :prop="item.columnName"
          :label="item.label"
          :align="item.align"
        >
          <template slot-scope="scope">
            <span>{{ handleFilterSpan(scope.row, item) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.hasBtn"
              @click="handleLook(scope.row)"
              type="text"
              size="small"
              class="btn-color-look"
              >{{(scope.row.usableFlag&&'禁用') || '启用'}}</el-button
            >
            <el-button
                v-if="scope.row.level == 1"
                @click="handleAdd('2', 'add', scope.row)"
                type="text"
                size="small"
                class="btn-color-del"
                >添加二级分类</el-button
              >
            <el-button
                @click="handleEdit(scope.row, 'edit')"
                type="text"
                size="small"
                class="btn-color-edit"
                >编辑</el-button
              >
          </template>
        </el-table-column>
      </el-table>
      <div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-sizes="[20, 50, 100, 200]"
          :page-size="pageSize"
          layout="sizes, prev, pager, next"
          :total="total"
        >
        </el-pagination>
      </div>
    </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="categoryName">
          <el-input v-model="form.categoryName" size="small" style="width: 180px;"></el-input>
        </el-form-item>
        
        <!-- <el-form-item label="状态">
          <el-switch v-model="form.usableFlag"></el-switch>
        </el-form-item> -->
        <el-form-item v-if="addLevel == '2'" label="奖励积分">
          <el-input-number v-model="form.awardPoint" :min="0" size="small" label="描述文字"></el-input-number>
        </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>
export default {
  data() {
    return {
      tableLoading: false,
      btnLoading: false,
      disabled: false,
      pageLoading: false,
      dialogVisible: false,
      currentPage: 1,
      pageSize: 20,
      total: null,
      tableData: [],
      addLevel: '1',
      addType: 'add',
      value: '',
      options: [
        {
          label: '是',
          value: 1
        },{
          label: '否',
          value: 2
        }
      ],
      demandOptions: [],
      tableHeader: [
        {
          label: '分类名称',
          align: 'left',
          columnName: 'categoryName'
        }, {
          label: '状态',
          columnName: 'usableFlag',
          align: 'center',
          options: [{
            value: true,
            label: '启用'
          }, {
            value: false,
            label: '禁用'
          }]
        }
      ],
      customerId: '',
      form: {
        firstCategoryCode: '',
        categoryName: '',
        awardPoint: '',
        usableFlag: false
      },
      rules: {
        categoryName: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }]
      }
    }
  },
  async created() {
    this.customerId = localStorage.getItem('customerId')
    this.getTableData()
    this.getOptions()
    this.pageLoading = true
  },
  mounted() {
  },
  methods: {
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pageSize = val
      this.getTableData()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.currentPage = val
      this.getTableData()
    },
    handleFilterSpan(row, item) {
      let _val = ''
      if (item.options && item.options.length > 0) {
        item.options.forEach((n) => {
          if (n.value === row[item.columnName]) _val = n.label
        })
      }
      return _val || row[item.columnName]
    },
    handleSearch(val) {
      console.log('searchhh--', val)
      this.currentPage = 1
      this.getTableData()
    },
    handleAdd(type, addType, row) {
      this.addLevel = type
      this.addType = addType
      if (type == '2') this.form = { ...row, categoryName: '' }
      this.dialogVisible = true
    },
    handlerCancle() {
      this.dialogVisible = false
    },
    async handleLook(row) {
      const params = {
        categoryId: row.categoryId,
        usableFlag: !row.usableFlag
      }
      this.$http
        .post('/heart/icresidemanddict/updatestatus', params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            this.getTableData()
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
    },
    async handleEdit(row, addType) {
      
      this.form = { ...row }
      this.addLevel = row.level
      this.addType = addType
      this.dialogVisible = true
    },
    async addLevelFirst() {
      const _form = {
        customerId: localStorage.getItem('customerId'),
        categoryName: this.form.categoryName
      }
      await this.$http
        .post('/heart/icresidemanddict/addfirst', _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 = {
        customerId: localStorage.getItem('customerId'),
        categoryName: this.form.categoryName,
        parentCategoryCode: this.form.categoryCode,
        awardPoint: this.form.awardPoint
      }
      await this.$http
        .post('/heart/icresidemanddict/addchild', _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 editCate() {
      const _form = {
        customerId: localStorage.getItem('customerId'),
        categoryName: this.form.categoryName,
        categoryId: this.form.categoryId,
        level: this.form.level,
        awardPoint: this.form.awardPoint
      }
      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
    },
    handleSUbmit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.btnLoading = true
          if (this.addType == 'add') {
            if (this.addLevel == '1') this.addLevelFirst()
            else this.addLevelChild()
          } else this.editCate()
          
        } else {
          console.log('error submit!!');
          return false;
        }
      });
      
    },
    handleDel(row) {
      let params = {
        formCode: 'resi_base_info',
        icResiUserId: row.icResiUserId
      }
      console.log('row1', row)
      this.$http
        .post('/epmetuser/icresiuser/delete', params)
        .then(({ data: res }) => {
          console.log('row2', row)
          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('网络错误')
        })
    },
    sortData() {
      const _data = this.tableData.map((item, index)=> {
        return {
          id: item.id,
          sort: index
        }
      })
      this.$http
        .post('/oper/customize/resicategorystatsconfig/updatesort', _data)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            // this.getTableData()
          }
        })
        .catch((err) => {
          console.log('row4', err)
          return this.$message.error('网络错误')
        })
    },
    async getOptions() {
      const params = {
        parentCategoryCode: 0
      }
      this.$http
        .post('/heart/icresidemanddict/subcodelist', params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            this.demandOptions = res.data
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
    },
    async getTableData() {
      this.tableLoading = true
      let params = {
        // formCode: 'resi_base_info',
        customerId: localStorage.getItem('customerId'),
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        firstCategoryCode: this.form.firstCategoryCode
      }
      await this.$http
        .post('/heart/icresidemanddict/pagelist', params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            this.tableData = res.data.list.map((item, index) => {
              return {
                ...item,
                index: index + 1,
                hasBtn: true,
                children: item.children.map(n => {
                  return {
                    ...n,
                    hasBtn: item.usableFlag
                  }
                })
              }
            })
            this.total = res.data.total
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
      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-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>
