<template>
  <Tooltip placement="top">
    <template #title>
      <span>{{ $t('component.table.batchQueryItem') }}</span>
    </template>
    <Popover placement="bottomLeft" trigger="click" v-model:visible="visible">
      <template #content>
        <!-- <Row>
          <Input style="width: 100px" size="small">查询字段</Input>
          <Input style="width: 100px" size="small">匹配方式</Input>
          <Input style="width: 100px" size="small">是否包含空值</Input>
          <Input style="width: 100px" size="small">操作</Input>
        </Row> -->
        <Row
v-for="(domain) in dynamicValidateForm.domains" :key="domain.Key" ref="formRef" name="dynamic_form_item"
          :model="dynamicValidateForm" v-bind="formItemLayoutWithOutLabel" layout="vertical" style="padding: 5px;">
          <Select
allowClear size="small" style="width: 100px" v-model:value="domain.Key" placeholder
            :options="ColOption">
          </Select>
          <Select
allowClear size="small" style="width: 100px;margin-left: 1px;" v-model:value="domain.MatchCase"
            placeholder :options="compareType">
          </Select>
          <Select
allowClear size="small" style="width: 100px;margin-left: 1px;" v-model:value="domain.Value"
            placeholder v-if="_isCombox(domain.Key)" :options="getOption(domain.Key)">
          </Select>
          <Select
allowClear size="small" style="width: 100px;margin-left: 1px;" v-model:value="domain.Value"
            placeholder v-else-if="_isCheckbox(domain.Key)" :options="getCheckOption()">
          </Select>
          <Input v-else style="width: 100px;margin-left: 1px;" v-model:value="domain.Value" size="small" />
          <!-- <Checkbox v-model:value="domain.IsNull" style="margin-left: 1px;" /> -->
          <MinusCircleOutlined
style="margin-top: 3px;margin-left: 1px;" v-if="dynamicValidateForm.domains.length > 1"
            class="dynamic-delete-button" :disabled="dynamicValidateForm.domains.length === 1"
            @click="removeDomain(domain)" />
          <!-- </Row>
          </FormItem> -->
        </Row>
        <Row style="padding: 5px;">
          <Select
style="width:100%" allowClear size="small" v-model:value="currentSelect"
            :placeholder="$t('component.table.selectColInfo')" @change="handleChooseChange" :options="ColOption">
          </Select>
        </Row>
        <Row style="padding: 5px;text-align: right;">
          <Button size="small" @click="handleConfirm" style="float: right;">{{ $t('component.table.confirm') }}</Button>
          <Button size="small" @click="handleReset" style="float: right;">{{ $t('common.resetText') }}</Button>
          <Button size="small" @click="handleCancel" style="float: right;">{{ $t('component.table.cancel') }}</Button>
        </Row>
      </template>
      <i class="icon icon-search" :style="showColor"></i>
    </Popover>
  </Tooltip>
</template>

<script lang="ts" setup>
import { Tooltip, Popover, Select, Input, Row,Button } from "ant-design-vue"
import { computed, ref, onMounted, reactive, nextTick } from "vue"
import { cloneDeep } from 'lodash-es';
import { useTableContext } from '../../hooks/useTableContext'
import type { TableColumn } from '../../types/column';
import { formatAutoCols } from "../../hooks/commonMethods"
import { isObject } from "../../../../../utils/is";
import { type cloumnFilterItem } from "../../dynamic-table"
import { i18n } from "../../../../../locales/index"
import type { optionItem } from "../../types/table"


const emit = defineEmits(["complex-query"])

type TableColumnType<T = any> = TableColumn<T> & {
  /** 目的是解决：类型实例化过深，且可能无限 */
  formItemProps?: any;
};
type fieldOptionType = {
  label: string,
  value: string
}
//查询参数的匹配方式
const compareType = [
  {
    label: "模糊查询",
    value: "Like"
  },
  {
    label: "相等",
    value: "Equal"
  },
  {
    label: "In",
    value: "In"
  },
  {
    label: "小于",
    value: "LessThan"
  },
  {
    label: "不小于",
    value: "NotLessThan"
  },
  {
    label: "大于",
    value: "MoreThan"
  },
  {
    label: "不大于",
    value: "NotMoreThan"
  },
  {
    label: "NotIn",
    value: "NotIn"
  },
  {
    label: "介于之间",
    value: "BetWeen"
  },
  {
    label: "介于之间",
    value: "BetWeen"
  },
  {
    label: "不等于",
    value: "NotEqual"
  },

]

