<template>
  <div>
    <!--查询区域-->
    <div class="jeecg-basic-table-form-container" v-if="!props.isNoSearch">
      <a-form @keyup.enter.native="searchQuery" :model="queryParam" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row :gutter="24">
          <a-col :lg="8">
            <a-form-item label="开课单位">
              <!-- <a-input placeholder="请输入开课单位" v-model:value="queryParam.kkdw"></a-input> -->
              <j-dict-select-tag placeholder="请选择开课单位" v-model:value="queryParam.kkdw" dictCode="kc_kkdw_view,kkdw,id"/>
            </a-form-item>
          </a-col>
          <a-col :lg="8">
            <a-form-item label="星期">
              <j-dict-select-tag placeholder="请选择星期" v-model:value="queryParam.week" dictCode="week"/>
            </a-form-item>
          </a-col>
          <a-col :lg="8">
            <a-form-item label="节次">
              <j-dict-select-tag placeholder="请选择节次" v-model:value="queryParam.hh" dictCode="skjc"/>
            </a-form-item>
          </a-col>
          <a-col :lg="8">
            <a-form-item label="课程性质">
              <!-- <a-input placeholder="请输入课程性质" v-model:value="queryParam.kcxz"></a-input> -->
              <j-dict-select-tag v-model:value="queryParam.kcxz" dictCode="kcxz" placeholder="请选择课程性质"/>
            </a-form-item>
          </a-col>
          <a-col :lg="8">
            <a-form-item label="课程名称或教师名">
              <a-input placeholder="请输入课程名称或教师名" v-model:value="queryParam.searchInput"></a-input>
            </a-form-item>
          </a-col>
          <!-- <a-col :lg="8">
            <a-form-item label="授课教师">
              <a-input placeholder="请输入授课教师" v-model:value="queryParam.skjs"></a-input>
            </a-form-item>
          </a-col> -->
          <!--<template v-if="toggleSearchStatus">-->
          <!--</template>-->
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-col :lg="6">
                <a-button type="primary" preIcon="ant-design:search-outlined" @click="searchQuery">查询</a-button>
                <a-button type="primary" preIcon="ant-design:reload-outlined" @click="searchReset" style="margin-left: 8px">重置</a-button>
                <!--<a @click="toggleSearchStatus = !toggleSearchStatus" style="margin-left: 8px">
                  {{ toggleSearchStatus ? '收起' : '展开' }}
                  <Icon :icon="toggleSearchStatus ? 'ant-design:up-outlined' : 'ant-design:down-outlined'" />
                </a>-->
              </a-col>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <vxe-toolbar>
      <template #buttons>
        <a-button type="primary" class="pl1r" @click="handleAdd" preIcon="ant-design:plus-outlined" v-if="!props.isNoSearch"> 新增</a-button>
        <a-button type="primary" class="pl1r" @click="handleEdit" preIcon="ant-design:plus-outlined"> 修改</a-button>
        <a-button type="danger"  class="pl1r" @click="batchHandleDelete" preIcon="ant-design:delete-outlined">删除</a-button>
      </template>
    </vxe-toolbar>
    <JVxeTable
      ref="tableRef"
      row-number
      row-selection
      keep-source
      clickSelectRow
      bordered
      rowSelectionType="radio"
      :loading="loading"
      :dataSource="dataSource"
      :columns="columns"
      :pagination="pagination"
      style="margin-top: 8px"
      @page-change="handlePageChange"
      @value-change="valueChange"
      @select-row-change="selectRowChange"
    >
    </JVxeTable>

    <!-- 表单区域 -->
    <KcKechengbiaoModal ref="registerModal" @success="handleSuccess"></KcKechengbiaoModal>
    <!--引用表格-->
    <KcKetangbiaoList v-show="selectedRows[0]" :currentRowKey="selectedRows[0]"/>
  </div>
</template>

