<template>
    <div class="hc-page-layout-box">
        <div :style="`width:${leftWidth}px;`" class="hc-layout-left-box menu">
            <div class="hc-menu-header-box">
                <div class="text-xl name">设备分类 - 检修记录</div>
            </div>
            <div class="hc-menu-contents-box">
                <el-scrollbar>
                    <HcMenuSimple :datas="menus" :keys="menuKey" :props="menusProps" @change="menuChange" />
                </el-scrollbar>
            </div>
            <!-- 左右拖动 -->
            <div class="horizontal-drag-line" @mousedown="onmousedown" />
        </div>
        <div class="hc-page-content-box">
            <HcNewCard>
                <template #header>
                    <HcTooltip keys="tentative_device_overhaul_add">
                        <el-button hc-btn type="primary" @click="addFormModalClick">
                            <HcIcon name="add-circle" />
                            <span>新增</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="tentative_device_overhaul_edit">
                        <el-button :disabled="tableCheckedKeys.length <= 0" hc-btn type="primary" color="#12C060" style="color: white;" @click="editFormModalClick">
                            <HcIcon name="edit" />
                            <span>编辑</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="tentative_device_overhaul_del">
                        <el-button v-del-com:[delNodeModalClick] :disabled="tableCheckedKeys.length <= 0" hc-btn color="#e03997">
                            <HcIcon name="delete-bin-2" />
                            <span>删除</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="tentative_device_overhaul_printer">
                        <el-button
                            :disabled="tableCheckedKeys.length <= 0" :loading="printerLoading" hc-btn color="#567722"
                            @click="printerClick"
                        >
                            <HcIcon name="printer" />
                            <span>打印</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="tentative_device_overhaul_import">
                        <el-button hc-btn color="#A16222" @click="importModalClick">
                            <HcIcon name="folder-upload" />
                            <span>导入</span>
                        </el-button>
                    </HcTooltip>
                </template>
                <template #search>
                    <div class="w-64">
                        <HcDatePicker :dates="betweenTime" clearable @change="betweenTimeUpdate" />
                    </div>
                    <div class="w-72 ml-2">
                        <el-input
                            v-model="searchForm.queryValue" clearable placeholder="请输入设备名称\设备型号查询"
                            @keyup="keyUpEvent"
                        />
                    </div>
                    <div class="ml-2">
                        <el-button type="primary" @click="searchClick">
                            <HcIcon name="search-2" />
                            <span>搜索</span>
                        </el-button>
                    </div>
                </template>
                <HcTable
                    ref="tableRef" :column="tableColumn" :datas="tableData" :loading="tableLoading"
                    is-new :index-style="{ width: 60 }" is-check :check-style="{ width: 29 }"
                    @selection-change="tableSelection"
                />
                <template #action>
                    <HcPages :pages="searchForm" @change="pageChange" />
                </template>
            </HcNewCard>
        </div>

        <!-- 新增/编辑 -->
        <hc-new-dialog
            v-model="addEditFormModal" :loading="addEditFormLoading" title="新增/编辑 设备检修信息" widths="50rem"
            @close="addEditFormModalClose" @save="addEditFormClick"
        >
            <el-form
                ref="addEditFormRef" :model="addEditFormModel" :rules="addEditFormRules" label-width="auto"
                size="large"
            >
                <div class="hc-form-item">
                    <el-form-item label="设备分类">
                        <el-select
                            v-model="addEditFormModel.deviceClassId" :disabled="deviceFormLoading" block
                            @change="deviceClassIdChange"
                        >
                            <el-option v-for="item in typeData" :label="item.className" :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="维修/检定日期">
                        <el-date-picker
                            v-model="addEditFormModel.overhaulDate" :clearable="false" class="block"
                            type="date" value-format="YYYY-MM-DD"
                        />
                    </el-form-item>
                </div>
                <div class="hc-form-item">
                    <el-form-item label="设备编号">
                        <el-select
                            v-model="addEditFormModel.deviceNumber" :disabled="deviceFormLoading" block
                            @change="deviceNumberChange"
                        >
                            <el-option
                                v-for="item in deviceFormSelectData" :label="item.deviceNumber"
                                :value="item.deviceNumber"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="维修/检定人">
                        <hcAutoComplete
                            v-model="addEditFormModel.managerName" :datas="userListData" keys="userName"
                            placeholder="请选择或输入维修/检定人"
                        />
                    </el-form-item>
                </div>
                <div class="hc-form-item">
                    <el-form-item label="设备名称">
                        <el-select
                            v-model="addEditFormModel.deviceName" :disabled="deviceFormLoading" block
                            @change="deviceNameChange"
                        >
                            <el-option
                                v-for="item in deviceFormSelectData" :label="item.deviceName"
                                :value="item.deviceName"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item />
                </div>
                <el-form-item label="维修/检定内容">
                    <el-input v-model="addEditFormModel.overhaulText" :autosize="{ minRows: 3 }" type="textarea" />
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="addEditFormModel.remarks" :autosize="{ minRows: 3 }" type="textarea" />
                </el-form-item>
            </el-form>
        </hc-new-dialog>

        <!-- 导入 -->
        <hc-new-dialog
            v-model="importModal" :loading="importModalLoading" is-table title="导入设备检修数据"
            widths="70rem" @close="importModalClose" @save="importModalYesClick"
        >
            <div class="text-orange mb-6">
                <span>请先下载模板模板表格 (</span>
                <span class="text-link" @click="downloadImportClick">范例试验设备文件</span>
                <span>) ,按模板样式编辑试验容器后，在点击“选择文件”按钮选择编辑好的文件，点击确认即可导入成功！</span>
            </div>
            <HcDragUpload action="overhaul/read-excel" @finished="uploadFinished" @progress="uploadprogress" />
            <div class="hc-import-modal-table-box">
                <HcTable
                    ref="tableImportRef" :column="tableColumn" :datas="tableImportData" :loading="tableImportLoading"
                    is-new :index-style="{ width: 60 }" is-check :check-style="{ width: 29 }"
                    @selection-change="tableImportSelection"
                />
            </div>
        </hc-new-dialog>
    </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { useAppStore } from '~src/store'
