<template>
  <a-card v-if="initValues.length">
    <sd-form v-show="!searchFold" 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">
              <sd-group-picker
                v-if="item.name === 'deptId'"
                v-model="model.deptId"
                :hierarchical="false"
                :root-node="rootNode"
                :single="true"
              />
              <sd-user-picker
                v-if="item.name === 'userId'"
                v-model="model.userId"
                :hierarchical="false"
                :root-node="rootNode"
                :single="true"
              />
            </sd-form-item-td>
            <td
              v-if="index === tableInfo.length - 1"
              align="right"
              :colspan="tableInfo.length === 3 ? 4 : 2"
              class="ant-form-item-label ant-form-item-label"
            >
              <a-space
                ><a-button v-show="!searchFold" type="primary" @click="search">查询</a-button>
                <a-button v-show="!searchFold" @click="reset">重置</a-button></a-space
              ></td
            >
          </tr>
        </table>
      </template>
    </sd-form>
    <a-space>
      <a-button type="link" :icon="searchFold ? 'down' : 'up'" @click="searchFold = !searchFold">
        {{ searchFold ? '展开' : '收起' }}
      </a-button>
    </a-space>
  </a-card>
</template>

<script>
import storeMixin from '@/common/store-mixin'
import components from './_import-components/sd-log-form-import'

export default {
  name: 'SdLogForm',
  components,
  mixins: [storeMixin],
  props: {
    initValues: {
      type: Array,
      default: () => {
        return []
      },
    },
  },
  data() {
    return {
      searchFold: false,
    }
  },
  computed: {
    rootNode() {
      const belongedOrgIds =
        this.userInfo?.belongedOrgIds || this.userInfo?.default.belongedOrgIds || []
      return {
        code:
          belongedOrgIds.length > 0
            ? belongedOrgIds[0].id
            : this.userInfo?.deptId || this.userInfo?.default.deptId,
        name: this.userInfo?.deptName || this.userInfo?.default.deptName,
      }
    },
    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() {
      let t = []
      const fieldsValue = this.$refs.form.getFieldsValue()
      this.initValues.forEach((item) => {
        if (fieldsValue[item.name]) {
          if (item.dataType === 'string' || item.dataType === 'title') {
            if (item.name === 'eventId') {
              const exp = fieldsValue[item.name]
              if (exp) {
                const ids = exp.split(',')
                const orList = []
                const andList = []
                for (let i = 0; i < ids.length; i++) {
                  const id = ids[i]
                  const minus = id.indexOf('-')
                  if (minus === -1) {
                    const n = parseInt(id)
                    if (isNaN(n)) {
                      // 忽略非法数字
                      continue
                    }
                    orList.push({
                      dataType: 'long',
                      name: 'eventId',
                      op: 'eq',
                      longValue: n,
                    })
                  } else if (minus === 0) {
                    const n = parseInt(id.substring(1))
                    if (isNaN(n)) {
                      // 忽略非法数字
                      continue
                    }
                    andList.push({
                      dataType: 'long',
                      name: 'eventId',
                      op: 'ne',
                      longValue: n,
                    })
                  } else {
                    const from = parseInt(id.substring(0, minus))
                    const to = parseInt(id.substring(minus + 1))
                    if (isNaN(from) || isNaN(to)) {
                      continue
                    }
                    orList.push({
                      type: 'group',
                      op: 'and',
                      expValue: [
                        {
                          name: 'eventId',
                          op: 'ge',
                          longValue: from,
                        },
                        {
                          name: 'eventId',
                          op: 'lt',
                          longValue: to,
                        },
                      ],
                    })
                  }
                }
                if (andList.length > 0) {
                  t = t.concat(andList)
                }
                if (orList.length > 0) {
                  if (orList.length === 1) {
                    t.push(orList[0])
                  } else {
                    t.push({
                      dataType: 'expressions',
                      type: 'group',
                      op: 'or',
                      expressionsValue: orList,
                    })
                  }
                }
              }
            } else {
              t.push({
                dataType: 'str',
                name: item.name,
                op: 'like',
                stringValue: '%' + fieldsValue[item.name] + '%',
              })
            }
          }
          if (item.dataType === 'selectperson' && fieldsValue[item.name].length === 1) {
            if (item.name === 'userId') {
              t.push({
                dataType: 'string',
                name: item.name,
                op: 'eq',
                stringValue: fieldsValue[item.name][0].code,
              })
            } else {
              t.push({
                dataType: 'long',
                name: item.name,
                op: 'eq',
                longValue: fieldsValue[item.name][0].code,
              })
            }
          }
          if (item.dataType === 'selectlist') {
            if (item.name === 'createdTime') {
              let now = new Date().getTime()
              if (fieldsValue[item.name] === '1h') {
                now = now - 3600 * 1000
              } else if (fieldsValue[item.name] === '12h') {
                now = now - 12 * 3600 * 1000
              } else if (fieldsValue[item.name] === '1d') {
                now = now - 24 * 3600 * 1000
              } else if (fieldsValue[item.name] === '7d') {
                now = now - 7 * 24 * 3600 * 1000
              } else if (fieldsValue[item.name] === '30d') {
                now = now - 30 * 24 * 3600 * 1000
              } else {
                now = null
              }
              if (now !== null) {
                t.push({
                  name: item.name,
                  op: 'ge',
                  dateTimeValue: new Date(now),
                })
              }
            } else {
              t.push({
                dataType: 'str',
                name: item.name,
                op: 'eq',
                stringValue: fieldsValue[item.name],
              })
            }
          }
        }
      })
      this.$emit('search', t)
    },
    reset() {
      for (const x in this.$refs.form.getFieldsValue()) {
        this.$refs.form.setFieldValue(x, undefined)
      }
      this.search()
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.form table {
  table-layout: fixed;
}
</style>
