<template>
  <div :class="$style.wrapper">
    <div :class="[$style.caption]">
      <div v-if="!readOnly && deleteqx" :class="$style.header">
        <a-button
          type="link"
          :disabled="selectedRowKeys.length === 0"
          @click="remove(selectedRowKeys)"
          ><a-icon type="minus-circle" :theme="'filled'" />
          删除
        </a-button>
      </div>
    </div>
    <sd-table
      size="middle"
      :columns="_columns"
      sortable
      :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(record, index)
              },
            },
          }
        }
      "
      @update:data-source="($event) => $emit('change', $event)"
    >
      <template v-for="field in fields" :slot="'sd_' + field.name" slot-scope="text, record, index">
        <slot v-bind="{ field, text, record, index }" :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: 1200 }"
      :mask-closable="false"
      :footer="readOnly || !findinfoeditable ? 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 { Modal } from 'ant-design-vue'
import { getComponentSpec } from '@/common/components/sd-form'
import axios from '@/common/services/axios-instance'
import components from './_import-components/audit-rectchild-table-import'

/**
 * 主子表、动态表格字段
 * @displayName SdChildTable 主子表
 */
export default {
  name: 'AuditRectChildTable',
  components: {
    ...components,
    sdForm: () => import('@/common/components/sd-form'),
  },
  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,
    },
    rowclick: {
      type: Boolean,
      default: true,
    },
    fnrowclick: {
      type: Function,
      default: null,
    },
    findinfoeditable: {
      type: Boolean,
      default: true,
    },
    /** 删除权限 */
    deleteqx: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      selectedRowKeys: [],
      visible: false,
      editRecord: [], // 待修改或编辑的记录
      attkeys: {}, // 附件组件的key,行编辑了就修改对应的附件key,强制更新附件列表
      pageOption: {
        maxResults: 10,
      },
      cardIndex: null,
      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,
      }, // 分页属性
    }
  },
  computed: {
    _columns() {
      const fields = JSON.parse(JSON.stringify(this.fields))
      const obj = 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 === false)
      const newobj = []
      this.columns.forEach((item) => {
        const lso = obj.find((o) => o.dataIndex === item.dataIndex)
        if (lso !== undefined) {
          newobj.push(lso)
        }
      })
      return newobj
    },
  },
  mounted() {
    this.pagination.pageSize = this.pages
  },
  methods: {
    getDisplayVaule(field, text) {
      if (getComponentSpec(field).getDisplayValue) {
        if (typeof text !== 'undefined' && text !== null) {
          const value = getComponentSpec(field).parseBackendValue?.(text) || text
          return getComponentSpec(field).getDisplayValue(value)
        } else {
          return ''
        }
      }
      return text
    },
    add() {
      if (this.handleBeforeAdd) {
        this.handleBeforeAdd(null, (res) => {
          if (!res) {
            this.addMethod()
          }
        })
      } else {
        this.addMethod()
      }
    },
    addMethod() {
      this.editRecord = this.fields
      this.action = 'add'
      const att = this.editRecord.find((item) => item.dataType === 'attachment')
      if (att) {
        axios('api/xcoa-mobile/v1/attachment-extend/attachments-create-group-code').then((res) => {
          att.value = JSON.stringify({
            value: res.data,
          })
          this.visible = true
        })
      } else {
        this.visible = true
      }
    },
    edit(record, index) {
      if (this.fnrowclick) {
        this.fnrowclick(record)
      }
      if (!this.rowclick) {
        this.$emit('rowclick', record)
      } else {
        const indexNum = (this.pagination.current - 1) * this.pagination.pageSize + index
        this.editRecord = JSON.parse(JSON.stringify(this.fields))
        this.editRecord.forEach((item) => {
          // 把值放到字段信息fields里
          item.value = this.value[indexNum][item.name]
        })
        this.visible = true
        this.action = indexNum
      }
    },
    editlsfk(index, editable) {
      const indexNum = (this.pagination.current - 1) * this.pagination.pageSize + index
      this.editRecord = JSON.parse(JSON.stringify(this.fields))
      this.editRecord.forEach((item) => {
        // 把值放到字段信息fields里
        item.value = this.value[indexNum][item.name]
      })
      this.visible = true
      this.action = indexNum
    },
    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
        }
        /**
         * 动态表格值变化时触发
         * @property {Object} data 子表的值
         */
        this.$emit('change', [...data])
        this.visible = false
      })
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    remove(keys) {
      Modal.confirm({
        title: '确认删除所选中的数据吗？',
        okType: 'danger',
        onOk: () => {
          // 用的序号作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 "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: absolute;
  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;
      }
    }
  }
}

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