<template>
    <!-- 添加或修改项目信息对话框 -->
    <div class="el-drawer__wrapper">
        <el-drawer :title="title" v-model="visible" direction="rtl" size="100%">
            <div class="page-container form-container">
                <div class="form-btns-container">
                    <span class="title-label"><el-icon>
                            <Document />
                        </el-icon> 发票信息</span>
                    <el-button-group>
                        <el-button v-show="editStatus" type="primary" size="small" icon="Finished"
                            @click="submitForm(0)" v-hasPermi="['business:invoice:save']">保存</el-button>

                        <el-button v-show="editStatus" v-hasPermi="['business:invoice:submit']"
                            style="margin-left: 10px;" type="primary" size="small" icon="Finished"
                            @click="submitForm(1)">提交</el-button>
                        <el-button v-show="form.id && editStatus" type="info" size="small" icon="Close"
                            style="margin-left: 10px;" @click="editStatus = false">取消编辑</el-button>
                        <div style="display: flex; gap: 10px;">
                            <el-button v-show="!editStatus && (form.status == 0|| form.status == 4)" type="warning"
                                size="small" icon="Edit" @click="editStatus = true"
                                v-hasPermi="['business:invoice:edit']">编辑</el-button>
                            <el-button v-show="!editStatus && (form.status == 0|| form.status == 4)"
                                v-hasPermi="['business:invoice:submit']" style="margin-left: 10px;" type="primary"
                                size="small" icon="Finished" @click="submitForm(1)">提交</el-button>
                        </div>

                        <div style="display: flex; gap: 10px;">
                            <el-button v-show="!editStatus && form.status == 1" type="danger" size="small" icon="Close"
                                @click="refuseStatus" v-hasPermi="['business:invoice:refuse']">拒绝</el-button>
                            <el-button v-show="!editStatus && form.status == 1" type="primary" size="small" icon="Check"
                                @click="passStatus" v-hasPermi="['business:invoice:pass']">通过</el-button>
                            <el-button v-show="!editStatus && form.status == 1" type="warning" size="small" icon="Back"
                                @click="returnStatus" v-hasPermi="['business:invoice:return']">退回</el-button>
                        </div>


                    </el-button-group>
                    <div class="screen-btn" @click="handleScreen">
                        <template v-if="!isFullscreen">
                            <i class="fa fa-window-maximize" aria-hidden="true" />
                            <!-- <span>全屏</span> -->
                        </template>
                        <template v-else>
                            <i class="fa fa-window-restore" aria-hidden="true" />
                            <!-- <span>还原</span> -->
                        </template>
                    </div>
                    <div class="close-btn" @click="cancel">
                        <i class="fa fa-times" aria-hidden="true" />
                        <!-- <span>关闭</span> -->
                    </div>
                </div>
                <div class="Y-scrollbar" style="position: absolute; top: 32px; bottom: 0; width: 100%; overflow: auto">
                </div>
                <el-form ref="invoiceRef" class="master-container" :model="form" :rules="rules" label-width="170px">
                    <el-row :gutter="30">
                        <el-col :span="12">
                            <el-form-item label="发票类型：" prop="invoiceType">
                                <el-select v-model="form.invoiceType" placeholder="请选择发票类型" size="small" clearable
                                    v-if="editStatus">
                                    <el-option label="增值税专用发票" :value="1"></el-option>
                                    <el-option label="增值税普通发票" :value="2"></el-option>
                                </el-select>
                                <span v-else style="width: 100%">
                                    {{ form.invoiceType == 1 ? '增值税专用发票' : '增值税普通发票' }}
                                </span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" v-if="form.refuseReason != null && form.refuseReason != '' && 
                        ( form.status == 4)">
                            <el-form-item label="退回原因：" prop="refuseReason">
                                <span>{{form.refuseReason}}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="30">
                        <el-col :span="6">
                            <el-form-item label="合同编号：" required>
                                <el-input v-if="editStatus" style="width: 100%" v-model.trim="form.contractNo"
                                    size="small" type="text" placeholder="请选择" :clearable="true">
                                    <template #append>
                                        <el-button icon="Search" @click="() => contractChoiceHandler()" />
                                    </template>
                                </el-input>
                                <span v-else style="width: 100%">
                                    <el-link :underline="false" type="primary" @click="handleContract(form)">{{
                                        form.contractNo }}</el-link>
                                </span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="可开票金额：">
                                {{allowAmount + "元" }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="申请开票金额： " prop="allowInvoiceAmount">
                                <el-input v-if="editStatus" v-model.number="form.allowInvoiceAmount"
                                    placeholder="申请开票金额" size="small">
                                    <template #append>元</template>
                                </el-input>
                                <span v-else>{{ form.allowInvoiceAmount + "元"}}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="开票内容：" prop="invoiceContent">
                                <el-select v-if="editStatus" v-model="form.invoiceContent" placeholder="开票内容"
                                    size="small">
                                    <el-option v-for="item in invoice_type" :key="item.value" :label="item.label"
                                        :value="item.id"></el-option>
                                </el-select>
                                <span v-else>{{ form.invoiceContent }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="开票方：" prop="invoiceMy">
                                <el-input v-if="editStatus" v-model="form.invoiceMy" placeholder="开票方" size="small" />
                                <span v-else>{{ form.invoiceMy }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="社会信用代码：" prop="myCreditSocietyCode">
                                <el-input v-if="editStatus" v-model="form.myCreditSocietyCode" placeholder="社会信用代码"
                                    size="small" />
                                <span v-else>{{ form.myCreditSocietyCode }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="开票方地址、电话：" prop="myAddress">
                                <el-input v-if="editStatus" v-model="form.myAddress" placeholder="开票方地址、电话"
                                    size="small" />
                                <span v-else>{{ form.myAddress }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="开票方开户行及账号：" prop="myAccount">
                                <el-input v-if="editStatus" v-model="form.myAccount" placeholder="开票方开户行及账号"
                                    size="small" />
                                <span v-else>{{ form.myAccount }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="收票方：" prop="invoiceOther">
                                <el-input v-if="editStatus" v-model="form.invoiceOther" placeholder="请输入收票方"
                                    size="small" />
                                <span v-else>{{ form.invoiceOther }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="社会信用代码：" prop="otherCreditSocietyCode">
                                <el-input v-if="editStatus" v-model="form.otherCreditSocietyCode" size="small"
                                    placeholder="社会信用代码" />
                                <span v-else>{{ form.otherCreditSocietyCode }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="收票方地址、电话：" prop="otherAddress">
                                <el-input v-if="editStatus" v-model="form.otherAddress" placeholder="收票方地址、电话"
                                    size="small" />
                                <span v-else>{{ form.otherAddress }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="收票方开户行及账号：" prop="otherAccount">
                                <el-input v-if="editStatus" v-model="form.otherAccount" placeholder="收票方开户行及账号"
                                    size="small" />
                                <span v-else>{{ form.otherAccount }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" v-if="!editStatus">
                            <el-form-item label="申请人：" prop="applierName">
                                <span>{{ form.applierName }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" v-if="!editStatus">
                            <el-form-item label="申请时间：" prop="applierTime">
                                <span>{{ form.applierTime }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" v-if="!editStatus">
                            <el-form-item label="状态：" prop="status">
                                <span v-if="form.status == 0">未提交</span>
                                <span v-if="form.status == 1">待开票</span>
                                <span v-if="form.status == 2">已拒绝</span>
                                <span v-if="form.status == 3">已开票</span>
                            </el-form-item>
                        </el-col>


                    </el-row>
                    <el-row :gutter="30">
                        <el-col :span="12">
                            <el-form-item label="备注：" prop="remark">
                                <el-input v-if="editStatus" v-model="form.remark" placeholder="请输入备注" size="small" />
                                <span v-else>{{ form.remark }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="30" v-show="form.status == 2">
                        <el-col :span="6">
                            <el-form-item label="拒绝原因：" prop="refuseReason">
                                <span>{{ form.refuseReason }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="30" v-show="form.status == 3">
                        <el-col :span="6">
                            <el-form-item label="开票人：" prop="inoviceName">
                                <span>{{ form.invoiceName }}</span>
                            </el-form-item>
                        </el-col>

                        <el-col :span="6">
                            <el-form-item label="开票时间：" prop="inoviceTime">
                                <span>{{ form.invoiceTime }}</span>
                            </el-form-item>
                        </el-col>

                        <el-col :span="6">
                            <el-form-item label="开票备注：" prop="invoiceRemark">
                                <span>{{ form.invoiceRemark }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-show="form.status == 3">
                        <el-form-item label="凭证文件：">
                            <img style="height: 148px; width: 148px" :src="`${baseUrl}/${form.evidenceFile}`"
                                class="avatar" @click="openEvidience('evidenceFile')" />
                        </el-form-item>

                    </el-row>
                </el-form>
            </div>
        </el-drawer>

        <el-dialog title="拒绝开票" v-model="refuseFlag" width="620px" append-to-body draggable
            :close-on-click-modal="false">
            <el-form ref="formRef" :model="form" :rules="refuseRules" label-width="100px">
                <el-row :gutter="30">
                    <el-col :span="12">
                        <el-form-item label="拒绝原因" prop="refuseReason">
                            <el-input :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" v-model="form.refuseReason"
                                placeholder="请输入拒绝原因" size="small" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button type="primary" @click="changeStauts1">确 定</el-button>
                <el-button @click="refuseFlag = false">取 消</el-button>
            </template>
        </el-dialog>

        <el-dialog title="退回开票" v-model="returnFlag" width="620px" append-to-body draggable
            :close-on-click-modal="false">
            <el-form ref="formRef" :model="form" :rules="returnRules" label-width="100px">
                <el-row :gutter="30">
                    <el-col :span="12">
                        <el-form-item label="退回原因" prop="refuseReason">
                            <el-input :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" v-model="form.refuseReason"
                                placeholder="请输入退回原因" size="small" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button type="primary" @click="changeStauts2">确 定</el-button>
                <el-button @click="returnFlag = false">取 消</el-button>
            </template>
        </el-dialog>

        <el-dialog title="开票审核通过" v-model="passFlag" width="70%" append-to-body draggable :close-on-click-modal="false">
            <el-form ref="formRef" :model="form" :rules="passRules" label-width="100px">
                <el-row :gutter="30">
                    <el-col :span="8">
                        <el-form-item label="收票方" prop="invoiceOther">
                            <span>{{ form.invoiceOther }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="6">
                        <el-form-item label="申请开票金额 " prop="allowInvoiceAmount">
                            <span>{{ form.allowInvoiceAmount }}</span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="开票人 " prop="allowInvoiceAmount">
                            <span>{{useUserStore().user.nickName }}</span>
                        </el-form-item>
                    </el-col>

                </el-row>
                <el-row :gutter="30">
                    <el-col :span="8">
                        <el-form-item label="开票时间 " prop="invoiceTime">
                            <el-date-picker v-model.trim="form.invoiceTime" size="small" :clearable="true"
                                style="width: 100%" format="YYYY-MM-DD" value-format="YYYY-MM-DD" align="center"
                                type="date" placeholder="开票时间" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="14">
                        <el-form-item label="社会信用代码" prop="otherCreditSocietyCode">
                            <span>{{ form.otherCreditSocietyCode }}</span>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-col :span="24">
                    <div class="details-btns-container">
                        <el-form-item label="凭证文件" prop="evidenceFile">
                            <dragUpload :accept="accept" style="width:50%" @file="upload"
                                v-if="form.evidenceFile == null || form.evidenceFile == ''" />
                            <img v-else style="height: 148px; width: 148px" :src="`${baseUrl}/${form.evidenceFile}`"
                                class="avatar" @click="openEvidience('evidenceFile')" />
                            <div v-if="!isView|| emptyForm.status !== 3">
                                <el-icon :size="20" v-if="form.evidenceFile !== '' ||form.evidenceFile == null "
                                    @click="form.evidenceFile = ''" class="delete-button">
                                    <Delete />
                                </el-icon>
                            </div>
                        </el-form-item>

                    </div>
                </el-col>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="开票备注" prop="invoiceRemark">
                            <el-input type="textarea" v-model="form.invoiceRemark" placeholder="开票备注"
                                :autosize="{ minRows: 2, maxRows: 4 }" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button type="primary" @click="changeStauts3">确 定</el-button>
                <el-button @click="passFlag = false">取 消</el-button>
            </template>
        </el-dialog>
        <dialog-contract-choice ref="contractChoiceRef" @choice="contractChoiceHandle" />
        <contract-form ref="contractRef" :get-list="getList" />
    </div>
</template>
<script setup>
    import { getInvoice, getCollectionToAmount, addInvoice, getInfoByName, updateInvoice } from "@/api/business/invoice";
    import { getInfoByTenantId } from "@/api/business/info";
    import DialogContractChoice from "./ContractChoice";
    import { getToken, getTenant } from "@/utils/auth";
    import contractForm from "@/views/business/crm/order/form.vue";
    import dragUpload from "@/components/dragUpload"
    import useUserStore from "@/store/modules/user";
    import { uploadFile } from "@/api/tool/file";
    const { proxy } = getCurrentInstance()
    const baseUrl = import.meta.env.VITE_APP_BASE_API;
    /** 父组件传参 */
    const props = defineProps({
        getList: {
            type: Function,
            default: () => { }
        }
    })
    const userStore = useUserStore();
    const { getList } = toRefs(props)
    /** 字典数组区 */
    const { invoice_type } = proxy.useDict("invoice_type");
    /** 表单抽屉 页变量 */
    const title = ref("")
    const loading = ref(false)
    const multiple = ref(true)
    const visible = ref(false)
    const refuseFlag = ref(false)
    const returnFlag = ref(false)
    const passFlag = ref(false)
    const editStatus = ref(false)
    const allowAmount = ref(0)
    const fileList = ref([]);
    const isFullscreen = ref(false)
    const webHost = import.meta.env.VITE_APP_BASE_API
    const data = reactive({
        form: {},
        rules: {
            invoiceMy: [{ required: true, trigger: "blur", message: "请输入开票方" }],
            myCreditSocietyCode: [{ required: true, max: 18, min: 18, message: "社会信用代码为18位", trigger: "blur" }],
            invoiceOther: [{ required: true, trigger: "blur", message: "请输入请输入收票方" }],
            otherCreditSocietyCode: [{ required: true, max: 18, min: 18, message: "社会信用代码为18位", trigger: "blur" }],
            allowInvoiceAmount: [
                { required: true, type: 'number', message: '请输入正确数据', trigger: 'blur' }
            ],
            invoiceContent: [
                { required: true, trigger: "change", message: "请选择开票内容" }
            ],
            invoiceType: [{ required: true, trigger: "change", message: "请选择发票类型" }],
        },
        returnRules: {
            refuseReason: [{ required: true, trigger: "blur", message: "请输入退回原因" }],
        },
        refuseRules: {
            refuseReason: [{ required: true, trigger: "blur", message: "请输入拒绝原因" }],
        },
        passRules: {
            evidenceFile: [{ required: true, trigger: "blur", message: "请上传图片" }],
            invoiceTime: [{ required: true, trigger: "change", message: "请选择开票时间" }],
        }
    });
    const { form, rules, returnRules, refuseRules, passRules } = toRefs(data);
    /***********************  方法区  ****************************/
    /** 打开抽屉 */
    function open(id) {
        reset();
        visible.value = true;
        if (id) {
            getInvoice(id).then(response => {
                form.value = response.data;
                editStatus.value = false
                title.value = "修改发票信息"
                //通过合同id 查询出已收款的合同
                getCollectionToAmount(form.value.contractId).then(res => {
                    allowAmount.value = res.data
                })
            })
        } else {
            editStatus.value = true
            title.value = "添加发票信息"
            getCodeInfo()
        }
    }
    function openEvidience() {

        window.open(`${baseUrl}${form.value.evidenceFile}`);
    }
    /** 取消按钮 */
    function cancel() {
        visible.value = false;
        reset();
    }

    /** 表单重置 */
    function reset() {
        form.value = {
            id: null,
            invoiceType: null,
            contractId: null,
            allowInvoiceAmount: null,
            invoiceContent: null,
            invoiceMy: null,
            myCreditSocietyCode: null,
            myAddress: null,
            myAccount: null,
            invoiceOther: null,
            otherCreditSocietyCode: null,
            otherAddress: null,
            applierId: null,
            applierTime: null,
            status: null,
            invoiceId: null,
            invoiceTime: null,
            remark: null,
            invoiceRemark: null,
            createTime: null,
            creatorId: null,
            updateTime: null,
            updaterId: null,
            deleted: null,
            version: null
        };
        proxy.resetForm("invoiceRef");
    }

    /** 全屏缩放 */
    function handleScreen() {
        const dom = document.querySelector('.list-container > .el-drawer__wrapper > .el-overlay')
        isFullscreen.value = !isFullscreen.value
        dom.style.position = isFullscreen.value ? 'fixed' : 'absolute'
    }
    function handleContract() {
        proxy.$refs.contractRef.open(form.value.contractId);
    }
    function getCodeInfo() {
        getInfoByTenantId().then(res => {
            if (res.data != null) {
                form.value.myCreditSocietyCode = res.data.code
                form.value.myAddress = res.data.address
                form.value.myAccount = res.data.account
                form.value.invoiceMy = res.data.name
            }
        })
    }
    function refuseStatus() {


        refuseFlag.value = true
    }

    function returnStatus() {

        returnFlag.value = true
    }

    function passStatus() {
        passFlag.value = true
    }
    function changeStauts1() {
        if (form.value.refuseReason === "" || form.value.refuseReason == null) {
            proxy.$modal.msgError("请填写拒绝原因");
            return;
        }
        form.value.status = 2
        updateInvoice(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            visible.value = false;
            refuseFlag.value = false
            getList.value()
        });
    }
    /** 文件上传 */
    function upload(param) {
        const formData = new FormData();
        formData.append("file", param);
        uploadFile(formData).then((res) => {
            if (res.code === 200) {
                const file = {};
                file.fileName = res.newFileName;
                file.url = res.fileName;
                file.originalFileName = res.originalFilename;
                file.fileUrl = res.fileName;
                fileList.value.push(file);
                form.value.evidenceFile = file.fileUrl;
                form.value.originalFileName = res.originalFilename;
                form.value.fileName = res.newFileName;
            }
        });
    }
    function changeStauts2() {
        if (form.value.refuseReason === "" || form.value.refuseReason == null) {
            proxy.$modal.msgError("请填写退回原因");
            return;
        }
        form.value.status = 4
        updateInvoice(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            visible.value = false;
            returnFlag.value = false
            getList.value()
        });
    }
    function changeStauts3() {
        console.log(form.value.refuseReason);

        if (form.value.invoiceTime === "" || form.value.invoiceTime == null) {
            proxy.$modal.msgError("请选择开票时间");
            return;
        }

        if (form.value.evidenceFile === "" || form.value.evidenceFile == null) {
            proxy.$modal.msgError("请上传图片");
            return;
        }
        form.value.status = 3
        updateInvoice(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            visible.value = false;
            passFlag.value = false
            getList.value()
        });
    }
    /** 提交按钮 */
    function submitForm(status) {
        if (form.value.contractNo === "" || form.value.contractNo == null) {
            proxy.$modal.msgError("请选择合同");
            return;
        }
        proxy.$refs["invoiceRef"].validate(valid => {
            if (valid) {
                if (form.value.status == 4 && status == 0) {
                    form.value.status = 4
                } else {
                    form.value.status = status
                }

                if (form.value.id != null) {
                    updateInvoice(form.value).then(response => {
                        proxy.$modal.msgSuccess("修改成功");
                        visible.value = false;
                        getList.value()
                    });
                } else {
                    addInvoice(form.value).then(response => {
                        proxy.$modal.msgSuccess("新增成功");
                        visible.value = false;
                        getList.value()
                    });
                }
            }
        });
    }
    function contractChoiceHandler() {

        proxy.$refs.contractChoiceRef.open();
    }
    function contractChoiceHandle(info) {
        form.value.contractId = info.id
        form.value.contractNo = info.contractNo
        form.value.invoiceOther = info.companyName
        getInfoByName(info.companyName).then(res => {
            if (res.data != null) {
                form.value.otherCreditSocietyCode = res.data.code
                form.value.otherAddress = res.data.address
                form.value.otherAccount = res.data.account
            }
        })
        //通过合同id 查询出已收款的合同
        getCollectionToAmount(info.id).then(res => {
            allowAmount.value = res.data
        })
    }
    /** 查询表单信息  */
    function getForm() {
        loading.value = true
        getInvoice(form.value.id).then(response => {
            loading.value = false
            form.value = response.data
        })
    }

    /** 暴露给父组件的方法 */
    defineExpose({
        open
    })
</script>