<template>
  <sd-form ref="form" :key="updateKey" :init-values="initValues" :class="$style.statis">
    <template v-slot="{ model }">
      <a-row v-for="index in Math.ceil(dispValues.length / 2)" :key="index">
        <a-col v-for="i in [0, 1]" :key="i" :span="12">
          <!-- 搜索字段为待选项（单选、多选、下拉）都采用多选组件 -->
          <sd-form-item
            v-if="dispValues[(index - 1) * 2 + i]"
            :name="
              initValues[(index - 1) * 2 + i].dataType === 'number'
                ? initValues[(index - 1) * 2 + i].rangeName
                : initValues[(index - 1) * 2 + i].name
            "
            :component="
              initValues[(index - 1) * 2 + i].dataType === 'date'
                ? 'ARangePicker'
                : initValues[(index - 1) * 2 + i].statisType === 'group' ||
                  initValues[(index - 1) * 2 + i].statisType === 'merge'
                ? 'ASelect'
                : initValues[(index - 1) * 2 + i].statisType === 'chartType'
                ? 'ARadioGroup'
                : initValues[(index - 1) * 2 + i].dataType === 'selectlist'
                ? 'ACheckboxGroup'
                : undefined
            "
            :input-props="
              initValues[(index - 1) * 2 + i].dataType === 'selecttree'
                ? {
                    allowClear: true,
                    single: true,
                    allNodesSelectable: true,
                  }
                : {
                    allowClear: true,
                    single: true,
                  }
            "
            @change="fieldChange(initValues[(index - 1) * 2 + i].name)"
          >
            <template v-if="initValues[(index - 1) * 2 + i].statisType === 'group'">
              <div :class="$style['warp-group']">
                <ASelect
                  v-model="model.group"
                  :options="initValues[(index - 1) * 2 + i].attr.selectListItem"
                  allow-clear
                  :class="$style['group']"
                  @change="fieldChange(initValues[(index - 1) * 2 + i].name)"
                />
                <ARadioGroup
                  v-if="cateFieldType === 'date'"
                  v-model="model.dateGroupType"
                  :options="dateGroupOptions"
                  :class="$style['group-type']"
                />

                <sd-tree-level-select
                  v-if="cateFieldType === 'selecttree'"
                  v-model="groupTreeLevel"
                  :data-source="groupSelectTreeField.attr.selectTreeItem"
                  :class="$style['group-type']"
                >
                </sd-tree-level-select>
              </div>
            </template>
          </sd-form-item>
        </a-col>
      </a-row>
    </template>
  </sd-form>
</template>

<script>
import components from './_import-components/sd-statis-form-import'

