
<template>


<ResizePageWrapper   :hasLeft="false">
 
 
 <template #resizeRight>
<BasicTable @register="registerTable" isMenuTable ref="tableRef"  :row-selection="{ selectedRowKeys: selectedKeys, onChange: onSelectChange }"
   
  >
       
        <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>
 
  
  
   <CgdhModal @register="registerModal" @success="handleFormSuccess"   @cancel="handleFormCancel"/>
  
  
   
  
  
</ResizePageWrapper>


</template>
<script lang="ts" setup>
  import { ref, computed,provide,Ref,  
} from 'vue';
  
  import { BasicTable, useTable, TableAction, ActionItem } from '/@/components/Table';
  import { getMesWarehouseArrivedPage, deleteMesWarehouseArrived} from '/@/api/ckgl/cgdh';
  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 { useUserStore } from '/@/store/modules/user';
  
  
  
  
  
  import { useModal } from '/@/components/Modal';
  
  
  
  import CgdhModal from './components/CgdhModal.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","create"]);
  const buttonConfigs = computed(()=>{
    const list = [{"buttonId":"2009445983314264064","name":"查看","code":"view","icon":"ant-design:eye-outlined","isDefault":true,"isUse":true},{"buttonId":"2009445983314264066","name":"编辑","code":"edit","icon":"ant-design:form-outlined","isDefault":true,"isUse":true,"isEnableLock":true},{"buttonId":"2009478676487966720","name":"同步","code":"get","icon":"ant-design:arrow-down-outlined","isDefault":false,"isUse":true,"setting":[],"showType":"top","buttonType":"primary"},{"buttonId":"2012037219988561920","name":"生成入库单","code":"create","icon":"ant-design:download-outlined","isDefault":false,"isUse":true,"setting":[],"showType":"inline","buttonType":"primary"}]
    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,edit : handleEdit,create : handleCreate}

  
  const { currentRoute } = useRouter();
  
  
  const formIdComputedRef = computed(() => currentRoute.value.meta.formId as string);
  provide<Ref<string>>('currentFormId', formIdComputedRef);
  
   
   
  
  const selectedKeys = ref<string[]>([]);
  const selectedRowsData = ref<any[]>([]);
  
   
  
  const [registerModal, { openModal }] = useModal();
  
  
   
   
  const [registerTable, { reload,   }] = useTable({
    title: 'Cgdh列表',
    api: getMesWarehouseArrivedPage,
    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) => {
      
      
       
      
      selectedKeys.value = [];
      selectedRowsData.value = [];
      
    },
    useSearchForm: true,
    showTableSetting: true,
    
    
    
    striped: false,
    actionColumn: {
      width: 195,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    tableSetting: {
      size: false,
    },
    customRow,
    isAdvancedQuery:  false,
    querySelectOption: JSON.stringify(searchFormSchema),
    objectId: formIdComputedRef.value, ////系统表单formId,自定义表单releaseId的id值
  });

  
  

  function buttonClick(code) {
    
    btnEvent[code]();
  }
    
  
  
  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 onSelectChange(selectedRowKeys: [], selectedRows) {
    selectedKeys.value = selectedRowKeys;
    selectedRowsData.value = selectedRows;
  }
  
  function customRow(record: Recordable) {
    return {
      
      onClick: () => {
        let selectedRowKeys = [...selectedKeys.value];
        if (selectedRowKeys.indexOf(record.id) >= 0) {
          let index = selectedRowKeys.indexOf(record.id);
          selectedRowKeys.splice(index, 1);
        } else {
          selectedRowKeys.push(record.id);
        }
        selectedKeys.value = selectedRowKeys;
      },
      ondblclick: () => {
        if (record.isCanEdit && hasPermission("cgdh:edit")) {
          handleEdit(record);
        }
      },
    };
  }
  
  function handleSuccess() {
    
    
        selectedKeys.value = [];
        selectedRowsData.value = [];
    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);    
  }


  async function handleCreate(record: Recordable) {
    try {
      // 获取token\
      const store = useUserStore();
      let token = store.token

      // 调用后端接口
      const response = await fetch('http://localhost:8053/ckgl/cgrk', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + token, // 添加token到请求头
        },
        body: JSON.stringify(record), // 将当前行数据作为参数传递
      });

      if (response.ok) {
        const result = await response.json();
        notification.success({
          message: '操作成功',
          description: '生成入库单成功',
        });
        // 刷新表格数据
        reload();
      } else {
        const error = await response.json();
        notification.error({
          message: '操作失败',
          description: error.message || '生成入库单失败',
        });
      }
    } catch (error) {
      notification.error({
        message: '操作失败',
        description: '网络错误，请稍后重试',
      });
    }
  }
  
  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) => {
      // 检查是否应该显示当前按钮
      let shouldShowButton = true;

      // 控制create按钮的显示/隐藏
      if (button.code === 'create') {
        // 质检状态为"草稿"或"已质检"时隐藏
        if (record.zt === '草稿' || record.zt === '已质检') {
          shouldShowButton = false;
        }
        // 质检状态为"质检合格"或"质检不合格"时显示
        else if (record.zt === '质检合格' || record.zt === '质检不合格') {
          shouldShowButton = true;
        }
        // 其他状态默认隐藏
        else {
          shouldShowButton = false;
        }
      }

      // 如果按钮应该显示，则继续处理
      if (shouldShowButton) {
        if (!record?.workflowData?.processId) {
          record.isCanEdit = true;
          actionsList.push({
            ...button,

            auth: `cgdh:${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: `cgdh:${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;
  }
  
  
  
  
</style>