import HcDragUpload from './components/HcDragUpload.vue'
import { deviceClassListInit, getClassList, queryDeviceList, querySampleList } from '~api/tentative'
import { getContractUserList } from '~api/other'
import { arrToId, formValidate, getArrValue } from 'js-fast-way'
import dataApi from '~api/tentative/device/overhaul'
import { getRowsValue } from '~uti/tools'
import { HcDelMsg } from 'hc-vue3-ui'
import { toPdfPage } from '~uti/btn-auth'


//初始变量
const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId)
const contractId = ref(useAppState.getContractId)
const isCollapse = ref(useAppState.getCollapse)

//监听
watch(() => [
    useAppState.getCollapse,
], ([Collapse]) => {
    isCollapse.value = Collapse
})

//渲染完成
onMounted(() => {
    deviceClassListInitdata()
    getClassListData()
    getTableData()
    getUserListData()
})

//获取用户列表
const userListData = ref([])
const getUserListData = async () => {
    const { data } = await getContractUserList({
        contractId: contractId.value,
    })
    userListData.value = getArrValue(data)
}

//左侧菜单
const menuKey = ref('0')
const menuItem = ref({})
const menusProps = ref({
    key: 'id',
    label: 'className',
})
//获取菜单数据
const menus = ref([])
const typeData = ref([])
const getClassListData = async () => {
    const { data } = await getClassList({
        contractId: contractId.value,
    })
    const arr = getArrValue(data)
    typeData.value = arr
    menus.value = [{ id: '0', className: '全部', isNoContextMenu: true }, ...arr]
}
//初始化设备分类
const deviceClassListInitdata = async () => {
    const { data } = await deviceClassListInit({
        contractId: contractId.value,
    })
}
//菜单被点击
const menuChange = (item) => {
    menuItem.value = item
    menuKey.value = item?.id
    searchForm.value.deviceClassId = item?.id
    searchForm.value.current = 1
    getTableData()
}

//搜索表单
const searchForm = ref({
    deviceClassId: '', startTime: null, endTime: null, queryValue: null,
    current: 1, size: 20, total: 0,
})


