import { shallowRef, reactive, computed } from 'vue'
import { v4 } from 'uuid'
import { useDataTable } from '@/hooks/datatable'
import { cjjcApply, queryGZCJJCOrder, cjjcMemberOperate, queryGZCJJCOrderDetail, queryGzcjjcorderoperate } from '@/services/api/customs'
import { ClientType } from '@/constants/client'
import { useLoginStore } from '@/stores'
import Long from 'long'

const loginStore = useLoginStore()
const { userId, loginInfo } = loginStore.$toRefs()

// 出境检测列表
export function useCJJCOrderList() {
    const { dataList, total, pageIndex, pageSize } = useDataTable<Ermcp.GZCJJCOrderRsp>()
    const loading = shallowRef(false)

    const getGZCJJCOrderList = async (params: Partial<Ermcp.GZCJJCOrderReq> = {}) => {
        try {
            loading.value = true
            const res = await queryGZCJJCOrder({
                page: pageIndex.value,
                pagesize: pageSize.value,
                userid: userId.value,
                executestatus: params.executestatus,
            })
            total.value = res.total
            dataList.value = res.data
        } finally {
            loading.value = false
        }
    }

    return {
        loading,
        dataList,
        total,
        pageIndex,
        pageSize,
        getGZCJJCOrderList,
    }
}

// 出境检测单据明细
export function useGZCJJCOrderDetail(selectedRow: Ermcp.GZCJJCOrderRsp) {
    const loading = shallowRef(false)
    const detailList = shallowRef<Ermcp.GZCJJCOrderDetailRsp[]>([])

    const columns = computed<Ermcp.TableColumn[]>(() => {
        switch (selectedRow.gzcjaccounttype) {
            case 1: {
                return [
                    { prop: 'gzno', label: '货物编号' },
                    { prop: 'gzcjshapetype', label: '形状', width: 200 },
                    { prop: 'weight', label: '重量ct' },
                    { prop: 'amount', label: '参考货值USD' },
                    { prop: 'colorinfo', label: '彩钻信息' },
                    { prop: 'remark', label: '其他' },
                ]
            }
            case 2: {
                return [
                    { prop: 'gzno', label: '货物编号' },
                    { prop: 'gzcjshapetype', label: '形状', width: 200 },
                    { prop: 'weight', label: '重量ct' },
                    { prop: 'amount', label: '参考货值USD' },
                    { prop: 'gzcjmarktype', label: '刻印服务(证书号/ 其他/ 无)', width: 220 },
                    { prop: 'gzcjpublishtypestring', label: '是否披露处理' },
                    { prop: 'gzcjservicetypestring', label: '服务类别' },
                    { prop: 'origincertno', label: '原证书号' },
                    { prop: 'colorinfo', label: '彩钻信息' },
                    { prop: 'remark', label: '其他' },
                ]
            }
        }
        return []
    })

    const getGZCJJCOrderDetailList = async () => {
        try {
            loading.value = true
            const res = await queryGZCJJCOrderDetail({
                userid: userId.value,
                orderid: selectedRow.orderidstr,
            })
            detailList.value = res.data
        } finally {
            loading.value = false
        }
    }

    return {
        loading,
        detailList,
        columns,
        getGZCJJCOrderDetailList,
    }
}

