import { CustomerFeeSetQueryParam } from "@/api/customerfee/CustomerFeeSetModel";
import { ref, unref, reactive, computed, onMounted } from "vue";
import { getCustomerFeeSetListApi, getCustomerFeeSetParentListApi } from "@/api/customerfee/customerfeeset"
import { ListIitem } from "@/api/base/BaseDataModel"
import { getproductApi, getCustomertApi, getFeeSetTypeApi, getBranchCompanyCustomersApi } from "@/api/base/basedata"
import { BaseFeesetAction } from "@/type/BaseFeesetAction";
import {
    Edit,
    Plus,
    Setting,
    Delete,
    Download,
    CopyDocument,
    Refresh,
    Odometer,
    UserFilled,
    SetUp,
    Open,
    Warning,
    DocumentCopy
} from "@element-plus/icons-vue";
import { useReturnData } from "@/utils/useReturnData";
import { useQueryList } from "@/hooks/useQueryList";
import { isArrayLength } from "@/utils/is";
import { useMessage } from "@/hooks/useMessage";
import { BasicTableProps, VxeBasicTable, VxeGridInstance, VxeGridPropTypes, VxeTableDataRow } from '@/components/VxeTable/index';
import { ActionOptions } from "@/components/DropDownButtons/type";
import { useEleFormValidate } from "@/hooks/useEleFormValidate";
import { cloneDeep } from "@/utils/cloneDeep";
import { FeeSetType } from "@/type/BaseBusinessFeeseType";

const { createMessage } = useMessage()
/**
 * 客户费用设置列表
 */

