<template>
  <div class="rating-level-wrap">
    <Card>
      <div class="toolbar">
        <Button type="primary" icon="md-add" v-if="showAdd" @click="openAdd">新增</Button>
        <Button type="primary" icon="md-create" v-if="showEdit" @click="openEdit">修改</Button>
      </div>
      <Table border :loading="loading" :columns="columns" :data="list" />
    </Card>

    <Modal v-model="modal.visible" :title="modalTitle" width="900">
      <Form :model="form" :label-width="120" ref="form" :rules="rules">
        <FormItem label="重点人员类别">
          <Input :value="renderCategoryLabel(category)" disabled />
        </FormItem>
        <FormItem label="评分等级设置">
          <Table :columns="editColumns" :data="form.items" border>
            <template slot="start" slot-scope="{ row, index }">
              <Input v-model="form.items[index].rating_start_score" placeholder="起始分数(>=0)" />
            </template>
            <template slot="end" slot-scope="{ row, index }">
              <Input v-model="form.items[index].rating_end_score" placeholder="结束分数(>)" />
            </template>
            <template slot="rule" slot-scope="{ row }">
              <span>{{ renderRule(row.rating_start_score, row.rating_end_score) }}</span>
            </template>
          </Table>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="modal.visible=false">取消</Button>
        <Button type="primary" :loading="modal.submitting" @click="submit">保存</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import { getDictList } from '@/api/common'
