<template>
  <div class="c-search-panel">
    <template v-if="panelWrapped">
      <c-panel :title="title">
        <template #extra>
          <span v-if="isSaveQueryFlag" class="save-search" @click="saveQuery">{{
            isSaveQuery ? "取消保存查询条件" : "保存查询条件"
          }}</span>
          <c-button type="default" style="margin-right: 10px" @click="reset">{{
            $cyt("重置")
          }}</c-button>
          <c-button type="primary" @click="query">{{ $cyt("查询") }}</c-button>
        </template>

        <c-dynamic-form
          ref="dynamicFormRef"
          :form-schema="formSchema"
          @keyup.enter.native="query"
        >
          <template
            v-for="item in Object.keys($slots)"
            #[item]="data"
            :key="item"
          >
            <slot :name="item" v-bind="data || {}"></slot>
          </template>
        </c-dynamic-form>
        <div class="search-submitButtons">
          <template
            v-if="(fields || []).length > 0 && calcTotalRows > defaultShowRows"
          >
            <a @click="toggleAdvanced">
              {{ state.advanced ? $cyt("收起") : $cyt("展开") }}
              <DownOutlined
                :style="`transform: rotate(${turn})`"
                class="collapse-icon"
              />
            </a>
          </template>
        </div>
      </c-panel>
    </template>
    <template v-else>
      <Space direction="vertical">
        <div class="action-group">
          <Space>
            <c-button
              type="default"
              style="margin-right: 10px"
              @click="reset"
              >{{ $cyt("重置") }}</c-button
            >
            <c-button type="primary" @click="query">{{
              $cyt("查询")
            }}</c-button>
          </Space>
        </div>
        <c-dynamic-form
          ref="dynamicFormRef"
          :form-schema="formSchema"
          @keyup.enter.native="query"
        >
          <template
            v-for="item in Object.keys($slots)"
            #[item]="data"
            :key="item"
          >
            <slot :name="item" v-bind="data || {}"></slot>
          </template>
        </c-dynamic-form>
        <div class="search-submitButtons">
          <template
            v-if="(fields || []).length > 0 && calcTotalRows > defaultShowRows"
          >
            <a @click="toggleAdvanced">
              {{ state.advanced ? $cyt("收起") : $cyt("展开") }}
              <DownOutlined
                :style="`transform: rotate(${turn})`"
                class="collapse-icon"
              />
            </a>
          </template>
        </div>
      </Space>
    </template>
  </div>
</template>

<script lang="ts">
export default {
  name: "c-search-panel",
};
</script>

<script setup lang="ts">
import { reactive, computed, ref, PropType } from "vue";
import { Space } from "ant-design-vue";
import { DownOutlined } from "@ant-design/icons-vue";
import type { FormItemSchema } from "../../CDynamicForm";
import CDynamicForm from "../../CDynamicForm/schema-form.vue";
// import { schemas } from "../../../examples/views/dynamicForm/form-config";
import { FormSchema } from "../../CDynamicForm";

