<template>
    <div>
        <SearchBox ref="SearchBoxRef" formName="query" :formData="query" @PopupNo="PopupNo" @reset="reset">
        </SearchBox>

        <ButtonBar @search="handleSearch" @add="handleAdd" @effect="handleEffect" @invalid="handleInvalid">
        </ButtonBar>
        <el-card :body-style="cardBodyStyle">
            <el-table :data="tableData" border highlight-current-row @selection-change="handleSelectionChange"
                @row-click="DoubleClick">
                <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="cmpNm" label="公司名称" header-align="center" align="center"
                    show-overflow-tooltip>
                </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="status" label="状态" header-align="center" align="center"
                    show-overflow-tooltip>
                    <template #default="{ row }">
                        <el-tag v-if="row.status == 'A'">新增</el-tag>
                        <el-tag type="success" v-else-if="row.status == 'B'">生效</el-tag>
                        <el-tag type="info" v-else-if="row.status == 'C'">失效</el-tag>
                    </template>
                </el-table-column>
                <el-table-column v-if="true" prop="contTy" label="合同类型" header-align="center" align="center"
                    show-overflow-tooltip :formatter="formatter">
                </el-table-column>

                <el-table-column label="操作" header-align="center" align="center" fixed="right">
                    <template #default="{ row }">
                        <el-button plain type="warning" @click="handleEdit(row)" v-if="row.status != 'B'">编辑</el-button>
                        <el-button plain type="danger" @click="handleDelete(row)" v-if="row.status != 'B'">删除</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="400px"
            top="5vh" @open="openDialog">
            <el-form :model="form" label-width="80px" label-position="right" inline ref="ruleFormRef" :rules="rules">
                <el-form-item label="公司名称" prop="cmpNm">
                    <el-input v-model="form.cmpNm" clearable style="width: 200px" disabled></el-input>
                </el-form-item>
                <el-form-item label="模板名称" prop="tempNm">
                    <el-input v-model="form.tempNm" clearable style="width: 200px"></el-input>
                </el-form-item>
                <el-form-item label="合同类型" prop="contTy">
                    <el-select v-model="form.contTy" placeholder="请选择" clearable style="width: 200px">
                        <el-option v-for="item in dicList.CONTRACT_TYPE" :key="item.dicCode" :label="item.dicName"
                            :value="item.dicCode" />
                    </el-select>
                </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>

        <addLineVue :tmp=tmp></addLineVue>


    </div>
</template>

<script setup>
import ButtonBar from '@/components/ButtonBar.vue'
import addLineVue from '@/views/cot/settle/TmpLine.vue'
import {
    ref,
    reactive,
    onMounted,
    getCurrentInstance
} from 'vue'

const {
    proxy
} = getCurrentInstance()

import tools from '@/tools'
import Attachment from "@/components/Attachment.vue";
import SearchBox from "@/components/SearchBox.vue";
const cardBodyStyle = ref(tools.style.card)
const inputStyle = ref(tools.style.input)

onMounted(() => {
    getDictList()
    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({
    CONTRACT_TYPE: [],
})
const getDictList = () => {
    var url = 'framework/Common/querySelectorList'
    var param = {
        type: JSON.stringify(['CONTRACT_TYPE'])
    }
    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 'contTy':
            cellValue = dicList.value.CONTRACT_TYPE.find(item => item.dicCode == cellValue)?.dicName
            break
    }
    return cellValue
}


/**
 *   查询
 */
const query = ref({
    tempNm: '',
    contTy: '',
    cmpNm: '',
})
const tableData = ref([])
const handleSearch = () => {
    tmp.value = null
    currentPage.value = 1
    getTableData()
}

const getTableData = () => {
    var url = 'cot/Tmp/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 title = ref('')
const dialogVisible = ref(false)
const form = ref({
    tempNm: '',
    contTy: '',
    cmpNm: '',
    addId: '',
    addCode: '',
    addName: '',
    addDeptId: '',
    addDeptCode: '',
    addDeptName: '',
    addTime: '',
    modifyCode: '',
    modifyName: '',
})
const ruleFormRef = ref()
const rules = reactive({
    tempNm: [{
        required: true,
        message: '请输入模版名称',
        trigger: 'change' | 'blur'
    }],
    contTy: [{
        required: true,
        message: '请输入合同类型',
        trigger: 'change' | 'blur'
    }],
    cmpNm: [{
        required: true,
        message: '请输入公司名称',
        trigger: 'change' | 'blur'
    }],
})

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

    form.value = {
        tempNm: '',
        contTy: '',
        cmpNm: deptTree[0].deptName,
        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 handleEffect = () => {
    if (multipleSelection.value.length < 1) {
        ElMessage({
            type: 'warning',
            message: '请选择要生效的数据!'
        })
        return
    }

    updateStatus('B')
}
const handleInvalid = () => {
    if (multipleSelection.value.length < 1) {
        ElMessage({
            type: 'warning',
            message: '请选择要失效的数据!'
        })
        return
    }

    updateStatus('C')
}
const updateStatus = (status) => {
    var url = 'cot/Tmp/updateStatus'
    var param = {
        json: JSON.stringify(multipleSelection.value),
        status: status
    }
    proxy.$axios.post(url, param).then(response => {
        if (response.data.code == 0) {
            ElMessage({
                message: '保存成功',
                type: 'success',
            })
            getTableData()
        } else {
            ElMessage({
                message: '操作失败' + response.data.msg,
                type: 'error'
            })
        }
    })
}
/**
 * 新增
 */


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

const openDialog = () => {
}

const handleSave = (ruleFormRef) => {
    ruleFormRef.validate((valid, fields) => {
        if (valid) {
            var url = 'cot/Tmp/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.error('操作失败！' + response.data.msg)
                    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
    dialogVisible.value = true
}
const handleDelete = (row) => {
    ElMessageBox.confirm(
        '确定删除本条记录?',
        '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
    }
    )
        .then(() => {
            var url = 'cot/Tmp/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 multipleSelection = ref([])
const handleSelectionChange = (val) => {
    multipleSelection.value = val
    // tmp.value = val
}

const tmp = ref(null)
const DoubleClick = (row) => {
    tmp.value = row
}

const handleRemoveBatch = () => {
    console.log('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/Tmp/removeBatch'
        var param = {
            ids: JSON.stringify(ids)
        }
        proxy.$axios.post(url, param).then(response => {
            if (response.data.code == '0') {
                ElMessage({
                    type: 'success',
                    message: '操作成功!',
                });
                getTableData()
                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>
