<template>
    <div>
        <el-card :body-style="cardBodyStyle">
            <el-form :inline="true">
                <el-form-item label="退款单号" style="margin-bottom: 5px;" prop="refundNo">
                    <el-input v-model="query.refundNo" placeholder="" clearable></el-input>
                </el-form-item>
                <el-form-item label="申请单号" style="margin-bottom: 5px;" prop="refundNo">
                    <el-input v-model="query.reqNo" placeholder="" clearable></el-input>
                </el-form-item>
                <el-form-item label="申请单行号" style="margin-bottom: 5px;" prop="refundNo">
                    <el-input v-model="query.reqLn" placeholder="" clearable></el-input>
                </el-form-item>
            </el-form>
        </el-card>

        <ButtonBar @search="handleSearch" @add="handleAdd"> </ButtonBar>

        <el-card :body-style="cardBodyStyle">
            <el-table :data="tableData" border highlight-current-row @selection-change="handleSelectionChange"
                height="63vh">
                <el-table-column type="selection" fixed></el-table-column>
                <el-table-column type="index" label="序号" align="center" width="60" fixed>
                    <template #default="scope">
                        <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
                    </template>
                </el-table-column>
                <el-table-column v-if="true" prop="refundNo" label="退款单号" width="250" header-align="center"
                    align="center" show-overflow-tooltip fixed>
                </el-table-column>
                <el-table-column v-if="true" prop="tradePartnerCode" label="供应商编码" width="150" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="tradePartnerName" label="供应商名称" width="250" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="reqNo" label="申请单号" width="200" header-align="center" align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="reqLn" label="申请单行号" width="100" header-align="center" align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="accountNo" label="结算单号" width="200" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="invoiceNo" label="发票编码" width="200" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="purContrCd" label="合同编号" width="150" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="payedAmount" label="已支付金额" width="120" header-align="center"
                    align="right" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="false" prop="actPayDate" label="实际支付日期" width="120" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="false" prop="reqTy" label="申请类型" min-width="100" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="false" prop="payMth" label="付款方式" width="120" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="refundAmount" label="退款金额" width="100" header-align="center"
                    align="right" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="refundDate" label="退款日期" width="120" header-align="center"
                    align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="refundSts" label="退款状态" width="100" header-align="center"
                    align="center" show-overflow-tooltip :formatter="formatter">
                </el-table-column>
                <el-table-column v-if="true" prop="workModel.flowStatusName" label="流程状态" width="120"
                    header-align="center" align="center" show-overflow-tooltip>
                    <template #default="{ row }">
                        <div>
                            <el-tag v-if="row.workId !== undefined && row.workModel.flowStatus === '110'">{{
                                row.workModel.flowStatusName }}</el-tag>
                            <el-tag type="success"
                                v-else-if="row.workId !== undefined && row.workModel.flowStatus === '170'">{{
                                    row.workModel.flowStatusName }}</el-tag>
                            <el-tag type="danger"
                                v-else-if="row.workId !== undefined && (row.workModel.flowStatus === '130' || row.workModel.flowStatus === '180' || row.workModel.flowStatus === '190')">{{
                                    row.workModel.flowStatusName }}</el-tag>
                            <el-tag type="warning" v-else>'---'</el-tag>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="操作" header-align="center" align="center" width="400px" fixed="right">
                    <template #default="{ row }">
                        <el-button plain type="warning" @click="handleEdit(row)"
                            v-if="row.workId === '' || row.workModel.opType === '1'">编辑
                        </el-button>
                        <el-button plain type="danger" @click="handleDelete(row)"
                            v-if="row.workId === '' || row.workModel.opType === '1'">删除
                        </el-button>
                        <el-button plain type="success" @click="handleSubmit(row)"
                            v-if="row.workId === '' || row.workModel.opType === '1'">发起
                        </el-button>
                        <el-button plain type="primary" @click="handleDetail(row)"
                            v-if="row.workId !== ''">详情</el-button>
                        <el-button plain type="info" @click="handleCancel(row)"
                            v-if="row.workId !== '' && row.workModel.opType !== '1' && row.workModel.flowStatus !== '170'">撤回</el-button>
                    </template>
                </el-table-column>

            </el-table>
        </el-card>


        <el-card :body-style="cardBodyStyle">
            <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="pageSizes" :total="totalRows"
                background="background" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                @current-change="handleCurrentChange">
            </el-pagination>
        </el-card>

        <el-dialog :close-on-click-modal="false" draggable :title="title" v-model="dialogVisible" width="800px"
            top="5vh" @open="openDialog">
            <el-form :model="form" label-width="110px" label-position="right" inline ref="ruleFormRef" :rules="rules">

                <el-form-item label="供应商编码" prop="tradePartnerCode">
                    <el-input v-model="form.tradePartnerCode" clearable style="width: 200px" disabled>
                    </el-input>
                </el-form-item>
                <el-form-item label="供应商名称" prop="tradePartnerName">
                    <el-input v-model="form.tradePartnerName" clearable style="width: 200px" disabled>
                    </el-input>
                </el-form-item>
                <el-form-item label="申请单号" prop="reqNo">
                    <el-input v-model="form.reqNo" clearable style="width: 200px" disabled>
                    </el-input>
                </el-form-item>
                <el-form-item label="申请单行号" prop="reqLn">
                    <el-input v-model="form.reqLn" clearable style="width: 200px" readonly>
                        <template #append>
                            <el-button :icon="Search" @click="handleSearchPayReqLine" />
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item label="结算单号" prop="accountNo">
                    <el-input v-model="form.accountNo" clearable style="width: 200px" disabled>
                    </el-input>
                </el-form-item>
                <el-form-item label="发票编号" prop="invoiceNo">
                    <el-input v-model="form.invoiceNo" clearable style="width: 200px" disabled>
                    </el-input>
                </el-form-item>
                <el-form-item label="合同编号" prop="purContrCd">
                    <el-input v-model="form.purContrCd" clearable style="width: 200px" disabled>
                    </el-input>
                </el-form-item>
                <el-form-item label="已付金额" prop="payedAmount">
                    <el-input v-model="form.payedAmount" clearable style="width: 200px" disabled></el-input>
                </el-form-item>
                <el-form-item label="退款金额" prop="refundAmount">
                    <el-input-number v-model="form.refundAmount" :precision="2" :step="0.1" :min="0.01"
                        controls-position="right" clearable style="width: 200px"></el-input-number>
                </el-form-item>
                <el-form-item label="退款日期" prop="refundDate">
                    <el-date-picker v-model="form.refundDate" type="date" style="width: 200px;"
                        value-format="YYYY-MM-DD" format="YYYY-MM-DD" :disabled-date="disabledDate"></el-date-picker>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button plain type="success" @click="handleCheck(ruleFormRef)"
                        :disabled="saveLineButton">保存</el-button>
                    <el-button plain type="danger" @click="handleCancelSave">取消</el-button>
                </div>
            </template>
        </el-dialog>

        <PopupPurPayReqLine ref="PopupRefPayReqLine" @receive-from-child="retuPayReqLine"></PopupPurPayReqLine>
    </div>
