<template>


  <ResizePageWrapper :hasLeft="false">


    <template #resizeRight>
      <BasicTable @register="registerTable" isMenuTable ref="tableRef"
        :row-selection="{ selectedRowKeys: selectedKeys, onChange: onSelectChange }">

        <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>



    <KcykModal @register="registerModal" @success="handleFormSuccess" @cancel="handleFormCancel" />





  </ResizePageWrapper>


</template>
<script lang="ts" setup>
import {
  ref, computed, provide, Ref,
} from 'vue';
import { getAppEnvConfig } from '/@/utils/env';
import { getToken } from '/@/utils/auth';
import { BasicTable, useTable, TableAction, ActionItem } from '/@/components/Table';
import { getMesWarehouseProfitandlossPage, deleteMesWarehouseProfitandloss } from '/@/api/ckgl/kcyk';
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 KcykModal from './components/KcykModal.vue';







import { searchFormSchema, columns } from './components/config';

import Icon from '/@/components/Icon/index';










const listSpliceNum = ref(3); //操作列最先展示几个






import { useConcurrentLock } from '/@/hooks/web/useConcurrentLock';
import { log } from 'console';

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 actionButtons = ref<string[]>(["create"]);
const buttonConfigs = computed(() => {
  const list = [{ "buttonId": "2016441785685393408", "name": "生成单据", "code": "create", "icon": "ant-design:download-outlined", "isDefault": false, "isUse": true, "setting": [], "showType": "inline", "buttonType": "primary" }]
  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 = {
  create: async (record) => {
    try {
      const response = await fetch(getAppEnvConfig().VITE_GLOB_API_URL + '/ckgl/kcyk/addslip', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${getToken()}`
        },
        body: JSON.stringify(record)
      });
      if (response.ok) {
        notification.success({
          message: '成功',
          description: '生成单据成功'
        });
        // 刷新列表
        reload();
      } else {
        const error = await response.json();
        notification.error({
          message: '失败',
          description: error.message || '生成单据失败'
        });
      }
    } catch (error) {
      notification.error({
        message: '错误',
        description: '生成单据时发生错误'
      });
      console.error('生成单据失败:', error);
    }
  }
}


const { currentRoute } = useRouter();


const formIdComputedRef = computed(() => currentRoute.value.meta.formId as string);
provide<Ref<string>>('currentFormId', formIdComputedRef);




const selectedKeys = ref<string[]>([]);
const selectedRowsData = ref<any[]>([]);



const [registerModal, { openModal }] = useModal();




const [registerTable, { reload, }] = useTable({
  title: 'Kcyk列表',
  api: getMesWarehouseProfitandlossPage,
  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) => {




    selectedKeys.value = [];
    selectedRowsData.value = [];

  },
  useSearchForm: true,
  showTableSetting: true,



  striped: false,
  actionColumn: {
    width: 65,
    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 onSelectChange(selectedRowKeys: [], selectedRows) {
  selectedKeys.value = selectedRowKeys;
  selectedRowsData.value = selectedRows;
}

function customRow(record: Recordable) {
  console.log(record);
  // 强制根据盈亏状态设置行背景色
  let rowStyle = {};
  if (record.ykzt == '亏') {
    // 亏损状态 - 红色背景
    rowStyle = {
      'color': 'red'
    };
  } else if (record.ykzt == '盈') {
    // 盈利状态 - 绿色背景
    rowStyle = {
      'color': 'green'
    };
  }
  return {
    style: rowStyle,
    onClick: () => {
      let selectedRowKeys = [...selectedKeys.value];
      if (selectedRowKeys.indexOf(record.id) >= 0) {
        let index = selectedRowKeys.indexOf(record.id);
        selectedRowKeys.splice(index, 1);
      } else {
        selectedRowKeys.push(record.id);
      }
      selectedKeys.value = selectedRowKeys;
    },
    ondblclick: () => {
      if (record.isCanEdit && hasPermission("kcyk:edit")) {
        handleEdit(record);
      }
    },
  };
}

function handleSuccess() {


  selectedKeys.value = [];
  selectedRowsData.value = [];
  reload();

}


function handleFormSuccess() {
  handleSuccess();
  handleCloseFormEnableLocke(buttonConfigs.value, 'edit');
}
function handleFormCancel() {
  handleCloseFormEnableLocke(buttonConfigs.value, 'edit');
}






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: `kcyk:${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: `kcyk:${button.code}`,
          label: button?.name,
          onClick: btnEvent[button.code]?.bind(null, record),
        });
      }
    }
  });
  return actionsList;
}


</script>
<style lang="less" scoped>
:deep(.ant-table-selection-col) {
  width: 50px;
}

.show {
  display: flex;
}

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