
<template>


<ResizePageWrapper   :hasLeft="false">
 
 
 <template #resizeRight>
<BasicTable @register="registerTable" isMenuTable ref="tableRef"   @expand="expandedRowsChange" 
   
  >
       
        <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'">
            <div style="display: flex; align-items: center;">
              <!-- 其他按钮使用TableAction组件 -->
              <TableAction
                :actions="getLessActions(record)"
                :dropDownActions="getMoreActions(record)"
              />
              <!-- 单独渲染流程按钮 -->
              <template v-if="!record.taskId">
                <a-button 
                  type="text" 
                  size="small" 
                  style="margin-left: 8px;color: #1c8dff; "
                  @click="openFlowLaunchModal(record.id)"
                >
                  <template #icon><Icon style="color: #1c8dff;"  :icon="'ant-design:rocket-outlined'" /></template>
                  发起流程
                </a-button>
              </template>
              <template v-else>
                <a-button 
                  type="text" 
                  size="small" 
                  style="margin-left: 8px;color: #1c8dff;"
                  @click="viewProcess(record)"
                >
                  <template #icon><Icon style="color: #1c8dff;" :icon="'ant-design:eye-outlined'" /></template>
                  查看流程
                </a-button>
              </template>
            </div>
          </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>
        
        <template #expandedRowRender="{ record }">
          <a-table
            v-for="item in subFormList"
            :key="item.key"
            :columns="innerColumns[item.field]"
            :data-source="getInnerDataSource(record.id, item.field)"
            :pagination="false"
            :scroll="{ x: 'max-content' }"
          >
            <template #bodyCell="{ column, record: innerRecord }">
              <template v-if="column.componentType === 'picker-color'">
                <ColorPicker v-model:value="innerRecord[column.dataIndex]" :disabled="true" />
              </template>
                <template v-else-if="column.componentType === 'labelComponent'">
                  <XjrLabelComponentInfo
                    :value="innerRecord[column.dataIndex]"
                    :styleConfig="column.styleConfig"
                  />
                </template>
              <template v-else-if="column.componentType === 'money-chinese'">
                {{ moneyChineseData(innerRecord[column.dataIndex]) }}
              </template>
            </template>
          </a-table>
        </template>
           
        
      </BasicTable>
 </template>
 
  
  
   <BhgpclModal @register="registerModal" @success="handleFormSuccess"   @cancel="handleFormCancel"/>
  
  
   <ExportModal
      v-if="visibleExport"
      @close="visibleExport = false"
      :columns="columns"
      @success="handleExportSuccess"
    />
  
  <!-- 流程发起对话框 -->
  <a-modal
    v-model:visible="visibleFlowLaunchModal"
    title="流程模板列表"
    width="80%"
    :bodyStyle="{ height: '620px', padding: '0' }"
    :footer="null"
    @cancel="visibleFlowLaunchModal = false"
  >
    <a-spin :spinning="loading" tip="发起流程中..." style="min-height: 500px;">
      <PageLayout
        :title="'流程模板列表'"
        :searchConfig="searchConfig"
        @search="searchFlowTemplate"
        @scroll-height="scrollHeight"
      >
        <template #search> </template>

        <template #right>
          <div v-if="flowLaunchData.list.length > 0" style="height: 550px;padding: 10px;" class="list-page-box relative">
            <div
              class="flex flex-wrap my-10px overflow-y-auto"
              style="height: calc(100% - 62px); align-content: baseline"
            >
              <TemplateCard
                v-for="(item, index) in flowLaunchData.list"
                :key="index"
                :item="item"
                :width="'calc((100% - 39px) / 4)'"
                @click="launchProcess(item.id)"
              />
            </div>
            <div class="page-box">
              <a-pagination
                v-model:current="flowLaunchData.pagination.current"
                :total="flowLaunchData.pagination.total"
                v-model:pageSize="flowLaunchData.pagination.pageSize"
                :showSizeChanger="true"
                :showQuickJumper="true"
                :show-total="(total) => `共 ${total} 条数据`"
                @change="handleFlowTemplatePageChange"
            /></div>
          </div>

          <div v-else>
            <EmptyBox />
          </div>
        </template>
      </PageLayout>
    </a-spin>
  </a-modal>
  
  <!-- 查看流程组件 -->
  <LookProcess
    v-if="visibleLookProcess"
    :visible="visibleLookProcess"
    :taskId="taskIdProcess"
    :processId="processIdProcess"
    @close="visibleLookProcess = false"
  />
  
</ResizePageWrapper>