//日期时间被选择
const betweenTime = ref(null)
const betweenTimeUpdate = ({ arr }) => {
    betweenTime.value = arr
    if (arr.length > 0) {
        searchForm.value.startTime = arr[0]
        searchForm.value.endTime = arr[1]
    } else {
        searchForm.value.startTime = ''
        searchForm.value.endTime = ''
    }
}

//回车搜索
const keyUpEvent = (e) => {
    if (e.key === 'Enter') {
        searchForm.value.current = 1
        getTableData()
    }
}

//搜索
const searchClick = () => {
    searchForm.value.current = 1
    getTableData()
}

//分页被点击
const pageChange = ({ current, size }) => {
    searchForm.value.current = current
    searchForm.value.size = size
    getTableData()
}

//表格数据
const tableRef = ref(null)
const tableColumn = ref([
    { key: 'deviceName', name: '设备名称' },
    { key: 'deviceClassName', name: '设备分类' },
    { key: 'deviceNumber', name: '设备编号' },
    { key: 'deviceModel', name: '设备型号' },
    { key: 'factoryNumber', name: '出厂编号' },
    { key: 'overhaulDate', name: '维修/检定日期' },
    { key: 'overhaulText', name: '维修/检定内容' },
    { key: 'managerName', name: '维修/检定人' },
    { key: 'remarks', name: '备注' },
])
const tableLoading = ref(false)

//获取数据
const tableData = ref([])
const getTableData = async () => {
    tableLoading.value = true
    const { error, code, data } = await dataApi.queryPage({
        projectId: projectId.value,
        contractId: contractId.value,
        ...searchForm.value,
    })
    //处理数据
    tableLoading.value = false
    if (!error && code === 200) {
        tableData.value = getArrValue(data['records'])
        searchForm.value.total = data.total || 0
    } else {
        tableData.value = []
        searchForm.value.total = 0
    }
}

//多选
const tableCheckedKeys = ref([])
const tableSelection = (rows) => {
    tableCheckedKeys.value = rows
}

//删除
const delNodeModalClick = async (_, resolve) => {
    await tableRemoveData()
    resolve()
}

//批量删除
const tableRemoveData = async () => {
    const rows = tableCheckedKeys.value
    if (rows.length > 0) {
        const ids = arrToId(rows)
        //删除请求
        const { error, code } = await dataApi.removeData({
            contractId: contractId.value,
            ids: ids,
        })
        //处理数据
        if (!error && code === 200) {
            window?.$message?.success('操作成功')
            searchClick()
        }
    }
}

//打印
const printerLoading = ref(false)
const printerClick = async () => {
    const rows = tableCheckedKeys.value
    if (rows.length > 0) {
        printerLoading.value = true
        const ids = arrToId(rows)
        //删除请求
        const { error, code, data } = await dataApi.exportPdf({
            projectId: projectId.value,
            contractId: contractId.value,
            ids: ids,
        })
        //处理数据
        printerLoading.value = false
        if (!error && code === 200) {
            toPdfPage(data)
            //window.open(data, '_blank')
        }
    }
}


//导入
const importModal = ref(false)
const importModalClick = () => {
    tableImportData.value = []
    importModal.value = true
}


//上传进度
const uploadprogress = (res) => {
    importModalLoading.value = res
    tableImportLoading.value = res
}

//上传完成
const uploadFinished = (data) => {
    tableImportData.value = getArrValue(data)
}


//确认导入
const importModalLoading = ref(false)
const importModalYesClick = () => {
    const keys = tableImportKeys.value
    if (keys.length > 0) {
        samplingRecord(keys)
    } else {
        window?.$message?.warning('请先勾选要导入的数据')
    }
}

//导入数据保存
const samplingRecord = async (keys) => {
    importModalLoading.value = true
    const { error, code } = await dataApi.samplingRecord({
        projectId: projectId.value,
        contractId: contractId.value,
        list: keys,
    })
    //处理数据
    importModalLoading.value = false
    if (!error && code === 200) {
        importModal.value = false
        getTableData()
    } else {
        importModal.value = false
    }
}

