<!--
@ 作者: 秦东
@ 时间: 2026-01-28 09:13:22
@ 备注: 
-->
<script lang='ts' setup>
import { checkboxUnit, choiceUnit, inputUnit, orgDeptUnit, orgUnit, switchUnit, timeUnit } from '@/api/DesignForm/fieldUnit';
import { attrButton, FormPageConfig, FormPageList, tableButton, viewPageType } from '@/api/DesignForm/tableButton';
import { echatsViewStruct } from '@/api/DesignForm/types';
import { formatNumber } from '@/api/DesignForm/utils';
import { useDesignFormStore } from '@/store/DesignForm/designForm';
import { json2string } from '@/utils/DesignForm/form';
import { FormInstance } from 'element-plus';
import { useRoute } from 'vue-router';
import { formHasPower } from '@/directive/permission/button';
import { gainFormPageListCont } from '@/api/DesignForm/requestapi';
import request from '@/utils/request';

//引入组件
import SearchSelect from "@/components/DesignForm/app/calendar/selectSearch.vue";
import exportPanel from "@/components/DesignForm/exportPanel.vue";

//引入页面
import TablesList from "@/components/DesignForm/app\pageViews\tableList.vue"


const props = withDefaults(
    defineProps<{
        data: FormPageList | any;
        searchData?: attrButton[] | any;
        config?: FormPageConfig;
        appKey?: string;
        formId?: string;
        signCode?: string;
        beforeRequest?: (params: any, rout: any) => any;
        afterResponse?: (result: any) => any | string;
        beforeDelete?: (params: any, route: any) => any;
        showPage?: boolean;
        requestUrl?: string; // 请求的api
        deleteUrl?: string; // 删除的api
        dict?: { [key: string | number]: string | number };
        fixedBottomScroll?: boolean;
        query?: { [key: string]: any }; // 一些附加的请求参数
        autoLoad?: boolean; // 初始时自动请求加载数据
        delKey?: string; // 删除标识
        lookPageIsShow?: boolean;
        versionid?: string;
        pickAppMenu?: any;
        versiontitle?: string;
        viewPage?: viewPageType | any;
        formBasicConfig?: any;
        fieldsDetailList?: any;
        orgAndManTree?: any;
        echatsViews: echatsViewStruct;
    }>(),
    {
        showPage: true,
        data: () => {
            return { columns: [], controlBtn: [], operateBtn: [], config: {} };
        },
        searchData: () => {
            return [];
        },
        config: ():FormPageConfig => {
            return {
                pageSize: 0,
                searchIsShow: false,
                searchFormIsShow: false,
                openPageMode: ''
            };
        },
        dict: () => {
            return {};
        },
        appKey: () => {
            return "";
        },
        requestUrl: () => {
            return "";
        },
        deleteUrl: () => {
            return "";
        },
        formId: () => {
            return "";
        },
        signCode: () => {
            return "";
        },
        versionid: () => {
            return "";
        },
        versiontitle: () => {
        return "";
        },
        fixedBottomScroll: true,
        autoLoad: true,
        delKey: "id",
        query: () => {
            return {};
        },
        lookPageIsShow: () => {
            return false;
        },
        viewPage: ():viewPageType => {
            return {
                card: undefined,
                list: {
                    status: false,
                    isClick: false,
                    form: {
                        sortWord: '',
                        sortClass: 0
                    }
                },
                date: {
                    status: false,
                    isClick: false,
                    form: {
                        startTime: '',
                        endTime: '',
                        dayType: 0
                    }
                },
                time: {
                    status: false,
                    isClick: false,
                    form: {
                        sortWord: '',
                        sort: 0
                    }
                },
                gantt: {
                    status: false,
                    isClick: false,
                    form: {
                        startTime: '',
                        endTime: '',
                        dayType: 0,
                        sortWord: '',
                        sort: 0
                    }
                },
                map: {
                    status: false,
                    isClick: false,
                    form: {
                        mapWord: '',
                        sortWord: '',
                        sort: 0
                    }
                },
                chart: {
                    status: false,
                    isClick: false,
                    form: {
                        mapWord: '',
                        sortWord: '',
                        sort: 0
                    }
                }
            };
        },
        formBasicConfig: () => {
            return {};
        },
        fieldsDetailList: () => {
            return {};
        },
        orgAndManTree: () => {
            return {};
        },
        pickAppMenu: () => {
            return {};
        },
        beforeRequest: (params: any, rout: any):any => {
            return
        },
        afterResponse: (result: any):any | string => {
            return
        },
        beforeDelete: (params: any, rout: any):any => {
            return
        }
    }
)

