<template>
    <PageLayer>
        <template #header class="hd-cl">
            <el-button type="primary" icon="Plus" @click="onAddItem" style="margin-left: 5px">新增</el-button>
        </template>
        <template #mainMaxContentHeight>
            <el-table :data="ypPrintNameData" border style="width: 100%" :height="tableHeight" stripe highlight-current-row>
                <el-table-column type="index" label="序号" width="80" />
                <el-table-column prop="chargeCode" label="药品编码" width="100" />
                <el-table-column prop="printName" label="药品别名" width="300">
                    <template v-slot="scope">
                        <el-input v-if="scope.row.isEdit" size="small" v-model="scope.row.printName"></el-input>
                        <span v-else>{{ scope.row.printName }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="pyCode" label="拼音码" width="160" />
                <el-table-column prop="dcode" label="五笔码" width="160" />
                <el-table-column prop="ypFlag" label="类别" width="120">
                    <template #default="scope">
                        <div v-if="scope.row.isEdit">
                            <el-select v-model="scope.row.ypFlag" clearable placeholder="请选择类别">
                                <el-option v-for="option in ypFlagOptions" :key="option.code" :label="option.name"
                                    :value="option.code"></el-option>
                            </el-select>
                        </div>
                        <div v-else>
                            <el-select v-model="scope.row.ypFlag" disabled placeholder="请选择类别">
                                <el-option v-for="option in ypFlagOptions" :key="option.code" :label="option.name"
                                    :value="option.code"></el-option>
                            </el-select>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" min-width="180" width="180" center>
                    <template #default="scope">
                        <el-button type="primary" size="small" v-if="!scope.row.isEdit"
                            @click="editPrintName(scope.row)">编辑</el-button>
                        <el-button type="primary" size="small" v-if="scope.row.isEdit"
                            @click="updatePrintName(scope.row)">保存</el-button>
                        <el-button type="primary" size="small" v-if="scope.row.isEdit"
                            @click="cancelPrintName(scope.row)">取消
                        </el-button>
                        <el-button type="danger" size="small" @click.prevent="deletePrintName(scope.$index, scope.row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </template>
    </PageLayer>
</template>
<script setup name="YpPrintName">
import { ref, onMounted, nextTick } from 'vue'
import PageLayer from '@/layout/PageLayer.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { selectYpPrintNameData, savePrintName, delYpPrintNameByPrintName } from '@/api/yp-dict/yp-print-name.js'

const tableHeight = '500'
const ypFlagOptions = [{ code: 'T', name: '通用名' }, { code: '1', name: '商用名' }, { code: '2', name: '别名' }]
const ypPrintNameData = ref([])
const props = defineProps({
    ypPrintNameDetail: {
        type: Object,
        default: {}
    }
})


onMounted(async () => {
    await nextTick(() => {
        selectYpPrintNameList()

    })

})

const selectYpPrintNameList = () => {
    selectYpPrintNameData(props.ypPrintNameDetail.chargeCode)
        .then((res) => {
            res.forEach(row => {
                // 是否标记
                row['isEdit'] = false
                // 是否新增
                row['isAdd'] = false
            })
            ypPrintNameData.value = res
        })
        .catch(() => {
            ypPrintNameData.value = []
        })

}

// 新增
const onAddItem = () => {
    ypPrintNameData.value.push({
        chargeCode: '',
        printName: '',
        ypFlag: '',
        pyCode: '',
        dCode: '',
        isEdit: true,
        isAdd: true,
    })
}

// 编辑
const editPrintName = (row) => {
    // 备份原始数据
    row['oldRow'] = JSON.parse(JSON.stringify(row))
    row.isEdit = true
}
// 取消
const cancelPrintName = (row) => {
    // 如果是新增的数据
    if (row.isAdd) {
        ypPrintNameData.value.splice(ypPrintNameData.value.length - 1, 1)
    } else {
        // 不是新增的数据  还原数据
        for (const i in row.oldRow) {
            row[i] = row.oldRow[i]
        }
    }
}
// 保存
const updatePrintName = (row) => {
    if (!row.chargeCode || !row.printName) {
        ElMessage({
            type: "warning",
            message: "药品的编码或别名不存在，请检查!",
            duration: 2500,
            showClose: true,
        });
        return
    }

    if (row.isAdd) {
        let fe = 0
        for (let num in ypPrintNameData.value) {
            if (ypPrintNameData.value[num].printName === row.printName) {
                fe++
            }
        }
        if (fe == 2) {
            ElMessage({
                type: "warning",
                message: "存在重复的药品别名，请核对!",
                duration: 2500,
                showClose: true,
            });
            return
        } else {
            callSavePrintName(row, null)
        }

    } else {
        let oldName = row.oldRow.printName
        if (oldName !== row.printName) {
            let fe = 0
            for (let num in ypPrintNameData.value) {
                if (ypPrintNameData.value[num].printName === row.printName) {
                    fe++
                }
            }
            if (fe == 2) {
                ElMessage({
                    type: "warning",
                    message: row.printName + "存在重复的药品别名，请核对!",
                    duration: 2500,
                    showClose: true,
                });
                return
            } else {
                callSavePrintName(row, oldName)
            }
        } else {
            callSavePrintName(row, oldName)
        }
    }
}

const callSavePrintName = (row, oldName) => {
    let title = '请确认是否保存<span style="color:#d12020;">' + row.printName + '</span>?'
    ElMessageBox.confirm(title, {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning',
        distinguishCancelAndClose: true,
        dangerouslyUseHTMLString: true
    }).then(() => {
        savePrintName(row).then((res) => {
            ElMessage({
                type: "success",
                message: res.cg,
                duration: 2500,
                showClose: true,
            });
            if (oldName !== null && oldName !== row.printName) {
                // 删除原始数据
                delYpPrintNameByPrintName(row.chargeCode, oldName).then((res) => {
                    selectYpPrintNameList()
                })
                return
            } else {
                selectYpPrintNameList()
            }
        })
    }).catch((action) => {
        if (action === 'cancel') {
            selectYpPrintNameList()
        }
    })
}

const deletePrintName = (index, row) => {
    let title = '请确认是否删除<span style="color:#d12020;">' + row.printName + '</span>?'
    ElMessageBox.confirm(title, {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning',
        distinguishCancelAndClose: true,
        dangerouslyUseHTMLString: true
    }).then(() => {
        delYpPrintNameByPrintName(row.chargeCode, row.printName).then((res) => {
            ElMessage({
                type: "success",
                message: res.cg,
                duration: 2500,
                showClose: true,
            });
            selectYpPrintNameList()
            return
        })
    }).catch((action) => {
        if (action === 'cancel') {
            selectYpPrintNameList()
        }
    })
}
</script>