<script lang="ts" name="ktgl-kcKechengbiao" setup>
  import { ref, reactive, onMounted, watch } from 'vue';
  // import { BasicTable, useTable, TableAction } from '/@/components/Table';
  // import { useListPage } from '/@/ho   oks/system/useListPage';
  import { propTypes } from '/@/utils/propTypes';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { columns } from './KcKechengbiao.data';
  import { list, batchDelete, saveOrUpdate } from './KcKechengbiao.api';
  import KcKechengbiaoModal from './components/KcKechengbiaoModal.vue'
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import KcKetangbiaoList from './KcKetangbiaoList.vue'

  import { JVxeTableInstance } from '/@/components/jeecg/JVxeTable/types';
  import { filterObj } from '/@/utils/common/compUtils';

  //--------------------------------------变量区---------------------------------------------------------------------------

  const props = defineProps({
    searchParam: propTypes.object.def({}),
    isNoSearch: propTypes.bool.def(false)
  });

  const tableRef = ref<JVxeTableInstance>();
  const loading = ref(false);

  const selectedRows = ref([]);
  const selectedRowKeys = ref([]);

  const dataSource = ref<any[]>([]);
  const pagination = reactive({
    current: 1,
    pageSize: 5,
    pageSizeOptions: ['10', '20', '30', '100', '200'],
    total: 0,
  });

  const queryParam = ref<any>({ });
  const filterInfo = ref<any>({ xnxq: '2022-2023-2' });
  const registerModal = ref();

  const labelCol = reactive({ xs: { span: 24 }, sm: { span: 7 }, });
  const wrapperCol = reactive({ xs: { span: 24 }, sm: { span: 16 }, });

  const { createMessage } = useMessage();

  //--------------------------------------变量区END------------------------------------------------------------------------
  //--------------------------------------初始化---------------------------------------------------------------------------


  onMounted(() => {
    loadData(1);
  })

  watch(() => props.searchParam, async (newRow, oldRow) => {
    reload();
  });
  //--------------------------------------初始化END---------------------------------------------------------------------------
  //--------------------------------------与后台交互---------------------------------------------------------------------------
  function loadData(pageNo?){
    loading.value = true;
    if(pageNo == 1){
      pagination.current = 1;
    }
    //参数
    let { current, pageSize } = pagination;
    let param = { column: 'createTime', order: 'desc', pageNo: current, pageSize, ...queryParam.value, ...filterInfo.value, ...props.searchParam }
    list(filterObj(param)).then(res => {
      dataSource.value = res?.records??[];
      pagination.total = res?.total??0;
      //如果是隐藏模式，则直接选中
      if(props.isNoSearch){
        selectedRows.value = Array<never>(dataSource.value[0]);
        console.log('tableRef =>',tableRef);

      }

    }).finally(() => {
      // 这里是无论成功或失败都会执行的方法，在这里关闭loading
      loading.value = false;
    });
  }

  // 部分数据保存
  function saveByCell({ value, key, id }) {
    createMessage.loading({ content: `正在保存!`, key: '_save_fake_data', duration: 0, });
    const params = { id, };
    params[key] = value;
    return new Promise((resolve) => {
      saveOrUpdate(params ,true).then(res => {
        if (res.success) {
          createMessage.success({ content: `记录已保存`, key: '_save_fake_data', duration: 2, });
          resolve(true);
        } else {
          createMessage.error({ content: `保存失败：${res.message}`, key: '_save_fake_data', duration: 2, });
          resolve(false);
        }
      });
    });
  }
  //--------------------------------------与后台交互---------------------------------------------------------------------------
  //--------------------------------------表格功能事件---------------------------------------------------------------------------
  function selectRowChange({ selectedRows: rows, $table }) {
    if(rows && rows[0]){
      selectedRows.value = Array<never>(rows[0])
    }else{
      selectedRows.value = [];
    }
  }
  function handlePageChange(event) {
    // 重新赋值,分页
    pagination.current = event.current;
    pagination.pageSize = event.pageSize;
    //查询数据
    loadData();
  }
  function valueChange({ value, col, row }) {
    let key = col?.key
    let id = row?.id
    //异步改数据
    saveByCell({ value, key, id })
  }
  //--------------------------------------表格功能事件---------------------------------------------------------------------------
  //--------------------------------------按钮以及其他功能---------------------------------------------------------------------------

  /**
   * 查询
   */
   function searchQuery() {
    reload();
  }

  /**
   * 重置
   */
  function searchReset() {
    queryParam.value = {};
    selectedRowKeys.value = [];
    //刷新数据
    reload();
  }

  //刷新列表数据
  function reload() {
    loadData(1);
  }

  /**
   * 新增事件
   */
  function handleAdd() {
    registerModal.value.disableSubmit = false;
    registerModal.value.add();
  }

  /**
   * 编辑事件
   */
  function handleEdit() {
    let record = selectedRows.value[0];
    if(!record){
      createMessage.error('请您至少选择一条记录进行操作。');
      return;
    }
    registerModal.value.disableSubmit = false;
    registerModal.value.edit(record);
  }

  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    let record = selectedRows.value[0];
    if(!record){
      createMessage.error('请您至少选择一条记录进行操作。');
      return;
    }
    await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
  }

  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }

  //--------------------------------------按钮以及其他功能---------------------------------------------------------------------------

</script>

<style lang="less" scoped>
  .jeecg-basic-table-form-container {
    .table-page-search-submitButtons {
      display: block;
      margin-bottom: 24px;
      white-space: nowrap;
    }
    .query-group-cust{
      width: calc(50% - 15px);
      min-width: 100px !important;
    }
    .query-group-split-cust{
      width: 30px;
      display: inline-block;
      text-align: center
    }
  }
  .pl1r {
    margin-left: 1rem;
  }
</style>