const dateGroupOptions = [
  {
    label: '年',
    value: 'year',
  },
  // {
  //   label: '季度',
  //   value: 'quarter',
  // },
  {
    label: '月',
    value: 'month',
  },
  {
    label: '日',
    value: 'day',
  },
]
export default {
  name: 'SdStatisForm',
  metaInfo: {
    title: 'SdStatisForm',
  },
  components,
  props: {
    onlListColumnDefs: {
      type: Array,
      default: undefined,
    },
  },
  data() {
    return {
      updateKey: 0,
      cateFieldType: '',
      groupSelectTreeField: null,
      groupTreeLevel: '',
      dateGroupOptions,
    }
  },
  computed: {
    initValues() {
      let searchField = []
      const ranges = []
      searchField = this.onlListColumnDefs
        .filter((item) => {
          return item.isStatisWhere
        })
        .map((item) => {
          const dispName = item.fieldId.replace('.', '')
          if (item.attr && item.attr.displayExpr && item.attr.displayExpr !== '') {
            delete item.attr.displayExpr
          }
          if (item.attr && item.attr.defaultValue && item.attr.defaultValue !== '') {
            delete item.attr.defaultValue
          }
          if (item.fieldType === 'date' || item.fieldType === 'number') {
            ranges.push({
              name: dispName + '-Max',
              caption: item.fieldName,
              attr: item.attr,
              dataType: item.fieldType,
              rangeName: [dispName, dispName + '-Max'],
            })
          }

          let dataType = item.fieldType.replace(/selectgroup|selectuser/, 'selectperson')
          let selectionType = item.attr?.selectionType || ''
          if (item.fieldId === 'CREATOR_NAME') {
            // 内置字段创建人创建部门特殊处理下，改成选者器
            dataType = 'selectperson'
            selectionType = 'User'
          }
          if (item.fieldId === 'CREATE_DEPT_NAME') {
            dataType = 'selectperson'
            selectionType = 'Group'
          }

          const attrs = Object.assign(item.attr ? item.attr : {}, {
            selectionType,
          })
          if (item.fieldType === 'selectlist') {
            attrs.multiple = 'true'
          }
          return {
            name: dispName,
            realName: item.fieldId,
            attr: attrs,
            caption: item.fieldName,
            dataType: dataType,
            rangeName:
              item.fieldType === 'date' || item.fieldType === 'number'
                ? [dispName, dispName + '-Max']
                : item.fieldId,
          }
        })

      const groupField = this.onlListColumnDefs
        .filter((item) => {
          return item.isStatisGroup
        })
        .map((item) => {
          return {
            value: item.fieldId,
            label: item.fieldName,
          }
        })

      const mergeField = this.onlListColumnDefs
        .filter((item) => {
          return item.isStatisSum
        })
        .map((item) => {
          return {
            value: item.fieldId,
            label: item.fieldName,
          }
        })

      mergeField.push({
        value: 'count',
        label: '条目数',
      })

      searchField.push({
        statisType: 'group',
        name: 'group',
        required: true,
        attr: {
          selectListItem: groupField,
        },
        dataType: 'selectlist',
        caption: '统计分类',
      })

      searchField.push({
        statisType: 'merge',
        name: 'merge',
        attr: {
          selectListItem: mergeField,
        },
        required: true,
        dataType: 'selectlist',
        caption: '展示数据',
      })

      searchField.push({
        statisType: 'chartType',
        name: 'chartType',
        value: 'pie',
        attr: {
          selectListItem: [
            {
              value: 'bar',
              label: '柱图',
            },
            {
              value: 'line',
              label: '折线',
            },
            {
              value: 'pie',
              label: '饼图',
            },
          ],
        },
        dataType: 'selectlist',
        caption: '图表类型',
      })

      searchField.push({
        statisType: 'dateGroupType',
        name: 'dateGroupType',
        value: 'day',
        attr: {
          selectListItem: dateGroupOptions,
        },
        dataType: 'selectlist',
        caption: '日期类型',
      })

      return searchField.concat(ranges)
    },
    dispValues() {
      let searchField = []
      searchField = this.onlListColumnDefs.filter((item) => {
        return item.isStatisWhere
      })

      searchField.push({
        statisType: 'group',
        name: 'group',
        attr: {
          selectListItem: [],
        },
        dataType: 'selectlist',
        caption: '统计分类',
      })

      searchField.push({
        statisType: 'merge',
        name: 'merge',
        attr: {
          selectListItem: [],
        },
        dataType: 'selectlist',
        caption: '展示数据',
      })

      searchField.push({
        statisType: 'chartType',
        name: 'chartType',
        attr: {
          selectListItem: [
            {
              value: 'bar',
              label: '柱图',
            },
            {
              value: 'line',
              label: '折线',
            },
            {
              value: 'pie',
              label: '饼图',
            },
          ],
        },
        dataType: 'selectlist',
        caption: '图表类型',
      })

      return searchField
    },
    groupValues() {
      return this.onlListColumnDefs.filter((item) => {
        return item.isStatisGroup
      })
    },
  },
  watch: {
    initValues: function() {
      this.updateKey++
    },
  },
  methods: {
    getGroupSelectTreeData() {
      if (this.$refs.form) {
        const fieldsValue = this.$refs.form.getFieldsValue()

        const groupField = this.groupValues.find((item) => {
          return item.fieldId === fieldsValue.group
        })

        if (groupField) {
          this.groupSelectTreeField = groupField
        }
      }
    },
    showCateFieldType() {
      if (this.$refs.form) {
        const fieldsValue = this.$refs.form.getFieldsValue()

        const groupField = this.groupValues.find((item) => {
          return item.fieldId === fieldsValue.group
        })
        if (groupField) {
          return groupField.fieldType
        }
        return ''
      } else {
        return ''
      }
    },
    fieldChange(name) {
      if (name === 'chartType') {
        const fieldsValue = this.$refs.form.getFieldsValue()
        const curInput = this.getSearchInput()
        if (curInput.statis.aggregateColumns && curInput.statis.groupByColumns) {
          this.$emit('changeChartType', fieldsValue.chartType)
        }
      } else if (name === 'group') {
        this.cateFieldType = this.showCateFieldType()
        if (this.cateFieldType === 'selecttree') {
          this.getGroupSelectTreeData()
        }
      }
    },
    resetFields() {
      this.cateFieldType = ''
      this.$refs.form.resetFields()
    },
    validateFields() {
      return this.$refs.form.validateFields()
    },
    getSearchInput() {
      const t = []
      const groupColumn = {}
      let mergeColumns = []
      const fieldsValue = this.$refs.form.getFieldsValue()
      this.initValues.forEach((item, index) => {
        if (this.dispValues[index]) {
          if (
            item.statisType === 'merge' ||
            item.statisType === 'group' ||
            item.statisType === 'chartType' ||
            item.statisType === 'dateGroupType'
          ) {
            if (item.statisType === 'group') {
              groupColumn.title = item.attr.selectListItem.filter((option) => {
                return option.value === fieldsValue[item.name]
              })[0].label
              groupColumn.dataIndex = fieldsValue[item.name]
            }
            if (item.statisType === 'merge') {
              mergeColumns = item.attr.selectListItem.map((option) => {
                return {
                  title: option.label,
                  dataIndex: option.value,
                }
              })
            }
          } else {
            if (
              fieldsValue[item.name] !== null &&
              fieldsValue[item.name] !== undefined &&
              fieldsValue[item.name] !== ''
            ) {
              if (item.dataType === 'string' || item.dataType === 'title') {
                t.push({
                  dataType: 'str',
                  name: item.realName ? item.realName : item.name,
                  op: 'like',
                  stringValue: '%' + fieldsValue[item.name] + '%',
                })
              }
              if (item.dataType === 'selectlist' && fieldsValue[item.name].length !== 0) {
                t.push({
                  dataType: 'str',
                  name: item.realName ? item.realName : item.name,
                  op: 'in',
                  stringValues: fieldsValue[item.name],
                })
              }
              if (item.dataType === 'selecttree' && fieldsValue[item.name].length !== 0) {
                t.push({
                  dataType: 'str',
                  name: item.realName ? item.realName : item.name,
                  op: 'eq',
                  stringValue: fieldsValue[item.name][0],
                })
              }
              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.realName ? item.realName : item.name,
                  op: 'eq',
                  stringValue,
                })
              }
              if (item.dataType === 'date' && fieldsValue[item.name].length) {
                t.push({
                  dataType: 'long',
                  name: item.realName ? item.realName : 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.realName ? item.realName : item.name,
                  op: 'le',
                  longValue: new Date(
                    fieldsValue[item.name][1].format('YYYY-MM-DD') + ' 23:59:59'
                  ).valueOf(),
                })
              }
            }

            if (item.dataType === 'number' && !item.name.endsWith('-Max')) {
              if (
                fieldsValue[item.name] !== null &&
                fieldsValue[item.name] !== undefined &&
                fieldsValue[item.name] !== ''
              )
                t.push({
                  dataType: 'long',
                  name: item.realName ? item.realName : item.name,
                  op: 'ge',
                  longValue: fieldsValue[item.name],
                })
              if (
                fieldsValue[item.name + '-Max'] !== null &&
                fieldsValue[item.name + '-Max'] !== undefined &&
                fieldsValue[item.name + '-Max'] !== ''
              )
                t.push({
                  dataType: 'long',
                  name: item.realName ? item.realName : item.name,
                  op: 'le',
                  longValue: fieldsValue[item.name + '-Max'],
                })
            }
          }
        }
      })

      const groupFieldType = this.showCateFieldType()

      const params = {
        statis: {
          expressions: t,
          aggregateColumns: fieldsValue.merge,
          groupByColumns:
            fieldsValue.group + (groupFieldType !== 'date' ? '' : ':' + fieldsValue.dateGroupType),
        },
        groupField: fieldsValue.group,
        dataColumns: [groupColumn].concat(mergeColumns),
        chartType: fieldsValue.chartType,
      }

      if (
        groupFieldType === 'selecttree' &&
        this.groupTreeLevel !== null &&
        this.groupTreeLevel !== undefined &&
        this.groupTreeLevel !== ''
      ) {
        params.statis.attr = {
          selectTreeLevel: this.groupTreeLevel,
        }
      }

      return params
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.statis {
  // 由于直接使用的a-col配合sd-form-item做的表单布局，label与内容区域需要显示在一行，特此处理
  :global(.ant-form-item) {
    display: flex;
    margin-bottom: auto;
    :global(.ant-form-item-label) {
      width: auto;
    }
    :global(.ant-form-item-control-wrapper) {
      flex: 1;
      padding-right: 5%;
    }
  }
  .warp-group {
    display: flex;
    height: 40px;
    .group {
      align-self: center;
    }
    .group-type {
      display: flex;
      align-self: center;
      width: 50%;
      margin-left: 10px;
      div {
        width: 100%;
      }
    }
  }
}
</style>
