<template>
    <div>
        <el-card :body-style="cardBodyStyle">
            <el-button plain type="primary" @click="handleAdd" :disabled="readonly">新增</el-button>
        </el-card>
        <el-card :body-style="cardBodyStyle">
            <el-table :data="tableData" border highlight-current-row @selection-change="handleSelectionChange">
                <el-table-column type="selection" fixed></el-table-column>
                <el-table-column type="index" label="序号" align="center" width="60">
                    <template #default="scope">
                        <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
                    </template>
                </el-table-column>
                <el-table-column v-if="true" prop="tempNm" label="模板名称" header-align="center" align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="settleItem" label="结算项目" header-align="center" align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="settleNo" label="结算项目编码" header-align="center" align="center"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="settleValueTo" label="结算项目上限" header-align="center" align="right"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="settleValueFrom" label="结算项目下限" header-align="center" align="right"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="referenceValue" label="基准值" min-width="100" header-align="center"
                    align="right" show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="settleSpan" label="结算项跨度" header-align="center" align="right"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column v-if="true" prop="settleDiffer" label="结算差额" header-align="center" align="right"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column label="操作" header-align="center" align="center" width="250px" fixed="right">
                    <template #default="{ row }">
                        <el-button plain type="primary" @click="handleDetail(row)" v-if="readonly">查看</el-button>
                        <el-button plain type="warning" @click="handleEdit(row)" v-if="!readonly">编辑</el-button>
                        <el-button plain type="danger" @click="handleDelete(row)" v-if="!readonly">删除</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="1200px"
            top="5vh" @open="openDialog">
            <el-form :model="form" label-width="120px" label-position="right" inline ref="ruleFormRef" :rules="rules">
                <el-form-item label="模板名称" prop="tempNm">
                    <el-input v-model="form.tempNm" clearable style="width: 200px" disabled></el-input>
                </el-form-item>
                <el-form-item label="结算项目" prop="settleItem">
                    <el-select v-model="form.settleItem" placeholder="请选择" clearable style="width: 200px"
						@change="typeChange2" :disabled="readonly">
						<el-option v-for="item in dicList.SETTLE_ITEM" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
                </el-form-item>
                <el-form-item label="结算项目编码" prop="settleNo">
                    <el-input v-model="form.settleNo" clearable style="width: 200px" disabled></el-input>
                </el-form-item>
                <el-form-item label="结算项目上限" prop="settleValueTo">
                    <el-input-number v-model="form.settleValueTo" :precision="2" :step="0.1" :min="0" :max="100"
                        controls-position="right" clearable style="width: 200px"
                        @input="validateSettleValueTo" :readonly="readonly"></el-input-number>
                </el-form-item>
                <el-form-item label="结算项目下限" prop="settleValueFrom">
                    <el-input-number v-model="form.settleValueFrom" :precision="2" :step="0.1" :min="0" :max="100"
                        controls-position="right" clearable style="width: 200px"
                        @input="validateSettleValueFrom" :readonly="readonly"></el-input-number>
                </el-form-item>
                <el-form-item label="基准值" prop="referenceValue">
                    <el-input-number v-model="form.referenceValue" :precision="2" :step="0.1" controls-position="right"
                        clearable style="width: 200px" :readonly="readonly" :disabled="form.rejectFlag === 'Y'"></el-input-number>
                </el-form-item>
                <el-form-item label="结算项目跨度" prop="settleSpan">
                    <el-input-number v-model="form.settleSpan" :precision="2" :step="0.1" controls-position="right"
                        clearable style="width: 200px" :readonly="readonly" :disabled="form.rejectFlag === 'Y'"></el-input-number>
                </el-form-item>
                <el-form-item label="结算差额" prop="settleDiffer">
                    <el-input-number v-model="form.settleDiffer" :precision="2" :step="0.1" controls-position="right"
                        clearable style="width: 200px" :readonly="readonly" :disabled="form.rejectFlag === 'Y'"></el-input-number>
                </el-form-item>
                <el-form-item label="是否扣重">
					<el-checkbox v-model="weightDeducted" @change="updateWeightDeducted" :disabled="readonly || weightDeductedButton"/>
				</el-form-item>
                <el-form-item label="拒收或退货">
                    <el-checkbox v-model="rejectFlag" @change="updateRejectFlag" :disabled="readonly"/>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="success" @click="handleSave(ruleFormRef)">保存</el-button>
                    <el-button type="danger" @click="handleCancelSave">取消</el-button>
                </div>
            </template>
        </el-dialog>


    </div>
</template>

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


import {
    ref,
    reactive,
    onMounted,
    getCurrentInstance,
    watch
} from 'vue'

const {
    proxy
} = getCurrentInstance()

import tools from '@/tools'
import Selector from "@/components/Selector.vue";
import { ElMessage } from 'element-plus';
const cardBodyStyle = ref(tools.style.card)
const inputStyle = ref(tools.style.input)

onMounted(() => {
    getDictList()
    //handleSearch()
})

