<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="800" @ok="handleSubmit">
    <template #footer></template>
    <a-form :model="actModel">
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-item label="">
            <BasicTable @register="registerTable" @selection-change="handlerRowClick">
              <!-- update-begin-author:taoyan date:2022-5-25 for: VUEN-1112一对多 用户选择 未显示选择条数，及清空 -->
              <!--<template #tableTitle></template>-->
              <!-- update-end-author:taoyan date:2022-5-25 for: VUEN-1112一对多 用户选择 未显示选择条数，及清空 -->
              <template #action="{ record }">
                <TableAction :actions="getTableAction(record)" />
              </template>
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'collectionName'">
                  <JEllipsisFormat :isLink="true" :value="record.collectionName" :length="60" @click="goToCa(record)" />
                </template>
              </template>
            </BasicTable>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-item label="">
            <a-button type="primary" style="width: 100%" @click="newAddCollections">新增集合</a-button>
          </a-form-item>
        </a-col>
      </a-row>
      <StCaMainCollectionModal @register="registerModalNew" @success="handleSuccess" />
    </a-form>
  </BasicModal>
</template>
<script setup>
  import { computed, reactive, ref, toRaw, unref } from 'vue';
  import { useRouter } from 'vue-router';
  import { BasicModal, useModal, useModalInner } from '/@/components/Modal';
  import { BasicTable, TableAction } from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  import JEllipsisFormat from '/@/views/standardlib/components/JEllipsisFormat.vue';
  import { list } from '/@/views/standardlib/controlactivity/StCaMainCollection.api';
  import { joinCheck } from '/@/views/standardlib/controlactivity/StCaMainRelCollection.api';
  import StCaMainCollectionModal from '/@/views/standardlib/controlactivity/components/StCaMainCollectionModal.vue';
  const router = useRouter();
  const isUpdate = ref(true);
  const caNos = ref([]);
  const type = ref('');
  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter });
    caNos.value = data?.record['caNos'];
    type.value = data?.record['type'];
  });

  //设置标题
  const title = computed(() => (!unref(isUpdate) ? '选择活动集合' : '选择活动集合'));
  //表单提交事件
  async function handleSubmit(v) {
    try {
      //let values = await validate();
      setModalProps({ confirmLoading: true });
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
  const [registerModalNew, { openModal }] = useModal();
  const props = defineProps({});
  const emit = defineEmits(['success']);
  const actinfo = ref({});
  const columns = [
    {
      title: '集合名称',
      align: 'left',
      dataIndex: 'collectionName',
    },
    {
      title: '集合说明',
      align: 'left',
      dataIndex: 'collectionDesc',
    },
  ];
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: '',
      api: list,
      columns,
      canResize: false,
      useSearchForm: false,
      scroll: { x: false },
      //actionColumn: {ifShow: false},
      //clickToRowSelect: true,
      showIndexColumn: true,
      //  rowSelection: {
      //       hideSelectAll: true,
      //       onSelect: handlerChecked,
      //       onChange: handlerChange,
      //   },
      actionColumn: {
        width: 160,
      },
      showTableSetting: false,
      beforeFetch(params) {
        params = Object.assign(params, { column: 'updatedTime', order: 'desc' });
      },
    },
  });
  const [registerTable, { setProps, reload }, { rowSelection, selectedRowKeys }] = tableContext;

  function handleAdd() {
    openModal(true, {
      isUpdate: false,
      showFooter: true,
    });
  }
  function handleSuccess() {
    reload();
  }

  function handlerChange(selectedRowKeys, selectedRows) {
    if (selectedRowKeys.length == 0) {
      Object.assign(actinfo, { caNo: '', caName: '' });
    }
  }
  function handlerChecked(record, selected, selectedRows, nativeEvent) {
    if (selected) {
      selectedRowKeys.value = [record.id];
      Object.assign(actinfo, record);
    } else {
      Object.assign(actinfo, { caNo: '', caName: '' });
    }
  }
  function handlerRowClick({ keys, rows }) {
    if (keys.length > 1) {
      let index = keys.length - 1;
      selectedRowKeys.value = [rows[index].id];
      Object.assign(actinfo, rows[index]);
    } else {
      Object.assign(actinfo, rows[0]);
    }
  }

  function handleSelect(record) {
    try {
      //let values = await validate();
      setModalProps({ confirmLoading: true });
      joinCheck({ collectionNo: record.collectionNo, caIds: caNos.value, type: type.value });
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  function goToCa(record) {
    if (record.collectionName == '-') {
      return;
    }
    closeModal();
    router.push({ path: '/standardlib/controlactivity/StCaMainCollectionList', query: { bizNo: record.collectionNo } });
  }

  function getTableAction(record) {
    return [
      {
        label: '选择',
        onClick: handleSelect.bind(null, record),
      },
    ];
  }

  function newAddCollections() {
    openModal(true, {
      isUpdate: false,
      showFooter: true,
    });
  }
  // function initActCheckbox(){
  //   let actInfo = toRaw(props.actCheckbox)
  //   let item = {}
  //   for(let k in actInfo){
  //       item[k] = false
  //   }
  //   Object.assign(props.actCheckbox,item)
  // }

  const actModel = ref({
    caName: '',
    lableCodes: '',
  });
  const labelCol = reactive({
    xs: { span: 24 },
    sm: { span: 4 },
  });
  const wrapperCol = reactive({
    xs: { span: 24 },
    sm: { span: 20 },
  });
  function updateSelectLable(val) {
    actModel.value.lableCodes = val;
  }
  // const pagination = reactive({
  //     current: 1,
  //     pageSize: 10,
  //     total: 0,
  //     showTotal: total => `共 ${total} 条数据`
  // })
  function searchQuery() {
    setProps({ searchInfo: toRaw(actModel) });
    reload();
  }
</script>
