<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose title="选择控制项" width="50%" @ok="handleOk">
    <a-form :model="searchModel" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-row :gutter="16">
        <a-col :span="18">
          <vxe-input v-model="srhContent" :clearable="true" placeholder="请输入" style="width: 60%; margin: 10px" />
          <vxe-button status="primary" @click="handleSearch()">搜索</vxe-button>
        </a-col>
        <a-col :span="6">
          <vxe-button type="primary" style="margin: 10px" @click="handleAdd()">新建</vxe-button>
          <vxe-button type="primary" style="margin: 10px" @click="handleRefresh()">刷新</vxe-button>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <blockquote class="info" style="margin: 10px 0">
            <a-row :gutter="16" style="width: 100%">
              <a-col span="5"> 记录数: <a-badge :count="actDatas.length" overflow-count="100000"/> </a-col>
              <a-col span="19">
                <a-tag v-for="(item, i) in selectTag" :key="item.id" closable @close="handlerTagClose(item)" color="#108ee9" style="margin: 2px 2px">{{ item.caName }}</a-tag>
              </a-col>
            </a-row>
          </blockquote>
          <vxe-table
            ref="tableRef"
            :loading="loading"
            show-overflow
            height="300"
            size="small"
            :data="actDatas"
            :show-checkbox="false"
            :row-config="{ isCurrent: true, isHover: true }"
            :columnConfig="{ resizable: true }"
            :scroll-y="{ enabled: true, gt: 50 }"
            v-on="gridEvents"
            :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>
        </a-col>
      </a-row>
    </a-form>
  </BasicModal>
  <AuditActModal @register="registerAddModal" @success="handleAddNewSuccess" />
</template>

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

  const [registerAddModal, { openModal }] = useModal();
  const tableRef = ref();
  const actDatas = ref([]);
  const tableDatas = ref([]);
  const selectTag = ref<{ caName: string; value: number }[]>([]);
  const loading = ref(false);
  const searchModel = {
    caName: '',
    domainCode: '',
    labels: '',
  };
  const srhContent = ref('');
  const labelCol = ref({
    xs: { span: 24 },
    sm: { span: 2 },
    lg: { span: 8 },
  });
  const wrapperCol = ref({
    xs: { span: 24 },
    sm: { span: 6 },
    lg: { span: 16 },
  });

  const gridEvents = {
    cellClick({ row }) {
      selectChangeEvent({ row: row });
    },
  };

  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);
      }
    }
  };
  // Emits声明
  const emit = defineEmits(['register', 'success', 'getSelectResult']);

  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    selectTag.value = [];
    loading.value = true;
    tableDatas.value = actDatas.value = await getAllActDatas({});
    loading.value = false;
    const $table = tableRef.value;
    if ($table && data.selActIds) {
      const ids = data.selActIds;
      nextTick(() => {
        const selRows = actDatas.value.filter((item) => ids.includes(item.id));
        $table.setCheckboxRow(selRows, true);
        selectTag.value = $table?.getCheckboxRecords();
      });
    }
    setModalProps({ confirmLoading: false });
  });

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

  const handleSearch = () => {
    if (!srhContent.value) {
      actDatas.value = tableDatas.value;
      return;
    }
    const filterContent = String(srhContent.value).trim().toLowerCase();
    const searchProps = ['caName', 'domainName', 'labels'];
    actDatas.value = tableDatas.value.filter((item) => searchProps.some((key) => String(item[key]).toLowerCase().indexOf(filterContent) > -1));
  };
  /**
   * 确定选择
   */
  function handleOk() {
    const $table = tableRef.value;
    if ($table) {
      let options: { label: string; value: number }[] = [];
      let ids: any[] = [];
      selectTag.value.forEach(function (ele) {
        ids.push(ele.id);
        options.push({ value: ele.id, label: ele.caName });
      });
      selectTag.value = [];
      $table.clearCheckboxRow();
      emit('getSelectResult', options, ids);
      closeModal();
    }
    return null;
  }

  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 handleAddNewSuccess(newAct) {
    if (newAct.id) {
      actDatas.value.unshift(newAct);
    }
  }

  async function handleRefresh(){
    loading.value = true;
    tableDatas.value = actDatas.value = await getAllActDatas({});
    loading.value = false;
  }
</script>

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

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