import { api_financialBillSummaryDownload, api_financialBillSummaryUploadApi, api_getFinancialBillSummaryByPId } from "@/api/financial/financialBillList/financialBillList";
import { PartialFinancialBillSummaryDto } from "@/api/financial/financialBillList/financialBillListModel";
import { useApiDownTemplate } from "@/hooks/useApiDownTemplate";
import { useDropDownData } from "@/hooks/useDropDownData";
import { useEleFormValidate } from "@/hooks/useEleFormValidate";
import { useMessage } from "@/hooks/useMessage";
import { DialogModel } from "@/type/BastType";
import { formatDateTime } from "@/utils/dateFormate";
import { deal_FindItemName } from "@/utils/dealFindData";
import { resCodeSuccess } from "@/utils/useReturnData";
import type { UploadInstance } from "element-plus";
import { cloneDeep } from "lodash";
import { ref, reactive, computed, unref } from "vue";

type DefineEmit = {
    (e: "saveConfirm", params: PartialFinancialBillSummaryDto, onclose: Fn): void;
};
const { createMessage, createConfirm } = useMessage()
/**
 * 新增账单
 * @returns
 */
function useFinancialBillSet(
    dialog: DialogModel,
    onClose: Fn,
    onShow: Fn,
    emit: DefineEmit
) {
    // 下拉列表数据
    // const storeFeesetList = useFeesetList();
    // const feeItemCategoryList = computed(
    //     () => storeFeesetList.getFeeItemCategoryList
    // );
    const { companyEntityTypeList, allProvidersList } = useDropDownData();
    // 表单ref
    const financialBillSetFormRef = ref();
    // 基础数据
    const financialBillSetState = reactive({
        // 校验
        rulesFinancialBillSet: {
            stakeholder: [{ required: true, message: '请选择主体', trigger: 'change' }],
            billCode: [{ required: true, message: '请输入账单编号', trigger: 'blur' }],
            billName: [{ required: true, message: '请输入账单名称', trigger: 'blur' }],
            providerId: [{ required: true, message: '请选择渠道商', trigger: 'change' }],
            billTime: [{ required: true, message: '请选择账单时间', trigger: 'change' }],
            belongTime: [{ required: true, message: '请选择归账时间', trigger: 'change' }],
            uploadFile: [{ required: true, message: '请上传文件', trigger: 'change' }],
        },
    });
    // col宽度百分比
    const setFormItemWidth = computed(() => {
        return { width: `calc(100% - 32px)` }
    })
    // 参数
    const financialBillSetForm = reactive<PartialFinancialBillSummaryDto>({
        id: undefined,
        stakeholder: undefined,
        stakeholderName: undefined,
        billCode: undefined,
        billName: undefined,
        feeItemCategoryName: undefined,
        providerId: undefined,
        providerName: undefined,
        billTime: undefined,
        belongTime: undefined,
        uploadFile: undefined,
        originalFile: undefined,
        uploadFileName: undefined,
        originalFileName: undefined,
    });
    const { formValidate, clearValidateForm, resetForm } = useEleFormValidate();
    // 初始化表单值
    const initFormData = async (id: number) => {
        const res = await api_getFinancialBillSummaryByPId({ id });
        if (res && res.code == 200) {
            const data = cloneDeep(res.data);
            Object.assign(financialBillSetForm, { ...data, providerId: String(data.providerId)});
            financialBillSetForm.uploadFile = undefined
            financialBillSetForm.uploadFileName = undefined
        }
    };
    // 显示
    const show = (id: number) => {
        id ? (dialog.title = "编辑") : (dialog.title = "新增");
        if (id) initFormData(id);
        onShow();
    };
    // 隐藏
    const onclose = () => {
        Object.keys(financialBillSetForm).forEach(((key) => {
            financialBillSetForm[key] = undefined
        }))
        uploadFileRef.value!.clearFiles()
        originalFileRef.value!.clearFiles()
        resetForm(financialBillSetFormRef.value);
        onClose();
    };
    // 清空原文件
    const closeUpload = () => {
        financialBillSetForm.originalFile = undefined
        financialBillSetForm.originalFileName = undefined
    }
    // 模版下载
    const { templateLoading, hanleOpenDownload: templateDownload } = useApiDownTemplate(api_financialBillSummaryDownload)
    // 文件上传
    const uploadFileRef = ref<UploadInstance>()
    const hanleUploadFile = (files) => {
        const isXlsx = files.raw.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        if (!isXlsx) {
            createMessage.error('只能上传 xlsx 文件！');
            return
        }
        const file = files.raw as File
        if(file) {
            financialBillSetForm.uploadFile = file
            financialBillSetForm.uploadFileName = file.name
        }
        uploadFileRef.value!.clearFiles()
        clearValidateForm(unref(financialBillSetFormRef), "uploadFile")
    }
    // 原文件上传
    const originalFileRef = ref<UploadInstance>()
    const originalFile = async (file) => {
        try {
            const res = await api_financialBillSummaryUploadApi({ file, data: { billFileType: 0 } })
            if(resCodeSuccess(res)) {
                financialBillSetForm.originalFile = res.data.filePath
                financialBillSetForm.originalFileName = res.data.fileName
            }
        } catch (error) {
            
        } finally {
            originalFileRef.value!.clearFiles()
        }
    }
    const hanleOriginalFile = (files) => {
        createConfirm({
            type: "warning",
            title: "系统提示",
            message: `确定是否上传 <span style="color: red;">${files.raw.name}</span> 该文件吗?`,
            cancelButtonText: "取消",
            confirmButtonText: "确定",
            dangerouslyUseHTMLString: true, 
            beforeClose: (action, instance, done) => {
                if (action === "confirm") {
                    originalFile(files.raw)
                }
                originalFileRef.value!.clearFiles()
                done()
            },
        })
    }
    // 上传文字显示
    const getUploadFile = computed(() => {
        return financialBillSetForm.uploadFileName ? financialBillSetForm.uploadFileName : '文件上传'
    })
    const getOriginalFile = computed(() => {
        return financialBillSetForm.originalFile ? financialBillSetForm.originalFileName : '文件上传'
    })
    // 处理参数
    const dealParams = () => {
        const stakeholderName = deal_FindItemName(Number(financialBillSetForm.stakeholder), unref(companyEntityTypeList))
        financialBillSetForm.stakeholderName = stakeholderName
        // const feeItemCategoryName = deal_FindItemName(String(financialBillSetForm.feeItemCategoryId), unref(feeItemCategoryList))
        // financialBillSetForm.feeItemCategoryName = feeItemCategoryName
        const providerName = deal_FindItemName(String(financialBillSetForm.providerId), unref(allProvidersList))
        financialBillSetForm.providerName = providerName
        financialBillSetForm.billTime = formatDateTime(financialBillSetForm.billTime)
        financialBillSetForm.belongTime = formatDateTime(financialBillSetForm.billTime)
        const params = cloneDeep(financialBillSetForm)
        return params
    }
    // 确定
    const confirm = async () => {
        const isValidate = await formValidate(financialBillSetFormRef.value);
        if (!isValidate) return;
        const params = dealParams();
        emit("saveConfirm", params, onclose);
    };

    return {
        financialBillSetForm,
        financialBillSetState,
        financialBillSetFormRef,
        uploadFileRef,
        originalFileRef,
        setFormItemWidth,
        show,
        onclose,
        confirm,
        closeUpload,
        templateDownload,
        templateLoading,
        hanleUploadFile,
        hanleOriginalFile,
        getUploadFile,
        getOriginalFile,
        companyEntityTypeList,
        allProvidersList,
    };
}

export { useFinancialBillSet };
