<template>
  <div :class="$style.wrapper">
    <div :class="[$style.caption]">
      <div v-if="!readOnly" :class="$style.header">
        <a-button v-if="selectData" type="link" @click="select">
          <a-icon type="plus-circle" :theme="'filled'" />
          选择
        </a-button>
        <a-button v-if="addData" type="link" @click="add">
          <a-icon type="plus-circle" :theme="'filled'" />
          新增
        </a-button>
        <a-button
          type="link"
          :disabled="selectedRowKeys.length === 0"
          @click="remove(selectedRowKeys)"
        >
          <a-icon type="minus-circle" :theme="'filled'" />
          删除
        </a-button>
      </div>
    </div>
    <sd-table
      ref="childTable"
      :key="sequenceColumn"
      size="middle"
      :columns="_columns"
      :sortable="false"
      :data-source="value"
      :row-key="(record, index) => index"
      :pagination="flagpage ? pagination : false"
      :row-selection="
        readOnly
          ? null
          : {
              getCheckboxProps(record) {
                return {
                  props: { disabled: !showSelection(record) },
                }
              },
              selectedRowKeys: selectedRowKeys,
              onChange: onSelectChange,
            }
      "
      :custom-row="
        (record, index) => {
          return {
            on: {
              click: () => {
                edit(index)
              },
            },
          }
        }
      "
      @update:data-source="($event) => $emit('change', $event)"
      @change="onChange"
    >
      <template v-for="field in fields" :slot="'sd_' + field.name" slot-scope="text, record, index">
        <slot v-bind="{ field, text, record }" :name="field.name">
          <sd-attachment
            v-if="field.dataType === 'attachment'"
            :key="attkeys[index]"
            :group-id="JSON.parse(text).value"
            read-only
          />
          <sd-quill-reader v-else-if="field.dataType === 'tinymce'" :value="text" />
          <span v-else :key="field.name">
            {{ getDisplayVaule(field, text) }}
          </span>
        </slot>
      </template>
    </sd-table>
  </div>
</template>

<script>
import sdChildTable from '@/common/components/sd-child-table/sd-child-table'
import components from './_import-components/risk-identification-child-table-import'

/**
 * 主子表、动态表格字段
 * @displayName RiskIdentificationChildTable 主子表
 */