import { selectRatingLevelList, saveRatingLevel } from '@/api/key-person'
export default {
  name: 'key-person-rating-level-index',
  props: { category: { type: String, default: '' } },
  data () {
    return {
      loading: false,
      list: [],
      levelOptions: [],
      columns: [
        { title: '重点人员类别', key: 'rating_dict_type', align: 'center', minWidth: 160, render: (h, { row }) => h('span', this.renderCategoryLabel(row.rating_dict_type)) },
        { title: '评分等级', key: 'rating_level_label', align: 'center', minWidth: 140 },
        { title: '对比规则', key: 'rule', align: 'center', minWidth: 220, render: (h, { row }) => h('span', this.renderRule(row.rating_start_score, row.rating_end_score)) }
      ],
      editColumns: [
        { type: 'index', title: '序号', align: 'center', width: 80 },
        { title: '评分等级', key: 'rating_level_label', align: 'center', minWidth: 160 },
        { title: '起始分数', slot: 'start', align: 'center', minWidth: 140 },
        { title: '结束分数', slot: 'end', align: 'center', minWidth: 140 },
        { title: '对比规则', slot: 'rule', align: 'center', minWidth: 200 }
      ],
      modal: { visible: false, submitting: false, isEdit: false },
      form: { items: [] },
      rules: {}
    }
  },
  computed: {
    showAdd () { return (this.list || []).length === 0 },
    showEdit () { return (this.list || []).length > 0 },
    modalTitle () { return this.modal.isEdit ? '修改评分等级划分' : '新增评分等级划分' },
    categoryMap () {
      return { '2': '刑满释放人员', '3': '严重精神障碍患者', '6': '重点未成年人' }
    }
  },
  created () {
    this.loadLevelDict()
    this.loadList()
  },
  methods: {
    renderCategoryLabel (val) {
      const s = String(val || this.category || '')
      return this.categoryMap[s] || s || '-'
    },
    renderRule (start, end) {
      const s = (start !== undefined && start !== null && start !== '') ? String(start) : '-'
      const e = (end !== undefined && end !== null && end !== '') ? String(end) : '-'
      return `${s} <= 实际评分 < ${e}`
    },
    loadLevelDict () {
      getDictList({ type: 'rating_level' }).then((ret) => {
        if (ret && ret.data && ret.data.errcode === 0) {
          const results = (ret.data.data && ret.data.data.results) || []
          const mapped = results.map(it => ({
            rating_level_value: String(it.value || it.dictValue),
            rating_level_label: it.label || it.name
          }))
          const toNum = v => (/^\d+$/.test(String(v)) ? Number(v) : null)
          this.levelOptions = mapped.sort((a, b) => {
            const an = toNum(a.rating_level_value)
            const bn = toNum(b.rating_level_value)
            if (an !== null && bn !== null) return bn - an
            const as = String(a.rating_level_label || a.rating_level_value)
            const bs = String(b.rating_level_label || b.rating_level_value)
            return bs.localeCompare(as)
          })
        } else {
          this.levelOptions = []
        }
      }).catch(() => { this.levelOptions = [] })
    },
    loadList () {
      this.loading = true
      const payload = { rating_dict_type: String(this.category || '') }
      selectRatingLevelList(payload).then((ret) => {
        if (ret && ret.data && ret.data.errcode === 0) {
          const results = (ret.data.data && ret.data.data.results) || ret.data.data || []
          const arr = Array.isArray(results) ? results.slice() : []
          const toNum = v => (/^\d+$/.test(String(v)) ? Number(v) : null)
          arr.sort((a, b) => {
            const an = toNum(a.rating_level_value)
            const bn = toNum(b.rating_level_value)
            if (an !== null && bn !== null) return bn - an
            const as = String(a.rating_level_label || a.rating_level_value)
            const bs = String(b.rating_level_label || b.rating_level_value)
            return bs.localeCompare(as)
          })
          this.list = arr
        } else {
          this.$Notice.error({ title: '查询失败', desc: (ret && ret.data && ret.data.errmsg) || '' })
        }
      }).finally(() => { this.loading = false })
    },
    openAdd () {
      this.modal.isEdit = false
      // 以字典评分等级为基准生成编辑项
      const items = (this.levelOptions || []).map((lv) => ({
        rating_level_value: lv.rating_level_value,
        rating_level_label: lv.rating_level_label,
        rating_start_score: '',
        rating_end_score: ''
      }))
      if (items.length > 0) items[0].rating_start_score = '0'
      this.form = { items }
      this.modal.visible = true
    },
    openEdit () {
      this.modal.isEdit = true
      const mapByValue = {}
      ;(this.list || []).forEach(it => { mapByValue[String(it.rating_level_value)] = it })
      // 用字典顺序对齐
      const items = (this.levelOptions || []).map((lv, idx) => {
        const hit = mapByValue[String(lv.rating_level_value)] || {}
        return {
          rating_level_value: lv.rating_level_value,
          rating_level_label: lv.rating_level_label,
          rating_start_score: hit.rating_start_score !== undefined ? String(hit.rating_start_score) : (idx === 0 ? '0' : ''),
          rating_end_score: hit.rating_end_score !== undefined ? String(hit.rating_end_score) : ''
        }
      })
      this.form = { items }
      this.modal.visible = true
    },
    submit () {
      const items = (this.form && this.form.items) ? this.form.items : []
      // 先确保第一行起始分为0（与展示顺序一致）
      const toNum = (v) => {
        if (v === null || v === undefined || v === '') return null
        if (!/^[\d]+$/.test(String(v))) return NaN
        return Number(v)
      }
      const firstStartVal = toNum(items[0] && items[0].rating_start_score)
      if (firstStartVal !== 0) { this.$Message.error('第一档起始分数必须为 0'); return }
      // 基础校验：为大于等于0的整数，start < end，连续分段且从0开始
      const parsed = items.map((it, idx) => ({
        idx,
        value: String(it.rating_level_value),
        label: it.rating_level_label,
        start: toNum(it.rating_start_score),
        end: toNum(it.rating_end_score)
      }))
      // 为保证连续性校验与提交顺序正确，这里按起始分数升序排序
      const sorted = parsed.slice().sort((a, b) => {
        const as = a.start === null || Number.isNaN(a.start) ? Infinity : a.start
        const bs = b.start === null || Number.isNaN(b.start) ? Infinity : b.start
        return as - bs
      })
      // 检查空值
      for (const p of sorted) {
        if (p.start === null || Number.isNaN(p.start)) { this.$Message.error(`请填写有效的起始分数（整数） - ${p.label}`); return }
        if (p.end === null || Number.isNaN(p.end)) { this.$Message.error(`请填写有效的结束分数（整数） - ${p.label}`); return }
        if (p.start < 0 || p.end < 0) { this.$Message.error(`${p.label} 分数必须为大于等于0的整数`); return }
        if (p.end <= p.start) { this.$Message.error(`${p.label} 结束分数必须大于起始分数`); return }
      }
      // 连续性与不交叉：左闭右开 [start, end)
      for (let i = 0; i < sorted.length; i++) {
        const cur = sorted[i]
        if (i === 0) {
          if (cur.start !== 0) { this.$Message.error('第一档起始分数必须为 0'); return }
        } else {
          const prev = sorted[i - 1]
          if (cur.start !== prev.end) { this.$Message.error(`评分等级必须首尾相接：${prev.label} 的结束分数应等于 ${cur.label} 的起始分数`); return }
        }
      }
      const payload = {
        rating_dict_type: String(this.category || ''),
        items: sorted.map(p => ({
          rating_level_value: p.value,
          rating_level_label: p.label,
          rating_start_score: String(p.start),
          rating_end_score: String(p.end)
        }))
      }
      this.modal.submitting = true
      saveRatingLevel(payload).then((ret) => {
        if (ret && ret.data && ret.data.errcode === 0) {
          this.$Notice.success({ title: '保存成功' })
          this.modal.visible = false
          this.loadList()
        } else {
          this.$Notice.error({ title: '保存失败', desc: (ret && ret.data && ret.data.errmsg) || '' })
        }
      }).finally(() => { this.modal.submitting = false })
    }
  }
}
</script>

<style scoped>
.rating-level-wrap { padding: 10px; }
.toolbar { margin-bottom: 10px; }
</style>
