<template>
  <div class="contradiction-div">
    <Card>
      <Table border :loading="loading" :columns="columns" :data="rows">
        <template slot="action" slot-scope="{ row }">
          <Button type="primary" size="small" @click="openEdit(row)">修改</Button>
        </template>
      </Table>
    </Card>

    <Modal v-model="editModal.visible" title="配置可见部门类型" width="500">
      <Form :label-width="110">
        <FormItem label="按钮权限标识">
          <Input :value="editModal.form.rating_dict_value" disabled />
        </FormItem>
        <FormItem label="按钮权限名称">
          <Input :value="editModal.form.rating_dict_label" disabled />
        </FormItem>
        <FormItem label="可见部门类型">
          <Select v-model="editModal.form.office_values" multiple clearable filterable placeholder="请选择">
            <Option v-for="opt in officeTypeOptions" :key="opt.value" :value="opt.value">{{ opt.label }}</Option>
          </Select>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="editModal.visible=false">取消</Button>
        <Button type="primary" :loading="editModal.saving" @click="save">保存</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import { selectPageButtonPowerList, savePageButtonPower } from '@/api/key-person'
import { selectDictList } from '@/api/contradiction'

export default {
  name: 'key-person-power-index',
  data () {
    return {
      loading: false,
      rows: [],
      columns: [
        { title: '按钮权限标识', key: 'rating_dict_value', align: 'center', minWidth: 160 },
        { title: '按钮权限名称', key: 'rating_dict_label', align: 'center', minWidth: 200 },
        { title: '可见部门类型', key: 'office_labels', align: 'center', minWidth: 240, render: (h, { row }) => h('span', this.renderOfficeLabels(row)) },
        { title: '操作', slot: 'action', align: 'center', width: 120 }
      ],
      officeTypeOptions: [],
      editModal: {
        visible: false,
        saving: false,
        form: {
          rating_dict_value: '',
          rating_dict_label: '',
          office_values: []
        }
      }
    }
  },
  created () {
    this.loadOfficeDict()
    this.init()
  },
  methods: {
    init () {
      this.loading = true
      selectPageButtonPowerList({}).then((ret) => {
        if (ret && ret.data && ret.data.errcode === 0) {
          const list = ret.data.data || ret.data.results || ret.data || []
          const raw = Array.isArray(list) ? list : (list.results || [])
          this.rows = this.groupRowsByButton(raw)
        } else {
          this.rows = []
        }
      }).finally(() => { this.loading = false })
    },
    groupRowsByButton (list) {
      if (!Array.isArray(list)) return []
      const map = {}
      list.forEach(item => {
        const key = item.rating_dict_value || item.rating_visit_dict_value || item.dictValue || item.value
        if (!key) return
        if (!map[key]) {
          map[key] = {
            rating_dict_value: item.rating_dict_value || item.rating_visit_dict_value || key,
            rating_dict_label: item.rating_dict_label || item.dictLabel || item.label || '',
            office_values_set: new Set(),
            office_labels_set: new Set()
          }
        }
        const valuesStr = item.office_values || item.rating_visit_office_value || ''
        const labelsStr = item.office_labels || item.rating_visit_office || ''
        String(valuesStr).split(',').map(s => s.trim()).filter(Boolean).forEach(v => map[key].office_values_set.add(v))
        String(labelsStr).split(',').map(s => s.trim()).filter(Boolean).forEach(l => map[key].office_labels_set.add(l))
      })
      const rows = Object.values(map).map(it => ({
        rating_dict_value: it.rating_dict_value,
        rating_dict_label: it.rating_dict_label,
        office_values: Array.from(it.office_values_set).join(','),
        office_labels: Array.from(it.office_labels_set).join(',')
      }))
      rows.sort((a, b) => String(a.rating_dict_label).localeCompare(String(b.rating_dict_label)))
      return rows
    },
    loadOfficeDict () {
      // 字典：sys_type_office
      selectDictList({ type: 'sys_type_office' }).then((res) => {
        const list = (res && res.data && (res.data.data || res.data.results)) || []
        this.officeTypeOptions = (Array.isArray(list) ? list : (list.results || []))
          .map(it => ({ label: String(it.label || it.name || ''), value: String(it.value || it.dictValue || '') }))
          .filter(it => it.label && it.value)
      })
    },
    renderOfficeLabels (row) {
      const txt = row ? (row.office_labels || row.rating_visit_office || '') : ''
      return txt || '-'
    },
    openEdit (row) {
      const valuesStr = row ? (row.office_values || row.rating_visit_office_value || '') : ''
      const values = String(valuesStr).split(',').map(s => s.trim()).filter(Boolean)
      this.editModal.form = {
        rating_dict_value: row.rating_dict_value,
        rating_dict_label: row.rating_dict_label,
        office_values: values
      }
      this.editModal.visible = true
    },
    save () {
      const form = this.editModal.form
      const valueToLabel = {}
      this.officeTypeOptions.forEach(it => { valueToLabel[String(it.value)] = it.label })
      const values = Array.isArray(form.office_values) ? form.office_values : []
      const labels = values.map(v => valueToLabel[String(v)]).filter(Boolean)
      const payload = {
        rating_dict_value: form.rating_dict_value,
        rating_dict_label: form.rating_dict_label,
        rating_visit_office_value: values.join(','),
        rating_visit_office: labels.join(',')
      }
      this.editModal.saving = true
      savePageButtonPower(payload).then((ret) => {
        if (ret && ret.data && ret.data.errcode === 0) {
          this.$Notice.success({ title: '保存成功' })
          this.editModal.visible = false
          this.init()
        } else {
          const msg = (ret && ret.data && (ret.data.errmsg || ret.data.message)) || '保存失败'
          this.$Notice.error({ title: '保存失败', desc: msg })
        }
      }).finally(() => { this.editModal.saving = false })
    }
  }
}
</script>

<style scoped>
.contradiction-div { padding: 10px; }
</style>
