<script>
import { deleteRule, getRuleList } from '@/api/rules/index'
import EditPromptRule from '@/views/knowledge/detail/components/words/AddRule.vue'
import EditSplitRule from '@/views/knowledge/detail/components/split/AddRule.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: '规则类型',
            render: (h, params) => {
              return h('span', this.tableConfig.ruleType[params.row.ruleType])
            }
          },
          { 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: 'danger', size: 'mini' },
                    on: { click: () => this.handleDelete(params.row, params.index) }
                  },
                  '删除'
                )
              ])
            }
          }
        ]
      },
      // 弹窗配置
      dialogOptions: {
        title: '',
        visible: false,
        width: '50%',
        currentComponent: void 0
      },
      tableData: [],
      // 查询表单
      form: {
        pickerOptions: void 0,
        ruleType: '',
        ruleName: '',
        createdDate: []
      }
    }
  },
  provide() {
    return {
      dialogOptions: this.dialogOptions,
      tableData: this.tableData
    }
  },
  components: {
    EditPromptRule,
    EditSplitRule,
    AddRules,
    Info
  },
  computed: {
    // 处理后的日期内容, 只保留 年月日, 日期格式是 年-月-日
    formattedDate() {
      // 如果没有日期，返回空字符串
      if (!this.form.createdDate.length) return ''

      return this.form.createdDate.map((date, index) => {
        return `${new Date(date).getFullYear()}-${String(new Date(date).getMonth() + 1).padStart(2, '0')}-${String(new Date(date).getDate()).padStart(
          2,
          '0'
        )} ${index === 0 ? '00:00:00' : '23:59:59'}`
      })
    }
  },
  watch: {
    form: {
      handler() {},
      deep: true
    }
  },
  created() {
    this.getTableData()
  },
  methods: {
    // 反转 ruleType ,获取 key 值
    reverseRuleType(value) {
      // const keys = Object.keys(this.tableConfig.ruleType)
      const values = Object.values(this.tableConfig.ruleType)
      const res = values.indexOf(value) + 1
      // 如果没有找到，默认查询所有内容
      if (res === -1) return ''
      return res
    },
    getTableData() {
      const payload = {
        page: this.tableConfig.currentPage,
        pageSize: this.tableConfig.pageSize,
        ruleType: this.form.ruleType,
        ruleNameLike: this.form.ruleName,
        startCreatedDate: this.formattedDate.length > 1 ? this.formattedDate[0] : '',
        endCreatedDate: this.formattedDate.length > 1 ? this.formattedDate[1] : ''
        // times: this.formattedDate
      }

      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.handleEdit(row, true)
    },
    // 处理修改规则
    handleEdit(row, isPreview = false) {
      console.log(`isPreview`, isPreview)
      this.dialogOptions.currentComponent = row.ruleType === 1 ? 'EditSplitRule' : 'EditPromptRule'

      if (this.dialogOptions.currentComponent === 'EditPromptRule') {
        this.$nextTick(() => {
          this.$refs.editPromptRule.init(row.id, { preview: isPreview })
        })
      } else if (this.dialogOptions.currentComponent === 'EditSplitRule') {
        this.$nextTick(() => {
          this.$refs.editSplitRule.init(row.id, { preview: isPreview })
        })
      }
    },
    // 处理删除规则`
    handleDelete(row, index) {
      this.$confirm('此操作将永久删除该规则, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRule([row.id])
          .then(() => {
            // 删除当前行
            this.tableData.splice(index, 1)
            this.getTableData()
            this.$notify.success({
              title: '删除成功',
              message: '删除成功',
              duration: 2000
            })
          })
          .catch(err => {
            this.$notify.error({
              title: '删除失败',
              message: h('i', { style: 'color: teal' }, '删除时出现错误，稍后再试' + err)
            })
          })
      })
    },
    // 处理查询
    handleQuery() {
      // 重置页码
      this.tableConfig.currentPage = 1

      this.getTableData()
    },
    // 处理重置
    handleReset() {
      this.form = {
        pickerOptions: void 0,
        ruleType: '',
        ruleName: '',
        createdDate: []
      }
      this.handleQuery()
    },
    // 处理新增
    handleAddSplit() {
      this.dialogOptions.currentComponent = 'EditSplitRule'
      this.$nextTick(() => {
        this.$refs.editSplitRule.init()
      })
    },
    handleAddPrompt() {
      this.dialogOptions.currentComponent = 'EditPromptRule'
      this.$nextTick(() => {
        this.$refs.editPromptRule.init()
      })
    }
  }
}
</script>

<template>
  <div class="rules-container container">
    <el-card shadow="hover">
      <div class="card-body">
        <el-form :model="form" label-width="100px" size="small">
          <!-- 查询条件 -->
          <el-row>
            <!-- 规则类型 -->
            <el-col :span="7">
              <el-form-item label="规则类型">
                <el-select v-model="form.ruleType" placeholder="请选择规则类型">
                  <el-option label="全部规则" value="">全部规则</el-option>
                  <el-option v-for="item in tableConfig.ruleType" :key="item" :label="item" :value="reverseRuleType(item)" />
                </el-select>
              </el-form-item>
            </el-col>
            <!-- 规则名称 -->
            <el-col :span="7">
              <el-form-item label="规则名称">
                <el-input v-model="form.ruleName" placeholder="请输入规则名称" />
              </el-form-item>
            </el-col>
            <!-- 创建时间 -->
            <el-col :span="6">
              <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" :offset="8">
              <el-button size="mini" type="primary" @click="handleQuery">查询</el-button>
              <el-button size="mini" type="primary" @click="handleReset">重置筛选</el-button>
              <el-button size="mini" type="primary" @click="handleAddSplit">新增拆分规则</el-button>
              <el-button size="mini" type="primary" @click="handleAddPrompt">新增题词规则</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 下方规则列表 -->
      <div class="p20">
        <r-table
          :columns="tableConfig.columns"
          :data="tableData"
          :deletion="false"
          :total="tableConfig.total"
          @currentChange="handleCurrentChange"
          @sizeChange="handleSizeChange"
          :currentPage="tableConfig.currentPage"
          :pageSize="tableConfig.pageSize"
        />
      </div>
    </el-card>
    <edit-prompt-rule ref="editPromptRule" v-if="dialogOptions.currentComponent === 'EditPromptRule'" @getDataList="handleQuery" />
    <edit-split-rule ref="editSplitRule" v-else-if="dialogOptions.currentComponent === 'EditSplitRule'" @getDataList="handleQuery" />
  </div>
</template>