</template>

<script setup>
import ButtonBar from '@/components/ButtonBar.vue'
import PopupPurPayReqLine from '@/views/pur/components/PopupPurPayReqLine.vue'

import {
    ref,
    reactive,
    onMounted,
    getCurrentInstance
} from 'vue'
import { Search } from '@element-plus/icons-vue'

const {
    proxy
} = getCurrentInstance()

import tools from '@/tools'
import { workflowSubmit, workflowCancel } from "@/tools/workflow.js"
import { ElMessage, formEmits } from 'element-plus'
import { TRUE } from 'sass'
const cardBodyStyle = ref(tools.style.card)
const inputStyle = ref(tools.style.input)

onMounted(() => {
    getDicList()
    handleSearch()
})


/**
 * 查询公司代码
 */
const userId = window.localStorage.getItem('userId')
const userCode = window.localStorage.getItem('userCode')
const userName = window.localStorage.getItem('userDesc')
const dept = JSON.parse(window.localStorage.getItem('dept'))
const deptTree = JSON.parse(window.localStorage.getItem('deptTree'))
/**
 * 查询公司代码
 */


/**
 *  查询字典
 */
const dicList = ref({
    PUR_REFUND_STS: [],
})
const getDicList = () => {
    var url = 'framework/Common/querySelectorList'
    var param = {
        type: JSON.stringify(['PUR_REFUND_STS'])
    }
    proxy.$axios.get(url, param).then(response => {
        if (response.data.code == '0') {
            dicList.value = response.data.data
        } else {
            ElMessage.error('操作失败！' + response.data.msg)
        }
    })
}
const formatter = (row, column, cellValue, index) => {
    if (!cellValue || cellValue == null || cellValue == '') {
        return cellValue
    }
    switch (column.property) {
        case 'refundSts':
            cellValue = dicList.value.PUR_REFUND_STS.find(item => item.dicCode == cellValue)?.dicName
            break
    }

    return cellValue
}
/**
 *  查询字典
 */


