<template>
    <!-- 工程在用检修预警 -->
    <div class="app-container">
        <el-form v-show="showSearch" :model="queryParams" ref="queryForm" size="small" inline>
            <el-form-item label="时间范围" prop="startTime">
                <el-date-picker
                v-model="queryParams.startTime"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="开始日期"
                @change="() => queryParams.endTime = ''"
                style="width: 130px"
                />
            </el-form-item>
            <el-form-item>-</el-form-item>
            <el-form-item prop="endTime">
                <el-date-picker
                v-model="queryParams.endTime"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="结束日期"
                :picker-options="{ disabledDate: (t) => t.getTime() < new Date(queryParams.startTime).getTime() - 86400000}"
                style="width: 130px"
                />
            </el-form-item>
            <el-form-item label="关键字" prop="keyWord">
                <el-input
                    clearable
                    style="width: 240px"
                    placeholder="请输入关键字"
                    v-model="queryParams.keyWord"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="机具类型" prop="">
                <el-cascader
                    v-model="typeIds"
                    :options="typeList"
                    :props="{ label: 'typeName', value: 'typeId' }"
                    filterable
                    clearable
                    @change="handleChangeType"
                    style="width: 240px"
                ></el-cascader>
            </el-form-item>
            <el-form-item label="规格型号" prop="typeId">
                <el-select v-model="queryParams.typeId" placeholder="请选择机规格型号" style="width: 240px">
                    <el-option
                        v-for="item in typeIdList"
                        :key="item.typeId"
                        :label="item.name"
                        :value="item.typeId"
                        filterable
                        clearable
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="设备状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择机设备状态" style="width: 240px">
                    <el-option
                        v-for="item in statusList"
                        :key="item.status"
                        :label="item.label"
                        :value="item.status"
                        filterable
                        clearable
                    ></el-option>
                </el-select>
            </el-form-item>

            <!-- 表单按钮 -->
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
                <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <!-- 通知暂未开发 -->
            <!-- <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-chat-dot-round" size="mini" @click="onHandleNotice">
                    通知
                </el-button>
            </el-col> -->
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">
                    导出数据
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <div style="color: red; font-size: 20px; font-weight: 800">总计：{{ total }}</div>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table :data="tableList" fit highlight-current-row style="width: 100%" :max-height="650">
            <!-- 多选 -->
            <el-table-column type="selection" width="55" align="center" @selection-change="selectionChange" />
            <el-table-column
                type="index"
                width="55"
                label="序号"
                align="center"
                :index="indexContinuation(queryParams.pageNum, queryParams.pageSize)"
            />
            <el-table-column
                v-for="column in tableColumns"
                :show-overflow-tooltip="column.showTooltip"
                :key="column.prop"
                :label="column.label"
                :prop="column.prop"
                :width="column.width"
                align="center"
            />
        </el-table>

        <!-- 分页 -->
        <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />
    </div>
</template>

<script>
import printJS from 'print-js'
import { getLeaseTaskList, deleteLeaseTask, getLeaseTask, getCodePDF } from '@/api/business/index'
import { getOverTimeListApi, getMaTypeApi } from '@/api/warning-analysis/engineering-in-use.js'
import { equipmentTypeTree } from '@/api/purchase/goodsArrived'

