<template>
  <PageWrapper dense fixedHeight contentFullHeight contentClass="flex">
      <BasicTable @register="registerTable" ref="tableRef"   @row-dbClick="dbClickRow">
       
        <template #toolbar>
          <template v-for="button in tableButtonConfig" :key="button.code">
            <a-button v-if="button.isDefault" :type="button.type" @click="buttonClick(button.code)">
              <template #icon><Icon :icon="button.icon" /></template>
              {{ button.name }}
            </a-button>
            <a-button v-else :type="button.type">
              <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="getActions(record)" />
          </template>
        </template>
      </BasicTable>
   <ContractSalesPngPurModal @register="registerModal" @success="handleSuccess" />
  <DataLog :logId="logId" :logPath="logPath" v-model:visible="modalVisible"/>
  </PageWrapper>
</template>
<script lang="ts" setup>
  const modalVisible = ref(false);
  const logId = ref('')
  const logPath = ref('/contract/contractSalesPngPur/datalog');
  import { DataLog } from '/@/components/pcitc';
  import { ref, computed, onMounted, onUnmounted,  

} from 'vue';
  
  import { BasicTable, useTable, TableAction, ActionItem } from '/@/components/Table';
  import { getLngContractSalesPngPointPage, deleteLngContractSalesPngPoint} from '/@/api/contract/ContractSalesPngPur';
  import { PageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { useFormConfig } from '/@/hooks/web/useFormConfig';
  import { useRouter } from 'vue-router';
  import { setIndexFlowStatus } from '/@/utils/flow/index'
  import { getLngContractSalesPngPoint } from '/@/api/contract/ContractSalesPngPur';
  import { useModal } from '/@/components/Modal';
  import ContractSalesPngPurModal from './components/ContractSalesPngPurModal.vue';
  import {formConfig, searchFormSchema, columns } from './components/config';
  import Icon from '/@/components/Icon/index';
  import useEventBus from '/@/hooks/event/useEventBus';
  import { cloneDeep } from 'lodash-es';
  import dayjs from 'dayjs';
  const defaultDate = ref([dayjs().subtract(1, 'month').format('YYYY-MM-DD'),dayjs().add(1, 'month').format('YYYY-MM-DD')]);

  const { bus, CREATE_FLOW, FLOW_PROCESSED, FORM_LIST_MODIFIED } = useEventBus();

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

  const filterColumns = cloneDeep(filterColumnAuth(columns));
  const customConfigColums =ref(filterColumns);
  const customSearchFormSchema =ref(searchFormSchema);
  
  const tableRef = ref();
  //所有按钮
  const buttons = ref([{"name":"编辑","code":"edit","icon":"ant-design:form-outlined","isDefault":true,"isUse":true},{"name":"刷新","code":"refresh","icon":"ant-design:reload-outlined","isDefault":true,"isUse":true},{"name":"查看","code":"view","icon":"ant-design:eye-outlined","isDefault":true,"isUse":true},{"name":"数据日志","code":"datalog","icon":"ant-design:profile-outlined","isDefault":true,"isUse":true}]);
  //展示在列表内的按钮
  const actionButtons = ref<string[]>(['view', 'edit','datalog', 'copyData', 'delete', 'startwork','flowRecord']);
  const buttonConfigs = computed(()=>{
    return filterButtonAuth(buttons.value);
  })

  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 = {edit : handleEdit,refresh : handleRefresh,view : handleView,datalog : handleDatalog,}

  const { currentRoute } = useRouter();
  const router = useRouter();
  const formIdComputedRef = ref();
  formIdComputedRef.value = currentRoute.value.meta.formId
  const schemaIdComputedRef = ref();
  schemaIdComputedRef.value = currentRoute.value.meta.schemaId
  const [registerModal, { openModal }] = useModal();
  const formName=currentRoute.value.meta?.title;
  const [registerTable, { reload,   }] = useTable({
    title: '' || (formName + '列表'),
    api: getLngContractSalesPngPointPage,
    rowKey: 'id',
    columns: customConfigColums,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: [
        {
          field: 'dateFrom',
          label: '销售合同有效期',
          component: 'RangePicker',
          // defaultValue: defaultDate.value,
          componentProps: {
            format: 'YYYY-MM-DD',
            style: { width: '100%' },
            getPopupContainer: () => document.body,
          },
        },
      {
        field: 'ksName',
        label: '销售合同号/名称',
        component: 'Input',
      },
      {
        field: 'cuName',
        label: '客户',
        component: 'Input',
      },
      ],
      fieldMapToTime: [['dateFrom', ['startDate', 'endDate'], 'YYYY-MM-DD']],
      showResetButton: true,
    },
    immediate: false,
    beforeFetch: (params) => {
      return { ...params, FormId: formIdComputedRef.value, PK: 'id',page:params.limit };
    },
    afterFetch: (res) => {
      tableRef.value.setToolBarWidth();
      
    },
    useSearchForm: true,
    showTableSetting: true,
    
    striped: false,
    actionColumn: {
      width: 160,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    tableSetting: {
      size: false,
      setting: false,
    },
    
  });
  
  function dbClickRow(record) {
    router.push({
      path: '/contract/ContractSalesPngPur/createForm',
      query: {
          formPath: 'contract/ContractSalesPngPur',
          formName: '查看'+formName,
          formId:currentRoute.value.meta.formId,
          id: record.ksppId,
          type: 'view'
      }
    });
  }

  function buttonClick(code) {
    
    btnEvent[code]();
  }
  function handleDatalog (record: Recordable) {
    modalVisible.value = true
    logId.value = record.id
  }
  function handleEdit(record: Recordable) {
    
    router.push({
      path: '/contract/ContractSalesPngPur/createForm',
      query: {
          formPath: 'contract/ContractSalesPngPur',
          formName: '编辑'+formName,
          formId:currentRoute.value.meta.formId,
          id: record.ksppId,
          type: 'edit'
      }
    });
  }
  function handleRefresh() {
    reload();
  }
  function handleSuccess() {
    
    reload();
  }
  
  function handleView(record: Recordable) {
      
      dbClickRow(record);
      
  }
  onMounted(() => {
    reload({ searchInfo: { startDate: defaultDate.value[0], endDate: defaultDate.value[1] }});
    if (schemaIdComputedRef.value) {
      bus.on(FLOW_PROCESSED, handleRefresh);
      bus.on(CREATE_FLOW, handleRefresh);
    } else {
      bus.on(FORM_LIST_MODIFIED, handleRefresh);
    }
    
    // 合并渲染覆盖配置中的列表配置，包括展示字段配置、搜索字段配置、按钮配置
    mergeCustomListRenderConfig();
  });
  onUnmounted(() => {
    if (schemaIdComputedRef.value) {
      bus.off(FLOW_PROCESSED, handleRefresh);
      bus.off(CREATE_FLOW, handleRefresh);
    } else {
      bus.off(FORM_LIST_MODIFIED, handleRefresh);
    }
  });
  function getActions(record: Recordable):ActionItem[] {
    
    const actionsList: ActionItem[] = actionButtonConfig.value?.map((button) => {
      if (!record.workflowData?.processId) {
        return {
          icon: button?.icon,
          tooltip: button?.name,
          color: button.code === 'delete' ? 'error' : undefined,
          onClick: btnEvent[button.code].bind(null, record),
        };
      } else {
        if (button.code === 'view') {
          return {
            icon: button?.icon,
            tooltip: button?.name,
            onClick: btnEvent[button.code].bind(null, record),
          };
        } else {
          return {};
        }
      }
    });
    return actionsList;
  }
  async function mergeCustomListRenderConfig(){
    if (formConfig.useCustomConfig) {
       let formId=currentRoute.value.meta.formId;
       //1.合并展示字段配置
       let cols= await mergeColumns(customConfigColums.value,formId);
       customConfigColums.value=cols;
       //2.合并搜索字段配置
       let sFormSchema= await mergeSearchFormSchema(customSearchFormSchema.value,formId);
       customSearchFormSchema.value=sFormSchema;
       //3.合并按钮配置
       let btns= await mergeButtons(buttons.value,formId);
       buttons.value=btns;
    }
  };
</script>
<style lang="less" scoped>
  :deep(.ant-table-selection-col) {
    width: 50px;
  }
  .show{
    display: flex;
  }
  .hide{
    display: none !important;
  }

  :deep( .ant-col-8:nth-child(1)) {
    width: 350px !important;
    max-width: 350px !important;;
  }
  :deep(.ant-col-8:nth-child(1) .ant-form-item-label) {
    width: 110px !important;
  }
  :deep(.ant-col-8:nth-child(1) .ant-form-item-label label) {
    width: 110px !important;
    max-width: 110px !important;
  }
   :deep(.ant-col-8:nth-child(2) .ant-form-item-label) {
    width: 120px !important;
  }
  :deep(.ant-col-8:nth-child(2) .ant-form-item-label label) {
    width: 120px !important;
    max-width: 120px !important;
  }
  :deep( .ant-col-8:nth-child(2)) {
    width: 300px !important;
    max-width: 300px !important;;
  }
</style>