</template>
<script lang="ts" setup>
  import { ref, computed,provide,Ref, onMounted,createVNode, reactive
} from 'vue';
  
  import { Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { BasicTable, useTable, TableAction, ActionItem } from '/@/components/Table';
  import { getMesQualityUnqualifiedPage, deleteMesQualityUnqualified, exportMesQualityUnqualified, getChildrenMesQualityUnqualified} from '/@/api/zlgl/bhgpcl';
  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 BhgpclModal from './components/BhgpclModal.vue';
  
  
  
  
  
  import { downloadByData } from '/@/utils/file/download';
  import ExportModal from '/@/views/form/template/components/ExportModal.vue';
    
  import { ColorPicker } from '/@/components/ColorPicker';
    import { XjrLabelComponentInfo } from '/@/components/LabelComponent';
  import { searchFormSchema, columns , formProps } from './components/config';
  
  import Icon from '/@/components/Icon/index';
   
   
  
  
  import { moneyChineseData,camelCaseString, } from '/@/utils/event/design';



  import { FormSchema } from '/@/components/Form/src/types/form';
import LookProcess from '/@/views/workflow/task/components/LookProcess.vue';
import TemplateCard from '/@bpmn/components/card/TemplateCard.vue';
import { EmptyBox } from '/@/components/ModalPanel/index';
import { getDesignPage } from '/@/api/workflow/design';
import { WorkflowPageModel } from '/@/api/workflow/model';
import { PageLayout } from '/@/components/ModalPanel';
import userTableScrollHeight from '/@/hooks/setting/userTableScrollHeight';
import { getAppEnvConfig } from '/@/utils/env';
import { getToken } from '/@/utils/auth';




   const listSpliceNum = ref(4); //操作列最先展示几个
   const visibleFlowLaunchModal = ref(false);
   const { scrollHeight } = userTableScrollHeight();
   const fromId = ref('');
   const loading = ref(false);
   
   // 查看流程相关变量
   const visibleLookProcess = ref(false);
   const taskIdProcess = ref('');
   const processIdProcess = ref('');
   
   // 流程模板数据
   const flowLaunchData = reactive({
     list: [] as WorkflowPageModel[],
     pagination: {
       current: 1,
       total: 0,
       pageSize: 20,
     },
   });
   
   // 搜索配置
   const searchConfig = [
     {
       field: 'code',
       label: '模板编码',
       type: 'input',
     },
     {
       field: 'name',
       label: '模板名称',
       type: 'input',
     },
   ];
   
   // 打开流程发起对话框
   function openFlowLaunchModal(id) {
     fromId.value = id;
     visibleFlowLaunchModal.value = true;
     // 初始化数据
     flowLaunchData.pagination.current = 1;
     flowLaunchData.pagination.total = 0;
     getFlowTemplateList();
   }
   
   // 获取流程模板列表
   async function getFlowTemplateList(params?: any) {
     const searchParams = {
       ...{
         limit: flowLaunchData.pagination.current,
         size: flowLaunchData.pagination.pageSize,
       },
       ...params,
       ...{ enabledMark: 1 }, // 流程发起list 需要隐藏 禁用的模板[enabledMark=1]
     };
     
     try {
       let res = await getDesignPage(searchParams);
       flowLaunchData.list = res.list;
       flowLaunchData.pagination.total = res.total;
     } catch (error) {
       console.error('获取流程模板列表失败:', error);
     }
   }
   
   // 搜索流程模板
   function searchFlowTemplate(params: any) {
     flowLaunchData.pagination.current = 1;
     getFlowTemplateList(params);
   }
   
   // 分页变化
   function handleFlowTemplatePageChange(page: number, pageSize: number) {
     flowLaunchData.pagination.current = page;
     flowLaunchData.pagination.pageSize = pageSize;
     getFlowTemplateList();
   }
   
   // 发起流程
   function launchProcess(schemaId: string) {
     Modal.confirm({
       title: '提示信息',
       icon: createVNode(ExclamationCircleOutlined),
       content: '是否确认发起流程？',
       okText: '确认',
       cancelText: '取消',
       onOk() {
         // 开始加载
         loading.value = true;
         // 调用接口发起流程
         fetch( getAppEnvConfig().VITE_GLOB_API_URL + '/zlgl/bhgpcl/launchProcess', {
           method: 'POST',
           headers: {
             'Content-Type': 'application/json',
             'Authorization': `Bearer ${getToken()}`
           },
           body: JSON.stringify({
             type: 1,
             schemaId: schemaId,
             fromId: fromId.value
           })
         })
         .then(response => response.json())
         .then(data => {
           // 结束加载
           loading.value = false;
           if (data.code == 0) {
             notification.success({
               message: '提示',
               description: '流程发起成功！',
             });
             visibleFlowLaunchModal.value = false;
             // 刷新不合格品列表数据
             reload();
           } else {
             notification.error({
               message: '提示',
               description: data.msg || '流程发起失败',
             });
           }
         })
         .catch(error => {
           // 结束加载
           loading.value = false;
           console.error('流程发起失败:', error);
           notification.error({
             message: '提示',
             description: '流程发起失败，请稍后重试',
           });
         });
       },
       onCancel() {},
     });
   }
   
   // 查看流程
   function viewProcess(record) {
     visibleLookProcess.value = true;
     taskIdProcess.value = record.taskId;
     processIdProcess.value = record.processId;
   }
 
  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 innerColumns = ref({});
  const innerDataSource = ref({});
  const subFormList = ref<any[]>([]);
  const visibleExport = ref(false);

  
  //展示在列表内的按钮
  const actionButtons = ref<string[]>(["view","edit","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":"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,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: 'Bhgpcl列表',
    api: getMesQualityUnqualifiedPage,
    rowKey: 'id',
    columns: filterColumns,
    pagination: {
      pageSize: 10,
    },
    formConfig: {
      labelWidth: 100,
      schemas: searchFormSchema,
      fieldMapToTime: [['djrq', ['djrqStart', 'djrqEnd'], '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) => {
      
      
       
      
      
    },
    useSearchForm: true,
    showTableSetting: true,
    
    
    
    striped: false,
    actionColumn: {
      width: 320,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    tableSetting: {
      size: false,
    },
    customRow,
    isAdvancedQuery:  false,
    querySelectOption: JSON.stringify(searchFormSchema),
    objectId: formIdComputedRef.value, ////系统表单formId,自定义表单releaseId的id值
  });

   const getSubFormList = (list) => {
    list?.map((item) => {
      if (['tab', 'grid', 'card'].includes(item.type)) {
        for (const child of item.children!) {
          getSubFormList(child.list);
        }
      } else if (item.type == 'table-layout') {
        for (const child of item.children!) {
          for (const sub of child.list) {
            getSubFormList(sub.children);
          }
        }
      } else if (item.type === 'form') {
        if (item.componentProps.isListView) {
          subFormList.value.push(item);
          innerColumns.value[item.field] = (item.componentProps! as FormSchema)
            .viewList!.filter((sub) => sub.checked)
            .map((sub) => {
              return {
                title: sub.label,
                dataIndex: camelCaseString(sub.field),
                componentType: sub.componentType,
              };
            });
        }
      }
    });
  };
  
  
  onMounted(() => {
  
  getSubFormList(formProps.schemas);
    });
  

  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() {
        deleteMesQualityUnqualified(ids).then((_) => {
          handleSuccess();
          notification.success({
            message: 'Tip',
            description: t('删除成功！'),
          });
        });
      },
      onCancel() {},
    });
  }
  
  
  
  
  
  
  function customRow(record: Recordable) {
    return {
      
      ondblclick: () => {
        if (record.isCanEdit && hasPermission("bhgpcl: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 exportMesQualityUnqualified({ isTemplate: false, columns: cols.toString(), ...pageParamsInfo.value});
    visibleExport.value = false;
    downloadByData(
      res.data,
      'Bhgpcl.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[] = [];  
    actionButtonConfig.value?.map((button) => {
    if (!record?.workflowData?.processId) {
        record.isCanEdit = true;
        actionsList.push({
          ...button,
            
          auth: `bhgpcl:${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: `bhgpcl:${button.code}`,
            label: button?.name,
            onClick: btnEvent[button.code]?.bind(null, record),
          });
        } 
      }
    });
    
    return actionsList;
  }
  
  
  function getInnerDataSource(id, field) {
    if (innerDataSource.value[id]) {
      return innerDataSource.value[id][field];
    }
    return [];
  }

  async function expandedRowsChange(isOpen, record) {
    if (!isOpen) return;
    const tableInfo = await getChildrenMesQualityUnqualified({
      id: record.id,
    });
    innerDataSource.value[record.id] = tableInfo;
  }
</script>
<style lang="less" scoped>

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

  .show{
    display: flex;
  }

  .hide{
    display: none !important;
  }
  
  
  
  :deep(.ant-table-expanded-row) {
    .ant-table {
      margin: 0 !important;
      height: 100%;

      .ant-table-thead {
        height: 40px;
      }

      .ant-empty-normal {
        margin: 16px 0;
      }
    }
    .ant-table-wrapper {
      height: 200px;
    }
  }
  
  /* 流程模板列表样式 */
  .list-page-box {
    height: calc(100% - 62px);
  }

  .page-box {
    height: 52px;
    border-top: 1px solid rgb(238 238 238 / 93%);
    text-align: right;
    padding: 10px 16px;
    background: #fff;
    position: absolute;
    right: 0;
    bottom: 0;
    left: 0;
    border-radius: 16px;
  }
  
  .my-10px {
    margin: 10px 0;
  }
  
</style>