export default {
    name: 'SafetyToolEarlyWarning',
    data() {
        return {
            showSearch: true,
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                keyWord: '', // 关键字
                thirdTypeId: '',
                typeId: '',
                status: null, // 设备状态
                timeRange: [], // 日期范围
                startTime: '',
                endTime: ''
            },
            typeIds: [],

            total: 0, // 总条数
            // 表头
            tableColumns: [
                { label: '本次检修时间', prop: 'thisCheckTime', width: '100' },
                { label: '下次检修时间', prop: 'nextCheckTime', width: '100' },
                { label: '物资类型', prop: 'materialType', showTooltip: true },
                { label: '机具类型', prop: 'typeName', showTooltip: true },
                { label: '规格型号', prop: 'typeModelName', showTooltip: true },
                { label: '设备编码', prop: 'maCode', showTooltip: true },
                { label: '单位名称', prop: 'unitName', width: '200' },
                { label: '工程名称', prop: 'projectName', width: '200' },
                { label: '分公司', prop: 'impUnit', width: '200' },
                { label: '协议号', prop: 'agreementCode', width: '140' },
                { label: '临检天数', prop: 'overDays', width: '100' }
            ],
            // 表格数据
            tableList: [],
            dialogTitle: '', // 弹框标题
            dialogVisible: false, // 弹框显示
            dialogForm: {
                proName: '', // 项目名称
                code: '' // 业务单号
            },
            dialogColumns: [
                { label: '名称', prop: 'maTypeName', width: '150px' },
                { label: '规格', prop: 'typeName', width: '150px' },
                { label: '单位', prop: 'unitName', width: '60px' },
                { label: '数量', prop: 'preNum', width: '60px' },
                { label: '备注', prop: 'remark', width: '' }
            ],
            dialogList: [],
            typeList: [],
            typeIdList: [],
            statusList: [
                { label: '正常', status: 0 }, 
                { label: '超期', status: 1 },
                { label: '超期7天内', status: 2 },
                { label: '超期15天内', status: 3 },
                { label: '超期30天内', status: 4 },
            ]
        }
    },
    created() {
        this.getList()
        this.getTreeList()
    },
    methods: {
        // 查询
        handleQuery() {
            this.getList()
        },
        // 重置
        handleReset() {
            this.queryParams.pageNum = 1
            this.queryParams.pageSize = 10
            this.typeIds = []
            this.queryParams.thirdTypeId = ''
            this.$refs.queryForm.resetFields()
            this.getList()
        },
        // 获取列表
        async getList() {
            console.log('列表-查询', this.queryParams)
            try {
                const params = {
                    ...this.queryParams,
                    // startTime: this.queryParams.timeRange[0] || '',
                    // endTime: this.queryParams.timeRange[1] || ''
                }
                const res = await getOverTimeListApi(params)
                console.log('🚀 ~ 获取列表 ~ res:', res)
                this.tableList = res.rows
                this.total = res.total
            } catch (error) {
                console.log('🚀 ~ 获取列表 ~ error:', error)
                this.tableList = []
                this.total = 0
            }
        },
        // 获取设备树
        async getTreeList() {
            try {
                const res = await equipmentTypeTree()
                console.log('🚀 ~ getTreeList ~ res:', res)
                if (res.data && res.data.length > 0) {
                    this.typeList = this.removeChildrenFromLevel3(res.data)
                }
            } catch (error) {
                console.log('🚀 ~ getTreeList ~ error:', error)
            }
        },
        removeChildrenFromLevel3(tree) {
            return tree.map(node => {
                const newNode = { ...node }

                if (newNode.level === '3') {
                    // 删除 children
                    delete newNode.children
                } else if (newNode.children && newNode.children.length > 0) {
                    // 递归处理子节点
                    newNode.children = this.removeChildrenFromLevel3(newNode.children)
                }

                return newNode
            })
        },

        handleChangeType(e) {
            this.typeIdList = []
            this.queryParams.typeId = ''
            this.queryParams.thirdTypeId = e[e.length - 1]
            console.log('🚀 ~ handleChangeType ~ :', this.queryParams.thirdTypeId)
            this.getMaTypeList()
        },
        async getMaTypeList() {
            try {
                const res = await getMaTypeApi({ typeId: this.queryParams.thirdTypeId })
                this.typeIdList = res.data || []
            } catch (error) {
                console.log('🚀 ~ getMaTypeList ~ error:', error)
            }
        },
        // 多选
        selectionChange(val) {
            console.log('selectionChange', val)
        },
        handleAdd() {
            console.log('领料申请')
            this.$router.push({ path: '/business/businessHandling/index' })
        },
        // 编辑
        handleEdit(row, type) {
            console.log('编辑', row)
            let params = {}
            if (type === 1) {
                params = { type: 'detail', id: row.id }
            } else {
                params = { type: 'edit', id: row.id }
            }
            this.$router.push({ path: '/business/businessHandling/index', query: params })
        },
        // 删除
        handleDelete(row) {
            console.log('删除', row)
            this.$confirm('是否删除该数据?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const res = await deleteLeaseTask(row.id)
                console.log('🚀 ~ 删除 ~ res:', res)
                this.getList()
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                })
            })
        },
        // 导出数据
        handleExport() {
            try {
                let fileName = `安全工器具到期预警数据_${new Date().getTime()}.xLsx`
                let url = '/material/useMaintenanceWarning/exportOverTimeList'
                const params = { ...this.queryParams }
                this.download(url, params, fileName)
            } catch (error) {
                console.log('导出数据失败', error)
            }
        },
        // 打印
        print() {
            printJS({
                printable: 'print-content',
                type: 'html', //
                // targetStyles: ['*'], // 打印的元素样式
                scanStyles: false, // 是否扫描页面样式
                // css: [
                //   'https://unpkg.com/element-ui/lib/theme-chalk/index.css' // Element UI 的样式表
                // ],
                maxWidth: '1400'
                // 其他配置选项
            })
        },
        // 获取弹框内容
        async getDialogContent(row) {
            console.log('🚀 ~ getDialogContent ~ row:', row.taskId)
            const loading = this.$loading({
                lock: true,
                text: '加载中...'
            })
            try {
                // 获取业务联系单
                const res = await getLeaseTask(row.id)
                console.log('🚀 ~ getDialogContent ~ res:', res)
                // 获取PDF
                // const PDFres = await getCodePDF(row.taskId)
                // console.log('🚀 ~ getDialogContent ~ res:', PDFres)
                this.dialogVisible = true
                this.dialogForm = {
                    ...res.data.leaseApplyInfo
                    // pdfUrl: PDFres.data.url
                }
                this.dialogList = res.data.leaseApplyDetailsList
                loading.close()
            } catch (error) {
                console.log('🚀 ~ 获取弹框内容 ~ error:', error)
                loading.close()
            }
        },
        // 处理时间格式 2021-09-01 转换为 2021年09月01日
        handleTimeFormat(time) {
            if (time) {
                return time.replace(/-/g, '年').replace(/-/g, '月') + '日'
            }
            return ''
        },
        // 通知按钮
        onHandleNotice() {
            console.log('通知--')
        }
    }
}
</script>

<style lang="scss" scoped></style>
