
<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>
 
  
      <LookProcess
        v-if="visibleLookProcessRef"
        :taskId="taskIdRef"
        :processId="processIdRef"
        @close="visibleLookProcessRef = false"
        :visible="visibleLookProcessRef"
      />
      <LaunchProcess
        v-if="visibleLaunchProcessRef"
        :schemaId="schemaIdRef"
        :form-data="formDataRef"
        :form-id="formIdComputedRef"
        :rowKeyData="rowKeyData"
        :draftsId="draftsId"
        @close="handleCloseLaunch"
      />
      <ApprovalProcess
        v-if="visibleApproveProcessRef"
        :taskId="taskIdRef"
        :processId="processIdRef"
        :schemaId="schemaIdRef"
        @close="handleCloseApproval"
        :visible="visibleApproveProcessRef"
      />
      <BasicModal
      v-if="visibleFlowRecordModal"
      :visible="visibleFlowRecordModal"
      :title="t('查看流转记录')"
      :paddingRight="15"
      :showOkBtn="false"
      :width="1200"
      @visible-change="
        (v) => {
          visibleFlowRecordModal = v;
        }
      "
      :bodyStyle="{ minHeight: '400px !important' }"
    >
      <FlowRecord :processId="processIdRef" />
    </BasicModal>
  
   <TkglModal @register="registerModal" @success="handleFormSuccess"   @cancel="handleFormCancel"/>
  
  
   <ExportModal
      v-if="visibleExport"
      @close="visibleExport = false"
      :columns="columns"
      @success="handleExportSuccess"
    />
  
  
</ResizePageWrapper>


