import { ListIitem } from '@/api/base/BaseDataModel';
import { api_ProductRateRatioAdd, api_ProductRateRatioChangeState, api_ProductRateRatioDelete, api_ProductRateRatioEdit, api_ProductRateRatioList, api_ProductRateRatioReGet, api_RatioRecordList } from '@/api/productrateratio/apiProductRateRatio';
import { ProductRateRatioDto, ProductRateRatioParam } from '@/api/productrateratio/apiProductRateRatioModel';
import { useDropDownData } from '@/hooks/useDropDownData';
import { useErrorConfirm } from '@/utils/useErrorConfirm';
import { useReturnData } from '@/utils/useReturnData';
import { EditType } from '@/type/BaseEnum';
import { BaseFeesetAction } from '@/type/BaseFeesetAction';
import { cloneDeep } from '@/utils/cloneDeep';
import { Refresh, Edit, Delete, } from "@element-plus/icons-vue";
import { ref, reactive, onMounted } from 'vue';
import { useQueryList } from '@/hooks/useQueryList';
import { ActionOptions } from '@/components/DropDownButtons/type';

const { report } = useErrorConfirm()
/**
 * 产品费率
 */
function useProductRateRatio() {
    const { resData } = useReturnData()
    // 下拉列表数据
    const { storeDropDownData, productList, feeItemLists, cycleTypecist, allProvidersList } = useDropDownData()
    //定义列表查询的参数
    const listParm = reactive<ProductRateRatioParam>({
        productId: '',
        feeItemId: '',
        cycleType: undefined,
        rateRatioState: undefined,
        pageNum: 1,
        pageSize: 10,
        total: 0
    })
    // 列表数据
    const productRateRatioList = reactive({
        mainList: [] as Recordable[],
        productList: [] as ListIitem[],//产品列表
        feeItemList: [] as ListIitem[],//费用类型
        cycleTypeList: [] as ListIitem[],//周期
        stateList: [{ label: '生效', value: 0 }, { label: '停用', value: 1 }],//状态
        expandActive: '',//展开折叠图标的显示
        expandedRowKeys: [] as Recordable[],//控制id展开数据
        loading: false,//加载
    })
    const addEditProductRateRatioRef = ref<{ show: (type: string, data?: Recordable) => void }>()
    // TODO 权限还未修改正取
    const actionOptions: ActionOptions[] = [
        {
            value: BaseFeesetAction.EDIT,//状态
            label: "编辑",//文本
            type: "primary",//按钮样式
            icon: Edit,//按钮图标
            permissions: ['sys:productRateRatio:edit']
        },
        {
            value: BaseFeesetAction.FEESET_ACTIVE,
            label: "生效",
            islabel: '停用',
            type: "success",
            icon: Refresh,
            permissions: ['sys:productRateRatio:edit']
        },
        {
            value: BaseFeesetAction.DELETE,
            label: "删除",
            type: "danger",
            icon: Delete,
            permissions: ['sys:productRateRatio:delete']
        }
    ]
    // 操作类型
    const hanleChangeAction = async (data: Recordable) => {
        const row = cloneDeep(data)
        const types = row.types;
        // 费用操作列表
        // console.log(types, ":费用操作类型", row);
        switch (types) {
            // 产品费率-编辑
            case BaseFeesetAction.EDIT:
                addEditProductRateRatioRef.value?.show(EditType.EDIT, row)
                break;
            case BaseFeesetAction.FEESET_ACTIVE:
                // 改变状态
                const rateRatioState = row.rateRatioState === 0 ? 1 : 0
                const stateRes = await api_ProductRateRatioChangeState({ ...row, rateRatioState })
                const stateCode = resData(stateRes)
                if (stateCode !== 500) getProductRateRatioList()
                break;
            // 产品费率-删除
            case BaseFeesetAction.DELETE:
                const deleteRes = await api_ProductRateRatioDelete({ id: row.id })
                const deleteCode = resData(deleteRes)
                if (deleteCode !== 500) getProductRateRatioList()
                break;
            default:
                break;
        }
    }

    // 查找周期名称
    const dealcycleType = (val: string | number) => {
        const findData = productRateRatioList.cycleTypeList.find(item => item.value === val)
        return findData?.label
    }

    // 关闭当前展开数据
    const clearExpandRow = () => {
        productRateRatioList.expandedRowKeys = []
        productRateRatioList.expandActive = ''
    }

    // 根据折叠id展开
    const hanleExpandRow = async (row: Recordable) => {
        // console.log(row.id, "《== parentid");
        row.loading = true;
        productRateRatioList.expandActive = row.id;

        // 判断展开的id，不相同则只展开最新的表格数据
        if (!productRateRatioList.expandedRowKeys.includes(row.id)) {
            try {
                row.providerFeeSetList = [];
                productRateRatioList.expandedRowKeys = [row.id];
                const recordParams = {
                    ...listParm, rateRatioId: row.id
                }
                const res = await api_RatioRecordList(recordParams)
                row.providerFeeSetList = resData(res);
                productRateRatioList.expandedRowKeys.push(row.id);
            } catch (error) {
                console.error(error);
            }
        } else {
            productRateRatioList.expandedRowKeys = []
        }
        row.loading = false;
        // 如果没有展开的数据则恢复图标转向
        if (productRateRatioList.expandedRowKeys.length === 0) productRateRatioList.expandActive = '';
    }

    // 获取
    const hanleRateRatioGet = async (row: Recordable) => {
        const reGetRes = await api_ProductRateRatioReGet({ id: row.id })
        resData(reGetRes)
    }

    //获取产品费率信息列表
    const getProductRateRatioList = async () => {
        try {
            productRateRatioList.loading = true
            clearExpandRow()
            let res = await api_ProductRateRatioList(listParams)
            if (res && res.code == 200) {
                productRateRatioList.mainList = res.data.records
                listParm.total = res.data.total;
            }
        } finally {
            productRateRatioList.loading = false
        }
    }

    // 重置
    const resetParams = () => {
        listParm.productId = '';
        listParm.feeItemId = '';
        listParm.cycleType = undefined;
    }
    // 初始化列表、分页数据
    const { sizeChange, currentChange, searchBtn, resetBtn, listParams } = useQueryList<ProductRateRatioParam>(getProductRateRatioList, resetParams, listParm)

    // 添加弹窗显示
    const addBtn = () => addEditProductRateRatioRef.value?.show(EditType.ADD)
    // 新增或编辑产品费率
    const hanleSaveProductRateRatio = async (params: ProductRateRatioDto, type: string, onclose: Fn, setLoading: Fn) => {
        try {
            // 新增
            if (type === EditType.ADD) {
                const addRes = await api_ProductRateRatioAdd(params)
                const codeData = resData(addRes)
                if (codeData !== 500) onclose()
            } else {
                // 编辑
                const editRes = await api_ProductRateRatioEdit(params)
                const codeData = resData(editRes)
                if (codeData !== 500) onclose()
            }
        } catch (error) {
            report(error)
        } finally {
            setLoading(false)
            // 刷新列表
            getProductRateRatioList();
        }
    }

    onMounted(async () => {
        const feeItemList = await storeDropDownData.addStratFeeItemList()//费用类型
        productRateRatioList.feeItemList = feeItemList.map(item => ({ label: item.itemName, value: item.id }))
        productRateRatioList.cycleTypeList = await storeDropDownData.addCycleTypeList()//周期类型
        storeDropDownData.addAllProvidersList()//服务商
        productRateRatioList.productList = await storeDropDownData.addProductList()//产品列表
    })

    return {
        listParm,
        productRateRatioList,
        actionOptions,
        searchBtn,
        resetBtn,
        addBtn,
        currentChange,
        sizeChange,
        hanleChangeAction,
        hanleSaveProductRateRatio,
        hanleExpandRow,
        dealcycleType,
        hanleRateRatioGet,
        addEditProductRateRatioRef,
        productList,
        feeItemLists,
        cycleTypecist,
        allProvidersList
    }
}

export {
    useProductRateRatio
}