// 出境检测申请
export function useCJJCOrderApply(selectedRow?: Ermcp.GZCJJCOrderRsp) {
    const { UserID, LoginID, LoginCode, AccountIDs } = loginInfo.value
    const loading = shallowRef(false)

    const formData = reactive<Partial<Proto.CJJCApplyReq>>({
        UserID,
        AccountID: AccountIDs[0],
        OperateID: LoginID, // 操作人ID，LoginAccount的LoginID,必填
        OperateAccount: LoginCode || LoginID.toString(), // 操作人账户，LoginAccount的LoginCode,LoginCode为空则填LoginID,必填
        GZCJCategoryDetails: [],
        ClientType: ClientType.Web,
    })

    if (selectedRow?.orderidstr) {
        ({
            userid: formData.UserID,
            accountid: formData.AccountID,
            gzcjaccounttype: formData.GZCJAccountType,
            gzcjaccount: formData.GZCJAccount,
            companynamecn: formData.CompanyNameCN,
            companynameen: formData.CompanyNameEn,
            addresscn: formData.AddressCN,
            addressen: formData.AddressEN,
            contactname: formData.ContactName,
            contactposition: formData.ContactPosition,
            contactphoneno: formData.ContactPhoneNo,
            email: formData.Email,
            gzcjcategorytype: formData.GZCJCategoryType,
            processingcountry: formData.ProcessingCountry,
            zsorigin: formData.ZSOrigin,
            gzcjdeliverytype: formData.GZCJDeliveryType,
        } = selectedRow)

        formData.OrderID = Long.fromString(selectedRow.orderidstr)

        queryGZCJJCOrderDetail({
            userid: UserID,
            orderid: selectedRow.orderidstr,
        }).then((res) => {
            res.data.forEach((e) => {
                formData.GZCJCategoryDetails?.push({
                    OrderIndex: e.orderindex,
                    GZNo: e.gzno,
                    GZCJShapeType: e.gzcjshapetype,
                    Weight: e.weight,
                    Amount: e.amount,
                    ColorInfo: e.colorinfo,
                    Remark: e.remark,
                    GZCJMarkType: e.gzcjmarktype,
                    GZCJPublishType: e.gzcjpublishtype,
                    GZCJServiceType: e.gzcjservicetype,
                    OriginCertNo: e.origincertno,
                })
            })
        })
    } else {
        // 每次申请自动带入。或者记录第一次申请成功的信息。
        queryGZCJJCOrder({
            page: 1,
            pagesize: 1,
            userid: UserID,
        }).then((res) => {
            if (res.data.length) {
                const item = res.data[0]
                formData.GZCJAccountType = item.gzcjaccounttype
                formData.GZCJAccount = item.gzcjaccount
                formData.CompanyNameCN = item.companynamecn
                formData.CompanyNameEn = item.companynameen
                formData.AddressCN = item.addresscn
                formData.AddressEN = item.addressen
                formData.ContactName = item.contactname
                formData.ContactPosition = item.contactposition
                formData.ContactPhoneNo = item.contactphoneno
                formData.Email = item.email
            }
        })
    }

    const formSubmit = async () => {
        try {
            loading.value = true
            return await cjjcApply({
                ...formData,
                GZCJAccount: formData.GZCJAccountType === 1 ? formData.GZCJAccount : '',
                ClientSerialNo: v4(),
            })
        } finally {
            loading.value = false
        }
    }

    return {
        loading,
        formData,
        formSubmit,
    }
}

// 出境检测单据操作
export function useCJJCOrderOperate({ orderidstr, gzcjstatus }: Ermcp.GZCJJCOrderRsp) {
    const loading = shallowRef(false)
    const details = shallowRef<Ermcp.GzcjjcorderoperateRsp>()

    const getGzcjjcorderoperate = () => {
        queryGzcjjcorderoperate({
            orderid: orderidstr,
            status: gzcjstatus
        }).then((res) => {
            if (res.data.length) {
                details.value = res.data[0]
            }
        })
    }

    return {
        loading,
        details,
        getGzcjjcorderoperate,
    }
}

// 出境检测操作
export function useCJJCMemberOperate(orderId: string) {
    const { UserID, LoginID, LoginCode } = loginInfo.value
    const loading = shallowRef(false)

    const formData = reactive<Proto.CJJCMemberOperateReq>({
        UserID, // 用户ID,必填
        OperateID: LoginID, // 操作人ID,必填，LoginAccount的LoginID
        OperateAccount: LoginCode || LoginID.toString(), // 操作人账户，LoginAccount的LoginCode,LoginCode为空则填LoginID,必
        OrderID: Long.fromString(orderId), // 单据ID,必填
        OperateType: 0, // 操作类型,必填,1：撤回2:确认发货3:确认检测结果
        ClientType: ClientType.Web, // 终端类型
        ClientSerialNo: '', // 客户端流水号
    })

    const formSubmit = async () => {
        try {
            loading.value = true
            return await cjjcMemberOperate({
                ...formData,
                ClientSerialNo: v4(),
            })
        } finally {
            loading.value = false
        }
    }

    return {
        loading,
        formData,
        formSubmit,
    }
}