<template>
  <div>
    <div :class="$style.wrapper">
      <div :class="$style.btnselect">
        <a-button type="link" :class="$style.batchselect" @click="addNewform">
          <a-icon type="plus-circle" :theme="'filled'" />
          添加
        </a-button>
        <a-button type="link" :class="$style.batchselect" @click="deleteRow">
          <a-icon type="minus-circle" :theme="'filled'" />
          删除
        </a-button>
      </div>
    </div>
    <xm-child-table
      ref="xmformchildtable"
      v-bind="$attrs"
      :label="labelCompute"
      :columns="columns"
      :addbuttonvisiable="false"
      :deletebuttonvisiable="false"
      v-on="$listeners"
    >
      <template v-slot:form>
        <span />
        <component
          :is="builder"
          :form-data="{
            attrFD: $attrs.childAttrFD || { columns: 1 },
            pageFieldInfos: $attrs.fields,
          }"
        />
      </template>
      <template
        v-for="field in items.filter((item) => item.componentForDisplay)"
        v-slot:[field.name]="{ text }"
      >
        <component
          :is="field.componentForDisplay"
          :key="field.name"
          :value="text"
          :read-only="true"
        />
      </template>
    </xm-child-table>
  </div>
</template>

<script>
import axios from '@/common/services/axios-instance'
import asyncComponent from '@/common/services/async-component'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import { message } from 'ant-design-vue'
import runtimeUtil from '../../../src/form-designer/runtime-util'
import XmChildTable from '../../../src_product/iam/components/xm-child-table.vue'
import components from './_import-components/xm-formchildtable-render-import'

const XmFormchildtableRender = {
  name: 'XmFormchildtableRender',
  components: {
    ...components,
    // 自动导入的是当前目录的child-table
    [XmChildTable.name]: XmChildTable,
  },
  inheritAttrs: false,
  model: {
    prop: 'value',
    event: 'change',
  },
  props: {
    label: {
      type: String,
      default: '',
    },
    hideCaption: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      builder: asyncComponent(() =>
        import(
          /* webpackChunkName: "sd-form-by-builder" */ '@/common/components/sd-form-by-builder.vue'
        )
      ),
    }
  },
  computed: {
    items() {
      if (this.$attrs.fields.length === 0) return []
      const results = runtimeUtil
        .getTableInfo(this.$attrs.fields, { columns: 1 })
        .map((tr) => tr[0])
      return results
    },
    columns() {
      return this.$attrs.fields
        .filter((item) => item.attrFD.hidden)
        .map((item) => {
          return {
            dataIndex: item.name,
            sdHidden: true,
          }
        })
        .concat(this.$attrs.columns || [])
    },
    labelCompute() {
      return this.hideCaption ? null : this.label
    },
  },
  inject: {
    SdFormContext: { default: () => {} },
  },
  methods: {
    // 添加行
    addNewform() {
      const url = '/sd-webform?pageId=' + this.$attrs.pageId + '&' + this.$attrs.urlQuery // 新建表单链接
      crossWindowWatcher.waitForChanged(url).then((res) => {
        if (res && res.pageFormData?.pageFieldInfos) {
          const tempJson = {}
          const id = res.pageFormData.pageFieldInfos.find((f) => {
            return f.name === 'id'
          })
          tempJson.id = id.value
          // 子表字段赋值
          this.$attrs.columns?.forEach((item) => {
            const tempc = res.pageFormData.pageFieldInfos.find((f) => {
              return f.name === item.dataIndex
            })
            tempJson[item.dataIndex] = tempc.value
          })
          // 子表追加值
          let tempArr = []
          if (this.SdFormContext.model[this.$attrs.fieldName]) {
            tempArr = [...this.SdFormContext.model[this.$attrs.fieldName]]
          }
          tempArr.push(tempJson)
          this.SdFormContext.model[this.$attrs.fieldName] = [...tempArr]
        }
      })
    },
    // 删除行
    deleteRow() {
      const keys = this.$refs.xmformchildtable.selectedRowKeys
      let ids = ''
      keys.forEach((i) => {
        if (ids === '') {
          ids = this.$attrs.value[i].id
        } else {
          ids = ids + ',' + this.$attrs.value[i].id
        }
      })
      if (ids !== '') {
        // 调用接口删除配置的formid对应库表数据
        const url = `api/framework/v1/page/${this.$attrs.formId}?ids=${ids}`
        this.delFormData(url)
          .then((res) => {
            if (res.status === 200) {
              // 用的序号作key，从大往小删，防止串了
              const removeKeys = keys.sort((a, b) => b - a)
              removeKeys.forEach((key) => {
                this.$attrs.value.splice(key, 1)
              })
              this.$refs.xmformchildtable.selectedRowKeys = []
              // 更新子表数据
              this.$refs.xmformchildtable.fnupdate(this.$attrs.value)
            }
          })
          .catch((e) => {
            message.error('删除失败，请联系管理员')
          })
      }
    },
    delFormData(url) {
      return axios.delete(url).then((res) => res)
    },
  },
}

// 默认导出：编辑模式的组件
export default XmFormchildtableRender
// forDisplay导出：只读模式的组件
export { XmFormchildtableRender as forDisplay }
</script>

<style module lang="scss">
@use '@/common/design' as *;
.btnselect {
  position: relative;
  top: 2px;
  float: right;
  .batchselect {
    z-index: 100;
    margin-left: 10px;
  }
}
</style>
