<script>
import { deleteRule, getRuleList } from '@/api/rules/index'
import EditPromptRule from './components/edit-prompt-rule/Index.vue'
import EditSplitRule from './components/edit-split-rule/Index.vue'
import AddRules from './components/add-rules/index.vue'
import Info from './components/info/index.vue'

export default {
  name: 'rules',
  data() {
    return {
      // 表格配置项
      tableConfig: {
        ruleType: {
          1: '提词规则',
          2: '知识拆分规则'
        },
        total: 0,
        currentPage: 1,
        pageSize: 10,
        columns: [
          { prop: 'ruleName', key: '规则名称' },
          { prop: 'ruleType', key: '规则类型' },
          { prop: 'createdDate', key: '创建时间' },
          {
            key: '操作',
            render: (h, params) => {
              return h('div', [
                h(
                  'el-button',
                  {
                    props: { type: 'text', size: 'mini' },
                    on: { click: () => this.handleInfoVisible(params.row) }
                  },
                  '查看详情'
                ),
                h(
                  'el-button',
                  {
                    props: { type: 'text', size: 'mini' },
                    on: { click: () => this.handleEdit(params.row) }
                  },
                  '修改'
                ),
                h(
                  'el-button',
                  {
                    props: { type: 'text', size: 'mini' },
                    on: { click: () => this.handleDelete(params.row, params.index) }
                  },
                  '删除'
                )
              ])
            }
          }
        ]
      },
      // 弹窗配置
      dialogOptions: {
        title: '',
        visible: false,
        width: '50%',
        currentComponent: void 0,
        currentRow: void 0
      },
      tableData: [],
      // 查询表单
      form: {
        query: true,
        pickerOptions: void 0,
        ruleType: '',
        ruleName: '',
        createdDate: []
      }
    }
  },
  provide() {
    return {
      dialogOptions: this.dialogOptions,
      tableData: this.tableData
    }
  },
  components: {
    EditPromptRule,
    EditSplitRule,
    AddRules,
    Info
  },
  computed: {
    // 当前的分页数据
    currentTableDate() {
      let filteredData
      // 过滤 table 列表,如果 form 相关项是空的，就不过滤
      if (this.form.query) {
        // 过滤 ruleType
        const map = {
          1: '知识拆分规则',
          2: '提词规则'
        }
        filteredData = this.tableData.filter(item => {
          if (!this.form.ruleType) return true
          return map[item.ruleType] === this.form.ruleType
        })

        // 过滤 ruleName
        filteredData = filteredData.filter(item => {
          if (!this.form.ruleName) return true
          return item.ruleName === this.form.ruleName
        })

        // 过滤 createdDate
        filteredData = filteredData.filter(item => {
          if (!this.form.createdDate.length) return true
          return item.createdDate >= this.form.createdDate[0] && item.createdDate <= this.form.createdDate[1]
        })
      } else {
        filteredData = this.tableData
      }
      return filteredData
    },

    // 获取表格数据
    getCurrentTableData() {
      // 需要处理 规则类型， 因为规则类型都是数字，需要转换成中文
      return this.currentTableDate.map(item => ({
        ...item,
        ruleType: item.ruleType === 1 ? '知识拆分规则' : '提词规则'
      }))
    },

    // 查询表单的 ruleTypeOptions
    ruleTypeOptions() {
      // 去重所有 ruleType， 然后映射成 option
      return [...new Set(this.tableData.map(item => item.ruleType))].map(type => this.tableConfig.ruleType[type])
    },
    // 查询表单的 ruleNameOptions
    ruleNameOptions() {
      const res = [...new Set(this.tableData.map(item => item.ruleName))]
      return res
    }
  },
  watch: {
    form: {
      handler() {
      },
      deep: true
    }
  },
  created() {
    this.getTableData()
  },
  methods: {
    getTableData() {
      const payload = {
        page: this.tableConfig.currentPage,
        pageSize: this.tableConfig.pageSize
        // docId: ''
      }

      getRuleList(payload).then(res => {
        const { content } = res.content

        this.tableData = content.list
        this.tableConfig.total = content.total
      })
    },
    // 页码改变
    handleCurrentChange(current) {
      this.tableConfig.currentPage = current
      this.getTableData()
    },
    // 页数改变
    handleSizeChange(size) {
      this.tableConfig.pageSize = size
      this.getTableData()
    },
    // 处理查看规则详情
    handleInfoVisible(row) {
      this.dialogOptions.title = '查看规则详情'
      this.dialogOptions.currentComponent = 'Info'
      this.dialogOptions.visible = true
      this.dialogOptions.currentRow = row
    },
    // 处理修改规则
    handleEdit(row, index) {
      this.dialogOptions.title = '修改规则'
      this.dialogOptions.currentComponent = row.ruleType === '知识拆分规则' ? 'EditSplitRule' : 'EditPromptRule'
      this.dialogOptions.visible = true
      this.dialogOptions.currentRow = row
    },
    // 处理删除规则
    handleDelete(row, index) {
      deleteRule([row.id])
        .then(() => {
          // 删除当前行
          this.tableData.splice(index, 1)
          this.getTableData()
        })
        .catch(err => {
          this.$notify.error({
            title: '删除失败',
            message: h('i', { style: 'color: teal' }, '删除时出现错误，稍后再试' + err)
          })
        })
    },
    // 处理查询
    handleQuery() {
      this.form.query = true
    },
    // 处理重置
    handleReset() {
      this.form = {
        query: true,
        pickerOptions: void 0,
        ruleType: '',
        ruleName: '',
        createdDate: []
      }
    },
    // 处理新增
    handleAdd() {
      this.dialogOptions.title = '新增规则'
      this.dialogOptions.visible = true
      this.dialogOptions.currentComponent = 'AddRules'
    }
  }
}
</script>

