import type { ListIitem } from '@/api/base/BaseDataModel';
import { useDropDownData } from '@/hooks/useDropDownData';
import { useErrorConfirm } from '@/utils/useErrorConfirm';
import { useReturnData } from '@/utils/useReturnData';
import { BaseFeesetAction } from '@/type/BaseFeesetAction';
import { ref, reactive, onMounted, computed, unref, Ref } from 'vue';
import { cloneDeep } from '@/utils/cloneDeep';
import { useQueryList } from '@/hooks/useQueryList';
import { BasicTableProps, VxeGridInstance } from '@/components/VxeTable';
import { ElMessageBox } from 'element-plus';
import { CostFeeSetParams, SubmitCostFeeSetModel } from '@/api/costFeeSet/costFeeSetModel';
import { api_costFeeSetActive, api_costFeeSetAdd, api_costFeeSetCopy, api_costFeeSetDelete, api_costFeeSetEdit, api_costFeeSetList } from '@/api/costFeeSet/costFeeSet';
import { useFeesetList } from '@/store/list_feeset';
import useInstance from '@/hooks/useInstance';
import { isArrayLength } from '@/utils/is';
import { openUrl } from '@/utils';
import { useEleFormValidate } from '@/hooks/useEleFormValidate';

const { report } = useErrorConfirm()
const { resData } = useReturnData()
/**
 * 成本费用设置页面
 */