/**
 *   查询
 */
const query = ref({
})
const tableData = ref([])
const handleSearch = () => {
    currentPage.value = 1
    getTableData()
}

const getTableData = () => {
    var url = 'pur/PayRefund/query'
    var param = {
        page: currentPage.value,
        rows: pageSize.value,
        params: JSON.stringify(query.value)
    }
    proxy.$axios.get(url, param).then(response => {
        if (response.data.code == '0') {
            tableData.value = response.data.data.records
            totalRows.value = response.data.data.total
        } else {
            ElMessage.error('操作失败！' + response.data.msg)
        }
    })
}
/**
 *   查询
 */

/**
 * 分页
 */
const currentPage = ref(1)
const totalRows = ref(0)
const pageSizes = ref([5, 10, 20, 30, 40])
const pageSize = ref(10)
const handleSizeChange = (val) => {
    pageSize.value = val
    getTableData()
}
const handleCurrentChange = (val) => {
    currentPage.value = val
    getTableData()
}
/**
 * 分页
 */


/**
 * 付款申请单明细
 */
const PopupRefPayReqLine = ref(null)
const handleSearchPayReqLine = () => {
    PopupRefPayReqLine.value.open()
}
const retuPayReqLine = (val) => {
    var url = 'pur/PayReqHead/queryByReqNo'
    var param = {
        reqNo: val.reqNo
    }
    proxy.$axios.get(url, param).then(response => {
        if (response.data.code == '0') {
            const payReqHead = response.data.data
            form.value.tradePartnerCode = payReqHead.tradePartnerCode
            form.value.tradePartnerName = payReqHead.tradePartnerName
            
            form.value.pId = val.id
            form.value.reqNo = val.reqNo
            form.value.reqLn = val.reqLn
            form.value.accountNo = val.accountNo
            form.value.invoiceNo = val.invoiceNo
            form.value.purContrCd = val.purContrCd
            form.value.payedAmount = val.payedAmount
            form.value.reqTy = val.reqTy
            form.value.payMth = val.payMth
        } else {
            ElMessage.error('操作失败！' + response.data.msg)
        }
    })
}

/**
 * 新增
 */
const title = ref('')
const dialogVisible = ref(false)
const form = ref({
    pId: '',
    reqNo: '',
    reqLn: '',
    accountNo: '',
    invoiceNo: '',
    purContrCd: '',
    payedAmount: '',
    reqTy: '',
    payMth: '',
    refundDate: '',
    addId: '',
    addCode: '',
    addName: '',
    addDeptId: '',
    addDeptCode: '',
    addDeptName: '',
    addTime: '',
    modifyId: '',
    modifyCode: '',
    modifyName: '',
    modifyTime: '',
    cancelId: '',
    cancelCode: '',
    cancelName: '',
})
const ruleFormRef = ref()
const rules = reactive({
    reqNo: [{
        required: true,
        message: '请输入申请单号',
        trigger: 'change' | 'blur'
    }],
    reqLn: [{
        required: true,
        message: '请输入申请单行号',
        trigger: 'change' | 'blur'
    }],
    purContrCd: [{
        required: true,
        message: '请输入采购合同',
        trigger: 'change' | 'blur'
    }],
    tradePartnerCode: [{
        required: true,
        message: '请输入供应商编码',
        trigger: 'change' | 'blur'
    }],
    tradePartnerName: [{
        required: true,
        message: '请输入供应商名称',
        trigger: 'change' | 'blur'
    }],
    payedAmount: [{
        required: true,
        message: '请输入已付金额',
        trigger: 'change' | 'blur'
    }],
    refundAmount: [{
        required: true,
        message: '请输入退款金额',
        trigger: 'change' | 'blur'
    }],
    refundDate: [{
        required: true,
        message: '请输入退款日期',
        trigger: 'change' | 'blur'
    }],
})

const handleAdd = () => {
    if (window.localStorage.getItem('deptTree') == JSON.stringify(new Array())) {
        ElMessage({
            type: 'warning',
            message: '请添加登录人所在公司'
        })
        return
    }

    if (ruleFormRef.value) {
        ruleFormRef.value.resetFields()
    }


    form.value = {
        pId: '',
        reqNo: '',
        reqLn: '',
        accountNo: '',
        invoiceNo: '',
        purContrCd: '',
        payedAmount: '',
        reqTy: '',
        payMth: '',
        addId: userId,
        addCode: userCode,
        addName: userName,
        addDeptId: dept[0].Id,
        addDeptCode: dept[0].deptCode,
        addDeptName: dept[0].deptName,
        addTime: '',
        modifyId: '',
        modifyCode: '',
        modifyName: '',
        modifyTime: '',
        cancelId: '',
        cancelCode: '',
        cancelName: '',
    }

    title.value = '新增'
    dialogVisible.value = true
}
/**
 * 新增
 */


