<template>
  <div>
    <a-row v-for="(c, index) in value" :key="index" type="flex" :gutter="[4, 0]">
      <!-- 目标表单字段 -->
      <a-col :span="8">
        <sd-field-picker
          v-model="c[destColumn]"
          :form-id="destFormId"
          :disabled-types="destDisabledTypes || disabledTypes"
          :type="c[srcColumn] && c[srcColumn][0] && c[srcColumn][0].type"
          :placeholder="destPlaceholder"
          @change="$emit('change', value)"
        />
      </a-col>
      <!-- op最初是=号，因op主要是用于后端sql拼接，改为sql可用的符号，显示时转换成=号 -->
      <a-col>{{ c.op === 'eq' ? '=' : c.op }}</a-col>
      <!-- 来源表单字段 -->
      <a-col :span="8">
        <sd-field-picker
          v-model="c[srcColumn]"
          :form-id="srcFormId"
          :child-table-name="srcChildTableName"
          :disabled-types="disabledTypes"
          :type="c[destColumn] && c[destColumn][0] && c[destColumn][0].type"
          :placeholder="srcPlaceholder"
          @change="$emit('change', value)"
        />
      </a-col>
      <a-col v-if="multiple">
        <a-button type="link" icon="plus-circle" @click="add" />
        <a-button type="link" icon="minus-circle" @click="remove(index)" />
      </a-col>
    </a-row>
  </div>
</template>

<script>
import components from './_import-components/sd-associate-conditions-import'

const newCondition = { destColumn: undefined, op: 'eq', srcColumn: undefined }
export default {
  name: 'SdAssociateConditions',
  components,
  model: {
    prop: 'value',
    event: 'change',
  },
  props: {
    // 条件
    value: {
      type: Array,
      default: () => [{ ...newCondition }],
    },
    // 目标表单id
    destFormId: {
      type: String,
      default: undefined,
    },
    // 来源表单id
    srcFormId: {
      type: String,
      default: undefined,
    },
    // 来源表单子表名
    srcChildTableName: {
      type: String,
      default: undefined,
    },
    // 目标字段
    destColumn: {
      type: String,
      default: 'destColumn',
    },
    // 来源字段
    srcColumn: {
      type: String,
      default: 'srcColumn',
    },
    // 禁用的字段类型
    disabledTypes: {
      type: Array,
      default: () => ['collection', 'attachment', 'OpinionView'],
    },
    // (目标字段)禁用的字段类型
    destDisabledTypes: {
      type: Array,
      default: undefined,
    },
    destPlaceholder: {
      type: String,
      default: '目标表单字段',
    },
    srcPlaceholder: {
      type: String,
      default: '当前表单字段',
    },
    multiple: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {}
  },
  methods: {
    add() {
      this.$emit('change', [...this.value, { ...newCondition }])
    },
    remove(index) {
      this.value.splice(index, 1)
      let data = [...this.value]
      // 最后一个也删了，默认添加一个空的
      if (data.length === 0) {
        data = [{ ...newCondition }]
      }
      this.$emit('change', data)
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
</style>
