<template>
  <div :class="[$style.wrapper, $style.inlineWrapper]">
    <div :class="[$style.caption, !label && readOnly ? $style.hideCaption : '']">
      {{ label }}
      <div v-if="!readOnly" :class="$style.header">
        <a-space>
          <!-- <a-button
            v-if="value.length < max && !disableAd"
            :disabled="selectedRowKeys.length === 0"
            @click="duplicate(selectedRowKeys)"
          >
            复制
          </a-button> -->
          <a-dropdown-button
            v-if="allowImport && value.length < max"
            :trigger="['click']"
            placement="bottomRight"
          >
            <a-upload :before-upload="importFromExcel" accept=".xlsx,.xls"> Excel导入 </a-upload>
            <a-menu slot="overlay" :class="$style.menu">
              <a-menu-item @click="exportTemplate"> 导出模板 </a-menu-item>
            </a-menu>
          </a-dropdown-button>
          <a-button
            v-for="(btn, index) in headerButtons"
            :key="index"
            :disabled="btn.buttonType === 'batch' ? selectedRowKeys.length === 0 : false"
            :title="btn.buttonDesc"
            type="link"
            @click="buttonClick(btn)"
          >
            {{ btn.buttonName }}
          </a-button>
          <a-button
            v-if="!!multipleSelector"
            type="link"
            @click="() => pickerData(multipleSelector)"
          >
            <a-icon type="plus-circle" :theme="'filled'" />
            选择
          </a-button>
          <a-button v-if="value.length < max && !disableAd" type="link" @click="add">
            <a-icon type="plus-circle" :theme="'filled'" />
            新增
          </a-button>
          <a-button
            v-if="!disableAd"
            :disabled="selectedRowKeys.length === 0"
            type="link"
            @click="remove(selectedRowKeys)"
          >
            <a-icon type="minus-circle" :theme="'filled'" />
            删除
          </a-button>
        </a-space>
      </div>
    </div>
    <component
      :is="sdform"
      ref="form"
      :init-values="fields"
      :get-popup-container="null"
      :form-relations="formRelations"
    >
      <sd-table
        ref="table"
        :key="sequenceColumn"
        :class="$style.table"
        size="middle"
        :columns="_columns"
        :sortable="action === undefined"
        :data-source="value"
        :row-key="(record, index) => record.id"
        :pagination="false"
        :row-selection="
          readOnly
            ? null
            : {
                getCheckboxProps(record) {
                  return {
                    props: { disabled: !showSelection(record) },
                  }
                },
                selectedRowKeys: selectedRowKeys,
                onChange: onSelectChange,
              }
        "
        @update:data-source="emitValue"
      >
        <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">
          <slot v-if="record.id === action && !readOnly" :name="field.name">
            <sd-form-item :key="field.name" :name="field.name" :label="null" />
          </slot>
          <slot v-else :name="field.name + '-read'">
            {{ getDisplayVaule(field, text) }}
          </slot>
        </template>
        <template slot="operation" slot-scope="text, record">
          <div :class="$style.operation">
            <span v-if="action === record.id">
              <a @click.stop="save">保存</a>
              <a
                @click.stop="
                  () => {
                    //新增的行直接取消，则删掉该行
                    if (record.newTempData) {
                      remove([record.id])
                    }
                    action = undefined
                  }
                "
                >取消</a
              >
            </span>
            <span v-else>
              <a
                @click.stop="
                  () => {
                    save().then(() => edit(record.id))
                  }
                "
                >编辑</a
              >
            </span>
          </div>
        </template>
      </sd-table>
    </component>
    <component :is="actionComponent" ref="actionComponent" />
  </div>
</template>

<script>
import { message } from 'ant-design-vue'
import sdChildTable from './sd-child-table/sd-child-table'
import components from './_import-components/sd-child-table-inline-import'
import asyncComponent from '@/common/services/async-component'
/**
 * 主子表、动态表格字段,支持行内编辑，不支持附件富文本组件,用法同主子表,不支持行编辑扩展（v-slot:form）和行字段扩展（v-slot:[field]）
 * @since 021
 * @displayName SdChildTableInline 主子表
 */
export default {
  name: 'SdChildTableInline',
  components,
  mixins: [sdChildTable],
  data() {
    return {
      sdform: asyncComponent(() =>
        import(/* webpackChunkName: "sd-form" */ '@/common/components/sd-form.vue')
      ),
      action: undefined,
    }
  },
  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) => {
            return !['id', 'tinymce', 'attachment'].includes(item.dataType)
          })
          .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
          })
          .concat([
            {
              title: '操作',
              dataIndex: 'operation',
              width: '120px',
              scopedSlots: { customRender: 'operation' },
              sdHidden: this.readOnly,
            },
          ]),
      ].filter((item) => item.sdHidden !== true)
    },
  },
  methods: {
    add() {
      if (this.action !== undefined) {
        return message.warn('请保存编辑行，再执行此操作')
      }
      const value = {}
      this.fields.forEach((item) => {
        value[item.name] = item.attr?.defaultValue
        value.newTempData = true
      })
      value.id = 'fakeId_' + Math.random()
      this.value.push(value)
      this.edit(value.id)
    },
    edit(key) {
      this.action = key
      this.$nextTick(() => {
        this.fields.forEach((item) => {
          const value = this.value.find((item) => item.id === key)[item.name]
          this.$refs.form.setFieldValue(
            item.name,
            value
              ? this.$refs.form.fieldOptions[item.name]?.parseBackendValue?.(value) || value
              : value
          )
        })
      })
    },
    save() {
      if (this.action === undefined) return Promise.resolve()
      // 保存行内编辑的值
      return this.$refs.form.validateFields().then(() => {
        const value = {}
        this.$refs.form.getBackendValues().forEach((item) => {
          value[item.name] = item.value
        })
        const data = this.value.find((item) => item.id === this.action)
        value.newTempData = undefined
        Object.assign(data, value)
        this.emitValue(this.value)
        this.action = undefined
      })
    },
  },
}
</script>

<style module lang="scss" src="./sd-child-table/sd-child-table.scss"></style>
