<template>
  <div>
    <a-form-model-item>
      <a-button :class="$style.settingBtn" @click="show = true">字段设置</a-button>
      <sdHeader
        v-if="!inline"
        :value="checkedOptions"
        :columns="selectOptions"
        @change="settingColumn"
      />
      <a-button
        :class="$style.settingBtn"
        :disabled="!selectOptions.length"
        @click="defaultShow = true"
        >默认值设置</a-button
      >
    </a-form-model-item>
    <!-- <a-form-model-item
      v-if="!inline && component.attrFD.formItemProps.inputProps.modalProps"
      label="弹框宽度(px)"
    >
      <a-input-number
        v-model="component.attrFD.formItemProps.inputProps.modalProps.width"
        :min="0"
      />
    </a-form-model-item> -->
    <a-form-model-item label="新建表单pageId">
      <a-input v-model="component.attrFD.formItemProps.inputProps.pageId" />
    </a-form-model-item>
    <a-form-model-item label="列表查询formId">
      <a-input v-model="component.attrFD.formItemProps.inputProps.formId" />
    </a-form-model-item>
    <a-form-model-item label="新建URL参数">
      <a-input v-model="component.attrFD.formItemProps.inputProps.urlQuery" />
    </a-form-model-item>
    <a-form-model-item label="赋值字段名">
      <a-input v-model="component.attrFD.formItemProps.inputProps.fieldName" />
    </a-form-model-item>
    <!-- <a-form-model-item label="行数范围">
      <sd-range-input
        :max.sync="component.attr.maxLength"
        :min.sync="component.attr.minLength"
        disable-negative
      />
    </a-form-model-item> -->
    <a-modal
      v-model="show"
      :footer="null"
      destroy-on-close
      width="92%"
      :class="{ [$style.inline]: inline, [$style.modal]: true }"
    >
      <component :is="formDesinger" ref="designer" :value="editData" :show-form-props="false">
        <template v-slot:toolbar>
          <component :is="sdSwitchModebtn" v-if="!inline" />
          <a-button icon="save" type="link" @click="saveColumn">
            确定
          </a-button>
        </template>
      </component>
    </a-modal>
    <!-- <a-modal v-model="defaultShow" :width="800" destroy-on-close title="设置默认值" @ok="handleOk">
      <SdChildTable
        v-model="defaultValue"
        :label="component.caption"
        :columns="columns"
        :min="parseInt(component.attr.maxLength) || 0"
        :max="parseInt(component.attr.maxLength) || Infinity"
        :fields="component.attr.dync.filter((item) => !item.attrFD.hidden)"
        :sequence-column="component.attrFD.formItemProps.inputProps.sequenceColumn"
      >
      </SdChildTable>
    </a-modal> -->
    <a-form-model-item>
      <a-checkbox slot="label" v-model="component.attr.disableAd">
        禁用新建删除
      </a-checkbox>
    </a-form-model-item>
    <a-form-model-item>
      <a-checkbox slot="label" v-model="component.attrFD.formItemProps.inputProps.hideCaption">
        隐藏表头
      </a-checkbox>
    </a-form-model-item>
    <!-- <a-form-model-item>
      <a-checkbox slot="label" v-model="component.attrFD.formItemProps.inputProps.sequenceColumn">
        显示序号
      </a-checkbox>
    </a-form-model-item> -->
    <!-- <a-form-model-item>
      <a-checkbox slot="label" v-model="component.attrFD.formItemProps.inputProps.importable">
        Excel导入
        <a-tooltip title="子表只有文本、数字和单选类型的字段时支持导入">
          <a-icon type="question-circle-o" />
        </a-tooltip>
      </a-checkbox>
    </a-form-model-item> -->
  </div>
</template>

<script>
import asyncComponent from '@/common/services/async-component'
import XmChildTable from '../../../src_product/iam/components/xm-child-table.vue'
import sdHeader from '../../../src/form-designer/component-library/child-table/sd-header-config'
import components from './_import-components/xm-formchildtable-import'

export const metaInfo = {
  caption: '新建表单子表',
  component: {
    props: ['designerData'],
    render() {
      const columns = this.designerData.attr.dync
        .filter((item) => item.attrFD.hidden)
        .map((item) => {
          return {
            dataIndex: item.name,
            sdHidden: true,
          }
        })
        .concat(this.designerData.attrFD.formItemProps?.inputProps?.columns || [])
      const defaultValue = JSON.parse(this.designerData.attr?.defaultValue || '[]')
      return (
        <XmChildTable
          readOnly
          label={
            this.designerData.attrFD.formItemProps?.inputProps?.hideCaption
              ? null
              : this.designerData.caption
          }
          fields={this.designerData.attr.dync.filter((item) => !item.attrFD.hidden)}
          // sd-table不支持响应列动态变化，这里加个key强制动态渲染
          key={this.designerData.key}
          // sequenceColumn={this.designerData.attrFD.formItemProps?.inputProps?.sequenceColumn}
          columns={columns}
          value={defaultValue}
          addbuttonvisiable={false}
          class='formchildtable'
        />
      )
    },
  },
  icon: 'sd-list',
  order: 900,
  excludeFormTypes: [3],
  hiddenProps: ['hideLabel'],
}

export const fieldProps = {
  dataType: 'collection',
  attr: { dync: [], disableAd: false },
  attrFD: {
    columns: 4,
    hideLabel: true,
    formItemProps: {
      inputProps: {
        // sequenceColumn: false,
        importable: false,
        columns: [],
        hideCaption: false,
        modalProps: {},
        pageId: '',
        formId: '',
        urlQuery: '',
        fieldName: '',
      },
    },
  },

  key: 1,
}

