<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 v-if="column.dataIndex === 'lngFileUploadList'">
          <div>
            <Upload :file-list="record.lngFileUploadList" :showUploadList="false" v-model:value="tableId" v-model:tableName="tableName" v-model:columnName="columnName"
              :multiple="true" :dataDelete="true" :isShowTip="false" :isShowBtnIcon="false" @click="onUpload(index)" @change="uploadChange" :showDownloadIcon="false"/>
            <div v-for="(item, idx) in record.lngFileUploadList">
                <a @click="handleDownload(item)">{{item.fileOrg}}</a>
            </div>
          </div>
        </template>
        </template>
      </BasicTable>
   <PngSettleHdrEcModal @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('/dayPlan/pngSettleHdrEc/datalog');
  import { DataLog } from '/@/components/pcitc';
  import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
  
  import { BasicTable, useTable, TableAction, ActionItem } from '/@/components/Table';
  import { getLngPngSettleHdrPage, deleteLngPngSettleHdr} from '/@/api/dayPlan/PngSettleHdrEc';
  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 { getLngPngSettleHdr } from '/@/api/dayPlan/PngSettleHdrEc';
  import { useModal } from '/@/components/Modal';
  import PngSettleHdrEcModal from './components/PngSettleHdrEcModal.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 { DataFormat, FormatOption, DATE_FORMAT, FormatType } from '/@/utils/dataFormat';
  import Upload from '/@/components/Form/src/components/Upload.vue';
  import { parseDownloadUrl} from '/@/api/system/file';
  import { downloadByUrl } from '/@/utils/file/download';

  const tableId = '';
  const tableName = 'PngSettleHdrEc';
  const columnName = 'PngSettleHdrEc';
  
  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 tableData = ref([])
  const curIdx = ref()
  //所有按钮
  const buttons = ref([{"isUse":true,"name":"刷新","code":"refresh","icon":"ant-design:reload-outlined","isDefault":true},{"isUse":true,"name":"数据日志","code":"datalog","icon":"ant-design:profile-outlined","isDefault":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 = {refresh : handleRefresh,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, getDataSource, updateTableDataRecord,setTableData }] = useTable({
    title: '' || (formName + '列表'),
    api: getLngPngSettleHdrPage,
    rowKey: 'id',
    columns: customConfigColums,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: customSearchFormSchema,
      fieldMapToTime: [['datePlan', ['startDate', 'endDate'], 'YYYY-MM']],
      showResetButton: true,
    },
    beforeFetch: (params) => {
      return { ...params, FormId: formIdComputedRef.value, PK: 'id' };
    },
    afterFetch: (res) => {
      tableData.value = res || []
      tableRef.value.setToolBarWidth();
      
    },
    useSearchForm: true,
    showTableSetting: true,
    
    striped: false,
    tableSetting: {
      size: false,
      setting: false,
    },
    
  });
  watch(
    () => tableData.value,
    (val) => {
      if (val) {
        let arr =  DataFormat.format(val, [
          FormatOption.createQty('qtySettleGj'),
          FormatOption.createQty('qtySettleM3'),
          FormatOption.createAmt('amount'),
        ]);
        if (arr.length) {
          setTableData(arr)
        }
      }  
    },
    {
      immediate: true,
      deep: true,
    }
  );
  const onUpload = (index) => {
    curIdx.value = index
  }
  const uploadChange = (val) => {
    let data = getDataSource()
    let record = data[curIdx.value]
    record.lngFileUploadList = val
    updateTableDataRecord(record.id, record)
  }
  const handleDownload = (info) => {
    const url = parseDownloadUrl(info.response ? info.response.data.fileUrl : info.fileUrl);
    const fileName = info.response ? info.response.data.fileOrg : info.fileOrg;
    downloadByUrl({ url, fileName: fileName});
  };
  function dbClickRow(record) {
    if (!actionButtonConfig?.value.some(element => element.code == 'view')) {
      return;
    }
    const { processId, taskIds, schemaId } = record.workflowData || {}; 
    if (taskIds && taskIds.length) {
      router.push({
        path: '/flow/' + schemaId + '/' + (processId || '') + '/approveFlow',
        query: {
          taskId: taskIds[0],
          formName: formName,
          formId:currentRoute.value.meta.formId
        }
      });
    } else if (schemaId && !taskIds && processId) {
      router.push({
        path: '/flow/' + schemaId + '/' + processId + '/approveFlow',
        query: {
          readonly: 1,
          taskId: '',
          formName: formName,
          formId:currentRoute.value.meta.formId
        }
      });
    } else {
      router.push({
        path: '/form/PngSettleHdrEc/' + record.id + '/viewForm',
        query: {
          formPath: 'dayPlan/PngSettleHdrEc',
          formName: formName,
          formId:currentRoute.value.meta.formId
        }
      });
    }
  }

  function buttonClick(code) {
    
    btnEvent[code]();
  }
  function handleDatalog (record: Recordable) {
    modalVisible.value = true
    logId.value = record.id
  }
  function handleRefresh() {
    reload();
  }
  function handleSuccess() {
    
    reload();
  }
  onMounted(() => {
    
    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;
  }
</style>