<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" width="50%" @ok="handleSubmit" @cancel="handleCancel" :centered="true">
    <template #footer>
      <a-button key="back" @click="handleCancel">取消</a-button>
      <a-button key="submit" type="primary" @click="handleSubmit">确定</a-button>
    </template>
    <vxe-toolbar>
      <template #buttons>
        <a-row style="width: 100%">
          <a-col :span="18">
            <vxe-input v-model="srhContent" type="search" placeholder="请输入" style="width: 60%; margin-left: 5px" />
            <vxe-button status="primary" @click="handleSearch()">搜索</vxe-button>
          </a-col>
          <a-col :span="6">
            <vxe-button type="primary" style="margin: 0 20px" @click="handleAddAct()">新建</vxe-button>
          </a-col>
        </a-row>
      </template>
    </vxe-toolbar>
    <blockquote class="info" style="margin:10px 0">
        <a-row :gutter="16" style="width:100%">
          <a-col span="3">
            记录数: <a-badge :count="tableList.length"/>
          </a-col>
          <a-col span="2">
            <span style="margin-right:0px">已选:</span>
          </a-col>
          <a-col span="19">
          <a-tag v-for="(item, i) in selectTag" :key="item.id" closable @close="handlerTagClose(item)" color="#108ee9">{{ item.caName }}</a-tag>
          </a-col>
        </a-row>
    </blockquote>
    <vxe-table
      ref="tableRef"
      show-overflow
      height="300"
      size="small"
      :data="tableList"
      :show-checkbox="false"
      :row-config="{ isCurrent: true, isHover: true }"
      :columnConfig="{ resizable: true }"
      :scroll-y="{ enabled: true, gt: 50 }"
      @cell-click="cellClickEvent"
      :checkbox-config="{ highlight: true,checkStrictly:true }"
      @checkbox-change="selectChangeEvent"
    >
      <vxe-column type="checkbox" width="40" />
      <vxe-column field="caName" type="html" title="控制项名称" />
      <vxe-column field="domainName" type="html" title="所属领域" />
      <vxe-column field="labels" type="html" title="标签" />
      <vxe-column field="id" title="" :visible="false" />
    </vxe-table>
    
  </BasicModal>
  <AuditActModal @register="registerAddModal" @success="handleAddNewSuccess" />
</template>

<script lang="ts" setup>
  import { ref, unref, nextTick } from 'vue';
  import { getAllActDatas } from '../api/AuditAct.api';
  import { BasicModal, useModal, useModalInner } from '/@/components/Modal';
  import AuditActModal from './AuditActModal.vue';

  const [registerAddModal, { openModal }] = useModal();

  const title = '设置控制项';
  const loading = ref(false);
  const dataList = ref([]);
  const tableList = ref([]);
  const tableRef = ref();
  const srhContent = ref('');
  const selectTag = ref([]);

  const emit = defineEmits(['saveRel', 'success']);
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    loading.value = true;
    let retData = await getAllActDatas({});
    tableList.value = dataList.value = retData;
    loading.value = false;

    setModalProps({ confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter });
    let ids = data.actIds;

    if (!ids) return;
    nextTick(() => {
      const $table = tableRef.value;
      setTimeout(() => {
        const selRows = tableList.value.filter((item) => ids.includes(item.id + ''));
        $table.setCheckboxRow(selRows, true);
        selectTag.value = $table?.getCheckboxRecords();
      }, 100);
    });
  });

  function handleCancel() {
    srhContent.value = '';
    closeModal();
  }

  function handleSubmit() {
    let ids = [];
    let actNames = [];
    const $table = tableRef.value;
    selectTag.value.forEach(function (ele) {
      ids.push(ele.id);
      actNames.push(ele.caName);
    });
    emit('saveRel', ids, actNames);
    srhContent.value = '';
    closeModal();
  }

  const handleSearch = () => {
    if (!srhContent.value) {
      tableList.value = dataList.value;
      return;
    }
    const filterContent = String(srhContent.value).trim().toLowerCase();
    const searchProps = ['caName', 'domainName', 'labels'];
    tableList.value = dataList.value.filter((item) => searchProps.some((key) => String(item[key]).toLowerCase().indexOf(filterContent) > -1));
  };

  const selectChangeEvent = (obj) => {
    let curRow = obj.row;
    const $table = tableRef.value;
    let curSelRows = $table.getCheckboxRecords();
    if (curSelRows.includes(curRow)) {
      if (!selectTag.value.includes(curRow)) {
        selectTag.value.push(curRow);
      }
    } else {
      if (selectTag.value.includes(curRow)) {
        selectTag.value = selectTag.value.filter((item) => item.id !== curRow.id);
      }
    }
  };

  function handlerTagClose(row) {
    const $table = tableRef.value;
    $table.toggleCheckboxRow(row);
    if (selectTag.value.includes(row)) {
      selectTag.value = selectTag.value.filter((item) => item.id !== row.id);
    }
  }

  function cellClickEvent({row, column} ){
    const $table = tableRef.value;
    if(!$table) return;
    $table.toggleCheckboxRow(row);
    selectChangeEvent({ row: row });
  }

  

  function handleAddAct() {
    openModal(true, {
      isUpdate: false,
      showFooter: true,
    });
  }

  function handleAddNewSuccess(isUpdate,newAct) {
    if(!isUpdate) {
      tableList.value.unshift(newAct);
    }
  }
</script>

<style lang="less" scoped>
  /** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.ant-calendar-picker) {
    width: 100%;
  }
</style>
