<template>
  <page-layout-list :no-padding="layoutNoPadding" :compact="layoutCompact">
    <template #filter v-if="withSearch">
      <cip-search-form v-model:model="searchFilter"
        v-model:defaultModel="defaultSearchModel"
        :field-list="searchFieldList"
        @search="search" />
    </template>
    <template #handle v-if="withHandle">
      <slot name="handle-buttons" :create-item="createItem" :get-item-list="getItemList"></slot>
      <template  v-if="withCreate">
        <cip-judge-privilege :privilege="permission.create">
          <cip-button button-type="create" @click="createItem(outParams)"></cip-button>
        </cip-judge-privilege>
      </template>
      <template v-if="batchDelete">
        <cip-judge-privilege :privilege="permission.batchDelete ?? permission.delete">
          <cip-button v-if="batchDelete" button-type="batchDelete" @click="deleteItemList(getSelectRows)"></cip-button>
        </cip-judge-privilege>
      </template>
    </template>
    <slot></slot>
<!--    从handle中去除 原因：withHandle false 将导致table内的 关于弹窗的按钮无法使用-->
    <cip-dialog v-model="itemDialog" :width="dialogWidth" :on-confirm="saveItem" :title="dialogTitle" :show-only="showOnly">
      <cip-form :label-width="formLabelWidth"
                v-model:model="item"
                :grid="formGrid"
                :label-suffix="formLabelSuffix"
                :show-only="showOnly"
                :field-list="saveFormFieldList"></cip-form>
      <template #footer="{confirm,loading,cancel}" v-if="$slots['dialog-handle']">
        <slot name="dialog-handle" v-bind="{confirm,loading,cancel}" :model="item" :get-item-list="getItemList"></slot>
      </template>
    </cip-dialog>
    <cip-table :data="itemList"
               :columns="tableColumns"
               ref="tableRef"
               size="small"
               :default-expand-all="defaultExpandAll"
               :row-key="tableRowKey"
               :tree-props="tableTreeProps"
               :offset="withIndex ? offset : undefined"
               :select-type="selectType"
               :selectable="tableSelectable"
               v-bind="tableAttrs"
               @sort="sortChange"
               v-loading="listLoading"
               :handlerWidth="tableHandleWidth"
               :withTableHandle="withTableHandle">
      <slot name="table-slots"></slot>
      <!--      <el-table-column label="操作" :width="tableHandleWidth" v-if="withTableHandle" fixed="right">-->
      <!--        <template #default="scope">-->
      <template #_handler="scope">
          <slot name="table-handle-prepend" v-bind="scope" :get-item-list="getItemList"></slot>
          <slot name="table-handle"
                v-bind="scope"
                :show-item="showItem"
                :delete-item="deleteItem"
                :edit-item="editItem"
                :get-item-list="getItemList">
            <cip-judge-privilege :privilege="permission.info">
              <cip-table-button @click="showItem(scope.row, fetchInfo)">查看</cip-table-button>
            </cip-judge-privilege>
            <cip-judge-privilege :privilege="permission.update">
              <cip-table-button @click="editItem(scope.row, fetchInfo)">修改</cip-table-button>
            </cip-judge-privilege>
            <template v-if="withTableDeleteButton &&(!judgeTableDeleteButtonFn || (judgeTableDeleteButtonFn && judgeTableDeleteButtonFn(scope)))" >
              <cip-judge-privilege :privilege="permission.delete">
                <cip-table-button type="danger" @click="deleteItem(scope.row)">删除</cip-table-button>
              </cip-judge-privilege>
            </template>
          </slot>
          <slot name="table-handle-append" v-bind="scope" :get-item-list="getItemList"></slot>
      </template>
    </cip-table>
    <!--        </template>-->
    <!--      </el-table-column>-->
    <template #pagination v-if="withPagination">
      <cip-pagination v-model:offset="offset"
                      v-model:limit="limit"
                      :total="total"
                      :current-page="currentPage"
                      :pageSizes="pageSizes"
                      @refresh="getItemList"></cip-pagination>
    </template>
  </page-layout-list>
</template>
<script>
import { computed, defineComponent, onActivated, ref } from 'vue'
import { ElLoading } from 'element-plus'
import PageLayoutList from '@cip/components/page-layout/list'
import CipSearchForm from '@cip/components/cip-search-form'
import CipForm from '@cip/components/cip-form'
import CipButton from '@cip/components/cip-button'
import CipDialog from '@cip/components/cip-dialog'
import CipTable from '@cip/components/cip-table'
import CipTableButton from '@cip/components/cip-table-button'
import CipPagination from '@cip/components/cip-pagination'
import CipJudgePrivilege from '@cip/components/cip-judge-privilege'
import { useCurd } from '@cip/hooks/use-curd'
import pageCurdProps from './props'
export default defineComponent({
  name: 'CipPageCurd',
  components: {
    PageLayoutList,
    CipSearchForm,
    CipPagination,
    CipTable,
    CipForm,
    CipButton,
    CipDialog,
    CipTableButton,
    CipJudgePrivilege
  },
  directives: {
    loading: ElLoading.directive
  },
  props: pageCurdProps,
  setup (props) {
    const tableRef = ref()
    const CURD = useCurd(props.entity, { ...props.curdFn, itemType: props.itemType })
    const { searchFilter, getItemList } = CURD
    const defaultSearchModel = ref({ ...props.outParams, ...props.defaultSearchFilter })
    searchFilter.value = { ...defaultSearchModel.value, ...searchFilter.value }
    // if (props.cache) {
    onActivated(() => {
      getItemList()
    })
    if (!props.autoSelected) { // 如果搜索中有autoSelect的字段则传true,避免请求两次数据不一致导致页面“跳动”
      getItemList()
    }
    // } else {
    // if (!props.autoSelected) { // 如果搜索中有autoSelect的字段则传true,避免请求两次数据不一致导致页面“跳动”
    //   getItemList()
    // }
    // }
    // 计算列表是否需要select
    const selectType = computed(() => {
      if (props.batchDelete) return 'checkbox'
      return props.tableSelectType
      // return undefined
    })

    const getSelectRows = () => { // 返回值 Ref<T[]>
      return tableRef.value.cipTableRef.value.store.states.selection
    }
    // 外层触发请求
    const getTableList = (item = {}) => {
      searchFilter.value = item
      getItemList()
    }
    const sortChange = ({ prop, order }) => {
      searchFilter.value = { ...searchFilter.value, ...{ orderBy: prop, orderAsc: order === 'ascending' } }
      getItemList()
    }

    const saveFormFieldList = computed(() => {
      if (props.updateFormFieldList) { // 如果存在updateFormFieldList则对当前进行判断
        return CURD.isUpdate.value ? props.updateFormFieldList : props.formFieldList
      } else {
        return props.formFieldList
      }
    })
    return {
      ...CURD,
      ...props.componentData, // 覆盖默认配置
      tableRef,
      saveFormFieldList,
      selectType,
      getSelectRows,
      getTableList,
      sortChange,
      defaultSearchModel
    }
  }
})
</script>
