<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 === 'qtyGjAll'">
            {{ Number.format(Number.parse(record.qtyGjAll),numFormat) }}
          </template>
          <template v-if="column.dataIndex === 'qtyGjJsz'">
            {{ Number.format(Number.parse(record.qtyGjJsz),numFormat) }}
          </template>
          <template v-if="column.dataIndex === 'qtyGjXs'">
            {{ Number.format(Number.parse(record.qtyGjXs),numFormat) }}
          </template>
          <template v-if="column.dataIndex === 'qtyGjYsp'">
            {{ Number.format(Number.parse(record.qtyGjYsp),numFormat) }}
          </template>
          <template v-if="column.dataIndex === 'action'">
            <TableAction :actions="getActions(record)" />
          </template>
        </template>
      </BasicTable>
   <PngApproJszModal @register="registerModal" @success="handleSuccess" />
  <DataLog :logId="logId" :logPath="logPath" v-model:visible="modalVisible"/>
   <rejectReplyModal :visible="isOpen" @success="handleRejectReply" />
  </PageWrapper>
</template>
<script lang="ts" setup>
  const modalVisible = ref(false);
  const logId = ref('')
  const logPath = ref('/dayPlan/pngApproJsz/datalog');
  import { DataLog } from '/@/components/pcitc';
  import { ref, computed, onMounted, onUnmounted, 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 { getLngPngApproPage, deleteLngPngAppro, approveLngPngAppro} from '/@/api/dayPlan/PngApproJsz';
  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 { getLngPngAppro } from '/@/api/dayPlan/PngApproJsz';
  import { useModal } from '/@/components/Modal';
  import PngApproJszModal from './components/PngApproJszModal.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 rejectReplyModal from '/@/components/common/rejectReplyModal.vue';
  import dayjs from 'dayjs';
  const { bus, CREATE_FLOW, FLOW_PROCESSED, FORM_LIST_MODIFIED } = useEventBus();
  const defaultDate = ref([dayjs().format('YYYY-MM-DD'),dayjs().add(1, 'day').format('YYYY-MM-DD')]);
  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 numFormat = "###,###,###,###,###,###.000"
  const tableRef = ref();
  //所有按钮
  const buttons = ref([
    {"name":"刷新","code":"refresh","icon":"ant-design:reload-outlined","isDefault":true,"isUse":true},
    {"isUse":true,"name":"审批","code":"approveJsz","icon":"ant-design:check-outlined","isDefault":true},
    {"isUse":true,"name":"驳回","code":"reject","icon":"ant-design:stop-outlined","isDefault":true}]);
  //展示在列表内的按钮
  const actionButtons = ref<string[]>(['reject', 'approveJsz']);
  const buttonConfigs = computed(()=>{
    return filterButtonAuth(buttons.value);
  })

  const tableButtonConfig = computed(() => {
     return [{"isUse":true,"name":"审批通过","code":"approveGD","icon":"ant-design:check-outlined","isDefault":true}]
    // 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,view : handleView,approveJsz : handleApprove,reject: handleReject,}
  const isOpen = ref(false)
  const selectedKeys = ref([])
  const curData = ref({})
  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='管道气接收站审批';
  const formName=currentRoute.value.meta?.title;
  const [registerTable, { reload, clearSelectedRowKeys  }] = useTable({
    title: '' || (formName + '列表'),
    api: getLngPngApproPage,
    rowKey: 'datePlan',
    columns: customConfigColums,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: [
        {
          field: 'datePlan',
          label: '计划日期',
          component: 'RangePicker',
          defaultValue: defaultDate.value, 
          componentProps: {
            format: 'YYYY-MM-DD',
            style: { width: '100%' },
            getPopupContainer: () => document.body,
          },
        },
      ],
      fieldMapToTime: [['datePlan', ['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' },
    },
    rowSelection: {
      type: 'checkbox',
      onChange: onSelectChange
    },
    tableSetting: {
      size: false,
      setting: false,
    },
    
  });
  function onSelectChange(rowKeys: string[]) {
    selectedKeys.value = rowKeys;
  }
  async function handleApprove(record: Recordable) {
    let obj = {
      "result": "C",
      "remark": "",
      "data": [{datePlan: record.datePlan}]
    }
    await approveLngPngAppro(obj)
    handleSuccess();
    notification.success({
      message: 'Tip',
      description: t('审批成功！'),
    });
  }
  function handleReject (record: Recordable) {
    curData.value = record
    isOpen.value = true
  }
  const handleRejectReply = async (val) => {
    let obj = {
      "result": "R",
      "remark": val.reply,
      "data": [{datePlan: curData.value.datePlan}]
    }
    await approveLngPngAppro(obj)
    isOpen.value = false
    handleSuccess();
    notification.success({
      message: 'Tip',
      description: t('已驳回！'),
    });
  }
  async function handleBatchApprove () {
    if (!selectedKeys.value.length) {
      notification.warning({
        message: 'Tip',
        description: t('请选择需要审批的数据'),
      });
      return;
    }
    let arr = selectedKeys.value.map(v=> {
      return {
        datePlan: v
      }
    })

    let obj = {
      "result": "C",
      "remark": "",
      "data": arr
    }
    await approveLngPngAppro(obj)
    handleSuccess();
    notification.success({
      message: 'Tip',
      description: t('审批成功！'),
    });
    clearSelectedRowKeys()
   
  }
  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/PngApproJsz/' + record.id + '/viewForm',
        query: {
          formPath: 'dayPlan/PngApproJsz',
          formName: formName,
          formId:currentRoute.value.meta.formId
        }
      });
    }
  }

  function buttonClick(code) {
    handleBatchApprove()
    // btnEvent[code]();
  }
  function handleDatalog (record: Recordable) {
    modalVisible.value = true
    logId.value = record.id
  }
  
  function handleAdd() {
    if (schemaIdComputedRef.value) {
      router.push({
        path: '/flow/' + schemaIdComputedRef.value + '/0/createFlow'
      });
    } else {
      router.push({
        path: '/form/PngApproJsz/0/createForm',
        query: {
          formPath: 'dayPlan/PngApproJsz',
          formName: formName,
          formId:currentRoute.value.meta.formId
        }
      });
    }
  }
  
  function handleEdit(record: Recordable) {
    
    router.push({
      path: '/form/PngApproJsz/' + record.id + '/updateForm',
      query: {
          formPath: 'dayPlan/PngApproJsz',
          formName: formName,
          formId:currentRoute.value.meta.formId
      }
    });
  }
  function handleDelete(record: Recordable) {
    deleteList([record.id]);
  }
  function deleteList(ids) {
    Modal.confirm({
      title: '提示信息',
      icon: createVNode(ExclamationCircleOutlined),
      content: '是否确认删除？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        deleteLngPngAppro(ids).then((_) => {
          handleSuccess();
          notification.success({
            message: 'Tip',
            description: t('删除成功！'),
          });
        });
      },
      onCancel() {},
    });
  }
  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[] {
    
    let actionsList: ActionItem[] = [];
    let editAndDelBtn: ActionItem[] = [];
    let hasFlowRecord = false; 
    actionButtonConfig.value?.map((button) => {
      if (['view', 'copyData', 'approveJsz', 'reject'].includes(button.code)) {
        actionsList.push({
          icon: button?.icon,
          tooltip: button?.name,
          onClick: btnEvent[button.code].bind(null, record),
        });
      }
      if (['edit', 'delete'].includes(button.code)) {
        editAndDelBtn.push({
          icon: button?.icon,
          tooltip: button?.name,
          color: button.code === 'delete' ? 'error' : undefined,
          onClick: btnEvent[button.code].bind(null, record),
        });
      }
      if (button.code === 'flowRecord') hasFlowRecord = true;
    });
    // if (record.workflowData?.enabled) {
    //   //与工作流有关联的表单
    //   if (record.workflowData.status) {
    //     actionsList.unshift(setIndexFlowStatus(record.workflowData))
    //   } else {
    //     actionsList = actionsList.concat(editAndDelBtn);
    //   }
    // } else {
    //   if (!record.workflowData?.processId) {
    //     //与工作流没有关联的表单并且在当前页面新增的数据 如选择编辑、删除按钮则加上
    //     actionsList = actionsList.concat(editAndDelBtn);
    //   }
    // }
    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: 320px !important;
    max-width: 320px !important;;
  }
  :deep(.ant-col-8:nth-child(1) .ant-form-item-label) {
    width: 80px !important;
  }
</style>