<template>
  <div class="rating-day-wrap">
    <Card>
      <div class="toolbar">
        <Button type="primary" icon="md-add" v-if="showAdd" @click="openAdd">新增</Button>
      </div>
      <Table border :loading="loading" :columns="columns" :data="list">
        <template slot="rating_range" slot-scope="{ row }">
          <span>{{ (row.rating_start_day || '-') + '天 至 ' + (row.rating_end_day || '-') + '天' }}</span>
        </template>
        <template slot="action" slot-scope="{ row }">
          <Button type="primary" size="small" @click="openEdit(row)">修改</Button>
        </template>
      </Table>
    </Card>

    <Modal v-model="modal.visible" :title="modalTitle" width="520">
      <Form :model="form" :label-width="120" ref="form" :rules="rules">
        <FormItem label="重点人员类别">
          <Input :value="renderCategoryLabel(form.rating_dict_type, form.rating_dict_label)" disabled />
        </FormItem>
        <FormItem label="循环天数" prop="rating_range" required>
          <div style="display:flex; align-items:center; gap:8px;">
            <InputNumber :min="1" v-model="form.rating_start_day" style="width: 100px" placeholder="起始天数" />
            <span>天</span>
            <span>至</span>
            <InputNumber :min="1" v-model="form.rating_end_day" style="width: 100px" placeholder="结束天数" />
            <span>天 评分一次</span>
          </div>
        </FormItem>
        <FormItem label="临期预警天数" prop="rating_over_day" required>
          <div style="display:flex; align-items:center; gap:8px;">
            <span>距离截止日期剩余</span>
            <InputNumber :min="1" v-model="form.rating_over_day" style="width: 100px" placeholder="请输入" />
            <span>天，进行临期提醒</span>
          </div>
        </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 { selectRatingDayList, saveRatingDay, selectRatingDictTypeList } from '@/api/key-person'
export default {
  name: 'key-person-rating-day-index',
  props: { category: { type: String, default: '' } },
  data () {
    return {
      loading: false,
      list: [],
      dictTypeOptions: [],
      categoryMap: { '2': '刑满释放人员', '3': '严重精神障碍患者', '6': '重点未成年人' },
      columns: [
        { type: 'index', title: '序号', align: 'center', width: 80 },
        { title: '重点人员类别', key: 'rating_dict_label', align: 'center', minWidth: 140, render: (h, { row }) => h('span', this.renderCategoryLabel(row.rating_dict_type, row.rating_dict_label)) },
        { title: '循环天数', slot: 'rating_range', align: 'center', minWidth: 200 },
        { title: '临期预警天数', key: 'rating_over_day', align: 'center', minWidth: 160 },
        { title: '操作', slot: 'action', align: 'center', width: 120 }
      ],
      modal: { visible: false, submitting: false, isEdit: false },
      form: { id: '', rating_dict_type: '', rating_dict_label: '', rating_start_day: null, rating_end_day: null, rating_over_day: null },
      rules: {
        rating_range: [
          { validator: (rule, value, cb) => {
            const s = this.form.rating_start_day
            const e = this.form.rating_end_day
            if (!s || !e) return cb(new Error('请填写起止天数'))
            if (!Number.isInteger(s) || s <= 0) return cb(new Error('起始天数需为正整数'))
            if (!Number.isInteger(e) || e <= 0) return cb(new Error('结束天数需为正整数'))
            if (Number(s) > Number(e)) return cb(new Error('起始天数不能大于结束天数'))
            cb()
          },
          trigger: 'change' }
        ],
        rating_over_day: [
          { validator: (rule, value, cb) => {
            const o = this.form.rating_over_day
            if (o == null || o === '') return cb(new Error('请输入临期预警天数'))
            if (!Number.isInteger(o) || o <= 0) return cb(new Error('临期预警天数需为正整数'))
            cb()
          },
          trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    showAdd () { return (this.list || []).length === 0 },
    modalTitle () { return this.modal.isEdit ? '修改评分周期设置' : '新增评分周期设置' }
  },
  created () {
    this.fetchDictTypes()
    this.loadList()
  },
  methods: {
    fetchDictTypes () {
      // 读取字典：rating_dict_type 以显示中文名
      selectRatingDictTypeList({}).then((ret) => {
        if (ret && ret.data && ret.data.errcode === 0) {
          const arr = (ret.data.data && ret.data.data.results) || []
          this.dictTypeOptions = arr.map(it => ({
            label: it.label || it.dictLabel || it.name || it.dict_name,
            value: String(it.value || it.dictValue || it.dict_value)
          }))
          // 若新增弹窗打开且尚未有中文名，则回填中文名
          if (this.modal.visible && !this.modal.isEdit && !this.form.rating_dict_label) {
            this.form.rating_dict_label = this.renderCategoryLabel(this.form.rating_dict_type)
          }
        }
      }).catch(() => { this.dictTypeOptions = [] })
    },
    renderCategoryLabel (val, fallback) {
      const v = String(val || this.category || '')
      const found = (this.dictTypeOptions || []).find(it => String(it.value) === v)
      if (found && found.label) return found.label
      if (this.categoryMap && this.categoryMap[v]) return this.categoryMap[v]
      return fallback || v || '-'
    },
    loadList () {
      this.loading = true
      const payload = { rating_dict_type: String(this.category || '') }
      selectRatingDayList(payload).then((ret) => {
        if (ret && ret.data && ret.data.errcode === 0) {
          const results = (ret.data.data && ret.data.data.results) || ret.data.data || []
          this.list = Array.isArray(results) ? results : []
        } else {
          this.$Notice.error({ title: '查询失败', desc: (ret && ret.data && ret.data.errmsg) || '' })
        }
      }).finally(() => { this.loading = false })
    },
    openAdd () {
      this.modal.isEdit = false
      this.form = { id: '', rating_dict_type: String(this.category || ''), rating_dict_label: '', rating_start_day: null, rating_end_day: null, rating_over_day: null }
      this.modal.visible = true
      // 如果字典已加载，立刻计算中文名；否则等待字典加载完成后由 fetchDictTypes 回填
      if ((this.dictTypeOptions || []).length > 0) {
        this.form.rating_dict_label = this.renderCategoryLabel(this.form.rating_dict_type)
      }
      this.$nextTick(() => { this.$refs.form && this.$refs.form.clearValidate() })
    },
    openEdit (row) {
      this.modal.isEdit = true
      this.form = {
        id: row.id || '',
        rating_dict_type: String(row.rating_dict_type || this.category || ''),
        rating_dict_label: row.rating_dict_label || this.renderCategoryLabel(String(row.rating_dict_type || this.category || '')),
        rating_start_day: Number(row.rating_start_day || 0) || null,
        rating_end_day: Number(row.rating_end_day || 0) || null,
        rating_over_day: Number(row.rating_over_day || 0) || null
      }
      this.modal.visible = true
      this.$nextTick(() => { this.$refs.form && this.$refs.form.clearValidate() })
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (!valid) return
        const start = Number(this.form.rating_start_day)
        const end = Number(this.form.rating_end_day)
        if (end < start) {
          this.$Message.error('结束循环天不能小于开始循环天')
          return
        }
        this.modal.submitting = true
        const payload = {
          rating_dict_type: String(this.form.rating_dict_type || this.category || ''),
          rating_start_day: String(this.form.rating_start_day || ''),
          rating_end_day: String(this.form.rating_end_day || ''),
          rating_over_day: String(this.form.rating_over_day || '')
        }
        saveRatingDay(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-day-wrap { padding: 10px; }
.toolbar { margin-bottom: 10px; }
</style>