export default function userCustomerFeeSetTable() {
    // 搜索表单
    const searchFormRef = ref()
    // 下拉列表数据
    const dropDownSelectList = reactive({
        productSelectList: [] as ListIitem[],//产品
        groupSelectList: [] as ListIitem[],//分组
        orgSelectList: [] as ListIitem[],//分公司机构
        customerSelectList: [] as ListIitem[],//客户
        feeSetTypeSelectList: [] as ListIitem[],//费用类型
        currentEffectiveList: [
            {
                value: true,
                label: '生效记录',
            },
            {
                value: false,
                label: '全部记录',
            }
        ]//当期生效记录
    })
    // 表格
    const customerFeeSetGridRef = ref<VxeGridInstance>()
    const customerFeeSetGridOptions = reactive<BasicTableProps>({
        id: 'customerfeeset_table',
        border: true,
        keepSource: true,
        showOverflow: true,
        height: 520,
        loading: false,
        stripe: true,
        rowConfig: {
            isHover: true,
            keyField: 'id',
        },
        rowClassName: ({ row }) => {
            if (!unref(isCustomerSettlement) && row.feeSetType === FeeSetType.OPERATING_ORGANIZATION) {
                return 'row-settlement-color'
            }
            return null
        },
        customConfig: {
            storage: {
                visible: true,
            }
        },
        columnConfig: {
            resizable: false,
        },
        expandConfig: {
            accordion: false,
            lazy: true,
            visibleMethod({ row }) {//判断是否显示展开图标
                if (row.haveSumRecord) {
                    return true
                } else {
                    return false
                }
            },
            toggleMethod(scope) {
                if (!scope.expanded) {
                    scope.row.isLoadSettlementPrice = false
                    scope.$table.clearRowExpandLoaded(scope.row)
                }
                return true
            },
            loadMethod(scope) {//异步展开
                return hanleExpandRow(scope)
            }
        },
        tooltipConfig: {
            showAll: true,
            enterable: true,
            contentMethod: ({ column, row }) => {
                const { field } = column
                if (field === 'groupName' && row && row.groupName) {
                    return row[field] ? 
                    `分组名称：${row.groupName}${row.customerGroupVersion ? '_'+row.customerGroupVersion : ''}\n所属客户：${row.customerNameList.join('、')}` : ''
                }
                return null
            }
        },
        columns: [
            { type: "expand", title: '#', slots: { content: 'expands' }, width: 40 },
            { type: "checkbox", width: 45, visible: true },
            { type: "seq", width: 55, title: '序号' },
            { field: 'feeSetName', title: '费用名称', resizable: true, minWidth: 200, visible: true, showOverflow: false },
            { field: 'productName', title: '产品名称', resizable: true, minWidth: 120, visible: true, showOverflow: false },
            { 
                field: 'groupName', 
                title: '分组', 
                resizable: true, 
                minWidth: 110,
                formatter: ({ row }) =>{
                    if (!row.groupName) return ''
                    return `${row.groupName}${row.customerGroupVersion ? '_'+row.customerGroupVersion : ''}`
                },
                visible: true 
            },
            { field: 'orgName', title: '机构名称', width: 100, visible: true },
            { field: 'customerName', title: '客户', resizable: true, minWidth: 100, visible: true },
            { field: 'feeSetTypeName', title: '类型名称', width: 80, visible: true },
            { field: 'activeFlag', title: '状态', slots: { default: 'activeFlag' }, width: 68, visible: true },
            { field: 'beginDate', title: '生效起始时间（>）', slots: { default: 'beginDate' }, width: 150, visible: true },
            { field: 'endDate', title: '生效结束时间（<=）', slots: { default: 'endDate' }, width: 155, visible: true },
            { field: 'remark', title: '备注', minWidth: 90, resizable: true, visible: true },
            { field: 'createUserName', title: '创建人', resizable: true, minWidth: 65, visible: true },
            { field: 'recalculate', title: '是否重算', minWidth: 80, slots: { default: 'recalculate' }, visible: true },
            { field: 'feeApprovalStatusName', title: '审批状态', slots: { default: 'feeApprovalStatusName' }, width: 92, visible: true },
            { field: 'recommendFeeSet', title: '建议价', slots: { default: 'recommendFeeSet' }, width: 65, visible: true },
            { field: 'createTime', title: '创建时间', resizable: true, width: 95, visible: true },
            { title: '操作', slots: { default: 'actions' }, width: 135, fixed: 'right', visible: true },
        ],
        data: []
    })
    const isCustomerSettlement = computed(() => {
        if (!customerFeeSetGridOptions.data) return false
        const isEvery = customerFeeSetGridOptions.data.every(item => item.feeSetType === FeeSetType.OPERATING_ORGANIZATION)
        return isEvery
    })
    const customerExpandFeeSetGridRef = ref<VxeGridInstance>()
    const customerExpandGridOptions = reactive<BasicTableProps>({
        id: 'customerexpand_table',
        border: false,
        keepSource: true,
        showOverflow: true,
        showHeader: false,
        minHeight: 0,
        rowConfig: {
            isHover: true,
            keyField: 'id',
        },
        rowClassName: ({ row }) => {
            if (!unref(isCustomerExpandSettlement) && row.feeSetType === FeeSetType.OPERATING_ORGANIZATION) {
                return 'row-settlement-color'
            }
            return null
        },
        customConfig: {
            storage: {
                visible: true,
            }
        },
        columnConfig: {
            resizable: false,
        },
        tooltipConfig: {
            showAll: true,
            enterable: true,
            contentMethod: ({ column, row }) => {
                const { field } = column
                if (field === 'groupName' && row && row.groupName) {
                    return row[field] ? 
                    `分组名称：${row.groupName}${row.customerGroupVersion ? '_'+row.customerGroupVersion : ''}\n所属客户：${row.customerNameList.join('、')}` : ''
                }
                return null
            }
        },
        columns: [
            { width: 85 },
            { type: "checkbox", width: 55, visible: true },
            { field: 'feeSetName', title: '费用名称', resizable: true, minWidth: 200, visible: true, showOverflow: false },
            { field: 'productName', title: '产品名称', resizable: true, minWidth: 120, visible: true, showOverflow: false },
            { 
                field: 'groupName', 
                title: '分组', 
                resizable: true, 
                minWidth: 110, 
                visible: true,
                formatter: ({ row }) =>{
                    if (!row.groupName) return ''
                    return `${row.groupName}${row.customerGroupVersion ? '_'+row.customerGroupVersion : ''}`
                },
            },
            { field: 'orgName', title: '机构名称', width: 100, visible: true },
            { field: 'customerName', title: '客户', resizable: true, minWidth: 100, visible: true },
            { field: 'feeSetTypeName', title: '类型名称', width: 80, visible: true },
            { field: 'activeFlag', title: '状态', slots: { default: 'activeFlag' }, width: 68, visible: true },
            { field: 'beginDate', title: '生效起始时间（>）', slots: { default: 'beginDate' }, width: 150, visible: true },
            { field: 'endDate', title: '生效结束时间（<=）', slots: { default: 'endDate' }, width: 155, visible: true },
            { field: 'remark', title: '备注', minWidth: 90, resizable: true, visible: true },
            { field: 'createUserName', title: '创建人', showOverflow: true, minWidth: 65, resizable: true, visible: true },
            { field: 'recalculate', title: '是否重算', minWidth: 80, slots: { default: 'recalculate' }, visible: true },
            { field: 'feeApprovalStatusName', title: '审批状态', slots: { default: 'feeApprovalStatusName' }, width: 92, visible: true },
            { field: 'recommendFeeSet', title: '建议价', slots: { default: 'recommendFeeSet' }, width: 65, visible: true },
            { field: 'createTime', title: '创建时间', width: 95, resizable: true, visible: true },
            { title: '操作', slots: { default: 'actions' }, width: 135, visible: true },
        ],
    })
    const isCustomerExpandSettlement = computed(() => {
        if (!customerExpandGridOptions.data) return false
        const isEvery = customerExpandGridOptions.data.every(item => item.feeSetType === FeeSetType.OPERATING_ORGANIZATION)
        return isEvery
    })
    const baseNewsInfoRef = ref<{ show: () => void }>()//通知弹窗

    //获取产品下拉框数据
    const getproductSelectList = async () => {
        let res = await getproductApi()
        if (res && res.code == 200) {
            dropDownSelectList.productSelectList = res.data;
        }
    };
    //获取客户数据
    const getCustomertSelectList = async () => {
        let res = await getCustomertApi()
        if (res && res.code == 200) {
            dropDownSelectList.customerSelectList = res.data;
        }
    };

    //获取费用类型数据
    const getFeeSetTypeSelectList = async () => {
        let res = await getFeeSetTypeApi()
        if (res && res.code == 200) {
            dropDownSelectList.feeSetTypeSelectList = res.data;
        }
    };

    //获取分公司数据
    const getbranchCompanyCustomersList = async () => {
        let res = await getBranchCompanyCustomersApi()
        if (res && res.code == 200) {
            dropDownSelectList.orgSelectList = res.data;
        }
    };

    const { resData } = useReturnData()
    // 根据折叠id展开
    const hanleExpandRow = async (scope: Recordable) => {
        if (scope.row.isLoadSettlementPrice) return
        try {
            scope.row.customerFeeSetList = [];
            const res = await getCustomerFeeSetParentListApi({ id: scope.row.id, parentId: scope.row.parentId })
            const list = resData(res);
            if (isArrayLength(list)) scope.row.customerFeeSetList = [...list]
        } catch (error) {
            console.error(error);
        }
        // const odlList = cloneDeep(scope.row.customerFeeSetList) || []
        // if(!isArrayLength(odlList)) {
        //     try {
        //         scope.row.customerFeeSetList = [];
        //         const res = await getCustomerFeeSetParentListApi({ id: scope.row.id, parentId: scope.row.parentId })
        //         const list = resData(res);
        //         scope.row.customerFeeSetList = [...list, ...odlList]
        //     } catch (error) {
        //         console.error(error);
        //     }
        // }
    }

    // 选中复选框
    const handleSelectionChange = ({ records }) => {
        customerFeeSetList.selectionDataSource = records
        const selection = records.map(item => `${item.productId}+${item.versionNumber}`)
        customerFeeSetList.multipleSelection = selection;
    }
    // 子复选框
    const handleSonSelectionChange = ({ records }) => {
        customerFeeSetList.selectionSonDataSource = records//折叠选中内容
        customerFeeSetList.sonMultipleSelection = records.map(item => `${item.productId}+${item.versionNumber}`)
    }
    // 合并复选框
    const multipleSelectionData = computed((): string[] => {
        return [...customerFeeSetList.multipleSelection, ...customerFeeSetList.sonMultipleSelection]
    })
    // 清空复选框内容
    const clearCheckboxRow = () => {
        customerFeeSetList.selectionDataSource = []
        customerFeeSetList.selectionSonDataSource = []
        const customerFeeSetGrid = unref(customerFeeSetGridRef)
        if (!customerFeeSetGrid) return
        customerFeeSetList.multipleSelection = []
        customerFeeSetList.sonMultipleSelection = []
        customerFeeSetGrid.clearCheckboxRow()
        customerFeeSetGrid.clearRowExpand()
    }
    // 通知弹窗
    const hanleNewsInfoRef = () => {
        if (!isArrayLength(multipleSelectionData.value)) {
            createMessage.warning('请选择产品名称！')
            return
        }
        baseNewsInfoRef.value?.show()
    }


    // 操作类别
    const actionOptions: ActionOptions[] = [
        {
            value: BaseFeesetAction.EDIT,//状态
            label: "编辑",//文本
            type: "primary",//按钮样式
            icon: Edit,//按钮图标
            permissions: ['sys:customerfeeset:edit'],
            isDisabled: true
        },
        {
            value: BaseFeesetAction.DELETE,
            label: "删除",
            type: "danger",
            icon: Delete,
            permissions: ['sys:customerfeeset:delete'],
            isDisabled: true
        },
        {
            value: BaseFeesetAction.VERSION,
            label: "新增版本",
            type: "success",
            icon: Plus,
            permissions: ['sys:customerfeeset:edit'],
            isDisabled: true
        },
        {
            value: BaseFeesetAction.FEESET_SETING,
            label: "设置费用",
            color: "#0078f3",
            icon: Setting,
            permissions: ['sys:customerfeeset:setFee'],
            isDisabled: true
        },
        {
            value: BaseFeesetAction.VIEW,
            label: "查看",
            color: "#01aee6",
            icon: Odometer,
            permissions: ['sys:customerfeeset:edit'],
        },
        // {
        //     value: BaseFeesetAction.FEESET_IMPORT,
        //     label: "费用导入",
        //     color: "#626aef",
        //     icon: Upload,
        //     permissions: ['sys:customerfeeset:edit']
        // },
        // {
        //     value: BaseFeesetAction.FEESET_EXPORT,
        //     label: "费用导出",
        //     color: "#32c2ff",
        //     type: "primary",
        //     icon: Download,
        //     permissions: ['sys:customerfeeset:edit']
        // },
        {
            value: BaseFeesetAction.FEESET_ACTIVE,
            label: "激活",
            islabel: "停用",
            color: "#409eff",
            type: "primary",
            icon: Refresh,
            permissions: ['sys:customerfeeset:active'],
            isDisabled: true
        },
        {
            value: BaseFeesetAction.PERSONNEL,
            label: "设置接管",
            color: "#2c75f1",
            icon: UserFilled,
            permissions: ['sys:customerFeeSetAdministrator:add']
        },
        {
            value: BaseFeesetAction.RECALCULATE,
            label: "重算设置",
            color: "#2B2F3A",
            icon: SetUp,
            permissions: ['sys:customerfeeset:recount']
        },
        {
            value: BaseFeesetAction.LOAD_SETTLEMENT_PRICE,
            label: "加载结算价",
            color: "#F9961B",
            icon: Open,
            permissions: ['sys:customerfeeset:edit']
        },
        {
            value: BaseFeesetAction.LOAD_ANNOUNCED_PRICE,
            label: "加载公布价",
            color: "#5763C1",
            icon: Open,
            permissions: ['sys:customerfeeset:edit']
        },
        {
            value: BaseFeesetAction.LOAD_SUGGESTED_PRICE,
            label: "加载建议价",
            color: "#FF7D53",
            icon: Open,
            permissions: ['sys:customerfeeset:edit']
        },
        {
            value: BaseFeesetAction.TERMINATION_TAKES_EFFECT,
            label: "终止生效",
            color: "#f56c6c",
            isDisabled: true,
            icon: Warning,
            permissions: ['sys:customerfeeset:stopEndDate']
        },
        {
            value: BaseFeesetAction.COPY,
            label: "拷贝",
            color: "#42b983",
            isDisabled: true,
            icon: CopyDocument,
            permissions: ['sys:customerfeeset:copy'],
            disabledText: '不能拷贝相同费用设置！'
        },
        {
            value: BaseFeesetAction.COPY_PROPORTION,
            label: "按数据拷贝",
            color: "#95BF47",
            icon: DocumentCopy,
            isDisabled: true,
            permissions: ['sys:customerfeeset:copy'],
            disabledText: '不能拷贝相同费用设置！'
        }
    ]


    //定义表格数据
    const customerFeeSetList = reactive({
        list: [],
        currentEffective: true,
        loading: false,//加载
        selectionDataSource: [],
        selectionSonDataSource: [],
        multipleSelection: [] as string[],//复选框选择的数据
        sonMultipleSelection: []//子复选框
    });
    //定义列表查询的参数
    const listParm = reactive<CustomerFeeSetQueryParam>({
        productId: undefined,
        customerIdList: undefined,
        orgId: null,
        feeSetName: '',
        feeSetType: null,
        belongUserId: null,
        currentEffective: true,
        activeFlag: null,
        pageNum: 1,
        pageSize: 10,
        total: 0
    })

    //获取客户费用设置信息列表
    const getCustomerFeeSetList = async () => {
        clearCheckboxRow()
        customerFeeSetList.loading = true
        customerFeeSetGridOptions.loading = true
        let res = await getCustomerFeeSetListApi(listParams)
        if (res && res.code == 200) {
            customerFeeSetList.currentEffective = listParm.currentEffective
            // isShowOrHidden()
            customerFeeSetGridOptions.data = res.data.records
            listParm.total = res.data.total;
        }
        customerFeeSetList.loading = false
        customerFeeSetGridOptions.loading = false
    }

    // 显示隐藏展开列内容
    const isShowOrHidden = () => {
        const columns = customerFeeSetGridOptions.columns
        const isExpand = columns?.some(item => item.type === 'expand')
        if (isExpand && !customerFeeSetList.currentEffective) {
            // 删除
            customerFeeSetGridOptions.columns?.shift()
            return false
        }
        const expands = columns?.filter(item => item.type === 'expand')
        if (expands?.length && expands?.length === 1) return false
        // 添加
        customerFeeSetGridOptions.columns?.unshift({ type: "expand", slots: { content: 'expands' }, width: 40 })
    }
    // 更新表格列配置
    const updateFeeSetGridColumns = (columns: VxeGridPropTypes.Columns<VxeTableDataRow>) => {
        const fixeds = columns.filter(item => !item.visible).map(item2 => item2.field).join(',')
        const json = { "_v":0,"customerfeeset_table": fixeds, "customerexpand_table": fixeds }
        window.localStorage.setItem("VXE_TABLE_CUSTOM_COLUMN_VISIBLE", JSON.stringify(json))
        customerFeeSetGridOptions.columns?.map((item) => {
            for (const sitem of columns) {
                if(item.field === sitem.field) {
                    item.visible = sitem.visible
                }
            }
            return item
        })
        customerExpandGridOptions.columns?.map((item) => {
            for (const sitem of columns) {
                if(item.field === sitem.field) {
                    item.visible = sitem.visible
                }
            }
            return item
        })
    }
    // 更新客户费用表格列配置
    const hanleToolbarConfirm = (columns) => {
        isShowOrHidden()
        updateFeeSetGridColumns(columns)
        const $table = customerFeeSetGridRef.value
        if ($table) $table.refreshColumn()
        const $table2 = customerExpandFeeSetGridRef.value
        if ($table2) {
            // XXX 待处理：暂存展开数据宽度问题 
            $table2.setAllRowExpand(false)
            $table2.loadColumn([])
            $table2.refreshColumn()
        }
    }
    // 重置表格列配置
    const hanleToolbarReset = (columns) => {
        updateFeeSetGridColumns(columns)
        isShowOrHidden()
        const $table = customerFeeSetGridRef.value
        if ($table) $table.resetColumn()
        const $table2 = customerExpandFeeSetGridRef.value
        if ($table2) $table2.resetColumn()
    }
    // 获取表格列内容
    const feeSetColumns = computed<VxeGridPropTypes.Columns<VxeTableDataRow>>(() => {
        const $table = customerFeeSetGridRef.value
        if($table) {
            return $table.getTableColumn().fullColumn
        }
        return []
    })

    const { resetForm } = useEleFormValidate()
    // 重置
    const resetParams = () => {
        listParm.currentEffective = true;
        resetForm(searchFormRef.value)
    }
    // 初始化列表、分页数据
    const { sizeChange, currentChange, searchBtn, resetBtn, listParams } = useQueryList<CustomerFeeSetQueryParam>(getCustomerFeeSetList, resetParams, listParm)

    onMounted(() => {
        getproductSelectList();
        getCustomertSelectList();
        // getFeeSetTypeSelectList();
        getbranchCompanyCustomersList();
    })

    return {
        dropDownSelectList,
        customerFeeSetList,
        multipleSelectionData,
        listParm,
        actionOptions,
        searchFormRef,
        hanleExpandRow,
        handleSelectionChange,
        handleSonSelectionChange,
        getCustomerFeeSetList,
        clearCheckboxRow,
        sizeChange,
        currentChange,
        searchBtn,
        resetBtn,
        hanleNewsInfoRef,
        hanleToolbarConfirm,
        hanleToolbarReset,
        baseNewsInfoRef,
        customerFeeSetGridRef,
        customerExpandFeeSetGridRef,
        customerFeeSetGridOptions,
        customerExpandGridOptions,
        VxeBasicTable,
        feeSetColumns,
        getproductSelectList
    }
};