<template>
    <el-card shadow="never" class="list-card">
        <template #header>
            <div class="search" v-show="showSearch">
                <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
                    <el-form-item prop="invoiceAmount">
                        <el-input v-model="queryParams.keyWord" placeholder="搜素关键词" clearable
                                  style="width: 240px" @keyup.enter="handleQuery"/>
                    </el-form-item>
                    <el-form-item prop="invoicingDate">
                        <el-date-picker
                            v-model="invoicingDate"
                            type="daterange"
                            range-separator="-"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            value-format="YYYY-MM-DD"
                            @change="getDate"
                            style="width: 250px"
                        />
                    </el-form-item>


                    <el-form-item prop="handleUserId">
                        <SelectDict v-model="queryParams.invoicingType" placeholder="票据类型"
                                    dictCode="invoice_type"></SelectDict>
                    </el-form-item>


<!--                    <el-form-item prop="ownerBy">-->
<!--                        <SelectUser placeholder="订单所属人员" v-model="queryParams.ownerBy"></SelectUser>-->
<!--                    </el-form-item>-->
                      <el-form-item prop="handleUserId">
                          <SelectUser placeholder="发票经受人员" v-model="queryParams.handleUserId"></SelectUser>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </template>

        <Table ref="invoiceRecordTable"
               :tableParams="tableParams"
               :btnRole="leftBtn"
               @handleAdd="handleAdd"
               @handleEdit="handleUpdate"
               @selectionChange="handleSelectionChange"
        >

        </Table>
    </el-card>
    <!-- 添加或修改发票对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="700px" append-to-body>
        <el-form ref="invoiceRecordFormRef" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="开票日期" prop="invoicingDate">
                <el-date-picker clearable
                                v-model="form.invoicingDate"
                                type="date"
                                value-format="YYYY-MM-DD"
                                placeholder="请选择开票日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="开票金额" prop="invoiceAmount">
                <el-input v-model="form.invoiceAmount" placeholder="请输入金额">
                    <template #append>
                        <span>元</span>
                    </template>
                </el-input>
            </el-form-item>
            <CorrelationSelect @custChange="getOrder" v-model="form.customerId" :isLiaison="false"/>
            <el-form-item label="关联订单">
                <el-select-v2
                    v-model="form.orderId"
                    :options="groupData"
                    placeholder="请选择关联订单"
                    filterable
                />
            </el-form-item>

            <el-form-item label="票据类型" prop="invoiceCode">
                <SelectDict v-model="queryParams.invoicingType" placeholder="票据类型"
                            dictCode="invoice_type"></SelectDict>
            </el-form-item>

            <el-form-item label="票据内容" >