/**
 * 保存、修改、删除
 */

const openDialog = () => {
}

const handleCheck = (ruleFormRefLine) => {
    ruleFormRefLine.validate((valid, fields) => {
        if (valid) {
            var url = 'pur/PayRefund/check'
            var param = {
                json: JSON.stringify(form.value),
            }
            proxy.$axios.post(url, param).then(response => {
                if (response.data.code == 0) {
                    handleSave()
                } else {
                    ElMessage({
                        message: '操作失败！' + response.data.msg,
                        type: 'error'
                    })
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })

}
const handleSave = () => {
    var url = 'pur/PayRefund/save'
    var param = {
        json: JSON.stringify(form.value),
    }
    proxy.$axios.post(url, param).then(response => {
        if (response.data.code == 0) {
            form.value = response.data.data
            ElMessage({
                message: '保存成功',
                type: 'success',
            })
            getTableData()
            dialogVisible.value = false
        } else {
            ElMessage({
                message: '操作失败' + response.data.msg,
                type: 'error'
            })
        }
    })
}
const handleCancelSave = () => {
    dialogVisible.value = false
}
const handleEdit = (row) => {
    if (ruleFormRef.value) {
        ruleFormRef.value.resetFields();
    }

    dialogVisible.value = true
    title.value = '编辑'
    form.value = { ...row }
    form.value.modifyCode = userCode
    form.value.modifyName = userName
    dialogVisible.value = true
}
const handleDelete = (row) => {
    ElMessageBox.confirm(
        '确定删除本条记录?',
        '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
    }).then(() => {
        var url = 'pur/PayRefund/remove'
        var param = {
            id: row.id
        }
        proxy.$axios.post(url, param).then(response => {
            if (response.data.code == 0) {
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
                getTableData()
            } else {
                ElMessage({
                    type: 'error',
                    message: '删除失败' + response.data.msg
                });
            }
        });
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消',
        })
    })
}

/**
 * 工作流相关
 */
const flowId = ref('purPayRefundFinance')
const handleSubmit = (row) => {
    ElMessageBox.confirm(
        '确定提交审批?',
        '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
    }).then(() => {
        let variables = {
            id: row.id,
            refundAmount: row.refundAmount
        }
        return workflowSubmit(
            flowId.value,
            '采购退款流程',
            '初始化提交',
            JSON.stringify(variables),
            row.workId,
            row.trackId)
    }).then((result) => {
        if (result.status === 'success') {
            var url = 'pur/PayRefund/saveProcessInfo'
            var process = {
                'id': row.id,
                'workId': result.workId,
                'trackId': result.trackId,
            }
            var param = {
                json: JSON.stringify(process),
            }
            proxy.$axios.post(url, param).then(response => {
                if (response.data.code === 0) {
                    form.value = response.data.data
                    ElMessage({
                        type: 'success',
                        message: '提交审批成功',
                    })
                    getTableData()
                }
            })
        }
        else {
            ElMessage({
                type: 'error',
                message: '提交审批失败' + result.msg
            });
        }
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消提交',
        })
    })
}

const handleCancel = (row) => {
    ElMessageBox.confirm(
        '确定撤回审批?',
        '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
    }).then(() => {
        return workflowCancel(row.workId, row.trackId);
    }).then((result) => {
        if (result.status === 'success') {
            ElMessage({
                type: 'success',
                message: '撤回审批成功',
            })
            getTableData()
        } else {
            ElMessage({
                type: 'error',
                message: '撤回审批失败' + result.msg
            })
        }
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消撤回',
        })
    })
}

const handleDetail = (row) => {
    if (row.workId === null) {
        ElMessage({
            type: 'info',
            message: '无法查看',
        })
    } else {
        sessionStorage.setItem('workflowQuery', JSON.stringify({
            flowId: flowId.value,
            workId: row.workId,
            trackId: row.trackId,
            date: new Date().getTime()
        }))

        proxy.$router.push({
            path: '/workflow/detail',
        })
    }
}

</script>

<style></style>