
<template>


<ResizePageWrapper   :hasLeft="false">
 
 
 <template #resizeRight>
<BasicTable @register="registerTable" isMenuTable ref="tableRef"  
   
  >
       
        <template #toolbar>
          <template v-for="button in tableButtonConfig" :key="button.code">
            <a-button v-if="button.isDefault" type="primary" @click="buttonClick(button.code)">
              <template #icon><Icon :icon="button.icon" /></template>
              {{ button.name }}
            </a-button>
            <CustomButtonModal v-else-if="button.buttonType == 'modal'" :info="button" />
            <a-button v-else :type="button.buttonType === 'danger' ? 'default' : button.buttonType || 'primary'" :danger="button.buttonType === 'danger'" >
              <template #icon><Icon :icon="button.icon" /></template>
              {{ button.name }}
            </a-button>
          </template>
        </template>
        <template #bodyCell="{ column, record }">
          
          
         
          <template v-if="column.dataIndex === 'action'">
          
           <TableAction
              :actions="getLessActions(record)"
              :dropDownActions="getMoreActions(record)"
            />
          </template>
          
          <template v-else-if="column.dataIndex && column?.listStyle">
            <span :style="executeListStyle(getValue(record, column, 'style'), column?.listStyle)">{{
              getValue(record, column, 'value')
            }}</span>
          </template>
        </template>
        
           
        
      </BasicTable>
 </template>
 
  
  
   <KczbModal @register="registerModal" @success="handleFormSuccess"   @cancel="handleFormCancel"/>
  
  
   
  
  
</ResizePageWrapper>