<!--                <editor v-model="form.invoiceContent" :min-height="192"/>-->
                <el-input v-model="form.invoiceContent" type="textarea" placeholder="请输入票据内容"/>
            </el-form-item>
            <el-form-item label="票据号码" >
                <el-input v-model="form.invoiceCode" placeholder="请输入票据号码"/>
            </el-form-item>
            <el-form-item label="经手人员" >
                <SelectUser placeholder="发票经手人员" v-model="form.handleUserId"></SelectUser>
            </el-form-item>
            <el-form-item label="备注信息" >
                <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
            </el-form-item>

        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm">提交</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 添加或修改发票对话框 -->
    <el-dialog :title="detailDialog.title" v-model="detailDialog.visible" width="700px" append-to-body>
        <el-descriptions column="2" title="基本信息" border>
            <el-descriptions-item  label="开票日期：">{{ form.invoicingDate }}</el-descriptions-item>
            <el-descriptions-item label="开票金额：">
                {{ form.invoiceAmount }}
            </el-descriptions-item>
            <el-descriptions-item label="关联客户：">
               {{form.customerId}}
            </el-descriptions-item>
            <el-descriptions-item label="关联订单：">{{ form.orderId  }}
            </el-descriptions-item>
            <el-descriptions-item label="票据类型">
                {{form.invoicingType}}
            </el-descriptions-item>
            <el-descriptions-item  :span="2" label="票据内容：">
                <span>{{ form.invoiceContent }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="票据号码：">
                <span>{{ form.invoiceCode }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="发票经手人员：">
                <span>{{ form.handleUserId }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="发票经手人员：">
                <span>{{ form.ownerBy }}</span>
            </el-descriptions-item>
            <el-descriptions-item  :span="2" label="备注信息：">
                <span>{{ form.ownerBy }}</span>
            </el-descriptions-item>

        </el-descriptions>
        <el-descriptions style="margin-top: 30px" column="1" title="系统信息"  border>
            <el-descriptions-item label="录入人员：">{{ form.createBy }}</el-descriptions-item>
            <el-descriptions-item label="创建时间：">
                {{ form.createTime }}
            </el-descriptions-item>
            <el-descriptions-item label="更新时间：">
                {{form.updateBy}}
            </el-descriptions-item>

        </el-descriptions>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="detailCancel">关 闭</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup name="InvoiceRecord" lang="ts">
import {
    listInvoiceRecord,
    getInvoiceRecord,
    delInvoiceRecord,
    addInvoiceRecord,
    updateInvoiceRecord
} from '@/api/finance/invoiceRecord';
import {InvoiceRecordVO, InvoiceRecordQuery, InvoiceRecordForm} from '@/api/finance/invoiceRecord/types';
import auth from '@/plugins/auth'
import Table from '@/components/Table/index.vue'
import {tableTypes} from '@/components/Table/types'
import {useDictCache} from "@/hooks/web/useDict";
import {listAllBusiness} from "@/api/business/allBusiness";
import {listOrderForm} from "@/api/orderForm";
const { queryDictDetailByCodes } = useDictCache(['invoice_type'])
queryDictDetailByCodes()
const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const invoicingDate = ref<[]>([])
const invoiceRecordList = ref<InvoiceRecordVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const leftBtn = ref(
    [
        {type: 'remove', hasPermi: 'finance:invoiceRecord:remove'},
        {type: 'add', hasPermi: 'finance:invoiceRecord:add'},
        {type: 'edit', hasPermi: 'finance:invoiceRecord:edit'},
        {type: 'import', hasPermi: 'finance:invoiceRecord:import'},
        {type: 'export', hasPermi: 'finance:invoiceRecord:export'},
    ]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const invoiceRecordFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
});

const cancel = reactive<DialogOption>({
    visible: false,
    title: ''
});

const detailDialog = reactive<DialogOption>({
    visible: false,
    title: ''
});
const getDate = (data:any) =>{
    queryParams.value.startDate = data[0]
    queryParams.value.endDate = data[1]
    handleQuery()
}


const groupData = ref<{ label: string; value: string | number }[]>([])
const getOrder  = async ()=>{
    if(!form.value.customerId) return
    const res = await listOrderForm({
        pageIndex: 1,
        pageSize: 1000,
        customerId: form.value.customerId
    })
    groupData.value = res.result.records.map(item=>{
        return {
            label: item.title,
            value: item.id
        }
    })

}
const tableParams = reactive<tableTypes<InvoiceRecordQuery, InvoiceRecordVO>>({
    tableColumn: [
        {show: true, label: '关联订单', prop: 'orderId', sortable: true},
        {show: true, label: '开票日期', prop: 'invoicingDate', sortable: true},
        {show: true, label: '票据类型', prop: 'invoicingType', sortable: true},
        {show: true, label: '开票金额', prop: 'invoiceAmount', sortable: true},
        {show: true, label: '发票号码', prop: 'invoiceCode', sortable: true},
        {show: true, label: '票据内容', prop: 'invoiceContent', sortable: true},
        // {show: true, label: '订单所属人员', prop: 'ownerBy', sortable: true},
        {show: true, label: '发票经手人员', prop: 'handleUserId', sortable: true},
        {show: true, label: '客户名称', prop: 'customerName', sortable: true},
        {
            show: true,
            label: '操作',
            width: 200,
            prop: 'operation',
            disabledMove: true,
            render: ({column}: { column: InvoiceRecordVO }) => {
                return [
                    auth.hasPermi('finance:invoiceRecord:detail') ? h(ElButton, {
                        link: true, type: 'primary', onClick: () => {
                           detail(column)
                        }
                    }, '详情') : '',
                ]
            }
        },
    ],
    keyId: 'id',
    queryParams: {
        invoicingDate: undefined,
        invoiceAmount: undefined,
        customerId: undefined,
        orderId: undefined,
        invoicingType: undefined,
        currencyUnitId: undefined,
        invoiceCode: undefined,
        invoiceContent: undefined,
        handleUserId: undefined,
        isDelete: undefined,
        enabled: undefined,
        ownerBy: undefined,
        sort: undefined,
    },
    listFn: listInvoiceRecord,
    delFn: delInvoiceRecord,
})


const initFormData: InvoiceRecordForm = {
    id: undefined,
    invoicingDate: undefined,
    invoiceAmount: undefined,
    customerId: undefined,
    orderId: undefined,
    invoicingType: undefined,
    currencyUnitId: undefined,
    invoiceCode: undefined,
    invoiceContent: undefined,
    remark: undefined,
    handleUserId: undefined,
    isDelete: undefined,
    enabled: undefined,
    ownerBy: undefined,
    sort: undefined
}
const data = reactive<PageData<InvoiceRecordForm, InvoiceRecordQuery>>({
    form: {...initFormData},
    rules: {
        id: [
            {required: true, message: "主键不能为空", trigger: "blur"}
        ],
        invoicingDate: [
            {required: true, message: "签单日期不能为空", trigger: "blur"}
        ],
        invoiceAmount: [
            {required: true, message: "开票金额不能为空", trigger: "blur"}
        ],
        customerId: [
            {required: true, message: "客户id不能为空", trigger: "blur"}
        ],
        orderId: [
            {required: true, message: "关联订单id不能为空", trigger: "blur"}
        ],
        invoicingType: [
            {required: true, message: "票据类型不能为空", trigger: "change"}
        ],
        currencyUnitId: [
            {required: true, message: "关联币种单位id不能为空", trigger: "blur"}
        ],
        invoiceCode: [
            {required: true, message: "票据号码不能为空", trigger: "blur"}
        ],
        invoiceContent: [
            {required: true, message: "票据内容不能为空", trigger: "blur"}
        ],
        remark: [
            {required: true, message: "备注信息不能为空", trigger: "blur"}
        ],
        handleUserId: [
            {required: true, message: "发票经手人员不能为空", trigger: "blur"}
        ],
    }
});

const {form, rules} = toRefs(data);

const {queryParams} = toRefs(tableParams);
/** 取消按钮 */
const detailCancel = () => {
    detailDialog.visible = false;
}

/** 表单重置 */
const reset = () => {
    form.value = {...initFormData};
    invoiceRecordFormRef.value?.resetFields();
}

const invoiceRecordTable = ref()
/** 搜索按钮操作 */
const handleQuery = () => {
    invoiceRecordTable.value.getData()
}

/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: InvoiceRecordVO[]) => {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
    reset();
    dialog.visible = true;
    dialog.title = "添加发票";
}
/** 修改按钮操作 */
const detail = async (row?: InvoiceRecordVO) => {
    const _id = row?.id
    const res = await getInvoiceRecord(_id);
    Object.assign(form.value, res.result);
    detailDialog.visible = true;
    detailDialog.title = "发票详情";
}
/** 修改按钮操作 */
const handleUpdate = async (row?: InvoiceRecordVO) => {
    reset();
    const _id = row?.id || ids.value[0]
    const res = await getInvoiceRecord(_id);
    Object.assign(form.value, res.result);
    dialog.visible = true;
    dialog.title = "修改发票";
}
const getList = () => {
    invoiceRecordTable.value.getData()
}
/** 提交按钮 */
const submitForm = () => {
    invoiceRecordFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            buttonLoading.value = true;
            if (form.value.id) {
                await updateInvoiceRecord(form.value).finally(() => buttonLoading.value = false);
            } else {
                await addInvoiceRecord(form.value).finally(() => buttonLoading.value = false);
            }
            proxy?.$modal.msgSuccess("操作成功");
            dialog.visible = false;
            await getList();
        }
    });
}


onMounted(() => {
});
</script>