export default {
  name: 'XmFormchildtable',
  components: { XmChildTable, ...components, sdHeader },
  props: {
    inline: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      show: false,
      defaultShow: false,
      formDesinger: asyncComponent(() =>
        import(
          /* webpackChunkName: "sd-form-designer" */ '../../../src/form-designer/sd-designer.vue'
        )
      ),
      sdSwitchModebtn: asyncComponent(() =>
        import(
          /* webpackChunkName: "sd-form-designer" */ '../../../src/form-designer/sd-switch-mode-btn.vue'
        )
      ),
    }
  },
  computed: {
    editData() {
      let attrFD = this.component?.attrFD.formItemProps?.inputProps?.childAttrFD
      if (attrFD) {
        attrFD.devMode = this.formProps.attrFD.devMode
      } else {
        attrFD = {
          columns: 1,
          theme: 'sd-default',
          type: this.inline ? 3 : 2,
          devMode: this.formProps.attrFD.devMode,
          layoutable: false,
        }
      }
      return {
        head: {
          tableTxt: '子表',
          tableName: 'form_' + Date.now(),
          tableType: 1, // 单表
          isDbSynch: this.formProps?.isDbSynch,
          attrFD,
        },
        fields: this.component?.attr?.dync || [],
      }
    },
    columns() {
      return this.component.attr.dync
        .filter((item) => item.attrFD.hidden)
        .map((item) => {
          return {
            dataIndex: item.name,
            sdHidden: true,
          }
        })
        .concat(this.component.attrFD.formItemProps?.inputProps?.columns || [])
    },
    defaultValue: {
      get() {
        return JSON.parse(this.component.attr?.defaultValue || '[]')
      },
      set(value) {
        this.$set(this.component.attr, 'defaultValue', JSON.stringify(value))
      },
    },
    selectOptions() {
      return this.component.attr.dync.filter(
        (item) => !item.attrFD.hidden && item.dataType !== 'collection'
      )
    },
    checkedOptions() {
      return this.component.attrFD.formItemProps.inputProps?.columns?.filter(
        (item) => !item.sdCandidate
      )
    },
  },
  created() {
    if (!this.component.attrFD.formItemProps.inputProps.modalProps) {
      this.component.attrFD.formItemProps.inputProps.modalProps = {}
    }
  },
  methods: {
    handleOk() {
      this.defaultShow = false
      this.component.key = this.component.key + 1
    },
    settingColumn(value) {
      const keys = [] // 设置的展示的列表
      const f = (arr) => {
        arr.forEach((a) => {
          a.dataIndex = a.name
          keys.push(a.name)
          if (a.children) f(a.children)
        })
      }
      f(value)
      // 其他的列设置成默认不展示
      const sdCandidateColumns = this.selectOptions
        .filter((item) => {
          return !keys.includes(item.name)
        })
        .map((item) => {
          return { sdCandidate: true, dataIndex: item.name }
        })
      // 设置子表列，包含树结构的情况
      this.$set(this.component.attrFD.formItemProps.inputProps, 'columns', [
        ...value,
        ...sdCandidateColumns,
      ])
      // dync排序按照列表的顺序排下
      const columnOrder = [...keys, ...sdCandidateColumns.map((item) => item.name)]
      this.component.attr.dync = this.component.attr.dync.sort((a, b) => {
        return columnOrder.indexOf(a.name) - columnOrder.indexOf(b.name)
      })
      this.component.key = this.component.key + 1
    },
    saveColumn() {
      this.$refs.designer.setComponentName(this.$refs.designer.selectedID)
      this.component.attr.dync = this.$refs.designer.getSaveData().fields
      this.component.attrFD.formItemProps.inputProps.childAttrFD = this.$refs.designer.getSaveData().head.attrFD
      this.updateColumns()
      this.show = false
    },
    updateColumns() {
      // 子表字段增减后，设置了列信息也同步修改
      const oldColumns = this.component.attrFD.formItemProps.inputProps.columns
      if (!oldColumns) {
        // 行内编辑，没有列设置
        this.component.key = this.component.key + 1
        return
      }
      let newColumns = this.component.attr.dync
      // 过滤掉被删除的字段
      const oldkeys = []
      const f = (columns) => {
        const c = columns.filter((item) => {
          const itemInew = newColumns.find((i) => i.name === item.dataIndex)
          if (itemInew) {
            oldkeys.push(item.dataIndex)
          }
          if (item.dataIndex.startsWith('auto') || itemInew) {
            return true
          }
        })
        columns.splice(0, 999)
        c.forEach((i) => columns.push(i))
        columns.forEach((column) => {
          if (column.children) f(column.children)
        })
      }
      f(oldColumns)
      // 找到新加的字段,追加到列设置里
      newColumns = newColumns
        .filter((i) => !oldkeys.includes(i.name))
        .map((m, index) => ({
          dataIndex: m.name,
          sdCandidate: index > 10 - oldkeys.length,
        }))
      this.component.attrFD.formItemProps.inputProps.columns = [
        ...oldColumns,
        ...newColumns,
      ].filter((item) => item.dataType !== 'collection')
      this.component.key = this.component.key + 1
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.modal {
  :global(.ant-modal) {
    // 覆盖style标签里面的样式
    /* stylelint-disable-next-line  */
    top: 0 !important;
  }
  :global(.ant-modal-body) {
    height: 100vh;
    max-height: 100vh;
    padding: 0;
  }
}
:global(.formchildtable) {
  :global(.caption_xm-child-table_product) {
    position: relative;
  }
}
.setting-btn {
  margin: 0 10px 10px 0;
}
.inline {
  :global(.ant-collapse-item:first-child) {
    display: none;
  }
}
.btnselect {
  position: relative;
  top: 2px;
  right: 80px;
  float: right;
  .batchselect {
    z-index: 100;
    margin-left: 10px;
  }
}
</style>