export default {
  name: 'RiskIdentificationChildTable',
  components: {
    ...components,
  },
  mixins: [sdChildTable],
  model: {
    prop: 'value',
    event: 'change',
  },
  props: {
    /**
     * 字表的值，{key:value}的格式
     */
    value: {
      type: Array,
      default: () => [],
    },
    /**
     * 字表的字段属性
     */
    fields: {
      type: Array,
      default: () => [],
    },
    /**
     * 是否只读
     */
    readOnly: {
      type: Boolean,
      default: false,
    },
    /**
     * 标签名
     */
    label: {
      type: String,
      default: '',
    },
    /**
     * 自定义子表列属性,如[{dataIndex:'shuxingmingzi15',width:'120px'}],8.0.4及以后版本支持
     */
    columns: {
      type: Array,
      default: () => [],
    },
    /**
     * 某行是否可选
     * @since 8.0.11
     */
    showSelection: {
      type: Function,
      default: () => true,
    },
    flagpage: {
      type: Boolean,
      default: false,
    },
    pages: {
      type: Number,
      default: 10,
    },
    // 是否显示选择按钮
    selectData: {
      type: Boolean,
      default: false,
    },
    // 是否显示新增按钮
    addData: {
      type: Boolean,
      default: false,
    },
    deletedIdentify: {
      type: Function,
      default: null,
    },
    type: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      editRecord: [], // 待修改或编辑的记录
      pagination: {
        current: 1,
        total: 0,
        showTotal: (total) => {
          return `总共 ${total} 条`
        },
        onChange: (page) => {
          this.pagination.current = page
          this.pageOption.startPosition = this.pageOption.maxResults * (page - 1)
          this.cardIndex = null
          this.updatedata(page)
        },
        pageSize: 10,
      }, // 分页属性
      sorter: null, // 排序属性
      defaultValue: [], // 默认数据
    }
  },
  computed: {
    _columns() {
      const fields = JSON.parse(JSON.stringify(this.fields))
      return [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '50px',
          scopedSlots: { customRender: 'index' },
          sdHidden: this.sequenceColumn !== true,
        },
        ...fields
          .filter((item) => item.dataType !== 'id')
          .map((item) => {
            const t = {
              dataIndex: item.name,
              key: item.name,
              title: item.caption,
              scopedSlots: { customRender: 'sd_' + item.name },
            }
            const column = this.columns.find((c) => c.dataIndex === item.name)
            if (column) Object.assign(t, column)
            return t
          }),
      ].filter((item) => item.sdHidden !== true)
    },
  },
  mounted() {
    // 默认排序，赋值有用
    Object.assign(this.defaultValue, this.value)
    this.pagination.pageSize = this.pages
    // 增加默认排序
    const defaultSorters = this.columns
      .filter((col) => col.defaultSortOrder)
      .map((col) => ({
        field: col.dataIndex,
        order: col.defaultSortOrder,
      }))
    // 排序方法
    if (defaultSorters.length > 0) {
      this.sorter = { ...defaultSorters[0] }
      this.sorterFun(defaultSorters[0], true)
    }
  },
  methods: {
    // 排序点击之后，重新排序
    onChange(pagination, filters, sorter) {
      this.sorter = { ...sorter }
      this.sorterFun(this.sorter)
    },
    // 排序方法
    sorterFun(sorts, isDefault) {
      if (!sorts) {
        // 如果没有sorts，说明是父组件调用，则增加默认值
        Object.assign(this.defaultValue, this.value)
        sorts = this.sorter
      }
      // 没有排序，则使用默认排序
      if (!sorts?.order) {
        while (this.value.length > 0) {
          this.value.splice(0, 1)
        }
        this.defaultValue.forEach((item) => {
          this.value.push(item)
        })
        return
      }
      const sortValue = this.value.sort((a, b) => {
        if (sorts.order === 'ascend') {
          // 升序
          if (a[sorts.field] + '' < b[sorts.field] + '') {
            return -1
          }
          if (a[sorts.field] + '' === b[sorts.field] + '') {
            return 0
          }
          if (a[sorts.field] + '' > b[sorts.field] + '') {
            return 1
          }
        } else {
          // 降序
          if (a[sorts.field] + '' < b[sorts.field] + '') {
            return 1
          }
          if (a[sorts.field] + '' === b[sorts.field] + '') {
            return 0
          }
          if (a[sorts.field] + '' > b[sorts.field] + '') {
            return -1
          }
        }
      })
      this.$set(this, 'value', sortValue)
    },
    add() {
      // 发布选择事件，外部组件完成逻辑
      this.$emit('add')
    },
    select() {
      // 发布新增事件，外部组件完成逻辑
      this.$emit('select')
    },
    edit(index) {
      // 没有功能
    },
    remove(keys) {
      // 用的序号作key，从大往小删，防止串了
      const removeKeys = keys.sort((a, b) => b - a)
      const valueid = []
      removeKeys.forEach((key) => {
        valueid.push(this.value[key].id)

        this.value.splice(key, 1)
      })
      this.selectedRowKeys = []
      this.$emit('change', this.value)
      this.deletedIdentify(valueid, this.type)
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;

.header {
  position: absolute;
  top: 0;
  right: 0;

  :global .ant-input-search {
    width: 200px;
  }

  :global .ant-btn {
    margin: 5px;
  }
}

.caption {
  // position: relative;
  position: absolute;
  top: -5px;
  width: 100%;
  min-height: 40px;
  margin: 3px 0;
  text-align: center;
}

.wrapper {
  :global(.ant-table-tbody) {
    .clickable-cell {
      color: $primary-color;
      cursor: pointer;

      &:hover {
        color: $primary-5;
      }

      &:active {
        color: $primary-7;
      }
    }
  }
}
</style>
