<template>
    <div class="hc-page-layout-box">
        <div class="hc-layout-left-box menu" :style="'width:' + leftWidth + 'px;'">
            <div class="hc-menu-header-box">
                <div class="text-xl name">设备分类 - 使用记录</div>
            </div>
            <div class="hc-menu-contents-box">
                <el-scrollbar>
                    <HcMenuSimple :props="menusProps" :datas="menus" :keys="menuKey" @change="menuChange"/>
                </el-scrollbar>
            </div>
            <!--左右拖动-->
            <div class="horizontal-drag-line" @mousedown="onmousedown"/>
        </div>
        <div class="hc-page-content-box">
            <HcCard>
                <template #header>
                    <HcTooltip keys="tentative_device_employ_add">
                        <el-button type="primary" hc-btn @click="addFormModalClick">
                            <HcIcon name="add-circle"/>
                            <span>新增</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="tentative_device_employ_edit">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" @click="editFormModalClick">
                            <HcIcon name="edit"/>
                            <span>编辑</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="tentative_device_employ_del">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" @click="delNodeModalClick">
                            <HcIcon name="delete-bin-2"/>
                            <span>删除</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="tentative_device_employ_printer">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" :loading="printerLoading" @click="printerClick">
                            <HcIcon name="printer"/>
                            <span>打印</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="tentative_device_employ_import">
                        <el-button hc-btn @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" placeholder="请输入设备名称\设备型号查询" clearable @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" isCheck @selection-change="tableSelection"/>
                <template #action>
                    <HcPages :pages="searchForm" @change="pageChange"/>
                </template>
            </HcCard>
        </div>

        <!--新增/编辑-->
        <HcDialog :show="addEditFormModal" title="新增/编辑 设备使用信息" widths="50rem" :loading="addEditFormLoading" @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 :disabled="deviceFormLoading" v-model="addEditFormModel.deviceClassId" 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="检测项目">
                        <HcSelectTree v-model="addEditFormModel.nodeId" :title="addEditFormModel.nodeName" :projectId="projectId" :contractId="contractId" :wbsId="projectInfo?.referenceWbsTemplateIdTrial" @change="HcSelectTreeChange"/>
                    </el-form-item>
                </div>
                <div class="hc-form-item">
                    <el-form-item label="设备编号" prop="deviceNumber">
                        <el-select :disabled="deviceFormLoading" v-model="addEditFormModel.deviceNumber" 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.materialName" :datas="nodeMaterialSelectData" keys="materialName" placeholder="请选择或输入样品名称"/>
                    </el-form-item>
                </div>
                <div class="hc-form-item">
                    <el-form-item label="设备名称">
                        <el-select :disabled="deviceFormLoading" v-model="addEditFormModel.deviceName" block @change="deviceNameChange">
                            <el-option v-for="item in deviceFormSelectData" :label="item.deviceName" :value="item.deviceName"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="样品编号">
                        <hcAutoComplete v-model="addEditFormModel.specificationNumber" :datas="nodeMaterialSelectData" keys="specificationNumber" placeholder="请选择或输入样品编号"/>
                    </el-form-item>
                </div>
                <div class="hc-form-item">
                    <el-form-item label="使用日期(起)" prop="startDate">
                        <el-date-picker type="date" v-model="addEditFormModel.startDate" class="block" value-format="YYYY-MM-DD" :clearable="false"/>
                    </el-form-item>
                    <el-form-item label="使用日期(止)"  prop="endDate">
                        <el-date-picker type="date" v-model="addEditFormModel.endDate" class="block" value-format="YYYY-MM-DD" :clearable="false"/>
                    </el-form-item>
                </div>
                <div class="hc-form-item">
                    <el-form-item label="使用人员">
                        <hcAutoComplete v-model="addEditFormModel.managerName" :datas="userListData" keys="userName" placeholder="请选择或输入使用人员名称"/>
                    </el-form-item>
                    <el-form-item/>
                </div>
                <el-form-item label="备注">
                    <el-input v-model="addEditFormModel.remarks" type="textarea" placeholder="备注" :autosize="{ minRows: 3}"/>
                </el-form-item>
            </el-form>
        </HcDialog>

        <!--导入-->
        <HcDialog :show="importModal" title="导入设备使用数据" widths="70rem" isTable isFooterCenter :loading="importModalLoading" @save="importModalYesClick" @close="importModalClose">
            <div class="text-orange mb-6">
                <span>请先下载模板模板表格 (</span>
                <span class="text-link" @click="downloadImportClick">范例试验设备文件</span>
                <span>) ,按模板样式编辑试验容器后，在点击“选择文件”按钮选择编辑好的文件，点击确认即可导入成功！</span>
            </div>
            <HcDragUpload action="use/read-excel" @progress="uploadprogress" @finished="uploadFinished"/>
            <div class="hc-import-modal-table-box">
                <HcTable ref="tableImportRef" :column="tableColumn" :datas="tableImportData" :loading="tableImportLoading" isCheck @selection-change="tableImportSelection">
                    <template #status="{row}">
                        {{row.status == 1?'启用中':'已停用'}}
                    </template>
                    <template #isCalibration="{row}">
                        {{row.isCalibration == 1?'是':'否'}}
                    </template>
                </HcTable>
            </div>
        </HcDialog>

    </div>