</template>
<script lang="ts" setup>
  import { ref, computed,provide,Ref, createVNode, 
} from 'vue';
  
  import { Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { BasicTable, useTable, TableAction, ActionItem } from '/@/components/Table';
  import { getMesWarehouseProductNumberPage, deleteMesWarehouseProductNumber} from '/@/api/ckgl/kczb';
  import { ResizePageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { usePermission } from '/@/hooks/web/usePermission';
    import CustomButtonModal from '/@/components/Form/src/components/CustomButtonModal.vue';
  import { executeListStyle, getValue } from '/@/hooks/web/useListStyle';//列表样式配置
  import { useRouter } from 'vue-router';
  
  
  
  
  
  import { useModal } from '/@/components/Modal';
  
  
  
  import KczbModal from './components/KczbModal.vue';
  
  
  
  
  
  
  
  import { searchFormSchema, columns  } from './components/config';
  
  import Icon from '/@/components/Icon/index';
   
   
  
  
  
  
  
  

  
   const listSpliceNum = ref(3); //操作列最先展示几个
   
  
  


 
  import { useConcurrentLock } from '/@/hooks/web/useConcurrentLock';

  const pageParamsInfo = ref<any>({});
  const { enableLockeData,handleOpenFormEnableLockeData, handleCloseFormEnableLocke, handleHasEnableLocke } =
    useConcurrentLock();

  const { notification } = useMessage();
  const { t } = useI18n();
  defineEmits(['register']);
  const { filterColumnAuth, filterButtonAuth, hasPermission } = usePermission();

  const filterColumns = filterColumnAuth(columns);
  const tableRef = ref();
  

  
  

  
  //展示在列表内的按钮
  const actionButtons = ref<string[]>(["view","edit","delete"]);
  const buttonConfigs = computed(()=>{
    const list = [{"buttonId":"2015737877640114176","name":"查看","code":"view","icon":"ant-design:eye-outlined","isDefault":true,"isUse":true},{"buttonId":"2015737877640114177","name":"新增","code":"add","icon":"ant-design:plus-outlined","isDefault":true,"isUse":true},{"buttonId":"2015737877640114178","name":"编辑","code":"edit","icon":"ant-design:form-outlined","isDefault":true,"isUse":true,"isEnableLock":true},{"buttonId":"2015737877640114179","name":"删除","code":"delete","icon":"ant-design:delete-outlined","isDefault":true,"isUse":true}]
    return filterButtonAuth(list);
  })

  const tableButtonConfig = computed(() => {
    return buttonConfigs.value?.filter((x) => !actionButtons.value.includes(x.code));
  });

  const actionButtonConfig = computed(() => {
    return buttonConfigs.value?.filter((x) => actionButtons.value.includes(x.code));
  });

  const btnEvent = {view : handleView,add : handleAdd,edit : handleEdit,delete : handleDelete,}

  
  const { currentRoute } = useRouter();
  
  
  const formIdComputedRef = computed(() => currentRoute.value.meta.formId as string);
  provide<Ref<string>>('currentFormId', formIdComputedRef);
  
   
   
  
  
   
  
  const [registerModal, { openModal }] = useModal();
  
  
   
   
  const [registerTable, { reload,   }] = useTable({
    title: 'Kczb列表',
    api: getMesWarehouseProductNumberPage,
    rowKey: 'id',
    columns: filterColumns,
    pagination: {
      pageSize: 10,
    },
    formConfig: {
      labelWidth: 100,
      schemas: searchFormSchema,
      fieldMapToTime: [],
      showResetButton: false,
    },
     bordered:false,
          beforeFetch: (params) => {
      pageParamsInfo.value = {...params, FormId: formIdComputedRef.value,PK: 'id' }
      return pageParamsInfo.value;
    },
    afterFetch: (res) => {
      
      
       
      
      
    },
    useSearchForm: true,
    showTableSetting: true,
    
    
    
    striped: false,
    actionColumn: {
      width: 195,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
      className: 'action-column-cell',
    },
    tableSetting: {
      size: false,
    },
    customRow,
    isAdvancedQuery:  false,
    querySelectOption: JSON.stringify(searchFormSchema),
    objectId: formIdComputedRef.value, ////系统表单formId,自定义表单releaseId的id值
  });

  
  

  function buttonClick(code) {
    
    btnEvent[code]();
  }
    
  
  function handleAdd() {
  
 
      openModal(true, { isUpdate: false, });
 
      }
      
  
  async function handleEdit(record: Recordable) {
    let field = 'id';
  try {
      let hasIn = handleHasEnableLocke(buttonConfigs.value, 'edit');
      if (hasIn) { 
        let res = await handleOpenFormEnableLockeData(
          record[field],
          formIdComputedRef.value,
        );
        if (res !== null) {
          return;
        }
      } 
    
    let info = {
      id: record[field],
      
      isUpdate: true,
      
    };
    
    openModal(true, info);
      } catch (error) {} 
  }
  
   
  
    
  function handleDelete(record: Recordable) {
  deleteList([record.id]);
  }
    
  function deleteList(ids) {
    Modal.confirm({
      title: '提示信息',
      icon: createVNode(ExclamationCircleOutlined),
      content: '是否确认删除？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        deleteMesWarehouseProductNumber(ids).then((_) => {
          handleSuccess();
          notification.success({
            message: 'Tip',
            description: t('删除成功！'),
          });
        });
      },
      onCancel() {},
    });
  }
  
  
  
  
  
  
  function customRow(record: Recordable) {
    //判断行数据是否需要变红
    const isRedRow = isNeedWarn(record);
    return {
      // 核心修改：添加类名，而非行内style
      class: isRedRow ? 'red-row' : '',
      ondblclick: () => {
        if (record.isCanEdit && hasPermission("kczb:edit")) {
          handleEdit(record);
        }
      },
    };
  }

  /**
   * 计算是否需要预警（变红）的函数
   * @param record
   */
  function isNeedWarn(record: Recordable): boolean {
    // 1. 校验字段是否存在，避免报错
    if (!record.dqsj || !record.tqyjts) return false;

    // 2. 解析到期时间（兼容字符串/时间戳）
    const dqsjDate = new Date(record.dqsj);
    // 校验时间格式是否合法
    if (isNaN(dqsjDate.getTime())) return false;

    // 3. 当前时间（取当天0点，避免时分秒干扰）
    const now = new Date();

    // 4. 计算到期时间 - 当前时间的毫秒差 → 转换为天数
    const timeDiff = dqsjDate.getTime() - now.getTime();
    const dayDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24)); // 向上取整（比如剩余1.2天算2天）

    // 5. 判断：天数差 < 提前预警天数且数量>0 → 需要预警（变红）
    // 补充：如果到期时间已过（dayDiff < 0），也强制变红
    let isNeedWarn = false;
    if (record.sl && record.sl > 0) {
      if (dayDiff < record.tqyjts || dayDiff < 0) {
        isNeedWarn = true;
      }
    }
    return isNeedWarn;
  }
  
  function handleSuccess() {
    
    
    reload();
    
  }
    
  
    function handleFormSuccess() {
    handleSuccess();
    handleCloseFormEnableLocke(buttonConfigs.value, 'edit');
  }
  function handleFormCancel() {
    handleCloseFormEnableLocke(buttonConfigs.value, 'edit');
  }

  
  function handleView(record: Recordable) {
  let info={
      isView: true,
     id: record.id,
    }

    openModal(true, info);    
  }
  
  
  
  
  function getLessActions(record: Recordable) {
    let list = getActions(record);
    return list.slice(0, listSpliceNum.value);
  }
  function getMoreActions(record: Recordable) {
    let list = getActions(record);
    return list.slice(listSpliceNum.value);
  }
  function getActions(record: Recordable):ActionItem[] {
    record.isCanEdit = false;
    
    let actionsList: ActionItem[] = [];  
    actionButtonConfig.value?.map((button) => {
    if (!record?.workflowData?.processId) {
        record.isCanEdit = true;
        actionsList.push({
          ...button,
           
          auth: `kczb:${button.code}`,
          label: button?.name,
          color: button.code === 'delete' ? 'error' : undefined,
          onClick: btnEvent[button.code]?.bind(null, record),
        });
      } else {
        if (!['edit', 'delete'].includes(button.code)) {
          actionsList.push({
             
            auth: `kczb:${button.code}`,
            label: button?.name,
            onClick: btnEvent[button.code]?.bind(null, record),
          });
        } 
      }
    });
    return actionsList;
  }
  
  
</script>
<style lang="less" scoped>

  :deep(.ant-table-selection-col) {
    width: 50px;
  }

  .show{
    display: flex;
  }

  .hide{
    display: none !important;
  }

  // 其他样式不变，修改预警行样式
  :deep(.ant-table-tbody > tr.red-row) {
    td {
      background-color: #ff4d4f !important;
      color: black !important;
    }
    // 覆盖操作列样式
    td.action-column-cell {
      background-color: white !important;
      color: black !important;
    }
    /*&:hover td {
      background-color: #ff1f1f !important;
    }
    &:hover td.action-column-cell {
      background-color: white !important;
    }*/
  }

</style>
