<template>
  <div :class="$style.wrapper">
    <div v-if="showBtn" :class="[$style.caption]">
      <span class="child-table-title">{{ label }}</span>
      <div v-if="!readOnly" :class="$style.header">
        <!-- <a-button 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
      :key="sequenceColumn"
      size="middle"
      :columns="_columns"
      :sortable="false"
      :data-source="value"
      :row-key="(record, index) => index"
      :pagination="flagpage ? pagination : false"
      :row-selection="
        readOnly || !showBtn
          ? 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 slot="index" slot-scope="text, record, index">
        {{ index + 1 }}
      </template>
      <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>
    <a-modal
      v-model="visible"
      :title="label || '预警指标反馈'"
      destroy-on-close
      v-bind="{ width: modalWidth }"
      :body-style="modalProps"
      :mask-closable="false"
      :footer="readOnly ? null : undefined"
      @ok="save"
      @cancel="attkeys[action] = Math.random()"
    >
      <sdForm ref="form" :init-values="editRecord" :read-only="readOnly">
        <template v-slot="scope">
          <!--
          @slot 详情表单内容,8.0.4及以后版本支持
          @binding {object} model 整个表单的数据，可用于 v-model 绑定
          @binding {object} fields 后台返回的字段定义
        -->
          <slot v-bind="scope" name="form">
            <sd-form-item
              v-for="field in fields"
              :key="field.name"
              :hidden="field.dataType === 'id'"
              :name="field.name"
            />
          </slot>
        </template>
      </sdForm>
    </a-modal>
  </div>
</template>

<script>
import axios from '@/common/services/axios-instance'
import sdChildTable from '@/common/components/sd-child-table/sd-child-table'
import components from './_import-components/kpi-alert-order-child-table-import'

/**
 * 主子表、动态表格字段
 * @displayName SdChildTable 主子表
 */
export default {
  name: 'KpiAlertOrderChildTable',
  components: {
    ...components,
    sdForm: () => import('@/common/components/sd-form'),
  },
  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,
    },
    // 子组件接收函数
    handleBeforeAdd: {
      type: Function,
    },
    flagpage: {
      type: Boolean,
      default: false,
    },
    pages: {
      type: Number,
      default: 10,
    },
    modalWidth: {
      type: String,
      default: '1200px',
    },
    /**
     * 传给详情 modal 的 props，可以用于设置样式等
     */
    modalProps: {
      type: Object,
      default: undefined,
    },
    // 是否可以编辑行
    editRow: {
      type: Boolean,
      default: false,
    },
    // 是否显示操作按钮
    showBtn: {
      type: Boolean,
      default: false,
    },
  },
  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: 'index',
          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() {
      if (this.handleBeforeAdd) {
        this.handleBeforeAdd(null, (res) => {
          if (!res) {
            this.addMethod()
          }
        })
      } else {
        this.addMethod()
      }
    },
    addMethod() {
      this.editRecord = this.fields
      this.action = 'add'
      const atts = this.editRecord.filter((item) => item.dataType === 'attachment')
      Promise.all(
        atts.map(() => {
          return axios('api/framework/v1/attachment-extend/attachments-create-group-code')
        })
      ).then((res) => {
        atts.forEach((att, index) => {
          att.value = JSON.stringify({
            value: res[index].data,
          })
        })
        this.visible = true
      })
    },
    edit(index) {
      if (!this.editRow) return
      this.editRecord = JSON.parse(JSON.stringify(this.fields))
      this.editRecord.forEach((item) => {
        // 把值放到字段信息fields里
        item.value = this.value[index][item.name]
      })
      this.visible = true
      this.action = index
      this.$emit('editchildrow', this.value[index])
    },
    save() {
      if (this.readOnly || !this.visible) {
        // 判断visable为false时，modal没有是为了防止快速重复点击确定
        this.visible = false
        return
      }
      this.$refs.form.validateFields().then(() => {
        const value = {}
        this.$refs.form.getBackendValues().forEach((item) => {
          value[item.name] = item.value
        })
        const data = this.value || [] // 兼容初始值是null的情况
        if (this.action === 'add') {
          // 新增
          data.push(value)
        }
        if (!isNaN(this.action)) {
          // 修改
          this.attkeys[this.action] = Math.random()
          data[this.action] = value
        }
        // 添加或修改之后，直接排序
        Object.assign(this.defaultValue, data)
        this.sorterFun(this.sorter)
        /**
         * 动态表格值变化时触发
         * @property {Object} data 子表的值
         */
        this.$emit('change', [...data])
        this.visible = false
      })
    },

    remove(keys) {
      // 用的序号作key，从大往小删，防止串了
      const removeKeys = keys.sort((a, b) => b - a)
      removeKeys.forEach((key) => {
        this.value.splice(key, 1)
      })
      this.selectedRowKeys = []
      this.$emit('change', this.value)
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
@use "@/common/components/sd-web-print.scss" as print;

.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;
      }
    }
  }
}

// 打印状态下 子表上选择列的按钮
@include print.wrapper-for-printer {
  .wrapper {
    :global(.ant-table-thead .anticon) {
      display: none;
    }
  }
}
</style>