const props = defineProps({
  title: {
    type: String,
    default: "查询面板",
  },
  /**
   * @deprecated 默认显示个数   一行 3 个元素  即 2 行
   *
   */
  defaultShowItems: {
    type: Number,
    default: 6,
  },
  /**
   * @description 默认显示行数
   */
  defaultShowRows: {
    type: Number,
    default: 2,
  },
  fields: {
    type: Array as PropType<FormItemSchema[]>,
  },
  /**
   * 是否外层使用面板包裹 默认是
   */
  panelWrapped: {
    type: Boolean,
    default: true,
  },
  /**
   * 是否启用保存 默认 否
   */
  isSaveQueryFlag: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits<{
  /**
   * @description 查询操作
   */
  (e: "query", param: any): void;
  (e: "reset"): void;
  (e: "saveQuery", param: any): void;
}>();

// const slots = useSlots();
const state = reactive({
  advanced: false,
});

const isSaveQuery = ref(false);

console.debug(props);
console.debug(props.fields);
const dynamicFormRef = ref(null);
/**
 * @description 展开/收起 图标旋转转数
 */
const turn = computed(() => `${state.advanced ? 0.5 : 0}turn`);

const formSchema = computed((): FormSchema => {
  return {
    rowProps: { gutter: 25 },
    schemas:
      !state.advanced && props.fields
        ? (props.fields as any).slice(0, calcDefaultRowsField.value)
        : props.fields,
    layout: "vertical",
    // labelWidth: 108,
    // labelAlign: "right",
    // labelCol: { style: "width:100px" },
  };
});

/**
 * @description 切换展开/收起 状态
 */
const toggleAdvanced = () => {
  state.advanced = !state.advanced;
};

const calcDefaultRowsField = computed(() => {
  let myRows: number = 1;
  let totalSpan: number = 24;
  let result: number = 0;
  for (let index = 0; index < (props.fields || []).length; index++) {
    const element = (props.fields as any)[index];
    const span = element.colProps?.span || 4;
    if (totalSpan < span) {
      myRows = myRows + 1;
      totalSpan = 24;
    }
    if (totalSpan <= 0) {
      myRows = myRows + 1;
      totalSpan = 24;
    }
    if (myRows > props.defaultShowRows) {
      result = index;
      break;
    }
    totalSpan = totalSpan - span;
  }
  if (result == 0) {
    result = props.fields?.length as any;
  }
  return result;
});

/**
 * 计算渲染后的总行数
 */
const calcTotalRows = computed(() => {
  let totalSpan: number = 0;
  if (props.fields && props.fields.length > 0) {
    // perSpan = props.fields[0].colProps?.span as number;
    props.fields.forEach((field) => {
      //如果没有指定 span 默认4
      const span: number = (field.colProps?.span as number) || 4;
      totalSpan = totalSpan + span;
    });
    return totalSpan / 24;
  } else {
    return 0;
  }
});
// const calcAdvancedItems = computed(() => {
//   let perSpan: number = 8;
//   if (props.fields && props.fields.length > 0) {
//     perSpan = props.fields[0].colProps?.span as number;
//   }
//   return props.defaultShowRows * (24 / perSpan);
// });

const reset = async () => {
  (dynamicFormRef.value as any).resetFields();
  emit("reset");
  // await query();
};
const query = async () => {
  const formModel = await (dynamicFormRef.value as any).validate();
  // console.log("queryParams", formModel);
  Object.keys(formModel).forEach((k) => {
    if (formModel[k] === undefined) {
      formModel[k] = null;
    }
  });
  emit("query", formModel);
};

const saveQuery = async () => {
  const formModel = isSaveQuery.value
    ? false
    : await (dynamicFormRef.value as any).validate();
  console.log("queryParams", formModel);
  console.log("isSaveQuery", isSaveQuery.value);

  Object.keys(formModel).forEach((k) => {
    if (formModel[k] === undefined) {
      formModel[k] = "";
    }
  });
  isSaveQuery.value = !isSaveQuery.value;
  emit("saveQuery", formModel);
};

/**
 * @description 用于更新form item 数据
 */
const updateSchema = (
  data: Partial<FormItemSchema> | Partial<FormItemSchema>[]
) => {
  (dynamicFormRef.value as any).updateSchema(data);
};
const setForm = (data) => {
  isSaveQuery.value = true;
  (dynamicFormRef.value as any).setFieldsValue(data);
};

const setFieldsValue = (data: any) => {
  (dynamicFormRef.value as any).setFieldsValue(data);
};

defineExpose({
  updateSchema,
  setForm,
  reset,
  setFieldsValue,
});
</script>

<style lang="less" scoped>
.c-search-panel {
  :deep(.ant-collapse-header) {
    // height: 56px;
  }
  .action-group {
    display: flex;
    justify-content: right;
  }

  .save-search {
    color: #0074ff;
    cursor: pointer;
    margin-right: 20px;
  }
  :deep(.ant-collapse-content-box) {
    padding: 16px;
  }
}
</style>
