<template>
  <div class="c-modal-table">
    <Modal
      :destroyOnClose="true"
      v-bind="$attrs"
      :title="title"
      v-model:visible="visibleModel"
    >
      <Space direction="vertical" :size="6">
        <c-search-panel
          v-bind="$attrs"
          title="查找"
          ref="searchFormRef"
          @reset="handleReset"
          @query="handleSearch"
          v-if="showSearch"
        />
        <c-table
          :rowKey="rowKey"
          :row-selection="
            props.checkable
              ? {
                  type: checkType,
                  selectedRowKeys: selectedKeys,
                  onChange: onSelectTableChange,
                  getCheckboxProps: checkBoxProps,
                }
              : null
          "
          @change="(didTableChange as any)"
          :loading="tableLoading"
          :pagination="enablePage"
          :data-source="dataState.tableData"
          :panel-wrapped="false"
          :columns="columns"
          :cellActions="cellActions"
          :actions="actions"
          @didClickCell="didClickCell"
          @didClick="didClick"
        >
        </c-table>
      </Space>
      <template #footer>
        <a-button key="back" @click="() => (visibleModel = false)">{{
          $cyt("取消")
        }}</a-button>
        <a-button key="submit" type="primary" @click="save">{{
          $cyt("保存")
        }}</a-button>
      </template>
    </Modal>
  </div>
</template>

<script setup lang="ts">
import { useVModel } from "@vueuse/core";
import { Modal, Space } from "ant-design-vue";
import { PropType, computed, watch, ref } from "vue";
import {
  CTableColumn,
  useTable,
  CTableAction,
  CTableCellAction,
} from "../../CTable";

const emit = defineEmits<{
  (e: "save", params: any[]): void;
  (e: "search", param: any): void;
  (e: "didClickCell", param: CTableCellAction | any): void;
  (e: "didClick", action: CTableAction): void;
}>();

const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  checkType: {
    type: String as PropType<"radio" | "checkbox">,
    default: "checkbox",
    required: false,
  },
  /**
   * v-modelnpm
   */
  selectedKeys: {
    type: Array as PropType<string[] | number[]>,
    required: false,
  },
  /**
   * @description 弹出框title
   */
  title: {
    type: String,
    default: "",
  },
  /**
   * 表格字段配置
   */
  columns: {
    type: Array as PropType<CTableColumn[]>,
  },
  /**
   * @description 数据源
   */
  dataSource: {
    type: Array as PropType<any[]>,
    required: false,
  },
  /**
   * @description 表格数据提供
   */
  provider: {
    type: Object as PropType<Fn>,
    required: false,
  },

  checkBoxProps: {
    type: Object as PropType<Fn>,
    required: false,
  },

  /**
   * @description 是否分页
   */
  pagination: {
    type: Boolean,
    default: true,
  },

  fieldsNames: {
    type: Object,
    required: false,
  },
  rowKey: {
    type: String,
    default: "id",
  },
  showSearch: {
    type: Boolean,
    default: false,
  },

  /**
   * 只在  panelWrapped true 时候生效
   */
  actions: {
    type: Array as PropType<CTableAction[]>,
    required: false,
  },

  /**
   * 表格行 事件
   */
  cellActions: {
    type: Array as PropType<CTableCellAction[]>,
    required: false,
  },

  checkable: {
    type: Boolean,
    default: true,
    required: false,
  },
});

const searchFormRef = ref();

let allSelectedRows: Map<number, Array<any>> = new Map();

const visibleModel = useVModel(props, "show");
const selectedKeys = useVModel(props, "selectedKeys");
const selectedRows = ref<any[]>([]);
const onSelectTableChange = (values: string[] | number[], rows) => {
  console.debug("onSelectTableChange", values);
  selectedKeys.value = values;
  selectedRows.value = rows;
  console.debug("selectValues", selectedKeys.value, rows);
  allSelectedRows.set(pageConfig.current, rows);
  console.debug("selectValues", allSelectedRows);
};

/**
 * @description
 */
const {
  pagination: pageConfig,
  dataState,
  didTableChange,
  getTableData,
  loading: tableLoading,
} = useTable({
  request: props.provider,
  staticData: props.dataSource,
});
const enablePage = computed(() => (props.pagination ? pageConfig : false));

// const getAllSelectedRows = () => {
//   allSelectedRows.forEach((i, key) => {
//     selectedRows.value = selectedRows.value.concat(
//       allSelectedRows.get(key as any)
//     );
//   });
// };

const save = () => {
  // getAllSelectedRows();
  console.debug("selectedRows", selectedRows.value);
  emit("save", selectedRows.value || []);
};

/**
 * 打开时 触发请求
 */
watch(
  () => visibleModel.value,
  (newVal) => {
    if (newVal != undefined && newVal && props.provider) {
      getTableData(true);
    }
  }
);

/**
 * 搜索 重置参数
 */

const handleReset = () => {
  emit("search", {});
};

/**
 * 搜索 查询操作
 */

const handleSearch = (formModel) => {
  emit("search", formModel);
  getTableData(true, formModel);
};

/**
 * 搜索 表格赋值
 */

const setSearchForm = (formData) => {
  searchFormRef.value.setForm(formData);
};
/**
 * 刷新表格数据
 */
const reloadTable = () => {
  getTableData(true, {});
};

const didClickCell = ({ record, action, index }) => {
  emit("didClickCell", { record, action, index });
};

const didClick = (action: CTableAction) => {
  emit("didClick", action);
};

defineExpose({
  setSearchForm,
  reloadTable,
});
</script>

<style lang="less" scoped>
:deep(.ant-space) {
  width: 100%;
}

.c-search-panel {
  :deep(.ant-collapse-header .title) {
    font-size: 14px;
  }
  :deep(.c-collapse-panel .ant-collapse) {
    border-color: #d2d5e1 !important;
    .ant-collapse-item,
    .ant-collapse-content {
      border-color: #d2d5e1 !important;
    }
  }
  :deep(.ant-btn-primary) {
    background-color: #0074ff !important;
    border-color: #0074ff !important;
  }
}

:deep(.ant-col .ant-form-item-label label) {
  color: #222;
}
</style>
