<template>
    <Page>
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="设备类型:">
                <el-select
                    v-model="formInline.devType"
                    placeholder="请选择设备类型"
                    style="width: 100%"
                    @change="devTypeChange"
                    clearable
                >
                    <el-option
                        v-for="item in devTypeOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="设备型号:">
                <el-select v-model="formInline.devModel" placeholder="请选择设备型号" style="width: 100%" clearable>
                    <el-option
                        v-for="item in devModelOptionsFilter"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="通讯协议:">
                <el-select
                    v-model="formInline.devAccessMethod"
                    placeholder="请选择通讯协议"
                    style="width: 100%"
                    clearable
                    @change="devModelChange"
                >
                    <el-option label="MQTT" value="mqtt"></el-option>
                    <el-option label="CLD" value="cloud"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="状态:">
                <el-select
                    v-model="formInline.status"
                    placeholder="请选择状态"
                    style="width: 100%"
                    clearable
                    @change="devModelChange"
                >
                    <el-option label="未注册" :value="1"></el-option>
                    <el-option label="注册" :value="2"></el-option>
                    <el-option label="接入" :value="3"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="search" icon="el-icon-search">查询</el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="resetFormInline" icon="el-icon-setting">重置</el-button>
            </el-form-item>
            <el-form-item style="display: flex; float: right">
                <el-button type="primary" @click="downLoadFile" icon="el-icon-download">模版下载</el-button>
                <el-upload
                    style="display: inline-block"
                    action=""
                    accept=".xlsx"
                    class="upload-demo"
                    :show-file-list="false"
                    :auto-upload="false"
                    :on-change="bulkImport"
                >
                    <el-button type="primary" icon="el-icon-tickets">批量导入</el-button>
                </el-upload>
                <el-button type="primary" @click="add" icon="el-icon-plus">新增设备</el-button>
            </el-form-item>
        </el-form>
        <el-table
            stripe
            style="width: 100%"
            :data="tableData"
            height="calc(100vh - 224px)"
            border
            v-loading="loading"
            highlight-current-row
            header-cell-class-name="table_header"
        >
            <el-table-column align="center" prop="name" label="设备名称"></el-table-column>
            <el-table-column align="center" prop="devType" label="设备类型">
                <template slot-scope="scope">
                    {{
                        devTypeOptions.filter(item => item.value == scope.row.devType)[0] &&
                        devTypeOptions.filter(item => item.value == scope.row.devType)[0].label
                    }}
                </template>
            </el-table-column>
            <el-table-column align="center" prop="devModel" label="设备型号">
                <template slot-scope="scope">
                    {{
                        devModelOptions.filter(item => item.value == scope.row.devModel)[0] &&
                        devModelOptions.filter(item => item.value == scope.row.devModel)[0].label
                    }}
                </template>
            </el-table-column>
            <el-table-column align="center" prop="devAccessMethod" label="通讯协议">
                <template slot-scope="scope">
                    {{
                        scope.row.devAccessMethod === 'MQTT'
                            ? 'MQTT'
                            : scope.row.devAccessMethod === 'cloud'
                            ? 'CLD'
                            : scope.row.devAccessMethod
                    }}
                </template>
            </el-table-column>
            <el-table-column align="center" prop="createTime" label="录入时间" min-width="150"></el-table-column>
            <!--            <el-table-column align="center" prop="programVersion" label="程序版本" min-width="130">-->
            <!--                <template slot-scope="scope">-->
            <!--                    {{-->
            <!--                        versionOptions.filter((item) => item.value == scope.row.programVersion)[0] &&-->
            <!--                        versionOptions.filter((item) => item.value == scope.row.programVersion)[0].label-->
            <!--                    }}-->
            <!--                </template>-->
            <!--            </el-table-column>-->
            <el-table-column align="center" prop="ndid" label="网络设备ID" min-width="120"></el-table-column>
            <el-table-column align="center" prop="status" label="状态" min-width="70">
                <template slot-scope="scope">
                    {{ scope.row.status == 1 ? '未注册' : scope.row.status == 2 ? '注册' : '接入' }}
                </template>
            </el-table-column>

            <el-table-column align="center" label="操作" min-width="340">
                <template slot-scope="scope">
                    <!-- <div class="table-operation"> -->
                    <el-button size="mini" type="primary" @click="edit(scope.row)" icon="el-icon-edit">编辑</el-button>
                    <el-button size="mini" type="primary" @click="qrCode(scope.row)" icon="el-icon-s-grid">
                        二维码
                    </el-button>
                    <el-button size="mini" type="primary" @click="reset(scope.row.ndid)" icon="el-icon-setting">
                        出厂恢复
                    </el-button>
                    <el-button
                        size="mini"
                        type="danger"
                        @click="deleteEquipmentDelivery(scope.row.id)"
                        icon="el-icon-delete"
                    >
                        删除
                    </el-button>

                    <!-- </div> -->
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            background
            align="right"
            @size-change="handleSizeChange"
            @current-change="pageChange"
            :current-page="formInline.pageNum"
            :page-sizes="[20, 30, 40, 50, 100]"
            :page-size="formInline.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            class="mt10"
        ></el-pagination>
        <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="30%" :before-close="closeDialog">
            <el-form :model="form" :label-width="formLabelWidth" :rules="rules" ref="form">
                <el-form-item label="设备名称:" prop="name">
                    <el-input
                        v-model="form.name"
                        autocomplete="off"
                        clearable
                        placeholder="请输入（项目名称+设备名称）"
                    ></el-input>
                </el-form-item>
                <el-form-item label="网络设备ID:" prop="ndid" class="top">
                    <el-input v-model="form.ndid" autocomplete="off" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="设备类型:" prop="devType" class="top">
                    <el-select
                        v-model="form.devType"
                        placeholder="请选择"
                        style="width: 100%"
                        @change="formDevTypeChange"
                        clearable
                    >
                        <el-option
                            v-for="item in devTypeOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="设备型号:" prop="devModel" class="top">
                    <el-select
                        v-model="form.devModel"
                        placeholder="请选择"
                        style="width: 100%"
                        clearable
                        @change="formDevModelChange"
                    >
                        <el-option
                            v-for="item in formDevModelOptionsFilter"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="通讯协议:" prop="devAccessMethod" class="top">
                    <el-select v-model="form.devAccessMethod" placeholder="请选择" style="width: 100%" clearable>
                        <el-option label="MQTT" value="MQTT"></el-option>
                        <el-option label="CLD" value="cloud"></el-option>
                    </el-select>
                </el-form-item>
                <!--                    <el-form-item label="程序版本:" prop="programVersion">-->
                <!--                        <el-select v-model="form.programVersion" placeholder="请选择" style="width: 100%">-->
                <!--                            <el-option v-for="item in versionOptionsFilter" :key="item.value" :label="item.label"-->
                <!--                                       :value="item.value">-->
                <!--                            </el-option>-->
                <!--                        </el-select>-->
                <!--                    </el-form-item>-->
                <!--                    <el-form-item label="MAC地址:" prop="mac">-->
                <!--                        <el-input v-model="form.mac" autocomplete="off" placeholder="请输入"></el-input>-->
                <!--                    </el-form-item>-->
                <!--                    <el-form-item label="调试人员:" prop="debugPerson">-->
                <!--                        <el-input v-model="form.debugPerson" autocomplete="off" placeholder="请输入"></el-input>-->
                <!--                    </el-form-item>-->
                <!--                    <el-form-item label="设备出厂日期:" prop="producteTime">-->
                <!--                        <el-date-picker value-format="yyyy-MM-dd" v-model="form.producteTime" type="date" style="width: 100%"-->
                <!--                                        placeholder="选择日期时间">-->
                <!--                        </el-date-picker>-->
                <!--                    </el-form-item>-->
                <!--                    <el-form-item label="检修日期:" prop="checkTime">-->
                <!--                        <el-date-picker value-format="yyyy-MM-dd" v-model="form.checkTime" type="date" style="width: 100%"-->
                <!--                                        placeholder="选择日期时间">-->
                <!--                        </el-date-picker>-->
                <!--                    </el-form-item>-->
                <!--                    <el-form-item label="调试日期:" prop="debugTime">-->
                <!--                        <el-date-picker value-format="yyyy-MM-dd" v-model="form.debugTime" type="date" style="width: 100%"-->
                <!--                                        placeholder="选择日期时间">-->
                <!--                        </el-date-picker>-->
                <!--                    </el-form-item>-->
                <el-form-item label="合同号:" prop="cntractNo" class="top">
                    <el-input v-model="form.cntractNo" autocomplete="off" placeholder="请输入"></el-input>
                </el-form-item>
                <!--                    <el-form-item label="营销经理:" prop="salesManager">-->
                <!--                        <el-input v-model="form.salesManager" autocomplete="off" placeholder="请输入"></el-input>-->
                <!--                    </el-form-item>-->
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeDialog">取 消</el-button>
                <el-button type="primary" @click="onSubmit">确 定</el-button>
            </div>
        </el-dialog>
        <div class="qrcode-label">
            <div class="qrcode-label-title">{{ deivce.mac }}</div>
            <img class="qrcode-label-img" alt="二维码加载失败" :src="deivce.qrPath" />
        </div>
    </Page>