export function useProviderFeeSet(providerFeeSetListOptions: BasicTableProps, providerFeeSetGridRef: Ref<VxeGridInstance | undefined>) {
    const { storeDropDownData, allProvidersList, deliverChannelList } = useDropDownData()
    // 费用设置列表stroe
    const storeFeesetList = useFeesetList()
    const { global } = useInstance();
    // 搜索 ref
    const searchFormRef = ref()
    // 搜索参数
    const listParm = reactive<CostFeeSetParams>({
        feeSetName: undefined,
        providerId: undefined,
        feeItemCategory: undefined,
        productId: undefined,
        currentEffective: true,
        pageNum: 1,
        pageSize: 10,
        total: 0
    })
    // 产品费用设置Ref
    const addEditProviderFeeSetRef = ref<{ show: (type: number, data?: SubmitCostFeeSetModel) => void }>()
    // 成本费用设置-基础数据
    const providerFeeSetList = reactive({
        effectivelist: [
            {
                value: true,
                label: '生效记录'
            },
            {
                value: false,
                label: '全部记录'
            }
        ],//当期生效记录
        tableList: [],//表格数据
        disabledArr: [] as number[],//禁用按钮组
        multipleSelection: [] as string[],//复选框选择的数据
        sonMultipleSelection: [],//子复选框
        selectionDataSource: [] as Recordable[],
        selectionSonDataSource: [] as Recordable[],
        currentEffective: true,
        loading: false,
    })

    // 费项列表
    const feeItemCategoryList = computed(() => storeFeesetList.getFeeItemCategoryList)
    // 父与子复选框内容
    const getSelectionDataSource = computed(() => {
        return [...providerFeeSetList.selectionDataSource, ...providerFeeSetList.selectionSonDataSource]
    })

    // 选中复选框
    const handleSelectionChange = ({ records }) => {
        providerFeeSetList.selectionDataSource = records
        const selection = records.map(item => `${item.productId}+${item.versionNumber}`)
        providerFeeSetList.multipleSelection = selection;
    }
    // 子复选框
    const handleSonSelectionChange = ({ records }) => {
        providerFeeSetList.selectionSonDataSource = records//折叠选中内容
        providerFeeSetList.sonMultipleSelection = records.map(item => `${item.productId}+${item.versionNumber}`)
    }
    // 合并复选框
    // const multipleSelectionData = computed((): string[] => {
    //     return [...providerFeeSetList.multipleSelection, ...providerFeeSetList.sonMultipleSelection]
    // })
    // 清空复选框内容
    const defineClearCheckboxRow = () => {
        const customerFeeSetGrid = unref(providerFeeSetGridRef)
        if (!customerFeeSetGrid) return
        providerFeeSetList.multipleSelection = []
        providerFeeSetList.sonMultipleSelection = []
        customerFeeSetGrid.clearCheckboxRow()
        customerFeeSetGrid.clearRowExpand()
    }

    // 操作类型
    const hanleChangeAction = async (data: Recordable) => {
        const row = cloneDeep(data)
        const types = row.types;
        // 费用操作列表
        console.log(types, ":费用操作类型", row);
        switch (types) {
            // 费用设置-删除
            case BaseFeesetAction.DELETE:
                deleteBtn(row.id)
                break;
            // 费用设置-编辑
            case BaseFeesetAction.EDIT:
                // 向其它窗口传递数据
                // const targetWindow = openUrl('test', { id: row.id, type: BaseFeesetAction.EDIT })
                // targetWindow?.postMessage({ id: row.id, type: BaseFeesetAction.EDIT }, window.location.origin)
                addEditProviderFeeSetRef.value?.show(BaseFeesetAction.EDIT, row)
                break;
            // 费用设置-查看
            case BaseFeesetAction.VIEW:
                addEditProviderFeeSetRef.value?.show(BaseFeesetAction.VIEW, row)
                break;
            // 新版本
            case BaseFeesetAction.VERSION:
                addEditProviderFeeSetRef.value?.show(BaseFeesetAction.VERSION, row)
                break;
            // 激活
            case BaseFeesetAction.FEESET_ACTIVE:
                const res = await api_costFeeSetActive({ id: row.id, activeFlag: !row.activeFlag })
                const codeData = resData(res)
                if (codeData !== 500) initProviderFeeSetList();
                break;
            // 拷贝
            case BaseFeesetAction.COPY:
                // 目标费用编号数据
                initFeesetCopy(row)
                break;
            default:
                break;
        }
    }

    //费用设置删除
    const deleteBtn = async (id: number) => {
        //信息确认
        let confirm = await global.$myconfirm('确定删除该数据吗?')
        if (confirm) {
            const deleteRes = await api_costFeeSetDelete({ id })
            const deleteCode = resData(deleteRes)
            if (deleteCode !== 500) initProviderFeeSetList()
        }
    }

    // 客户费用拷贝
    const initFeesetCopy = async (data) => {
        // 激活不能拷贝，并且提示对应已激活的费用名称
        const checkboxDataSource = unref(getSelectionDataSource)
        const isActiveFlag = checkboxDataSource.some(item => item.activeFlag)
        if (isActiveFlag) {
            const activeFlagList = checkboxDataSource.filter(item => item.activeFlag)
            const textArr = activeFlagList.map(item => item.feeSetName)
            ElMessageBox.alert(
                `当前费用已激活，禁止拷贝：<br/> ${textArr.join("<br/>")}`,
                { dangerouslyUseHTMLString: true }
            );
            return
        }
        const targetIds = checkboxDataSource.map(item => item.id)
        const resCopy = await api_costFeeSetCopy({ id: data.id, targetIds })
        const codeCopy = resData(resCopy)
        if (codeCopy !== 500) initProviderFeeSetList();
    }

    // 下拉按钮显示事件
    const changeVisibleChange = (val, scope) => {
        if (val) {
            // 是否激活状态
            const seting = scope.row.activeFlag ? BaseFeesetAction.EDIT : -1
            // 拷贝的禁用
            const isId = isArrayLength(unref(getSelectionDataSource)) ?
                unref(getSelectionDataSource).some(item => item.id === scope.row.id) : true
            const copy = isId ? BaseFeesetAction.COPY : -1
            providerFeeSetList.disabledArr = [copy, seting]
        }
    }

    // 显示隐藏展开列内容
    const isShowOrHidden = () => {
        const columns = providerFeeSetListOptions.columns
        const isExpand = columns?.some(item => item.type === 'expand')
        if (isExpand && !providerFeeSetList.currentEffective) {
            // 删除
            providerFeeSetListOptions.columns?.shift()
            return false
        }
        const expands = columns?.filter(item => item.type === 'expand')
        if (expands?.length && expands?.length === 1) return false
        // 添加
        providerFeeSetListOptions.columns?.unshift({ type: "expand", slots: { content: 'expands' }, width: 40 })
    }

    // 初始化列表数据
    const initProviderFeeSetList = async () => {
        defineClearCheckboxRow()
        providerFeeSetList.loading = true
        const res = await api_costFeeSetList(listParams)
        if (res && res.code == 200) {
            providerFeeSetList.currentEffective = listParm.currentEffective
            isShowOrHidden()
            providerFeeSetList.tableList = res.data.records
            listParm.total = res.data.total;
        }
        providerFeeSetList.loading = false
    }
    const { resetForm } = useEleFormValidate()
    // 重置
    const resetParams = () => {
        listParm.currentEffective = true;
        resetForm(searchFormRef.value)
    }
    // 初始化列表、分页数据
    const { sizeChange, currentChange, searchBtn, resetBtn, listParams } = useQueryList<CostFeeSetParams>(initProviderFeeSetList, resetParams, listParm)

    // 添加
    const addBtn = () => {
        addEditProviderFeeSetRef.value?.show(BaseFeesetAction.ADD)
    }
    // 保存成本费用设置
    const hanleSaveFeeBase = async (providerFeeSetDto: SubmitCostFeeSetModel, onclose: Function, type: number) => {
        await costFeeSetInit(providerFeeSetDto, onclose, type, initProviderFeeSetList)
    }

    onMounted(() => {
        //添加国家/地区列表
        storeDropDownData.addCountryList()
        //渠道商
        storeDropDownData.addAllProvidersList()
        // 费项
        storeFeesetList.addFeeItemCategoryList()
        //成本产品列表
        storeDropDownData.addDeliverChannelListApi()
    })

    return {
        listParm,
        searchFormRef,
        providerFeeSetList,
        addEditProviderFeeSetRef,
        feeItemCategoryList,
        allProvidersList,
        deliverChannelList,
        changeVisibleChange,
        searchBtn,
        resetBtn,
        addBtn,
        hanleChangeAction,
        sizeChange,
        currentChange,
        hanleSaveFeeBase,
        handleSelectionChange,
        handleSonSelectionChange,
    }
}

/**
 * 新增、编辑费用设置
 * @param providerFeeSetDto 
 * @param onclose 
 * @param type 
 * @param initProviderFeeSetList 
 */
export async function costFeeSetInit(providerFeeSetDto: SubmitCostFeeSetModel, onclose: Function, type: number, initProviderFeeSetList: Function) {
    try {
        let codeData
        // 新增、新增版本
        if (type === BaseFeesetAction.ADD || type === BaseFeesetAction.VERSION) {
            const res = await api_costFeeSetAdd(providerFeeSetDto)
            codeData = resData(res)
        } else {
            const res = await api_costFeeSetEdit(providerFeeSetDto)
            codeData = resData(res)
        }
        if (codeData !== 500) {
            onclose()
            //刷新表格
            initProviderFeeSetList();
        }
    } catch (error) {
        report(error)
    }
}