<template>
  <sd-advance-search v-if="initValues.length" @search="search" @reset="reset" @close="close">
    <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">
              <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 sdAdvanceSearch from '@/application-manage/sd-advance-search.vue'
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/xm-search-form-import'
export default {
  name: 'XmSearchForm',
  components: { sdRangeInput, sdAdvanceSearch, ...components },
  props: {
    onlListColumnDefs: {
      type: Array,
      default: undefined,
    },
  },
  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,
            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']
            } else {
              if (item.name.toLowerCase().indexOf('name') > -1) {
                // 创建人创建部门存的是就是名称字符串，这里特殊处理下
                stringValue = fieldsValue[item.name]?.[0]['name']
              } else if (item.name === 'startDept') {
                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: 'long',
              name: item.name,
              op: 'ge',
              longValue: Number(fieldsValue[item.name + 'min']),
            })
          }
          if (fieldsValue[item.name + 'max']) {
            t.push({
              dataType: 'long',
              name: item.name,
              op: 'le',
              longValue: Number(fieldsValue[item.name + 'max']),
            })
          }
        }
      })
      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')
    },
  },
}
</script>

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