const props = defineProps({
    tmp: {
        type: Object,
        required: true,
    }
})
const readonly = ref(false)
watch(() => props.tmp, (newVal, oldVal) => {
    query.value.tempId = newVal ? newVal.id : ""
    readonly.value = newVal && newVal.status === 'B'

    if (query.value.tempId != '') {
        handleSearch()
        getConTmpLine()
    } else {
        tableData.value = []
    }

    
})

/**
 * 查询公司代码
 */
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({
    SETTLE_ITEM: []
})
const getDictList = () => {
    var url = 'framework/Common/querySelectorList'
    var param = {
        type: JSON.stringify(['SETTLE_ITEM'])
    }
    proxy.$axios.get(url, param).then(response => {
        if (response.data.code == '0') {
            dicList.value = response.data.data
        } else {
            ElMessage.error('操作失败！' + response.data.msg)
        }
    })
}


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

const getTableData = () => {
    var url = 'cot/ConTmpLine/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(5)
const handleSizeChange = (val) => {
    pageSize.value = val
    getTableData()
}
const handleCurrentChange = (val) => {
    currentPage.value = val
    getTableData()
}
/**
 * 分页
 */


// 校验
const conTmpLineData = ref([])
const getConTmpLine = () => {
    var url = 'cot/ConTmpLine/queryByTempId'
    var param = {
        tempId: query.value.tempId
    }
    proxy.$axios.get(url, param).then(response => {
        if (response.data.code == '0') {
            conTmpLineData.value = response.data.data
        } else {
            ElMessage.error('操作失败！' + response.data.msg)
        }
    })
}
const typeChange2 = (val) => {
    form.value.settleNo = val
    validateSettleValue(form.value.settleValueTo, form.value.settleValueFrom, form.value.settleNo)

    if(form.value.settleNo === '110') {
		weightDeductedButton.value = false
		weightDeducted.value = true
	} else {
		weightDeductedButton.value = true
		weightDeducted.value = false
	}

    dicList.value.SETTLE_ITEM.forEach(item => {
        if (item.dicCode == val) {
            form.value.settleItem = item.dicName
            return
        }
    })
}
const validateSettleValueTo = (val) => {
    form.value.settleValueTo = val
    validateSettleValue(form.value.settleValueTo, form.value.settleValueFrom, form.value.settleNo)
}
const validateSettleValueFrom = (val) => {
    form.value.settleValueFrom = val
    validateSettleValue(form.value.settleValueTo, form.value.settleValueFrom, form.value.settleNo)
}

const validateSettleValue = (settleValueTo, settleValueFrom, settleNo) => {
    if (rules.settleValueTo.length == 2) {
        rules.settleValueTo.pop()
    }
    if (rules.settleValueFrom.length == 2) {
        rules.settleValueFrom.pop()
    }

    if (settleValueTo != null && settleValueFrom != null && settleValueTo <= settleValueFrom) {
        rules.settleValueTo[1] = { message: '结算项目上限大于结算项目下限', trigger: 'blur' }
        ruleFormRef.value.validateField('settleValueTo', (valid) => { })

        rules.settleValueFrom[1] = { message: '结算项目上限大于结算项目下限', trigger: 'blur' }
        ruleFormRef.value.validateField('settleValueFrom', (valid) => { })
        return
    }

    conTmpLineData.value
        .filter(item => item.id != form.value.id && item.tempCd === form.value.tempCd && item.settleNo === settleNo)
        .forEach(item => {
            if (!(settleValueTo <= item.settleValueFrom || item.settleValueTo <= settleValueFrom)) {
                rules.settleValueTo[1] = { message: '结算项目上下限不能交叉', trigger: 'blur' }
                ruleFormRef.value.validateField('settleValueTo', (valid) => { })

                rules.settleValueFrom[1] = { message: '结算项目上下限不能交叉', trigger: 'blur' }
                ruleFormRef.value.validateField('settleValueFrom', (valid) => { })
                return
            }
        })
}

const rejectFlag = ref(false)
const updateRejectFlag = (val) => {
	if(val) {
		form.value.rejectFlag = 'Y'
		form.value.referenceValue = 0
		form.value.settleSpan = 0
		form.value.settleDiffer = 0
	} else {
		form.value.rejectFlag = 'N'
		form.value.referenceValue = null
		form.value.settleSpan = null
		form.value.settleDiffer = null
	}
}

const weightDeductedButton = ref(true)
const weightDeducted = ref(false)
const updateWeightDeducted = (val) => {
	if(val) {
		form.value.weightDeducted = '10'
	} else {
		form.value.weightDeducted = '20'
	}
}

/**
 * 新增
 */
const title = ref('')
const dialogVisible = ref(false)
const form = ref({
    tempId: '',
    tempNm: '',
    settleLine: '',
    settleNo: '',
    settleItem: '',
    settleValueTo: null,
    settleValueFrom: null,
    settleSpan: null,
    settleDiffer: null,
    referenceValue: null,
    rejectFlag: '',
    addId: '',
    addCode: '',
    addName: '',
    addDeptId: '',
    addDeptCode: '',
    addDeptName: '',
    addTime: '',
    modifyCode: '',
    modifyName: '',
})
const ruleFormRef = ref()
const rules = reactive({
    tempNm: [{
        required: true,
        message: '模版名称必须录入',
    }],
    settleNo: [{
        required: true,
        message: '结算项目编码必须录入',
    }],
    settleItem: [{
        required: true,
        message: '结算项目必须录入',
    }],
    settleValueTo: [{
        required: true,
        message: '结算项目上限必须录入',
    }],
    settleValueFrom: [{
        required: true,
        message: '结算项目下限必须录入',
    }],
    referenceValue: [{
        required: true,
        message: '基准值必须录入',
    }],
    settleSpan: [{
        required: true,
        message: '结算项目跨度必须录入',
    }],
    settleDiffer: [{
        required: true,
        message: '结算项目差额必须录入',
    }],
})

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


    if (props.tmp === null || props.tmp.length > 1) {
        ElMessage.warning('请选择一条模版头添加！')
        return
    }

    const tmp = props.tmp.length ? props.tmp[0] : props.tmp;
    form.value = {
        tempId: tmp.id,
        tempNm: tmp.tempNm,
        settleLine: '',
        settleNo: '',
        settleItem: '',
        settleValueTo: null,
        settleValueFrom: null,
        settleSpan: null,
        settleDiffer: null,
        referenceValue: null,
        rejectFlag: '',
        addId: userId,
        addCode: userCode,
        addName: userName,
        addDeptId: dept[0].id,
        addDeptCode: dept[0].deptCode,
        addDeptName: dept[0].deptName,
        addTime: '',
        modifyCode: '',
        modifyName: '',
    }

    if (ruleFormRef.value) {
        ruleFormRef.value.resetFields()
    }
    title.value = '新增'
    dialogVisible.value = true
}
/**
 * 新增
 */


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

