
<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>
 
  
   <PrintPreview
    v-if="printData.visible"
    :id="printData.id"
    :request-params-configs="printData.requestParamsConfigs"
    :request-body-configs="printData.requestBodyConfigs"
    :request-header-configs="printData.requestHeaderConfigs"
     @close="handleClosePrintPreview"
  />
   <HgzglModal @register="registerModal" @success="handleFormSuccess"   @cancel="handleFormCancel"/>
  
  
   
  
  
</ResizePageWrapper>


</template>
<script lang="ts" setup>
  import { ref, computed,provide,Ref,  
 reactive, } from 'vue';
  
  import { BasicTable, useTable, TableAction, ActionItem } from '/@/components/Table';
  import { getMesHegezhengPage, deleteMesHegezheng} from '/@/api/jcsj/hgzgl';
  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 { getPrintConfigInfo } from '/@/api/system/generator/print';
		import PrintPreview from '/@/views/generator/print/Preview.vue'; 
	  import { PrintButton } from '/@/enums/printEnum';
	  import { InputParamItem } from '/@/components/ApiConfig/src/interface';
    
  
  import { useModal } from '/@/components/Modal';
  
  
  
  import HgzglModal from './components/HgzglModal.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"]);
  const buttonConfigs = computed(()=>{
    const list = [{"buttonId":"2013807357670838272","name":"查看","code":"view","icon":"ant-design:eye-outlined","isDefault":true,"isUse":true},{"buttonId":"2013807357670838273","name":"编辑","code":"edit","icon":"ant-design:form-outlined","isDefault":true,"isUse":true,"isEnableLock":true},{"buttonId":"2013807357670838275","name":"模板打印","code":"templateprint","icon":"ant-design:printer-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,edit : handleEdit,templateprint : handleTemplateprint,}

  
  const { currentRoute } = useRouter();
  
  const printMenuId = computed(() => currentRoute.value.meta.menuId as string);
  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();
  
  
  
    // 模板打印 入参参数
    let printData: {
      visible:boolean;
      id: string;
      code:string;
      requestParamsConfigs: Array<InputParamItem>;
      requestHeaderConfigs: Array<InputParamItem>;
      requestBodyConfigs: Array<InputParamItem>;
    
    } = reactive({
      visible:false,
      id: '',
      code:'',
      requestParamsConfigs: [],
      requestHeaderConfigs: [],
      requestBodyConfigs: [],
    });
     
   
  const [registerTable, { reload,   }] = useTable({
    title: 'Hgzgl列表',
    api: getMesHegezhengPage,
    rowKey: 'id',
    columns: filterColumns,
    pagination: {
      pageSize: 10,
    },
    formConfig: {
      labelWidth: 100,
      schemas: searchFormSchema,
      fieldMapToTime: [['csrq', ['csrqStart', 'csrqEnd'], 'YYYY-MM-DD HH:mm:ss ', true],],
      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: 130,
      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) {
    if (code.includes(PrintButton.CODE)) {
      printData.code = 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) {} 
  }
  
   
  
  
  
  
    // 模板打印
		 async function handleTemplateprint() {
		      if (!selectedKeys.value.length) {
		        notification.warning({
		          message: t('提示'),
		          description: t('请选择数据'),
		        });
		        return;
		      }
		      if (selectedKeys.value.length > 1) {
		        notification.warning({
		          message: t('提示'),
		          description: t('只能选择一条数据进行操作'),
		        });
		        return;
		      }
		      try {
  let id = selectedKeys.value[0];
		    const record = await getMesHegezheng(id);
		        let res = await getPrintConfigInfo(printData.code, printMenuId.value);
            if(res.enabledMark==null){
              notification.warning({
                message: t('提示'),
                description: t('当前功能未绑定打印模板，请绑定后再进行模板打印。'),
              });
              return ;
            }
            if(res.enabledMark==0){
              notification.warning({
                message: t('提示'),
                description: t('找不到打印模板，请联系管理员。'),
              });
              return ;
            }
            printData.id = res.schemaId;
		        if (res.apiConfig) {
		          let json = JSON.parse(res.apiConfig);
		          if (json.requestParamsConfigs && json.requestParamsConfigs.length > 0) {
		            printData.requestParamsConfigs = json.requestParamsConfigs.map((ele) => {
		              if (ele.config && record[ele.config] != undefined) {
		                ele.value = record[ele.config];
		              }
		              return ele;
		            });
		          }
		          if (json.requestHeaderConfigs && json.requestHeaderConfigs.length > 0) {
		            printData.requestHeaderConfigs = json.requestHeaderConfigs.map((ele) => {
		              if (ele.config && record[ele.config] != undefined) {
		                ele.value = record[ele.config];
		              }
		              return ele;
		            });
		          }
		          if (json.requestBodyConfigs && json.requestBodyConfigs.length > 0) {
		            printData.requestBodyConfigs = json.requestBodyConfigs.map((ele) => {
		              if (ele.config && record[ele.config] != undefined) {
		                ele.value = record[ele.config];
		              }
		              return ele;
		            });
		          }
		          printData.visible = true;
		        }else{
              notification.warning({
					        message: t('提示'),
					        description: t('当前功能未绑定打印模板，请绑定后再进行模板打印。'),
					      });
            }
		      } catch (error) {}
		    }

    function handleClosePrintPreview() {
      printData.visible = false;
      reload();
    }

    
  
  
  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("hgzgl: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);    
  }
  
  
  
  
  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: `hgzgl:${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: `hgzgl:${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>