<template>
  <sd-advance-search
    v-if="initValues.length"
    @search="search"
    @reset="reset"
    @close="close"
    :daochushow="daochushow"
    @fnexport="fnexport"
  >
    <component :is="sdform" ref="form" :init-values="initValues" :class="$style.form">
      <template v-slot="{ model }">
        <table>
          <sd-form-colgroup :columns="6" />
          <tr v-for="(row, index) in tableInfo" :key="index">
            <sd-form-item-td
              v-for="item in row"
              :key="item.name"
              v-bind="item"
              :input-props="{ allNodesSelectable: true, ...item.inputProps }"
            >
              <sdRangeInput
                v-if="item.dataType === 'number'"
                :max.sync="model[item.name + 'max']"
                :min.sync="model[item.name + 'min']"
              />
              <template v-if="item.attr.selectionType === 'GROUP'">
                <sd-group-picker
                  v-model="model[item.name]"
                  single
                  :class="item.attr.includeSub ? $style.dep : ''"
                />
                <a-checkbox v-if="item.attr.includeSub" v-model="model[item.name + 'includeSub']">
                  含子部门
                </a-checkbox>
              </template>
            </sd-form-item-td>
          </tr>
        </table>
      </template>
    </component>
  </sd-advance-search>
</template>

<script>
import sdRangeInput from '@/form-designer/sd-range-input'
import asyncComponent from '@/common/services/async-component'
import runtimeUtil from '@/form-designer/runtime-util'
import components from './_import-components/sd-search-form-import'
export default {
  name: 'SdSearchForm',
  components: { sdRangeInput, ...components },
  props: {
    onlListColumnDefs: {
      type: Array,
      default: undefined,
    },
    daochushow: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      sdform: asyncComponent(() =>
        import(/* webpackChunkName: "sd-form" */ '@/common/components/sd-form.vue')
      ),
      customFilterExpressions: [],
    }
  },
  computed: {
    initValues() {
      return this.onlListColumnDefs
        .filter((item) => {
          return item.search
        })
        .map((item) => {
          let dataType = item.fieldType.replace(/selectgroup|selectuser/, 'selectperson')
          let selectionType = item.fieldAttr?.selectionType || ''
          if (item.fieldId === 'CREATOR_NAME') {
            // 内置字段创建人创建部门特殊处理下，改成选者器
            dataType = 'selectperson'
            selectionType = 'User'
          }
          if (item.fieldId === 'CREATE_DEPT_NAME') {
            dataType = 'selectperson'
            selectionType = 'Group'
          }
          let component = runtimeUtil.getRender(item.fieldAttrFD?.cid)
          if (dataType === 'date') {
            component = 'ARangePicker'
          }
          if (component === 'a-checkbox-group') {
            // 不支持多选，弄成单选
            component = 'ARadioGroup'
          }
          if (component === 'a-textarea') {
            component = 'AInput'
          }
          return {
            name: item.fieldId.replace('.', ''),
            realname: item.fieldId,
            attr: {
              selectionType,
              selectListItem: item.fieldAttr?.selectListItem,
              selectTreeItem: item.fieldAttr?.selectTreeItem,
              showLevel: item.fieldAttr?.showLevel,
              includeSub: item.attrFD.includeSub,
            },
            caption: item.fieldName,
            dataType,
            inputProps: { allowClear: true, single: true },
            component,
          }
        })
    },
    tableInfo() {
      const rows = []
      this.initValues.forEach((item, index) => {
        // 整理成每行三列显示
        if (index % 3 === 0) {
          rows.push([item])
        } else {
          rows[rows.length - 1].push(item)
        }
      })
      return rows
    },
  },
  methods: {
    search() {
      const t = []
      const fieldsValue = this.$refs.form.getFieldsValue()
      this.initValues.forEach((item) => {
        if (fieldsValue[item.name]) {
          if (item.dataType === 'string' || item.dataType === 'title') {
            t.push({
              dataType: 'str',
              name: item.name,
              op: 'like',
              stringValue: '%' + fieldsValue[item.name] + '%',
            })
          }
          if (item.dataType === 'selectlist') {
            t.push({
              dataType: 'str',
              name: item.name,
              op: 'eq',
              stringValue: fieldsValue[item.name],
            })
          }
          if (item.dataType === 'selecttree' && fieldsValue[item.name].length) {
            t.push({
              dataType: 'str',
              name: item.name,
              op: 'eq',
              stringValue: fieldsValue[item.name].join(','),
            })
          }
          if (item.dataType === 'selectperson' && fieldsValue[item.name].length) {
            let stringValue = fieldsValue[item.name]?.[0]['code']
            if (['CREATE_DEPT_NAME', 'CREATOR_NAME'].includes(item.name)) {
              // 创建人创建部门存的是就是名称字符串，这里特殊处理下
              stringValue = fieldsValue[item.name]?.[0]['name']
            }
            t.push({
              dataType: 'str',
              name: item.name,
              op: 'eq',
              stringValue: `${
                fieldsValue[item.name + 'includeSub'] && item.attr.selectionType === 'GROUP'
                  ? '@includeSub@'
                  : ''
              }${stringValue}`,
            })
          }
          if (item.dataType === 'date' && fieldsValue[item.name].length) {
            t.push({
              dataType: 'long',
              name: item.name,
              op: 'ge',
              longValue: new Date(
                fieldsValue[item.name][0].format('YYYY-MM-DD') + ' 00:00:00'
              ).valueOf(),
            })
            t.push({
              dataType: 'long',
              name: item.name,
              op: 'le',
              longValue: new Date(
                fieldsValue[item.name][1].format('YYYY-MM-DD') + ' 23:59:59'
              ).valueOf(),
            })
          }
        }
        if (item.dataType === 'number') {
          if (fieldsValue[item.name + 'min']) {
            t.push({
              dataType: 'double',
              name: item.name,
              op: 'ge',
              doubleValue: Number(fieldsValue[item.name + 'min']),
            })
          }
          if (fieldsValue[item.name + 'max']) {
            t.push({
              dataType: 'double',
              name: item.name,
              op: 'le',
              doubleValue: Number(fieldsValue[item.name + 'max']),
            })
          }
        }
      })
      t.forEach((item) => {
        item.name = this.initValues.find((i) => i.name === item.name).realname
      })
      this.$emit('search', t)
    },
    reset() {
      for (const x in this.$refs.form.getFieldsValue()) {
        this.$refs.form.setFieldValue(x, undefined)
      }
      this.search()
    },
    close() {
      this.reset()
      this.$emit('close')
    },
    fnexport() {
      this.$emit('fnexport')
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.form table {
  table-layout: fixed;
}
.dep {
  width: calc(100% - 130px);
  margin-right: 10px;
}
</style>