<template>
  <div class="rules-container container">
    <el-card shadow="hover">
      <!-- <template #header>
        <div class="card-header">
          <h3>规则管理</h3>
        </div>
      </template> -->
      <div class="card-body">
        <el-form :model="form" label-width="100px" size="small">
          <!-- 查询条件 -->
          <el-row>
            <!-- 规则类型 -->
            <el-col :span="8">
              <el-form-item label="规则类型">
                <el-select v-model="form.ruleType" placeholder="请选择规则类型">
                  <el-option v-for="item in ruleTypeOptions" :key="item" :label="item" :value="item"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- 规则名称 -->
            <el-col :span="8">
              <el-form-item label="规则名称">
                <el-select v-model="form.ruleName" placeholder="请选择规则名称">
                  <el-option v-for="item in ruleNameOptions" :key="item" :label="item" :value="item"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- 创建时间 -->
            <el-col :span="8">
              <el-form-item label="创建时间">
                <el-date-picker v-model="form.createdDate" type="daterange" unlink-panels range-separator="至"
                                start-placeholder="开始日期" end-placeholder="结束日期"
                                :picker-options="form.pickerOptions">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 功能按钮组： 查询、重置、新增规则 -->
          <el-row class="p25">
            <el-col :span="16">
              <!--              <el-button size="mini" type="primary" @click="handleQuery">查询</el-button>-->
              <el-button size="mini" type="info" @click="handleReset">重置</el-button>
              <el-button size="mini" type="primary" @click="handleAdd">新增规则</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 下方规则列表 -->
      <div class="p20">
        <r-table :columns="tableConfig.columns" :data="getCurrentTableData" :deletion="false" :total="tableConfig.total"
                 @currentChange="handleCurrentChange" @sizeChange="handleSizeChange" />
      </div>
    </el-card>
    <!-- 规则详情弹窗 -->
    <el-drawer :visible.sync="dialogOptions.visible" size="50%" :title="dialogOptions.title">
      <!-- diglog 弹窗内容组件 -->
      <component class="container" v-if="dialogOptions.visible" :is="dialogOptions.currentComponent" :data="tableData"
                 :columns="columns" :currentRow="dialogOptions.currentRow" />
    </el-drawer>
  </div>
</template>