//关闭导入
const importModalClose = () => {
    importModal.value = false
}

//表格数据
const tableImportRef = ref(null)
const tableImportLoading = ref(false)
const tableImportData = ref([])

//多选
const tableImportKeys = ref([])
const tableImportSelection = (rows) => {
    tableImportKeys.value = rows
}


//新增
const addEditFormModal = ref(false)
const addFormModalClick = () => {
    addEditFormModel.value = {}
    addEditFormModal.value = true
}
//编辑
const editFormModalClick = () => {
    const keys = tableCheckedKeys.value
    if (keys.length === 1) {
        addEditFormModel.value = keys[0]
        addEditFormModal.value = true
    } else if (keys.length > 1) {
        window?.$message?.warning('只能选择一条数据编辑')
    }
}
//关闭
const addEditFormModalClose = () => {
    addEditFormModal.value = false
    addEditFormModel.value = {}
}

//新增/编辑 表单
const addEditFormRef = ref(null)
const addEditFormModel = ref({})
const addEditFormRules = {
    key1: {
        required: true,
        trigger: 'blur',
        message: '请输入',
    },
    key2: {
        required: true,
        trigger: 'blur',
        message: '请选择',
    },
}

//分类被选择
const deviceFormLoading = ref(false)
const deviceFormSelectData = ref([])
const deviceClassIdChange = async (val) => {
    deviceFormLoading.value = true
    const { data } = await queryDeviceList({
        projectId: projectId.value,
        contractId: contractId.value,
        deviceClassId: val,
    })
    //处理数据
    const records = getArrValue(data)
    deviceFormSelectData.value = records
    if (records.length > 0) {
        addEditFormModel.value.deviceNumber = records[0].deviceNumber
        addEditFormModel.value.deviceName = records[0].deviceName
        addEditFormModel.value.deviceInfoId = records[0].id
    } else {
        addEditFormModel.value.deviceNumber = ''
        addEditFormModel.value.deviceName = ''
        addEditFormModel.value.deviceInfoId = ''
    }
    deviceFormLoading.value = false
}
//设备编号
const deviceNumberChange = (val) => {
    addEditFormModel.value.deviceName = getRowsValue(deviceFormSelectData.value, 'deviceNumber', 'deviceName', val)
    addEditFormModel.value.deviceInfoId = getRowsValue(deviceFormSelectData.value, 'deviceNumber', 'id', val)
}
//设备名称
const deviceNameChange = (val) => {
    addEditFormModel.value.deviceNumber = getRowsValue(deviceFormSelectData.value, 'deviceName', 'deviceNumber', val)
    addEditFormModel.value.deviceInfoId = getRowsValue(deviceFormSelectData.value, 'deviceName', 'id', val)
}

//新增/编辑 保存
const addEditFormLoading = ref(false)
const addEditFormClick = async () => {
    const validate = await formValidate(addEditFormRef.value)
    if (validate) {
        addEditFormLoading.value = true
        const { error, code } = await dataApi.submitForm({
            ...addEditFormModel.value,
            projectId: projectId.value,
            contractId: contractId.value,
        })
        //处理数据

        if (!error && code === 200) {
            window?.$message?.success('操作成功')
            addEditFormModal.value = false
            addEditFormLoading.value = false
            await getTableData()
        }
    }
}

//下载导入模板
const downloadImportClick = () => {
    window.open('https://bladex-test-info.oss-cn-chengdu.aliyuncs.com//upload/20221109/d8011cf7b101ff694ed4f21ac4348542.xlsx', '_blank')
}


//左右拖动，改变树形结构宽度
const leftWidth = ref(240)
const onmousedown = () => {
    const leftNum = isCollapse.value ? 142 : 272
    document.onmousemove = (ve) => {
        let diffVal = ve.clientX - leftNum
        if (diffVal >= 220 && diffVal <= 400) {
            leftWidth.value = diffVal
        }
    }
    document.onmouseup = () => {
        document.onmousemove = null
        document.onmouseup = null
    }
}
</script>

<style lang="scss" scoped>
.hc-import-modal-table-box {
    position: relative;
    height: calc(100% - 228px);
    margin-top: 25px;
}
</style>