</template>

<script setup>
import {ref, onMounted, watch} from "vue";
import {useAppStore} from "~src/store";
import HcDragUpload from "./components/HcDragUpload.vue"
import HcSelectTree from "./components/HcSelectTree.vue"
import {getClassList,deviceClassListInit, queryDeviceList, querySampleList,getSampleInfo} from "~api/tentative";
import {getContractUserList} from "~api/other";
import {formValidate, getArrValue,getObjValue} from "vue-utils-plus"
import dataApi from "~api/tentative/device/employ";
import {getRowsValue, rowsToId} from "~uti/tools";

//初始变量
const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId);
const contractId = ref(useAppState.getContractId);
const projectInfo = ref(useAppState.getProjectInfo);
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:'startDate', name: '使用日期(起)'},
    {key:'endDate', name: '使用日期(止)'},
    {key:'nodeName', name: '检测试验项目'},
    {key:'specificationNumber', name: '样品编号'},
    {key:'materialName', name: '样品名称'},
    {key:'managerName', name: '使用人'},
    {key:'remarks', name: '备注'},
])
const tableData = ref([])

//获取数据
const tableLoading = ref(false)
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 = () => {
    window?.$messageBox?.alert('请谨慎考虑后，确认是否需要删除？', '删除提醒', {
        showCancelButton: true,
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning',
        callback: (action) => {
            if (action === 'confirm') {
                tableRemoveData()
            }
        }
    })
}

//批量删除
const tableRemoveData = async () => {
    const rows = tableCheckedKeys.value
    if (rows.length > 0 ) {
        const ids = rowsToId(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 = rowsToId(rows)
        //删除请求
        const { error, code, data } = await dataApi.exportPdf({
            projectId: projectId.value,
            contractId: contractId.value,
            ids: ids,
        })
        //处理数据
        printerLoading.value = false
        if (!error && code === 200) {
            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({
    deviceClassId:'',
    nodeName:'',
    deviceNumber:'',
    materialName:'',
    deviceName:'',
    specificationNumber:'',
    startDate:'',
    endDate:'',
    managerName:'',
    remarks:'',
})
const addEditFormRules = {
      startDate: {
        required: false,
        validator: (rule, value, callback) => {
            const endTime = addEditFormModel.value?.endDate ?? ''
            if (endTime&&value > endTime) {
                callback(new Error('使用停止日期 不能 小于 使用起始日期'))
            } else {
                callback()
            }
        },
        trigger: "blur",
    },
    endDate: {
        required: false,
        validator: (rule, value, callback) => {
            const startTime = addEditFormModel.value?.startDate ?? ''
            if (value < startTime) {
                callback(new Error('使用停止日期 不能 小于 使用起始日期'))
            } else {
                callback()
            }
        },
        trigger: "blur",
    },
    deviceNumber:{
         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 HcSelectTreeChange = ({title, primaryKeyId}) => {
    addEditFormModel.value.nodeName = title
    addEditFormModel.value.nodeId = primaryKeyId
    nodeMaterialChange(primaryKeyId)
}

//分类被选择
const nodeMaterialLoading = ref(false)
const nodeMaterialSelectData = ref([])
const nodeMaterialChange = async (val) => {
    nodeMaterialLoading.value = true
    // const {data} = await querySampleList({
    //     projectId: projectId.value,
    //     contractId: contractId.value,
    //     nodeId: val
    // })
      const {data} = await getSampleInfo({
        primaryKeyId: val
    })
    //处理数据
    if (data) {
        addEditFormModel.value.specificationNumber = data?.sampleNumbers 
        addEditFormModel.value.materialName = data?.sampleNames  
    } else {
        addEditFormModel.value.specificationNumber = ''
        addEditFormModel.value.materialName = ''
    }
    nodeMaterialLoading.value = false;
}


//新增/编辑 保存
const addEditFormLoading = ref(false)
const addEditFormClick = async () => {
    console.log('提交');
    const validate = await formValidate(addEditFormRef.value)
    // console.log(validate,'validate');
  
    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/aaafe6673c0338eeeba8ff537980e093.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>
