import { Idparams, ListIitem } from '@/api/base/BaseDataModel';
import { api_financialBillSummaryAdd, api_financialBillSummaryDelete, api_financialBillSummaryEdit, api_financialBillSummaryList, api_financialBillSummaryUpdateState, api_getFinancialBillSummaryVerify, api_getFinancialBillSummaryVerifyShare } from '@/api/financial/financialBillList/financialBillList';
import type { BillShareParam, PartialFinancialBillSummaryDto, PartialFinancialBillSummaryParam } from '@/api/financial/financialBillList/financialBillListModel';
import { BasicTableProps } from '@/components/VxeTable';
import { useDropDownData } from '@/hooks/useDropDownData';
import { useEleFormValidate } from '@/hooks/useEleFormValidate';
import { useMessage } from '@/hooks/useMessage';
import { useQueryList } from '@/hooks/useQueryList';
import { useFeesetList } from '@/store/list_feeset';
import { useStateFinancialType } from '@/store/list_financial';
import { BaseFinancialFinancialBillList } from '@/type/BaseFinancial';
import { cloneDeep } from '@/utils/cloneDeep';
import { formatDateTime } from '@/utils/dateFormate';
import { isArrayLength } from '@/utils/is';
import { resCodeSuccess, useReturnData } from '@/utils/useReturnData';
import { ref, reactive, unref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { downloadByUrl } from '@/utils/download';

const { resData } = useReturnData()
const { createConfirm } = useMessage()
/**
 * 财务应付账单
 * @returns 
 */
function useFinancialBillList(financialBillListOptions: BasicTableProps) {
    const { push } = useRouter()
    const { storeDropDownData, allProvidersList } = useDropDownData()
    const storeFeesetList = useFeesetList()
    const storeFinancialType = useStateFinancialType()
    // 表单 ref
    const financialBillListFormRef = ref()
    // 新增或编辑账单录入
    const financialBillSetRef = ref<{ show: Fn }>()
    // 账单分摊
    const financialShareRef = ref<{ show: Fn }>()
    // 基础数据
    const financialBillListState = reactive({
        loading: false,//加载
        disabledArr: [] as number[],//按钮组禁止
    })
    // 查询参数
    const financialBillListParams = reactive<PartialFinancialBillSummaryParam>({
        billCode: undefined,
        billName: undefined,
        providerId: undefined,
        billState: undefined,
        billDateType: undefined,
        pageNum: 1,
        pageSize: 10,
        total: 10
    })
    onMounted(() => {
        storeFinancialType.addBillDateTypeList()
        storeFinancialType.addFinancialBillStateList()
        storeFinancialType.addBillRateList()
        storeDropDownData.addAllProvidersList()
        storeDropDownData.addCompanyEntityTypeListApi()
        storeFeesetList.addFeeItemCategoryList()
    })
    // 处理时间参数
    const dealBeginDateEndDate = () => {
        const dateArr = financialBillListParams.beginDate
        if (isArrayLength(dateArr)) {
            listParams.beginDate = formatDateTime(dateArr[0])
            listParams.endDate = formatDateTime(dateArr[1])
        } else {
            listParams.beginDate = undefined
            listParams.endDate = undefined
        }
    }
    // 初始化数据
    const initList = async () => {
        dealBeginDateEndDate()
        const res = await api_financialBillSummaryList(listParams)
        if (resCodeSuccess(res)) {
            financialBillListOptions.data = res.data.records
            financialBillListParams.total = res.data.total
        }
    }
    // 校验表单
    const { resetForm } = useEleFormValidate();
    const resetParams = () => {
        resetForm(unref(financialBillListFormRef))
    }
    const { sizeChange, currentChange, searchBtn, resetBtn, listParams } = useQueryList<PartialFinancialBillSummaryParam>(initList, resetParams, financialBillListParams)
    // 新增
    const hanleAdd = () => unref(financialBillSetRef)?.show()
    // 上传文件下载
    const downloadUploadFile = (row) => downloadByUrl({ url: row.uploadFile, target: '_self' })
    // 原文件下载
    const downloadOriginalFile = async (row) => {
        downloadByUrl({ url: row.originalFile })
    }
    // 账单编辑是否禁止
    const changeVisibleChange = (val, row) => {
        if (!val) return
        const editBill = row.billState !== 0 ? BaseFinancialFinancialBillList.BILL_EDIT : -1
        const deleteBill = row.billState !== 0 ? BaseFinancialFinancialBillList.BILL_DELETE : -1
        financialBillListState.disabledArr = [editBill, deleteBill]
    }
    // 删除
    const deleteBill = async (id: number) => {
        const deleteRes = await api_financialBillSummaryDelete({ id })
        const deleteCode = resData(deleteRes)
        if (deleteCode !== 500) initList()
    }
    // 账单关账
    const updateStateBill = async (data) => {
        const res = await api_financialBillSummaryUpdateState({ id: data.id, billState: BaseFinancialFinancialBillList.BILL_CORRELATION })
        const deleteCode = resData(res)
        if (deleteCode !== 500) initList()
    }
    // 账单核账
    const billSummaryVerify = async (params: Idparams) => {
        const res = await api_getFinancialBillSummaryVerify(params)
        const resCode = resData(res)
        if (resCode !== 500) initList()
    }
    // 账单分摊
    const hanleSaveVersion = async (params: BillShareParam, onclose: Fn, setLoading: Fn) => {
        try {
            setLoading(true)
            const res = await api_getFinancialBillSummaryVerifyShare(params)
            const resCode = resData(res)
            if (resCode !== 500) onclose()
        } finally {
            setLoading(false)
        }
    } 
    // 操作
    const handleClickChange = (row) => {
        const data = cloneDeep(row)
        switch (data.types) {
            case BaseFinancialFinancialBillList.BILL_EDIT:
                unref(financialBillSetRef)?.show(data.id)
                break;
            case BaseFinancialFinancialBillList.BILL_DETAILS:
                push({
                    name: 'financialBillDetailList',
                    state: {
                        summaryId: data.id
                    }
                })
                break;
            case BaseFinancialFinancialBillList.BILL_DELETE:
                createConfirm({
                    type: "warning",
                    title: "系统提示",
                    message: "确定删除该数据吗?",
                    cancelButtonText: "取消",
                    confirmButtonText: "确定",
                    beforeClose: (action, instance, done) => {
                        if (action === "confirm") {
                            // 删除
                            deleteBill(data.id)
                        }
                        done()
                    },
                })
                break;
            case BaseFinancialFinancialBillList.BILL_AUDIT_ACCOUNTS:
                billSummaryVerify({ id: data.id })
                break;
            case BaseFinancialFinancialBillList.BILL_ALLOCATION:
                unref(financialShareRef)?.show(data)
                break;
            case BaseFinancialFinancialBillList.BILL_CORRELATION:
                updateStateBill(data)
                break;
            default:
                break;
        }
    }
    // 账单录入操作
    const hanleSaveConfirm = async (params: PartialFinancialBillSummaryDto, onclose: Fn) => {
        if (params.id) {
            const res = await api_financialBillSummaryEdit(params)
            const resCode = resData(res)
            if (resCode !== 500) {
                initList()
                onclose()
            }
        } else {
            const res = await api_financialBillSummaryAdd(params)
            const resCode = resData(res)
            if (resCode !== 500) {
                initList()
                onclose()
            }
        }

    }

    return {
        financialBillListParams,
        financialBillListState,
        financialBillListFormRef,
        financialBillSetRef,
        financialShareRef,
        sizeChange,
        currentChange,
        searchBtn,
        resetBtn,
        hanleAdd,
        downloadUploadFile,
        downloadOriginalFile,
        handleClickChange,
        changeVisibleChange,
        hanleSaveConfirm,
        hanleSaveVersion,
        storeFinancialType,
        allProvidersList
    }
}

export {
    useFinancialBillList
}