const dynamicValidateForm = reactive<{ domains: optionItem[] }>({
  domains: [],
});

const formItemLayoutWithOutLabel = {
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 20, offset: 4 },
  },
};
const table = useTableContext();
const defaultColumns = cloneDeep<TableColumnType[]>(table.columns.length > 0 ? table.columns : formatAutoCols(table, emit));

const visible = ref<boolean>(false);
const currentSelect = ref<string>("");

const ColOption = computed(() => {
  let tempArray = [] as fieldOptionType[]
  for (let i = 0; i < defaultColumns.length; i++) {
    let temp = {
      label: defaultColumns[i].title,
      value: defaultColumns[i].dataIndex
    }
    let copy = {} as fieldOptionType
    Object.assign(copy, temp);
    tempArray.push(copy)
  }
  return tempArray
})

const showColor = computed(() => {
  if (dynamicValidateForm.domains.length > 0) {
    return { color: '#555555' }

  } return {
    color: '#555555'
  }
})

const removeDomain = function (domain) {
  //移除相关选项
  let index = $.inArray(domain, dynamicValidateForm.domains)
  if (index == -1) {
    //如果为-1的话，表示没有找到
    return
  }
  dynamicValidateForm.domains.splice(index, 1)
}

const handleChooseChange = function (value) {
  console.log(value)
  let temp = {} as optionItem
  temp.Key = value
  temp.MatchCase = "Like"
  temp.Value = ""
  temp.IsNull = false
  dynamicValidateForm.domains.push(temp)
  currentSelect.value = "" //查询条件生成之后，需要清空选项
}
const initQueryData = function () {
  //将模糊查询数据初始化出来，作为基础数据查询
  dynamicValidateForm.domains = []
  for (let i = 0; i < table.columnFilter.length; i++) {
    let temp = {} as optionItem
    if (typeof table.columnFilter[i] == "string") {
      temp = {
        Value: "",
        Key: table.columnFilter[i] as string,
        MatchCase: "Like",
        IsNull: false
      }
      let copy = {} as optionItem
      Object.assign(copy, temp)
      dynamicValidateForm.domains.push(copy)
    } else if (isObject(table.columnFilter[i])) {
      temp = {
        Value: "",
        Key: (table.columnFilter[i] as cloumnFilterItem).prop as string,
        MatchCase: ((table.columnFilter[i] as cloumnFilterItem).type as string).toLowerCase() != "checkbox" || ((table.columnFilter[i] as cloumnFilterItem).type as string).toLowerCase() != "combox" ? "Equal" : "Like",
        IsNull: false
      }
      let copy = {} as optionItem
      Object.assign(copy, temp)
      dynamicValidateForm.domains.push(copy)
    }
  }
}

//检查是否下拉框
const _isCombox = function (prop) {
  for (var i in table.columnFilter) {
    var filter = table.columnFilter[i];
    if (typeof filter == 'object') {
      if (filter.prop && filter.prop == prop)
        if (filter.type && filter.type.toLocaleLowerCase() == "combox" && typeof filter.options != 'undefined') return true;
    }
  }
  return false;
}
const _isCheckbox = function (prop) {
  for (var i in table.columnFilter) {
    var filter = table.columnFilter[i];
    if (typeof filter == 'object') {
      if (filter.prop && filter.prop == prop)
        if (filter.type && filter.type.toLocaleLowerCase() == "checkbox") return true;
    }
  }
  return false;
}
const getOption = function (field) {
  for (let i in table.columnFilter) {
    var filter = table.columnFilter[i];
    if (typeof filter == 'object') {
      if (filter.prop == field) {
        return filter.options
      }
    }
  }
  return []
}

const getCheckOption = function () {
  const { t } = i18n.global
  return [
    {
      value: null,
      label: t("component.table.allLabel"),
    },
    {
      value: true,
      label: t("component.table.YesLabel"),
    },
    {
      value: false,
      label: t("component.table.NoLabel"),
    },
  ]
}

const handleConfirm = function () {
  visible.value = false
  emit("complex-query", dynamicValidateForm.domains);
}

const handleReset = function () {
  initQueryData() //重置查询条件
  nextTick(() => {
    emit("complex-query", dynamicValidateForm.domains);
  })

}

const handleCancel = function () {
  visible.value = false
}

onMounted(() => {
  initQueryData()
})


</script>