import { api_DownloadBillShare, editBillMainApi, getBillMainDetailListApi, uploadApi } from "@/api/billmain/billMain";
import { BaseTableProps, TableActionType } from "@/components/Table/src/types";
import { useEleFormValidate } from "@/hooks/useEleFormValidate";
import { useReturnData } from "@/utils/useReturnData";
import { EditType, Title } from "@/type/BaseEnum";
import { DialogModel } from "@/type/BastType";
import { formatDateTime } from "@/utils/dateFormate";
import { FormInstance, UploadInstance, UploadProps, UploadRawFile } from "element-plus";
import { ref, reactive, computed, unref } from "vue";
import { downloadByData, downloadByUrl } from '@/utils/download';
import { ListIitem } from "@/api/base/BaseDataModel";
import { useMessage } from "@/hooks/useMessage";
import { getAppEnvConfig } from "@/utils/env";
import { cloneDeep } from "@/utils/cloneDeep";
import { AddEditBillMainParams } from "@/api/billmain/billMainModle";

const { VITE_GLOB_BASE_EXPORT_URL, PROD } = getAppEnvConfig()
const { createMessage } = useMessage()

// TODO 处理：新增/编辑应付账单
export function useAddEditBillMain(dialog: DialogModel, onClose: Function, onShow: Function, methodsTable: TableActionType, emit, addEditBillMainTable: BaseTableProps, store) {
    // 定义基础数据
    const state = reactive({
        type: EditType.ADD,
        uploadDisabled: false,
        exportDisabled: false,
        queryDisabled: false,
        form: {
            rateVersionId: undefined,
            createUserId: undefined,
            updateUserId: undefined,
            updateUserName: undefined,
            createUserName: undefined,
            billDate: undefined,
            updateTime: undefined,
            billName: undefined,
            uploadFileName: undefined,//导入的名称
            createTime: undefined,
            stateFlag: 0,
            id: undefined,
            stateFlagName: undefined,
        },
        queryForm: {
            channelId: '',
            mainId: 0,
            waybillNo: '',
            enterpriseDominantNameImport: ''
        },
        // 是否均摊
        equalSharingList: [
            {
                value: true,
                label: '是'
            },
            {
                value: false,
                label: '否'
            }
        ],
        editingRow: {},//保存当前行数据
    })
    // 分页参数
    const listParm = reactive({
        pageNum: 1,
        pageSize: 10,
        total: 0,
        totalList: []
    })
    // 币种列表
    const currencyList = ref<ListIitem[]>()
    const uploadRef = ref<UploadInstance>()
    // 基础表单的ref
    const addbillMainFormRef = ref<FormInstance>()
    const addbillMainTableFormRef = ref<FormInstance>()
    const uploadDisabled = computed(() => {
        return state.uploadDisabled ? '导入中' : '导入'
    })
    // 汇率版本id变化
    const getRateVersionId = computed(() => {
        return state.form.rateVersionId
    })


    // 校验、重置表单
    const { formValidate, resetForm } = useEleFormValidate();
    // 处理返回数据
    const { resData } = useReturnData()


    // 明细列表
    const detailList = async () => {
        const res = await getBillMainDetailListApi(state.queryForm)
        const data = resData(res)
        // 只渲染10条数据
        pageSliceList(data)
        listParm.totalList = data
        listParm.total = data.length
        // addEditBillMainTable.dataSource = data;
        // console.log(data, ":明细列表");
    }

    // 查询列表
    const hanleQuery = () => {
        detailList()
    }

    // 显示操作
    const show = (type: string, row?: Recordable) => {
        dialog.title = EditType.ADD === type ? Title.ADD : EditType.EDIT === type ? `${Title.EDIT}(${row && row.billName})` : `${Title.SUPPLEMENT}(${row && row.billName})`
        currencyList.value = store.getCurrencyList
        // console.log(type, "弹框标题", row);
        if (type == EditType.EDIT && row) {
            Object.assign(state.form, { ...row, rateVersionId: String(row.rateVersionId) as never })
            state.queryForm.mainId = row.id
            detailList()
            //设置编辑属性
            state.type = type;
        } else if (type == EditType.SUPPLEMENT && row) {
            console.log(type, "弹框标题", row);
            Object.assign(state.form, { ...row, rateVersionId: String(row.rateVersionId) as never })
            state.queryForm.mainId = row.id
            state.type = type;
        }
        onShow()
    }

    // 取消弹窗
    const hanleOnClose = () => {
        // 清空表格数据
        addEditBillMainTable.dataSource = []
        resetForm(addbillMainFormRef.value)
        // 清空
        Object.keys(state.form).map((item) => {
            if (item === 'stateFlag') return
            state.form[item] = undefined
        })
        // 初始化分页参数
        listParm.pageNum = 1
        listParm.pageSize = 10
        listParm.total = 0
        listParm.totalList = []
        // 默认新增
        state.type = EditType.ADD
        onClose()
    }

    // 获取的数据
    const confirm = async () => {
        // 基础表单-校验
        const isFormValidate = await formValidate(addbillMainFormRef.value)
        if (!isFormValidate) return;
        // 动态表单-校验
        // const isFormValidate2 = await formValidate(addbillMainTableFormRef.value)
        // if (!isFormValidate2) return;
        // 获取动态表格数据
        // const billDetailDtoList = methodsTable.getDataSource().map(item => {
        //     // 时间转换
        //     if (item.billDate) {
        //         item.billDate = formatDateTime(item.billDate)
        //     }
        //     return item
        // })
        // console.log(billDetailDtoList, ":获取动态表单的数据", state.form, ":基础表单数据");
        // 新增或编辑的参数
        state.form.billDate = formatDateTime(new Date()) as never//处理的时间
        const propsData = {
            type: state.type,
            formProps: {
                ...state.form,
                billDetailDtoList: listParm.totalList.map((item: Recordable) => {
                    if (state.form.id) item.mainId = state.form.id
                    if (item.id) item.id = null
                    return item
                })
            }
        }
        switch (state.type) {
            // 新增
            case EditType.ADD:
                emit("saveBillMain", unref(propsData), hanleOnClose)//数据、弹窗事件
                break;
            // 编辑
            case EditType.EDIT:
                // 取消弹窗
                hanleOnClose()
                break;
            // 补录
            case EditType.SUPPLEMENT:
                emit("saveBillMain", unref(propsData), hanleOnClose)//数据、弹窗事件
                // 取消弹窗
                break;
            default:
                break;
        }
    }

    // === 导入 ===
    // 上传失败
    const handleError = (err, file) => {
        console.log(err, file, ":上传失败");
    }
    // 上传文件
    const handleChange = async (file) => {
        const isXlsx = file.raw.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        if (!isXlsx) {
            createMessage.error('只能上传 xlsx 文件！');
            return
        }
        state.uploadDisabled = true;
        try {
            const res = await uploadApi({ file: file.raw })
            const data = res.data
            if (res.code === 200 && data.length > 0) {
                // 上传文件名
                state.form.uploadFileName = file.name
                // 只渲染10条数据
                listParm.totalList = data.map((item, index) => {
                    if (!item.id) item.id = index + 1
                    return item
                })
                pageSliceList(listParm.totalList)
                listParm.total = data.length
                state.uploadDisabled = false;
            } else {
                state.uploadDisabled = false;
            }
        } catch (error) {
            state.uploadDisabled = false;
            console.error(error);
        }
    }
    // 限制上传
    const handleExceed: UploadProps['onExceed'] = (files) => {
        uploadRef.value!.clearFiles()
        const file = files[0] as UploadRawFile
        uploadRef.value!.handleStart(file)
    }

    // 导出模板
    const hanleExprot = async () => {
        state.exportDisabled = true
        const res = await api_DownloadBillShare({})
        if (res) {
            // 获取接口表格响应的头
            const header = res.headers['content-disposition'].split("''")
            // 转中文
            const fileName = decodeURIComponent(header[1])
            // 通过blod导出模板
            downloadByData(res.data, fileName)
            state.exportDisabled = false
        }
    }

    // 操作行数据
    const hanleAddColumns = async (actionType: string, rowData: Recordable) => {
        const index = rowData.$index
        const row = rowData.row
        // 获取所有数据当前索引
        const currentIndex = `${listParm.pageNum - 1}${index + 1}`
        // listParm.pageNum === 1 && listParm.pageSize ? index : 
        switch (actionType) {
            // 保存
            case EditType.ADD:
                if (state.type === EditType.ADD) {
                    rowData.row.stateEdit = false
                    // 改变当前索引的数据
                    const dataIndex = Number(currentIndex) - 1
                    // 深拷贝，防止关联主数据
                    const rowObj = cloneDeep(row) as never
                    listParm.totalList[dataIndex] = rowObj
                } else {
                    // 判断数据以及索引必须大于等0条件
                    if (row && Number(currentIndex) >= 0) {
                        rowData.row.stateEdit = false
                        // 改变当前索引的数据
                        const dataIndex = Number(currentIndex) - 1
                        // 深拷贝，防止关联主数据
                        const rowObj = cloneDeep(row) as never
                        listParm.totalList[dataIndex] = rowObj
                        state.form.billDate = formatDateTime(new Date()) as never//处理的时间
                        const params = {
                            ...state.form,
                            billDetailDtoList: [rowObj]
                        }
                        const resEdit = await editBillMainApi(params as never as AddEditBillMainParams)
                        // 响应数据
                        resData(resEdit)
                    }
                }
                break;
            // 删除
            case EditType.DELETE:
                if (Number(currentIndex) >= 0) {
                    listParm.totalList.splice(Number(currentIndex), 1)
                    listParm.total = listParm.totalList.length
                    pageSliceList(listParm.totalList)
                }
                break;
            // 编辑
            case EditType.EDIT:
                if (row) {
                    // 备份当前行数据
                    state.editingRow = { ...row }
                    rowData.row.stateEdit = true
                    // console.log(row, ":编辑");
                }
                break;
            // 补录-删除
            case EditType.SUPPLEMENT:
                if (Number(currentIndex) >= 0) {
                    const deleteIndex = Number(currentIndex) - 1
                    listParm.totalList.splice(deleteIndex, 1)
                    listParm.total = listParm.totalList.length
                    pageSliceList(listParm.totalList)
                }
                break;
            default:
                // 取消恢复之前数据
                Object.assign(row, state.editingRow)
                state.editingRow = {}
                rowData.row.stateEdit = false
                break;
        }
    }

    // 当点击其他行时，如有行处于编辑状态，则自动取消之前行的编辑状态
    const handleCurrentChange = (currentRow, oldRow) => {
        if (oldRow && oldRow.stateEdit) {
            const data = listParm.totalList.find((item: any) => item.id === oldRow.id)
            console.log(data, ":data");
            Object.assign(oldRow, data);
            oldRow.stateEdit = false;
        }
    }

    // 获取版本号
    const changeRateVersion = (rateVersionId) => {
        state.form.rateVersionId = rateVersionId
    }

    //页容量改变时触发
    const sizeChange = (size: number) => {
        listParm.pageSize = size;
        pageSliceList(listParm.totalList)
    }
    //页数改变时触发
    const currentChange = (page: number) => {
        listParm.pageNum = page;
        pageSliceList(listParm.totalList)
    }
    const pageSliceList = (list: Recordable) => {
        addEditBillMainTable.dataSource = []
        const data = cloneDeep(list)
        addEditBillMainTable.dataSource = data.slice(
            (listParm.pageNum - 1) *
            listParm.pageSize,
            listParm.pageNum * listParm.pageSize
        )
    }

    return {
        show,
        confirm,
        hanleOnClose,
        handleError,
        hanleAddColumns,
        handleChange,
        handleExceed,
        hanleExprot,
        changeRateVersion,
        sizeChange,
        currentChange,
        handleCurrentChange,
        hanleQuery,
        getRateVersionId,
        uploadRef,
        addbillMainFormRef,
        addbillMainTableFormRef,
        uploadDisabled,
        currencyList,
        listParm,
        state
    }
}