const emits = defineEmits(["selectionChange", "btnClick"]);
const tableDataList = ref([]); // 表格行数据
const calendarPageRef = ref(null);      //数据页面
const route = useRoute();
const designStore = useDesignFormStore();
//基础设定
const state = reactive({
    loading: false,
    currentPage: 1,
    pageSize: props.config?.pageSize || 2,
    total: 0,
    selectionChecked: [],
    dict: {}, // 接口返回的
    searchFormDown: false,
    treeValue: {}, // 侧栏树选中的值
    tableScrollMargin: 0,
    columnsCheck: designStore.getColumnsCheck(route.path),
    currentNodeKey: "",
});
const viewType = ref(1);        //试图类型 (1：列表视图；2：日历视图；3：时间轴；4：甘特图；5：地图视图；6：卡片视图；7：BI报表)
const viewLayout = ref<any>();  //当前视图框架
const ruleSearchForm = ref();   //搜索表单
const drawerWith = ref(); //编辑表单时抽屉宽度
const container = ref(); //实例化内容容器
const openTaskDrawer = ref(false); //新增数据
const idList = ref<string[]>([]);
//导出窗口的父元素
const dynamicVNode = ref<VNode | null>(null); //组件的父组件
const operState = ref<number>(1); //操作状态	1：新增；2：重新发起；3：申请修改；4：提交审批;5:普通表单修改
const tablePageClass = ref(1);
const pageInfoCont = ref<any>();
const lookPageInfoIsShow = ref(false);
// 重置所有视图的 isClick 状态
const resetViewClickStates = (excludeView?: string) => {
    if (!props.viewPage || typeof props.viewPage !== 'object') return;
    const views = ['list', 'date', 'time', 'gantt', 'map', 'card', 'chart'];
    views.forEach(view => {
        const viewObj = props.viewPage[view];
        if (view !== excludeView && viewObj && typeof viewObj === 'object') {
            viewObj.isClick = false;
        }
    });
};
/**
@ 作者: 秦东
@ 时间: 2026-01-28 10:43:43
@ 功能: 获取数据
*/
const getPageData = () => {
    let sendData = {
        formId: props.formId,
        page: state.currentPage,
        pagesize: state.pageSize,
        searchData: json2string(props.searchData),
    };

    console.error("返回值事什么-->",viewType.value)
    //根据页面类型获取数据
    switch (viewType.value) {
        case 2:
            nextTick(() => {
                // calendarPageRef.value.calendarSearchData(sendData);
            })
            break;
        case 3:
        
            break;
        case 4:
            
            break;
        case 5:
            
            break;
        case 6:
            
            break;
        case 7:
            
            break;
        default:
            state.loading = true;
            doGainFormPageListCont(sendData)
                .then((datas) => {
                    console.error("返回值事什么-->",datas)
                    tableDataList.value = datas.list;
                    state.total = datas.total;                    
                })
                .finally(() => {
                    state.loading = false;
                    asfs = [];
                    radios = [];
                    checkboxs = [];
                    switchs = [];
                    selects = [];
                    tables = [];
                    dofs = [];
                    getAsfs();
                })
            break;
    }
}
/**
@ 作者: 秦东
@ 时间: 2026-01-28 14:52:46
@ 功能: 
*/
const getAsfs = () => {
    let dataList = ref({});
    dataList.value = props.fieldsDetailList;
    if (dataList && Array.isArray(dataList.value) && dataList.value.length > 0) {
        for (let i = 0; i < dataList.value.length; i++) {
            if (dataList.value[i].type == "associatedForms") {
                asfs.push(dataList.value[i]);
            } else if (dataList.value[i].type == "radio") {
                radios.push(dataList.value[i]);
            } else if (dataList.value[i].type == "checkbox") {
                checkboxs.push(dataList.value[i]);
            } else if (dataList.value[i].type == "switch") {
                switchs.push(dataList.value[i]);
            } else if (dataList.value[i].type == "select") {
                selects.push(dataList.value[i]);
            } else if (
                dataList.value[i].type == "deptOrg" ||
                dataList.value[i].type == "orgCentent" ||
                dataList.value[i].type == "founder"
            ) {
                //||dataList.value[i].type == "owner"拥有者,"expand-user"选择用户
                dofs.push(dataList.value[i]);
            } else if (
                dataList.value[i].type == "card" ||
                dataList.value[i].type == "flex" ||
                dataList.value[i].type == "div" ||
                dataList.value[i].type == "table"
            ) {
                if (dataList.value[i].type == "table") {
                    tables.push(dataList.value[i]);
                }

                dataList.value[i].list.forEach((element: any) => {
                    if (element.type == "associatedForms") {
                        asfs.push(element);
                    } else if (element.type == "radio") {
                        radios.push(element);
                    } else if (element.type == "checkbox") {
                        checkboxs.push(element);
                    } else if (element.type == "switch") {
                        switchs.push(element);
                    } else if (element.type == "select") {
                        selects.push(element);
                    } else if (
                        element.type == "deptOrg" ||
                        element.type == "orgCentent" ||
                        element.type == "founder"
                    ) {
                        dofs.push(element);
                    }
                });
            } else if (dataList.value[i].type == "grid") {
                let columns = JSON.parse(JSON.stringify(dataList.value[i].columns));
                if (columns.length > 0) {
                    for (let z = 0; z < columns.length; z++) {
                        for (let x = 0; x < columns[z].list.length; x++) {
                            let a = JSON.parse(JSON.stringify(columns[z].list[x]));
                            if (a.type == "associatedForms") {
                                asfs.push(a);
                            } else if (a.type == "radio") {
                                radios.push(a);                                                                                                                                                         
                            } else if (a.type == "checkbox") {
                                checkboxs.push(a);
                            } else if (a.type == "switch") {
                                switchs.push(a);
                            } else if (a.type == "select") {
                                selects.push(a);
                            } else if (
                                a.type == "deptOrg" ||
                                a.type == "orgCentent" ||
                                a.type == "founder"
                            ) {
                                dofs.push(a);
                            }
                        }
                    }
                }
            } else if (dataList.value[i].type == "tabs") {
                //tabs标签页有可能再嵌套一层flex或者table
                let columns = JSON.parse(JSON.stringify(dataList.value[i].columns));
                if (columns.length > 0) {
                    for (let z = 0; z < columns.length; z++) {
                        for (let x = 0; x < columns[z].list.length; x++) {
                            let a = JSON.parse(JSON.stringify(columns[z].list[x]));

                            if (a.type == "associatedForms") {
                                asfs.push(a);
                            } else if (a.type == "radio") {
                                radios.push(a);
                            } else if (a.type == "checkbox") {
                                checkboxs.push(a);
                            } else if (a.type == "switch") {
                                switchs.push(a);
                            } else if (a.type == "select") {
                                selects.push(a);
                            } else if (
                                a.type == "deptOrg" ||
                                a.type == "orgCentent" ||
                                a.type == "founder"
                            ) {
                                dofs.push(a);
                            } else if (a.type == "flex" || a.type == "table") {
                                if (a.type == "table") {
                                    tables.push(dataList.value[i]);
                                }

                                if (a.list.length > 0) {
                                    for (let m = 0; m < a.list.length; m++) {
                                        let q = JSON.parse(JSON.stringify(a.list[m]));
                                        if (q.type == "associatedForms") {
                                            asfs.push(q);
                                        } else if (q.type == "radio") {
                                            radios.push(q);
                                        } else if (q.type == "checkbox") {
                                            checkboxs.push(q);
                                        } else if (q.type == "switch") {
                                            switchs.push(q);
                                        } else if (q.type == "select") {
                                            selects.push(q);
                                        } else if (
                                            q.type == "deptOrg" ||
                                            q.type == "orgCentent" ||
                                            q.type == "founder"
                                        ) {
                                            dofs.push(q);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
/**
@ 作者: 秦东
@ 时间: 2026-01-28 10:17:24
@ 功能: 切换视图展示方式
*/
const tabsView = (val: any, types: number) => {
    viewType.value = types;
    val.isClick = true;
    viewLayout.value = val;
    switch (types) {
    case 2:
      resetViewClickStates('date');
      break;
    case 3:
      resetViewClickStates('time');
      getPageData();
      break;
    case 4:
      resetViewClickStates('gantt');
      break;
    case 5:
     resetViewClickStates('map');
      break;
    case 6:
      resetViewClickStates('card');
      break;
    case 7:
      resetViewClickStates('chart');
      break;
    default:
      resetViewClickStates('list');
      break;
    }
}
/**
@ 作者: 秦东
@ 时间: 2026-01-28 10:58:02
@ 功能: 重置搜索表单
*/
const resetFields = (formEl: FormInstance | undefined) => {
    if (props.searchData && props.searchData.length > 0) {
        props.searchData.forEach((item: any) => {
            item.value = "";
        });
    }
}
/**
@ 作者: 秦东
@ 时间: 2024-03-28 16:03:12
@ 功能: 判断搜索组件类型
*/
const unitIsShow = (val: attrButton, unitName: string):boolean => {
    switch (val.fieldClass) {
        case "id": //自定义表单保留字
            return inputUnit.includes(unitName);
            break;
        case "masters_key": //自定义表单保留字
            return inputUnit.includes(unitName);
            break;
        case "creater": //自定义表单保留字
            return inputUnit.includes(unitName);
            break;
        case "creater_time": //自定义表单保留字
            return timeUnit.includes(unitName);
            break;
        case "edit_time": //自定义表单保留字
            return timeUnit.includes(unitName);
            break;
        case "flow_id": //自定义表单保留字
            return inputUnit.includes(unitName);
            break;
        case "baidumap": //自定义表单保留字
            return inputUnit.includes(unitName);
            break;
        case "input": //自定义表单保留字
            return inputUnit.includes(unitName);
            break;
        case "radio": //自定义表单保留字
            return choiceUnit.includes(unitName);
            break;
        case "switch": //自定义表单保留字
            return switchUnit.includes(unitName);
            break;
        case "orgCentent": //自定义表单保留字
            return orgUnit.includes(unitName);
            break;
        case "varchar": //自定义表单保留字
            return inputUnit.includes(unitName);
            break;
        case "checkbox":
            return checkboxUnit.includes(unitName);
            break;
        case "deptOrg":
            return orgDeptUnit.includes(unitName);
            break;
        default:
            if (val.fieldClass != "datePicker" && val.fieldClass != "timePicker") {
                return inputUnit.includes(unitName);
            }
        break;
    }
    return false;
}
// 选择数据转换，默认尝试转数字
const transformOption = (val: string | number, type?: string) => {
    return formatNumber(val);
};
/**
@ 作者: 秦东
@ 时间: 2026-01-28 13:04:09
@ 功能: 计算所有子列表的最大行数
*/
const subTableFieldsFilter = computed(() => {
    const arr: { table: string; field: string; label: string }[] = [];
    const names: string[] = [];
    props.fieldsDetailList.forEach((item: any) => {
        if (item.type === "table") {
            names.push(item.name);
            item.list.forEach((sub: any) => {
                arr.push({ table: item.name, field: sub.name, label: sub.item.label });
            });
        }
    });
    return { tables: names, fields: arr };
});
// 工具函数：处理 CSV 字段值
const processCsvField = (value: any): string => {
    if (value === undefined || value === null) {
        return "";
    }
    const stringValue = String(value);
    return stringValue.replaceAll(",", "，");
};
/**
@ 作者: 秦东
@ 时间: 2026-01-28 11:26:49
@ 功能: 表格导出
*/
const doExportTableData = () => {
    //fields表示主表单的导出字段，subs表示主表单包含的子表格的导出字段
    function exportFunc(
        fields: { field: string; label: string }[],
        subs: { table: string; field: string; label: string }[]
    ){
        let sendData = {
            formId: props.formId,
            page: 1,
            pagesize: 10000,
            searchData: json2string(props.searchData),
        };
        doGainFormPageListCont(sendData)
            .then((datas) => {
                const array: string[] = [];
                //写入表头行
                const title: string[] = [];
                for (let val of fields) {
                    title.push(val.label);
                }
                for (let val of subs) {
                    title.push(val.label);
                }
                array.push(title.join(","));
                //写入数据行
                datas.list.forEach((item: { [x: string]: { [x: string]: any; }[]; }) => {
                    const line = [];
                    let maxline = 0;
                    //写主表列
                    for (let val of fields) {
                        // if (typeof val === "string")
                        // line.push((item[val.field] as unknown as string).replaceAll(",", "，"));
                        // else line.push(item[val.field]);
                        if (val && val.field) {
                            line.push(processCsvField(item[val.field]));
                        } else {
                            line.push("");
                        }
                    }

                    //写子表列
                    if (subs.length > 0) {
                        //计算所有子列表的最大行数
                        for (let tab of subTableFieldsFilter.value.tables) {
                            if (item[tab] && item[tab].length > maxline) maxline = item[tab].length;
                        }
                        //全都是空的
                        if (maxline === 0) {
                            array.push(line.join(",") + "," + Array(subs.length).fill(""));
                            return;
                        }

                        //除第一行数据包含子表数据外，其他行都省略主表字段数据，用spaceprefix填充，避免重复
                        const spacePrefix = Array(line.length).fill("");

                        for (let i = 0; i < maxline; i++) {
                            const row: any[] = [];
                            subTableFieldsFilter.value.tables.forEach((name) => {
                                if (item[name] && item[name].length - 1 >= i) {
                                    //添加实际数据
                                    subs
                                        .filter((v) => v.table === name)
                                        .forEach((f) => {
                                            row.push(item[name][i][f.field]);
                                        });
                                } else {
                                    //添加字段长度的N个空列
                                    row.push(
                                        ...Array(subs.filter((v) => v.table === name).length).fill("")
                                    );
                                }
                            });

                            //写入总csv数组
                            if (i === 0) {
                                array.push(line.join(",") + "," + row.join(","));
                            } else {
                                array.push(spacePrefix + "," + row.join(","));
                            }
                        }

                        return;
                    }
                    //没有子表
                    array.push(line.join(","));
                });
                //去掉标题行的统计
                if (array.length - 1 !== datas.total){
                    alert(`导出记录数：${datas.total}, 共计：${array.length - 1} 行`);
                }
                const filename = props.pickAppMenu.label + ".csv";
                const csvString = array.join("\n");
                const blob = new Blob([csvString], { type: "text/csv;charset=utf-8;" });
                const link = document.createElement("a");
                if (link.download !== undefined) {
                    // feature detection
                    // Browsers that support HTML5 download attribute
                    const url = URL.createObjectURL(blob);
                    link.setAttribute("href", url);
                    link.setAttribute("download", filename);
                    link.style.visibility = "hidden";
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                }
            })
            .finally(() => (dynamicVNode.value = null));
    }
    dynamicVNode.value = h(exportPanel, {
        fields: columnsFilter.value.filter((item: { pattern: string; }) => item.pattern !== "table"),
        subtabs: columnsFilter.value.filter((item: { pattern: string; }) => item.pattern === "table"),
        subFields: subTableFieldsFilter.value.fields,
        commitFunc: exportFunc,
        closeFunc: () => (dynamicVNode.value = null),
    });
}
/**
@ 作者: 秦东
@ 时间: 2026-01-28 13:10:40
@ 功能: 获取表格头内容
*/
const columnsFilter = computed(() => {
    // console.log("props.data判断是否有标题", props.data);
    if (!state.columnsCheck?.length) {
        // console.log("props.data判断是否有标题",props.data)
        return props.data.columns;
    } else {
        // console.log("props.data.columns判断是否有标题",props.data)
        return props.data.columns.filter((item: any) => {
            return state.columnsCheck.includes(item.prop || item.type);
        });
    }
    // console.log("获取表格头内容", props.data.columns);
});
let asfs: any[] = [];
let radios: any[] = [];
let checkboxs: any[] = [];
let switchs: any[] = [];
let selects: any[] = [];
let tables: any[] = [];
let dofs: any[] = []; //deptOrgAndOrgCententAndFounderArr
let asfDetails = [];
let transferDetails = [];
let asfQueryParams: any[] = [];
let rangedDatePickerInTables: any[] = [];
const rangedDatePickerInTables1: any = []

const dateStringToTimestampLocal = (dateStr: string) => {
    const isoStr = dateStr.replace(' ', 'T');
    const timestamp = new Date(isoStr).getTime();
    if (isNaN(timestamp)) {
        //throw new Error('Invalid date string');
        return ''
    }
    return String(timestamp);
}
//liwenxuan 关联表单数据获取 start
const getAsfDataTitlesByIds = (asfQueryParams: any[]) => {
    return request({
        url: "/javasys/lowCode/AssociatedForms/getAsfDataTitlesByIds",
        method: "post",
        data: asfQueryParams,
    });
}

async function doGainFormPageListCont(sendData: any) {
    const data = await gainFormPageListCont(sendData);
    console.log("获取列表详细信息----------1111------->",data)
    rangedDatePickerInTables.forEach(element => {
        let x = element.split('^^^*^^^')
        rangedDatePickerInTables1.push(x)
        data.data.list.forEach((item: any) => {
            let tableValues = item[x[0]]
            tableValues.forEach((element1: any) => {
                let start = dateStringToTimestampLocal(element1[x[1]])
                let end = element1[x[1]+"_end"]
                let arr = [start,end]
                //console.log(arr)
                element1[x[1]] = arr
            });
        });
    });
    asfDetails = props.data.columns.filter((item: any) => {
        return item.fieldClass == "associatedForms";
    });
    transferDetails = props.data.columns.filter((item: any) => {
        return item.fieldClass == "lowcodeTransfer";
    });
    if (asfDetails.length > 0 && data.data.list != null) {
        //console.log(data.data.list)
        //拼装参数,asf值对象数组
        asfQueryParams = [];
        for (let j = 0; j < asfDetails.length; j++) {
            let asfQueryParamsItem: any = {};
            //console.log(asfDetails[j])
            asfQueryParamsItem.formId = asfDetails[j].control.formid;
            asfQueryParamsItem.field = asfDetails[j].field;

            let asfToSelectIds = [];
            // console.log(data.data.list)
            for (let i = 0; i < data.data.list.length; i++) {
                let asfMasterAndAsfId: any = {};
                asfMasterAndAsfId.asfId = data.data.list[i][asfDetails[j].field];
                asfMasterAndAsfId.asfMasterId = data.data.list[i].id;

                asfToSelectIds.push(asfMasterAndAsfId);
            }
            asfQueryParamsItem.asfToSelectIds = asfToSelectIds;
            asfQueryParams.push(asfQueryParamsItem);
        }
        let queryCount = 0;
        for (let i = 0; i < asfQueryParams[0].asfToSelectIds.length; i++) {
            if (asfQueryParams[0].asfToSelectIds[i].asfId != "") {
                queryCount++;
            }
        }
        //console.log(asfQueryParams)
        if (queryCount > 0) {
            //liwenxuan 关联表单数据获取 start
            let dataList = data;
            //-------------------直接return 异步结果----------------------
            return await getAsfDataTitlesByIds(asfQueryParams).then(({ data }) => {
                //console.log(data)
                for (let i = 0; i < dataList.data.list.length; i++) {
                //console.log(dataList.data.list[i])
                    for (let j = 0; j < data.length; j++) {
                        //console.log(data[j])
                        for (let n = 0; n < data[j].list.length; n++) {
                            if (dataList.data.list[i].id == data[j].list[n].asfMasterId) {
                                dataList.data.list[i][data[j].field] = data[j].list[n].label;
                            }
                            //console.log(data[j].list[n])
                        }
                    }
                }
                
                return dataList.data;
            });
        }
        console.error("获取列表详细信息------饭hi之----------->",data)
        return data.data;
    }else{
        return data.data;
    }




}


/**
@ 作者: 秦东
@ 时间: 2026-01-28 11:23:27
@ 功能: 功能按钮动作
*/
const setUpClick = (val: any, id?: string) => {
    switch(val.key){
        case "newAdd":
            drawerWith.value = container.value?.clientWidth;
            openTaskDrawer.value = true;
            break;
        case "export":
            doExportTableData();
            break;
        case "import":
            break;
        case "showQrCode":
            break;
        default:
    }
}
/**
@ 作者: 秦东
@ 时间: 2026-01-28 13:17:48
@ 功能: 取菲值
*/
const getNonValue = () => {
    // eslint-disable-next-line vue/no-mutating-props
    props.config.searchIsShow = !props.config.searchIsShow
}
/**
@ 作者: 秦东
@ 时间: 2026-01-28 14:41:24
@ 功能: 表格选择操作
*/
const selectionChange = (row: any) => {
    state.selectionChecked = row;
    emits("selectionChange", row);
    idList.value.length = 0;
    if (row && row.length > 0) {
    row.forEach((item: any) => {
        // console.log('item', item.masters_key)
        idList.value.push(item.masters_key.toString());
    });
  }
}
/**
@ 作者: 秦东
@ 时间: 2026-01-28 15:59:23
@ 功能: 判断是否有标题
*/
const writeListTitle = (val: any, viewConfig: any) => {
    var titleAry: any[] = [];
    if (viewConfig.form && viewConfig.form.title) {
        if (viewConfig.form.title.length > 0) {
            viewConfig.form.title.forEach((item: string|number, index: any) => {
                if (val[item]) {
                    titleAry.push(val[item]);
                }
            })
        }
    }
    if (titleAry.length > 0) {
        return titleAry.join();
    }  else {
        let firstWord = "";
        let powerAry = [
            "id",
            "creater_time",
            "edit_time",
            "masters_key",
            "states",
            "flow_id",
        ];
        for (let key in val) {
            if (val.hasOwnProperty(key)) {
                if (!powerAry.includes(key)) {
                    if (val[key] != "" && val[key] != null) {
                        firstWord = val[key];
                    }
                }
            }
        }
        return firstWord;
    }
}
/**
@ 作者: 秦东
@ 时间: 2026-01-28 16:08:28
@ 功能: 表格宽度
*/
const readerColumnSun = (column: any) => {
    // console.log("表头label长度-11->", column);
    let labelLong = 0; // 表头label长度
    if (column.label.length) {
        labelLong = column.label.length;
    }
    if (labelLong > 0) {
        if(labelLong > 6 ){
            return labelLong * 15;
        }else{
            return labelLong * 30;
        }
        
    }else{
        return 100;
    }
}
/**
@ 作者: 秦东
@ 时间: 2024-04-10 15:32:55
@ 功能: 提交审批
*/
const submitApproval = (val: any) => {
    operState.value = 4;
    tablePageClass.value = 2;
    pageInfoCont.value = val;
    drawerWith.value = container.value?.clientWidth;
    lookPageInfoIsShow.value = true;
};
/**
@ 作者: 秦东
@ 时间: 2026-01-28 15:01:16
@ 功能: 页面渲染完毕后加载
*/
onMounted(() => {
    getPageData();
    nextTick(() => {
        drawerWith.value = container.value?.clientWidth;
    });
})

</script>
<template>
    <div ref="container" v-loading="state.loading" class="table-list-comm">
        <el-row class="rowBox">
            <el-col :span="24">
                <el-form v-if="config.searchIsShow" ref="ruleSearchForm" class="seacherForm">
                    <div v-for="(item, index) in searchData" :key="index"  class="group group-input">
                        <el-form-item :label="item.label" class="form_cont">
                            <el-input
                                v-if="unitIsShow(item, 'input')"
                                v-model="item.value"
                                :placeholder="'请输入' + item.label"
                                clearable
                            />
                            <el-date-picker
                                v-if="unitIsShow(item, 'time')"
                                v-model="item.value"
                                type="datetime"
                                :placeholder="'请选择' + item.label"
                                
                            />
                            <SearchSelect
                                v-if="unitIsShow(item, 'radio')"
                                v-model:model-value="item.value"
                                :data="item"
                                :disabled="false"
                                :transform-option="transformOption"
                            />
                            <el-select
                                v-if="unitIsShow(item, 'switch')"
                                v-model="item.value"
                                clearable
                                :placeholder="'请选择' + item.label"
                            >
                            <el-option
                                :key="item.activeValue"
                                label="是"
                                :value="item.activeValue"
                            />
                            <el-option
                                :key="item.inactiveValue"
                                label="否"
                                :value="item.inactiveValue"
                            />
                            </el-select>
                            <SearchSelect
                                v-if="unitIsShow(item, 'checkbox')"
                                v-model:model-value="item.value"
                                :data="item"
                                :disabled="false"
                                :is-checkbox="true"
                                :transform-option="transformOption"
                            />
                            <el-date-picker
                                v-if="item.fieldClass == 'datePicker'"
                                v-model="item.value"
                                :type="item.auxiliary"
                                :placeholder="'请选择' + item.label"
                                value-format="x"
                            />
                            <el-time-picker
                                v-if="item.fieldClass == 'timePicker'"
                                v-model="item.value"
                                arrow-control
                                :placeholder="'请选择' + item.label"
                                value-format="x"
                            />
                            <DeptOrgSearch
                                v-if="unitIsShow(item, 'org')"
                                v-model="item.value"
                                clearable
                                :placeholder="'请选择' + item.label"
                            >
                            </DeptOrgSearch>
                            <DeptOrgSearch
                                v-if="unitIsShow(item, 'deptOrg')"
                                v-model:model-value="item.value"
                            />
                        </el-form-item>
                    </div>

                    <div v-if="searchData.length" class="group group-btn">
                        <el-button type="primary" @click="getPageData"><el-icon><Search /></el-icon>查询</el-button>
                        <el-button @click="resetFields(ruleSearchForm)"><el-icon><Refresh /></el-icon>重置</el-button>
                    </div>
                </el-form>
            </el-col>
            <el-col :span="24">
                <div class="operateButArea">
                    <div class="operatLeft">
                        <el-text v-if="data.controlBtn.length === 0" class="mx-1 tipBox" type="info">操作按钮区域</el-text>
                        <template v-for="item in data.controlBtn" :key="item.type">
                            <el-button
                                v-if="formHasPower(props.pickAppMenu.appkey,props.signCode,item.key,0)"
                                v-bind="item"
                                @click="setUpClick(item)"
                            >
                                {{ item.label }}
                            </el-button>
                        </template>
                    </div>
                    <div>
                        <el-button-group class="ml-4">
                            <el-tooltip
                                class="box-item"
                                effect="dark"
                                content="折叠查询表单"
                                placement="bottom"
                            >
                                <el-button
                                    size="small"
                                    class="fa fa-search"
                                    @click="getNonValue()"
                                />
                            </el-tooltip>
                            <el-tooltip
                                v-if="viewPage.list.status"
                                class="box-item"
                                effect="dark"
                                content="列表视图"
                                placement="top"
                            >
                                <el-button
                                    size="small"
                                    class="fa fa-table"
                                    :color="viewPage.list.isClick ? '#a0cfff' : ''"
                                    @click="tabsView(viewPage.list, 1)"
                                />
                            </el-tooltip>
                            <el-tooltip
                                v-if="props.viewPage.card && props.viewPage.card.status"
                                class="box-item"
                                effect="dark"
                                content="卡片视图"
                                placement="top"
                            >
                                <el-button
                                    size="small"
                                    class="fa fa-id-card-o"
                                    :color="
                                        props.viewPage.card && props.viewPage.card.isClick ? '#a0cfff' : ''
                                    "
                                    @click="tabsView(props.viewPage.card, 6)"
                                />
                            </el-tooltip>
                            <el-tooltip
                                v-if="viewPage.date.status"
                                class="box-item"
                                effect="dark"
                                content="日历视图"
                                placement="top"
                            >
                                <el-button
                                    size="small"
                                    class="fa fa-calendar"
                                    :color="viewPage.date.isClick ? '#a0cfff' : ''"
                                    @click="tabsView(viewPage.date, 2)"
                                />
                            </el-tooltip>
                            <el-tooltip
                                v-if="viewPage.time.status"
                                class="box-item"
                                effect="dark"
                                content="时间轴"
                                placement="top"
                            >
                                <el-button
                                    size="small"
                                    class="fa fa-clock-o"
                                    :color="viewPage.time.isClick ? '#a0cfff' : ''"
                                    @click="tabsView(viewPage.time, 3)"
                                />
                            </el-tooltip>
                            <el-tooltip
                                v-if="viewPage.gantt.status"
                                class="box-item"
                                effect="dark"
                                content="甘特图"
                                placement="top"
                            >
                                <el-button
                                    size="small"
                                    class="fa fa-bar-chart"
                                    :color="viewPage.gantt.isClick ? '#a0cfff' : ''"
                                    @click="tabsView(viewPage.gantt, 4)"
                                />
                            </el-tooltip>
                            <el-tooltip
                                v-if="viewPage.map.status"
                                class="box-item"
                                effect="dark"
                                content="地图视图"
                                placement="top"
                            >
                                <el-button
                                    size="small"
                                    class="fa fa-map-signs"
                                    :color="viewPage.map.isClick ? '#a0cfff' : ''"
                                    @click="tabsView(viewPage.map, 5)"
                                />
                            </el-tooltip>
                            <el-tooltip
                                v-if="viewPage.chart&&viewPage.chart.status"
                                class="box-item"
                                effect="dark"
                                content="BI报表"
                                placement="top"
                            >
                                <el-button
                                    size="small"
                                    class="fa fa-line-chart"
                                    :color="viewPage.chart.isClick ? '#a0cfff' : ''"
                                    @click="tabsView(viewPage.chart, 7)"
                                />
                            </el-tooltip>
                        </el-button-group>
                    </div>
                </div>
            </el-col>
            <!--列表视图-->
            <el-col v-if="viewType == 1" :span="24" class="tableTdClass">   
                
                <el-table
                    v-bind="data.tableProps"
                    ref="table"
                    v-loading="state.loading"
                    :data="tableDataList"
                    table-layout="fixed"
                    border
                    @selection-change="selectionChange"
                >
                    <template v-for="item in columnsFilter" :key="item.id || item.label">
                        <el-table-column
                            v-if="['-'].includes(item.fieldClass)"
                            :type="item.type"
                            :prop="item.field"
                            :label="item.label"
                            config=""
                            width="60"
                            fixed
                            header-align="center"
                            align="center"
                        >
                            <template v-if="item.help" #header="scope">
                                {{ scope.column.label }}
                                <tooltip :content="item.help" />
                            </template>
                        </el-table-column>
                        <el-table-column
                            v-else-if="item.fieldClass == '_lableTitle'"
                            label="标题"
                            config=""
                            min-width="20"
                            header-align="center"
                            align="center"
                        >
                            <template #default="scope">
                                {{ writeListTitle(scope.row, viewPage.list) }}
                            </template>
                        </el-table-column>
                        <el-table-column
                            v-else-if="item.fieldClass == ''"
                            :prop="item.field"
                            :label="item.label"
                            :min-width="readerColumnSun(item)"
                            header-align="center"
                            align="center"
                        >
                            <template #default>
                                <template v-if="item.pattern == 'table'">
                                    <template v-for="sunItem in item.children"> 
                                        {{ sunItem }}
                                        <!-- <el-table-column>
                                            <template #default="scopeChilder">
                                                <div v-html="tableChildren(sunItem.field,scopeChilder.row[item.field])"></div>
                                            </template>
                                        </el-table-column> -->
                                    </template>
                                </template>
                            </template>
                        </el-table-column>
                        <el-table-column
                            v-else-if="item.fieldClass == '__control'"
                            :prop="item.field"
                            :label="item.label"
                            config=""
                            min-width="220"
                            header-align="center"
                            align="center"
                            fixed="right"
                        >
                            <template #default="scope">
                                <el-button-group>
                                    <el-tooltip
                                        v-if="scope.row.flowIsOpens == 1 && scope.row.taskStatus == 1"
                                        class="box-item"
                                        effect="dark"
                                        content="提交审批"
                                        placement="top-end"
                                    >
                                        <el-button
                                        type="success"
                                        size="small"
                                        class="fa fa-send-o"
                                        @click="submitApproval(scope.row)"
                                        />
                                    </el-tooltip>
                                </el-button-group>
                            </template>
                        </el-table-column>
                    </template>
                </el-table>
            </el-col>
            <el-col v-if="viewType == 1 && state.total > 0" :span="24" >   

            </el-col>
            <!--日历视图-->
            <el-col v-if="viewType == 2" :span="24" >   

            </el-col>
            <!--时间轴-->
            <el-col v-if="viewType == 3" :span="24" >   

            </el-col>
            <!--甘特图-->
            <el-col v-if="viewType == 4" :span="24" >   

            </el-col>
            <!--地图视图-->
            <el-col v-if="viewType == 5" :span="24" >   

            </el-col>
            <!--卡片视图-->
            <el-col v-if="viewType == 6" :span="24" >   

            </el-col>
            <!--BI报表-->
            <el-col v-if="viewType == 7" :span="24" >   

            </el-col>
        </el-row>
    </div>
</template>
<style  lang='scss' scoped>
.table-list-comm {
  padding: 0px 5px 5px 5px;
}
.rowBox {
  width: 100%;
}
.seacherForm {
  min-height: auto;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
}
.pageBox {
  width: 100%;
  margin-top: 20px;
  text-align: center;
  display: flex;
  justify-content: center;
}
.operateButArea {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 15px;
  margin-bottom: 15px;
  .operatLeft {
    padding-bottom: 2px;
  }
  
}
.group {
  width: auto;
  margin-right: 10px;
}
.demo-image__error .block {
  padding: 0px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  display: inline-block;
  width: 100%;
  box-sizing: border-box;
  vertical-align: top;
}
.demo-image__error .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
.demo-image__error .el-image {
  padding: 0 5px;
  max-width: 300px;
  max-height: 200px;
  width: 100%;
  height: 200px;
}

.demo-image__error .image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}
table {
  border-collapse: collapse;
  width: 100%;
  font-size: 13px;
  text-align: center;
}

td,
th {
  border: 1px solid black;
  padding: 8px;
  vertical-align: middle; /* 设置文字上下居中 */
}
.tableTdClass{
  :deep .cell{
    padding: 0;
  }
  :deep .el-table--default .cell{
    padding: 0;
  }
}
</style>
