<template>
  <section class="AppKeywordManagement">
    <ai-list>
      <template #content>
        <ai-search-bar>
          <template #left>
            <el-button size="small" type="primary" icon="iconfont iconAdd" @click="toAdd('')">添加</el-button>
          </template>
          <template #right>
            <el-input size="small" placeholder="关键词搜索" v-model="search.name" clearable
              @clear="current = 1, search.name = '', getTableData()" suffix-icon="iconfont iconSearch"
              v-throttle="() => {(current = 1), getTableData();}"/>
          </template>
        </ai-search-bar>
        <ai-table :tableData="tableData" :total="total" :current.sync="current" :size.sync="size"
                  @getList="getTableData()" :col-configs="colConfigs" :dict="dict">
          <el-table-column slot="options" label="操作"  align="center">
            <template slot-scope="{ row }">
              <el-button type="text" @click="edit(row)">启用</el-button>
              <el-button type="text" @click="edit(row)">编辑</el-button>
              <el-button type="text" @click="del(row)">删除</el-button>
            </template>
          </el-table-column>
        </ai-table>
      </template>
    </ai-list>
    <ai-dialog
        :title="form.id ? '编辑敏感词' : '添加敏感词'"
        :visible.sync="dialog"
        :destroyOnClose="true"
        width="720px"
        @onConfirm="onConfirm"
        @closed="form={}">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="敏感词" prop="registerCount">
          <el-input v-model.trim="form.registerCount" placeholder="请输入正整数" size="small"></el-input>
        </el-form-item>
        <el-form-item label="生效地区" prop="friendCount">
          <el-input v-model.trim="form.friendCount" placeholder="请输入正整数" size="small"></el-input>
        </el-form-item>
        <el-form-item label="生效部门" prop="confidantCount">
          <el-input v-model.trim="form.confidantCount" placeholder="请输入正整数" size="small"></el-input>
        </el-form-item>
      </el-form>
    </ai-dialog>
  </section>

</template>

<script>
import { mapState } from "vuex";
export default {
  name: "AppKeywordManagement",
  label: '关键词管理',
  props: {
    instance: Function,
    dict: Object,
    permissions: Function,
    menuName:String
  },
  data() {
    return {
      search: {
        name: '',
        departmentId: '',
        current: 1,
        size: 10,
        areaId: '',
      },
      departIdList: [],
      tableData: [],
      size: 10,
      total: 0,
      current: 1,
      girdList: [],
      form: {
        registerCount: 0,
        friendCount: 0,
        confidantCount: 0
      },
      personList: [],
      dialog: false,
      girdOptions: [],
      defaultProps: {
        label: 'name',
        value: 'id',
        checkStrictly: true,
      },
      chooseUserList: [],
      flag: false,
    }
  },
  created() {
    this.$dict.load('integralCalcType')
    this.getTableData()
    this.getGridList()
  },
  computed: {
    ...mapState(['user']),
    colConfigs() {
      return [
        { prop: "name", label: '关键词', align: "left"},
        { prop: "areaName", label: '创建时间'},
        { prop: "departmentName", label: '创建人'},
        { prop: "phone", label: '生效地区'},
        { prop: "registerCount", label: '生效部门'},
        { slot: "options" },
      ]
    },
    rules() {
      return {
        registerCount: [{required: true, message: '请输入登记数', trigger: 'blur' },
          {pattern: /^[0-9]+$/, message: '请输入正整数'}],
        friendCount: [{required: true, message: '请输入朋友数', trigger: 'blur' },
          {pattern: /^[0-9]+$/, message: '请输入正整数'}],
        confidantCount: [{required: true, message: '请输入知己数', trigger: 'blur' },
          {pattern: /^[0-9]+$/, message: '请输入正整数'}],
      }
    },
  },
  methods: {
    getTableData() {
      this.instance.post(`/app/appwxuserfamiliarityrate/list`,null,{
        params: {
          ...this.search,
          current: this.current,
          size: this.size,
          total: this.total
        }
      }).then(res => {
        if(res?.data) {
          this.tableData = res.data.records
          this.total = res.data.total
        }
      })
    },
    onAreaChange () {
      this.search.current = 1

      this.$nextTick(() => {
        this.getTableData()
      })
    },
    del(row) {
      this.$confirm('确定删除该数据？').then(() => {
        this.instance.post(`/app/appwxuserfamiliarityrate/delete?id=${row.id}`).then(res => {
          if (res.code == 0) {
            this.$message.success('删除成功！')
            this.getTableData()
          }
        })
      })
    },

    edit(row) {
      this.dialog = true
      this.form = {...row}
    },

    selectPerson(val) {
      console.log(val)
      if (val) {
        this.personList = val
        this.form.ids = [...this.personList.map(e => e.sysUserId)]
      } else {
        this.form.ids = this.chooseUserList.map(e => e.sysUserId)
      }
    },

    getGridList() {
      this.instance.post(`/app/wxcp/wxdepartment/listAll`).then((res) => {
        if (res.code == 0) {
          this.girdOptions = this.toTree(res.data)
        }
      })
    },

    // 转树形结构
    toTree(data) {
      let result = [];
      if (!Array.isArray(data)) {
        return result
      }
      let map = {};
      data.forEach(item => {
        map[item.id] = item;
      });
      data.forEach(item => {
        let parent = map[item.parentid];
        if (parent) {
          (parent.children || (parent.children = [])).push(item);
        } else {
          result.push(item);
        }
      });
      return result;
    },

    gridChange(val) {
      this.departIdList = val
      this.search.departmentId = val?.[val.length - 1]
      this.$refs.cascader1.dropDownVisible = false;
      this.getTableData()
    },

    onConfirm() {
      if(this.flag) return

      this.$refs.form.validate((valid)=> {
        if(valid) {
          this.flag = true
          this.instance.post(`/app/appwxuserfamiliarityrate/webUpdate`,{...this.form}).then(res => {
            if(res?.code == 0) {
              this.$message.success('分类信息修改成功')
              setTimeout(() =>{
                this.dialog = false
                this.getTableData()
                this.flag = false
              }, 600)
            } else {
              this.flag = false
            }
          })
        }
      })

    },

    toDetail(id) {
      this.$emit('change', {
        type: 'Detail',
        params: {
          id: id
        }
      })
    }
  },
}
</script>

<style lang="scss" scoped>
.AppKeywordManagement {
  height: 100%;

  :deep( .ai-dialog .ai-dialog__content ){
    max-height: 600px!important;
  }



  .userlist {
    display: inline-block;
  }

  .userlist, .user {
    display: inline-block;
  }

  .user {
    position: relative;
    width: 70px;
    text-align: center;

    .remove-icon {
      position: absolute;
      right: 7px;
      top: -4px;
      line-height: 1;
      padding: 6px 0;
      font-size: 16px;
      cursor: pointer;

      &:hover {
        color: crimson;
      }
    }

    img, h2 {
      display: block;
      width: 40px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      margin: 0 auto 4px;
      font-size: 14px;
      color: #fff;
      border-radius: 50%;
    }

    h2 {
      background-color: $primaryColor;
    }

    span {
      color: #666;
      font-size: 14px;
      white-space: nowrap;
      overflow: hidden;
      word-break: break-all;
      text-overflow: ellipsis;
    }
  }

  :deep( .selectCont .pagination ){
    width: 100%!important;
    background: pink;
  }
}
</style>