</template>

<script>
import {
    getDeviceLeavesFactoryList,
    addEquipmentDelivery,
    deleteEquipmentDelivery,
    editEquipmentDelivery,
    uploadTopo,
    batchImportDevice,
    resetEquipmentDelivery
} from '@/api/app/device'
import { queryByCode, queryCsDictTree, queryByid, queryEdDataPage } from '@/api/app/setting'
import html2canvas from 'html2canvas'

export default {
    name: 'GovernManageFactory',
    data() {
        return {
            loading: true,
            dialogFormVisible: false,
            dialogTitle: '新增设备',
            form: {
                // checkTime: '',
                cntractNo: '',
                // debugPerson: '',
                // debugTime: '',
                devAccessMethod: 'mqtt',
                devModel: '',
                devType: '',
                // mac: '',
                name: '',
                ndid: ''
                // producteTime: '',
                // programVersion: '',
                // salesManager: '',
            },
            deivce: {},
            dialogImageUrl: '',
            dialogVisible: false,
            formLabelWidth: '120px',
            formInline: {
                devAccessMethod: '',
                devModel: '',
                devType: '',
                orderBy: '',
                pageNum: 1,
                pageSize: 20,
                searchBeginTime: '',
                searchEndTime: '',
                searchState: '',
                searchValue: '',
                sortBy: '',
                status: ''
            },
            // 设备类型
            devTypeOptions: [],
            // 设备型号
            devModelOptions: [],
            // 程序版本
            versionOptions: [],
            total: 0,
            tableData: [],
            engineeringList: [],
            tabHeight: 'calc(100vh - 205px)',
            rules: {
                name: [
                    { required: true, message: '设备名不能为空', trigger: 'blur' }
                    //     {
                    //     pattern:  /[^\u4E00-\u9FA5]/,
                    //     message: "请输入中文字符",
                    //     trigger: "blur",
                    //   },
                ],
                ndid: [{ required: true, message: '网络设备id不能为空', trigger: 'blur' }],
                devType: [{ required: true, message: '设备类型不能为空', trigger: 'blur' }],
                devModel: [{ required: true, message: '设备型号不能为空', trigger: 'blur' }],
                devAccessMethod: [{ required: true, message: '接入方式不能为空', trigger: 'blur' }],
                // programVersion: [{ required: true, message: '程序版本不能为空', trigger: 'blur' }],
                mac: [
                    {
                        required: true,
                        trigger: 'blur',
                        validator: (rule, value, callback) => {
                            if (value) {
                                // MAC地址正则表达式
                                let reg = /^([0-9a-fA-F]{2})(([/\s:-][0-9a-fA-F]{2}){5})$/
                                // IP4地址正则表达式
                                let reg2 =
                                    /^((([0-9]|([1-9][0-9])|(1[0-9]{2})|(2[0-4][0-9])|(25[0-5]))\.){3})([0-9]|([1-9][0-9])|(1[0-9]{2})|(2[0-4][0-9])|(25[0-5]))$/
                                if (reg.test(this.form.mac) || reg2.test(this.form.mac)) {
                                    callback()
                                } else {
                                    callback(new Error('请输入正确的MAC地址'))
                                }
                            } else {
                                callback(new Error('请输入正确的MAC地址'))
                            }
                        }
                    }
                ],
                debugPerson: [{ required: true, message: '调试人员不能为空', trigger: 'blur' }],
                producteTime: [
                    { required: false, message: '设备出场日期不能为空', trigger: 'blur' }
                    //   {
                    //     type: "email",
                    //     message: "'请输入正确的邮箱地址",
                    //     trigger: ["blur", "change"],
                    //   },
                ],
                checkTime: [
                    { required: false, message: '检修日期不能为空', trigger: 'blur' }
                    //   {
                    //     pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                    //     message: "请输入正确的手机号码",
                    //     trigger: "blur",
                    //   },
                ],
                debugTime: [{ required: true, message: '调试日期不能为空', trigger: 'blur' }],
                cntractNo: [
                    { required: true, message: '合同号不能为空', trigger: 'blur' }
                    //   {
                    //     required: true,
                    //     validator: (rule, value, callback) => {
                    //       let regexp =
                    //         /^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}$/;
                    //       let isCorrect = regexp.test(value);
                    //       if (value == "") {
                    //         return callback(new Error("请输入IP地址"));
                    //       } else if (!isCorrect) {
                    //         callback(new Error("请输入正确的IP地址"));
                    //       } else {
                    //         callback();
                    //       }
                    //     },
                    //     trigger: "blur",
                    //   },
                ],
                salesManager: [
                    { required: true, message: '销售经理不能为空', trigger: 'blur' }
                    //   {
                    //     required: true,
                    //     validator: (rule, value, callback) => {
                    //       let regexp =
                    //         /^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}$/;
                    //       let isCorrect = regexp.test(value);
                    //       if (value == "") {
                    //         return callback(new Error("请输入IP地址"));
                    //       } else if (!isCorrect) {
                    //         callback(new Error("请输入正确的IP地址"));
                    //       } else {
                    //         callback();
                    //       }
                    //     },
                    //     trigger: "blur",
                    //   },
                ]
            }
        }
    },
    computed: {
        vth() {
            return window.sessionStorage.getItem('appheight') - 95
        },

        devModelOptionsFilter() {
            return this.devModelOptions.filter(item => {
                if (this.formInline.devType) {
                    return item.pid == this.formInline.devType
                } else {
                    return true
                }
            })
        },
        formDevModelOptionsFilter() {
            return this.devModelOptions.filter(item => {
                if (this.form.devType) {
                    return item.pid == this.form.devType
                } else {
                    return true
                }
            })
        },
        versionOptionsFilter() {
            return this.versionOptions.filter(item => {
                if (this.form.devModel) {
                    return item.devType == this.form.devModel
                } else {
                    return true
                }
            })
        }
    },
    created() {
        this.search()
        queryByCode('Device_Type').then(res => {
            queryCsDictTree(res.data.id).then(res => {
                this.devTypeOptions = res.data.map(item => {
                    return {
                        value: item.id,
                        label: item.name,
                        ...item
                    }
                })
            })
            queryByid(res.data.id).then(res => {
                this.devModelOptions = res.data.map(item => {
                    return {
                        value: item.id,
                        label: item.name,
                        ...item
                    }
                })
            })
        })
        queryEdDataPage({
            pageNum: 1,
            pageSize: 1000
        }).then(res => {
            console.log(res)
            this.versionOptions = res.data.records.map(item => {
                return {
                    value: item.id,
                    label: item.versionNo,
                    ...item
                }
            })
        })
    },
    methods: {
        closeDialog() {
            this.resetForm()
            this.dialogFormVisible = false
        },
        // 表单重置
        resetForm() {
            if (this.$refs['form']) {
                this.$refs['form'].resetFields()
            }
        },

        downLoadFile() {
            window.open(window.location.origin + '/api/cs-device-boot/EquipmentDelivery/getExcelTemplate')
        },
        bulkImport(e) {
            console.warn(e)
            batchImportDevice(e.raw).then(res => {
                console.log(res)
                if (res.type === 'application/json') {
                    const reader = new FileReader()
                    reader.readAsText(res)
                    reader.onload = e => {
                        console.log(e)
                        let data = JSON.parse(e.target.result)
                        if (data.code === 'A0000') {
                            this.$message({
                                type: 'success',
                                message: data.message
                            })
                            this.search()
                        } else {
                            this.$message({
                                type: 'error',
                                message: data.message
                            })
                        }
                    }
                } else {
                    let url = window.URL.createObjectURL(res)
                    let link = document.createElement('a')
                    link.style.display = 'none'
                    link.href = url
                    link.setAttribute('download', '导入失败.xlsx')
                    document.body.appendChild(link)
                    link.click()
                    document.body.removeChild(link)
                }
            })
        },
        qrCode(item) {
            this.deivce = item
            this.deivce.qrPath = localStorage.getItem('STATIC_URL') + this.deivce.qrPath
            this.$nextTick(() => {
                html2canvas(document.querySelector('.qrcode-label'), {
                    useCORS: true
                }).then(canvas => {
                    let url = canvas.toDataURL('image/png')
                    // 下载图片
                    let a = document.createElement('a')
                    let event = new MouseEvent('click')
                    a.href = url
                    a.download = item.mac + '.png'
                    a.dispatchEvent(event)
                })
            })
        },
        deleteEquipmentDelivery(id) {
            this.$confirm('确定删除该设备吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteEquipmentDelivery(id).then(res => {
                    console.log(res)
                    if (res.code === 'A0000') {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        })
                        this.search()
                    }
                })
            })
        },
        reset(id) {
            this.$confirm('确定该设备恢复出厂吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                resetEquipmentDelivery(id).then(res => {
                    console.log(res)
                    if (res.code === 'A0000') {
                        this.$message({
                            type: 'success',
                            message: '恢复成功!'
                        })
                        this.search()
                    }
                })
            })
        },
        devTypeChange(e) {
            console.log(e)
            if (!e) {
                return
            }
            this.formInline.devModel = ''
        },
        formDevTypeChange(e) {
            console.log(e)
            if (!e) {
                return
            }
            this.form.devModel = ''
        },
        formDevModelChange(e) {
            console.log(e)
            if (!e) {
                return
            }
            // this.form.programVersion = ''
        },
        devModelChange(e) {
            console.log(e)
        },
        imageChange(e) {
            console.log(e)
            this.form.files.push(e)
        },
        handleRemove(file, fileList) {
            console.log(file, fileList)
            if (file.id) {
                delAppTopologyDiagram(file.id).then(res => {
                    console.log(res)
                })
            }
            this.form.files = fileList
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url
            this.dialogVisible = true
        },
        pageChange(e) {
            console.log('pageChange!')
            console.log(e)
            this.formInline.pageNum = e
            this.search()
        },
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`)
            this.formInline.pageNum = 1
            this.formInline.pageSize = val
            this.search()
        },
        search() {
            this.loading = true
            getDeviceLeavesFactoryList(this.formInline).then(res => {
                console.warn(res)
                this.tableData = res.data.records
                this.total = res.data.total
                this.loading = false
            })
        },
        resetFormInline() {
            for (let key in this.formInline) {
                if (key !== 'pageNum' && key !== 'pageSize') {
                    this.formInline[key] = ''
                }
            }
        },
        reload() {
            for (let key in this.formInline) {
                this.formInline[key] = ''
            }
            this.formInline.pageNum = 1
            this.formInline.pageSize = 20
            this.search()
        },
        onSubmit() {
            console.log(this.form)
            for (let key in this.form) {
                if (this.form[key] === '') {
                    this.$message.error('请填写完整信息')
                    return
                }
            }
            if (this.dialogTitle == '新增设备') {
                addEquipmentDelivery(this.form).then(res => {
                    console.log(res)
                    if (res.code === 'A0000') {
                        this.$message({
                            message: '新增成功',
                            type: 'success'
                        })
                        this.dialogFormVisible = false
                        this.reload()
                    }
                })
            } else {
                editEquipmentDelivery(this.form).then(res => {
                    if (res.code === 'A0000') {
                        this.$message({
                            message: '修改成功',
                            type: 'success'
                        })
                        this.dialogFormVisible = false
                        this.reload()
                    }
                })
            }
        },
        add() {
            for (let key in this.form) {
                if (key == 'files') {
                    this.form[key] = []
                    continue
                }
                this.form[key] = ''
            }
            delete this.form.id
            this.dialogTitle = '新增设备'
            this.dialogFormVisible = true
        },

        edit(item) {
            console.log(item)
            this.dialogTitle = '编辑设备'
            for (let key in this.form) {
                this.form[key] = item[key]
            }
            this.form.id = item.id
            this.dialogFormVisible = true
        },
        dialogClose() {
            this.form.id = ''
            this.form.name = ''
            this.dialogFormVisible = false
        }
    }
}
</script>
<style lang="less" scoped>
@import url('../../../styles/comStyle.less');
</style>
<style lang="scss">
.qrcode-label {
    position: absolute;
    top: 0;
    right: 0;
    z-index: -99;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 180px;
    height: 180px;
    padding: 10px;
    background: #fff;
    flex-direction: column;

    .qrcode-label-title {
        margin-bottom: 10px;
        font-size: 14px;
        font-weight: bold;
    }

    .qrcode-label-img {
        width: 140px;
        height: 140px;
    }
}
</style>