const openDialog = () => {
}

const handleSave = (ruleFormRef) => {
    ruleFormRef.validate((valid, fields) => {
        if (valid) {
            var url = 'cot/ConTmpLine/save'
            var param = {
                json: JSON.stringify(form.value),
            }
            console.log(form.value.settleItem)
            proxy.$axios.post(url, param).then(response => {
                if (response.data.code == 0) {
                    ElMessage({
                        message: '保存成功',
                        type: 'success',
                    })
                    form.value = response.data.data
                    getTableData()
                    getConTmpLine()
                    dialogVisible.value = false
                } else {
                    ElMessage({
                        message: '操作失败' + response.data.msg,
                        type: 'error'
                    })
                }
            })

        } else {
            console.log('error submit!', fields)
        }
    })
}
const handleCancelSave = () => {
    dialogVisible.value = false
}
const handleEdit = (row) => {
    if (ruleFormRef.value) {
        ruleFormRef.value.resetFields();
    }

    title.value = '编辑'
    form.value = { ...row }
    form.value.modifyCode = userCode
    form.value.modifyName = userName
    if(form.value.settleNo == '110') {
		weightDeductedButton.value = false
		weightDeducted.value = form.value.weightDeducted === '10'
	} else {
        weightDeductedButton.value = true
		weightDeducted.value = null
    }
    rejectFlag.value = form.value.rejectFlag === 'Y'
    dialogVisible.value = true
}
const handleDetail = (row) => {
    if (ruleFormRef.value) {
        ruleFormRef.value.resetFields();
    }

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

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

const multipleSelection = ref([])
const handleSelectionChange = (val) => {
    multipleSelection.value = val
}

const handleRemoveBatch = () => {
    if (multipleSelection.value.length < 1) {
        ElMessage({
            type: 'warning',
            message: '请选择要删除的数据!'
        })
        return
    }

    ElMessageBox.confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        var ids = []
        multipleSelection.value.forEach((item, index) => {
            ids.push(item.id)
        })
        var url = 'cot/ConTmpLine/removeBatch'
        var param = {
            ids: JSON.stringify(ids)
        }
        proxy.$axios.post(url, param).then(response => {
            if (response.data.code == '0') {
                ElMessage({
                    type: 'success',
                    message: '操作成功!',
                });
                getTableData()
                getConTmpLine()
                dialogVisible.value = false
            } else {
                ElMessage({
                    type: 'error',
                    message: '操作失败!' + response.data.msg
                });
            }
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消删除'
        })
    })
}

const handleEditBatch = () => {
    console.log('handleEditBatch')
    if (multipleSelection.value.length != 1) {
        ElMessage({
            type: 'warning',
            message: '请选择一条数据编辑!'
        })
        return
    }
    handleEdit(multipleSelection.value[0])
}

const handleUpload = () => {
    console.log('handleUpload')
}

const handleDownload = () => {
    console.log('handleDownload')
}

const handleImport = () => {
    console.log('handleImport')
}

const handleExport = () => {
    console.log('handleExport')
}

</script>

<style></style>