</template>
<script lang="ts" setup>
  import { ref, computed,provide,Ref, onMounted,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 { getMesWarehouseReturnPage, deleteMesWarehouseReturn, exportMesWarehouseReturn, getMesWarehouseReturn} from '/@/api/ckgl/tkgl';
  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,BasicModal } from '/@/components/Modal';
  
  
  import LookProcess from '/@/views/workflow/task/components/LookProcess.vue';
  import LaunchProcess from '/@/views/workflow/task/components/LaunchProcess.vue';
  import ApprovalProcess from '/@/views/workflow/task/components/ApprovalProcess.vue';
  import { getDraftInfo } from '/@/api/workflow/process';
  
  import TkglModal from './components/TkglModal.vue';
  
  
  
  
  
  import { downloadByData } from '/@/utils/file/download';
  import ExportModal from '/@/views/form/template/components/ExportModal.vue';
    
  
  
  import { searchFormSchema, columns  } from './components/config';
  
  import Icon from '/@/components/Icon/index';
   
   
  
  
  import { isValidJSON, } from '/@/utils/event/design';
  import FlowRecord from '/@/views/workflow/task/components/flow/FlowRecord.vue';
  
  

  
   const listSpliceNum = ref(3); //操作列最先展示几个
   
  
   import {getFormSchemaId } from '/@/api/form/design'; 


 
  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 visibleExport = ref(false);

  
  //展示在列表内的按钮
  const actionButtons = ref<string[]>(["view","edit","startwork","flowRecord","delete"]);
  const buttonConfigs = computed(()=>{
    const list = [{"isUse":true,"name":"查看","code":"view","icon":"ant-design:eye-outlined","isDefault":true},{"isUse":true,"name":"新增","code":"add","icon":"ant-design:plus-outlined","isDefault":true},{"isUse":true,"name":"编辑","code":"edit","icon":"ant-design:form-outlined","isDefault":true,"isEnableLock":true},{"isUse":true,"name":"快速导出","code":"export","icon":"ant-design:export-outlined","isDefault":true},{"isUse":true,"name":"发起审批","code":"startwork","icon":"ant-design:form-outlined","isDefault":true,"isEnableLock":true,"schemaInitConfig":{"enabled":false,"enabledAddApprove":false,"config":{"id":""}}},{"isUse":true,"name":"查看流转记录","code":"flowRecord","icon":"ant-design:form-outlined","isDefault":true},{"isUse":true,"name":"删除","code":"delete","icon":"ant-design:delete-outlined","isDefault":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,export : handleExport,startwork : handleStartwork,flowRecord : handleFlowRecord,delete : handleDelete,}

  
  const { currentRoute } = useRouter();
  
  
  const formIdComputedRef = computed(() => currentRoute.value.meta.formId as string);
  provide<Ref<string>>('currentFormId', formIdComputedRef);
  
  const visibleLookProcessRef = ref(false);
  const processIdRef = ref('');

  const visibleLaunchProcessRef = ref(false);
  const schemaIdRef = ref('');
  const formDataRef = ref();
  const rowKeyData = ref();
  const draftsId = ref();

  const visibleApproveProcessRef = ref(false);
  const taskIdRef = ref('');


  
  const visibleFlowRecordModal = ref(false);
  
   
   
  
  
   
      const schemaInitConfig = ref();
      onMounted(async () => {
       // 获取发起审批按钮配置信息
        let startWorkArr = buttonConfigs.value?.find((x) => x.code === 'startwork');
        if (startWorkArr) {
          schemaInitConfig.value = startWorkArr.schemaInitConfig;
          if (
            schemaInitConfig.value &&
            schemaInitConfig.value.config &&
            schemaInitConfig.value.config.id
          ) {
            let schemeId = await getFormSchemaId(schemaInitConfig.value.config.id);
            if (schemeId) schemaIdRef.value = schemeId;
          }
        }
    });
      
  
  const [registerModal, { openModal }] = useModal();
  
  
   
   
  const [registerTable, { reload,   }] = useTable({
    title: 'Tkgl列表',
    api: getMesWarehouseReturnPage,
    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: 390,
      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]();
  }
    
  
  function handleAdd() {
   
   // 发起审批按钮的配置中 启用并新增即审批 打开发起流程
    if (
      schemaInitConfig.value &&
      schemaInitConfig.value.enabled &&
      schemaInitConfig.value.enabledAddApprove
    ) {
      visibleLaunchProcessRef.value = true;
    } else {
  
 
      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() {
        deleteMesWarehouseReturn(ids).then((_) => {
          handleSuccess();
          notification.success({
            message: 'Tip',
            description: t('删除成功！'),
          });
        });
      },
      onCancel() {},
    });
  }
  
  
  
  
  
  
  function customRow(record: Recordable) {
    return {
      
      ondblclick: () => {
        if (record.isCanEdit && hasPermission("tkgl:edit")) {
          handleEdit(record);
        }
      },
    };
  }
  
  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);    
  }
  
  async function handleExport() {
    visibleExport.value = true;
  }
  
  async function handleExportSuccess(cols) {
    const res = await exportMesWarehouseReturn({ isTemplate: false, columns: cols.toString(), ...pageParamsInfo.value});
    visibleExport.value = false;
    downloadByData(
      res.data,
      'Tkgl.xlsx',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
    reload();
  }
  
  
  
  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[] = [];
    let editAndDelBtn: ActionItem[] = [];
    let pushorderBtn: ActionItem[] = [];
    let orderBtn: ActionItem[] = [];
    let hasStartwork = false;
   let hasFlowRecord = false; 
    actionButtonConfig.value?.map((button) => {
      const btns = {
        ...button,
        
        auth: `tkgl:${button.code}`,
        label: button?.name,
        color: button.code === 'delete' ? 'error' : undefined,
        onClick: btnEvent[button.code]?.bind(null, record),
      };

      if (['edit', 'delete'].includes(button.code)) {
        editAndDelBtn.push(btns);
      } else if (!['pushorder', 'startwork', 'flowRecord'].includes(button.code)) {
        orderBtn.push(btns);
      }
      if (button.code === 'pushorder') {
        pushorderBtn.push({
          
          auth: `tkgl:${button.code}`,
          label: button?.name,
          onClick: btnEvent[button.code].bind(null, record),
        });
      }
      if (button.code === 'startwork') hasStartwork = true;
      if (button.code === 'flowRecord') hasFlowRecord = true;
    });
    if (record?.workflowData?.enabled) {
      //与工作流有关联的表单
      if (record?.workflowData?.status) {
        //如果是本人需要审批的数据 就会有taskIds  所以需要修改绑定事件
        const act: ActionItem = {};
        if (hasStartwork) {
          if (record?.workflowData?.taskIds) {
            act.label = '查看流程(待审批)';
            
            act.onClick = handleApproveProcess.bind(null, record);
          } else {
            act.label =
              '查看流程' + (record.workflowData.status === 'ACTIVE' ? '(审批中)' : '(已完成)');
            
            act.onClick = handleStartwork.bind(null, record);
          }
        }
        actionsList.unshift(act);
        if (hasFlowRecord) {
          actionsList.splice(1, 0, {
          label: '查看流转记录',
            
            onClick: handleFlowRecord.bind(null, record),
          });
        }
       
      } else {
        if (hasStartwork) {
          actionsList.unshift({
             
            label: record?.workflowData?.draftId ? '编辑草稿' : '发起审批' ,
            onClick: handleLaunchProcess.bind(null, record),
          });
        }
        record.isCanEdit = true;
        actionsList = actionsList.concat(editAndDelBtn);
      }
    } else {
      if (!record?.workflowData?.processId) {
        record.isCanEdit = true;
        //与工作流没有关联的表单并且在当前页面新增的数据 如选择编辑、删除按钮则加上
        actionsList = actionsList.concat(editAndDelBtn);
      }
    }
    actionsList.unshift(...pushorderBtn, ...orderBtn);
    return actionsList;
  }



    
  
  function handleStartwork(record: Recordable) {
    if (record?.workflowData) {
      visibleLookProcessRef.value = true;
      processIdRef.value = record.workflowData?.processId;
    }
  }
  function handleFlowRecord(record: Recordable) {
    if (record?.workflowData) {
      visibleFlowRecordModal.value = true;
      processIdRef.value = record?.workflowData?.processId;
    }
  }
  
  async function handleLaunchProcess(record: Recordable) {
    try {
      let hasIn = handleHasEnableLocke(buttonConfigs.value, 'startwork');
      if (hasIn) {
        let dataId = record['id'];
        await handleOpenFormEnableLockeData(dataId, formIdComputedRef.value);
      }
      if (record?.workflowData) {
        if (record?.workflowData?.draftId) {
          let res = await getDraftInfo(record.workflowData.draftId);
          let data = isValidJSON(res.formData);
          if (data) {
            for (let key in data) {
              if (key.includes(formIdComputedRef.value)) {
                formDataRef.value = data[key];
              }
            }
          }
          draftsId.value = record.workflowData.draftId;
        } else {
          const result = await getMesWarehouseReturn(record['id']);
          formDataRef.value = result;
        }
        rowKeyData.value = record['id'];
        visibleLaunchProcessRef.value = true;
        schemaIdRef.value = record.workflowData.schemaId;
      }
     } catch (error) {}    
   
  }
  async function handleApproveProcess(record: Recordable) {
      try {
        let hasIn = handleHasEnableLocke(buttonConfigs.value, 'startwork');
        if (hasIn) {
          let dataId = record['id'];
          await handleOpenFormEnableLockeData(dataId, formIdComputedRef.value);
        }
        visibleApproveProcessRef.value = true;
        schemaIdRef.value = record.workflowData.schemaId;
        processIdRef.value = record.workflowData.processId;
        taskIdRef.value = record.workflowData.taskIds[0];
      } catch (error) {}    
   
  }
  function handleCloseLaunch() {
    visibleLaunchProcessRef.value = false;
    draftsId.value = '';
    
    reload();
     handleCloseFormEnableLocke(buttonConfigs.value, 'startwork');
  }
      

 
  function handleCloseApproval() {
    visibleApproveProcessRef.value = false;
    reload();
     handleCloseFormEnableLocke(buttonConfigs.value, 'startwork');
  }
  
  
</script>
<style lang="less" scoped>

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

  .show{
    display: flex;
  }

  .hide{
    display: none !important;
  }
  
  
  
  
</style>