<template>
    <!-- 编码设备管理 -->
    <div class="app-container" id="devices" v-if="!props.isShow">
        <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
        >
            <el-form-item label="关键字" prop="keyWord">
                <el-input
                    v-model="queryParams.keyWord"
                    placeholder="请输入关键字"
                    clearable
                    maxlength="50"
                    style="width: 240px"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="物品种类" prop="itemId">
                <el-select
                    v-model="queryParams.itemId"
                    placeholder="请选择物品种类"
                    clearable
                    filterable
                    style="width: 240px"
                    @change="selectItem"
                >
                    <el-option
                        v-for="typeItem in itemList"
                        :key="typeItem.typeId"
                        :label="typeItem.typeName"
                        :value="typeItem.typeId"
                    />
                </el-select>
            </el-form-item>

            <el-form-item label="设备类型" prop="deviceId">
                <el-select
                    v-model="queryParams.deviceId"
                    placeholder="请选择设备类型"
                    clearable
                    filterable
                    style="width: 240px"
                    :disabled="!queryParams.itemId"
                    @change="selectDevice"
                >
                    <el-option
                        v-for="typeItem in typeList"
                        :key="typeItem.typeId"
                        :label="typeItem.typeName"
                        :value="typeItem.typeId"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="规格型号" prop="typeId">
                <el-select
                    v-model="queryParams.typeId"
                    placeholder="请选择规格型号"
                    clearable
                    filterable
                    :disabled="!queryParams.deviceId"
                    style="width: 240px"
                >
                    <el-option
                        v-for="model in modelList"
                        :key="model.typeId"
                        :label="model.typeName"
                        :value="model.typeId"
                    />
                </el-select>
            </el-form-item>

            <el-form-item label="资产属性" prop="propId">
                <el-select
                    v-model="queryParams.propId"
                    clearable
                    filterable
                    placeholder="请选择资产属性"
                >
                    <el-option
                        v-for="keeper in propList"
                        :key="keeper.propId"
                        :label="keeper.propName"
                        :value="keeper.propId"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
                <el-date-picker
                    v-model="dateRange"
                    style="width: 240px"
                    value-format="yyyy-MM-dd"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                ></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    size="mini"
                    @click="handleQuery"
                    >搜索</el-button
                >
                <el-button
                    icon="el-icon-refresh"
                    size="mini"
                    @click="resetQuery"
                    >重置</el-button
                >
                <el-button
                    type="warning"
                    plain
                    icon="el-icon-download"
                    size="mini"
                    @click="handleExport"
                    v-hasPermi="['machinery:coding:export']"
                    >导出</el-button
                >
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <right-toolbar
                :showSearch.sync="showSearch"
                @queryTable="getList"
            ></right-toolbar>
        </el-row>

        <el-table
            v-loading="loading"
            :data="devicesList"
            border
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column
                align="center"
                label="序号"
                type="index"
                :index="
                    indexContinuation(queryParams.pageNum, queryParams.pageSize)
                "
            />
            <el-table-column label="物品种类" align="center" prop="itemType" />
            <el-table-column
                label="设备类型"
                align="center"
                prop="deviceType"
                show-overflow-tooltip
            />
            <el-table-column
                label="规格型号"
                align="center"
                prop="specificationType"
                show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
                label="设备编码"
                align="center"
                prop="maCode"
                width="200"
            />
            <el-table-column
                label="采购单号"
                align="center"
                prop="buyTask"
                width="180"
            />
            <el-table-column
                label="设备状态"
                align="center"
                prop="maStatusName"
            >
                <template slot-scope="scope">
                    <dict-tag
                        :options="dict.type.sys_normal_disable"
                        :value="scope.row.maStatusName"
                    />
                </template>
            </el-table-column>
            <el-table-column
                label="固定资产编号"
                align="center"
                prop="assetsCode"
            />
            <el-table-column label="设备原编号" align="center" prop="preCode" />

            <el-table-column
                label="二维码"
                align="center"
                prop="qrCode"
                width="120"
            >
                <template slot-scope="scope">
                    <span
                        style="color: blue; cursor: pointer"
                        @click="showQrCode(scope.row)"
                    >
                        {{ scope.row.qrCode }}</span
                    >
                </template>
            </el-table-column>
            <el-table-column label="IOT设备" align="center" prop="ownHouseName">
                <template slot-scope="{ row }">
                    <el-button type="text" @click="handleBindIOT(row)">{{
                        row.iotNum === 0 ? '未绑定' : row.iotNum
                    }}</el-button>
                </template>
            </el-table-column>
            <el-table-column
                label="位置信息"
                align="center"
                prop="ownHouseName"
            >
                <template slot-scope="{ row }">
                    <i
                        class="el-icon-location location-icon"
                        @click="handleMap(row)"
                        v-if="row.iotNum > 0"
                    />
                </template>
            </el-table-column>
            <!-- <el-table-column
                label="所在仓库"
                align="center"
                prop="ownHouseName"
            /> -->
            <!--      <el-table-column label="创建时间" align="center" prop="createTime" width="180">-->
            <!--        <template slot-scope="scope">-->
            <!--          <span>{{ parseTime(scope.row.createTime) }}</span>-->
            <!--        </template>-->
            <!--      </el-table-column>-->
            <el-table-column label="操作" align="center" width="150">
                <template slot-scope="scope">
                    <el-button
                        style="padding: 6px 10px"
                        size="mini"
                        type="primary"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                        v-hasPermi="['machinery:coding:edit']"
                        >编辑</el-button
                    >
                    <el-button
                        style="padding: 6px 10px"
                        size="mini"
                        type="danger"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                        v-hasPermi="['machinery:coding:del']"
                        >删除</el-button
                    >
                </template>
            </el-table-column>
        </el-table>

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

        <!-- 添加或修改参数配置对话框 -->
        <el-dialog
            :title="title"
            :visible.sync="open"
            width="1000px"
            append-to-body
            :close-on-click-modal="false"
        >
            <el-form
                ref="form"
                :model="form"
                :rules="rules"
                label-width="100px"
            >
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="物品种类" prop="itemType">
                            <el-input
                                v-model="form.itemType"
                                placeholder="请输入物品种类"
                                disabled
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="设备类型" prop="deviceType">
                            <el-input
                                v-model="form.deviceType"
                                placeholder="请输入设备类型"
                                disabled
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="规格型号" prop="specificationType">
                            <el-input
                                v-model="form.specificationType"
                                placeholder="请输入规格型号"
                                disabled
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="设备编号" prop="maCode">
                            <el-input
                                v-model="form.maCode"
                                placeholder="请输入设备编号"
                                disabled
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="设备状态" prop="maStatusName">
                            <el-input
                                v-model="form.maStatusName"
                                placeholder="请输入设备状态"
                                disabled
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="二维码编号">
                            <el-input v-model="form.qrCode" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="8">
                        <el-form-item label="采购单号" prop="buyTask">
                            <el-input
                                v-model="form.buyTask"
                                placeholder="请输入采购单号"
                                disabled
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="设备原编号" prop="preCode">
                            <el-input
                                v-model="form.preCode"
                                placeholder="请输入设备原编号"
                                maxlength="50"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="固定资产编号" prop="assetsCode">
                            <el-input
                                v-model="form.assetsCode"
                                placeholder="请输入固定资产编号"
                                maxlength="50"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="8">
                        <el-form-item label="所在仓库" prop="ownHouse">
                            <treeselect
                                v-model="form.ownHouse"
                                :options="deptOptions"
                                placeholder="请选择所在仓库"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="出入库次数" prop="inOutNum">
                            <el-input
                                v-model="form.inOutNum"
                                placeholder="请输入出入库次数"
                                disabled
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="资产属性" prop="propId">
                            <el-select
                                v-model="form.propId"
                                filterable
                                placeholder="请选择资产属性"
                            >
                                <el-option
                                    label="请选择"
                                    :value="0"
                                ></el-option>
                                <el-option
                                    v-for="keeper in propList"
                                    :key="keeper.propId"
                                    :label="keeper.propName"
                                    :value="keeper.propId"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="8">
                        <el-form-item label="本次检验人员" prop="checkMan">
                            <el-input
                                v-model="form.checkMan"
                                placeholder="请输入本次检验人员"
                                maxlength="50"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="本次检验时间" prop="thisCheckTime">
                            <el-date-picker
                                v-model="form.thisCheckTime"
                                value-format="yyyy-MM-dd"
                                type="date"
                                placeholder="本次检验时间"
                            ></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="下次检验时间" prop="nextCheckTime">
                            <el-date-picker
                                v-model="form.nextCheckTime"
                                value-format="yyyy-MM-dd"
                                type="date"
                                placeholder="下次检验时间"
                            ></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="出厂时间" prop="outFacTime">
                            <el-date-picker
                                v-model="form.outFacTime"
                                value-format="yyyy-MM-dd"
                                type="date"
                                placeholder="出厂时间"
                            ></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="出厂编号" prop="outFacCode">
                            <el-input
                                v-model="form.outFacCode"
                                placeholder="请输入出厂编号"
                                maxlength="50"
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="厂家" prop="maVender">
                            <el-select
                                v-model="form.maVender"
                                placeholder="机具厂家"
                                clearable
                                filterable
                                style="width: 180px"
                            >
                                <el-option
                                    v-for="item in supplierList"
                                    :key="item.supplierId"
                                    :label="item.supplier"
                                    :value="item.supplierId"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="16">
                        <el-form-item label="备注" prop="remark">
                            <el-input
                                v-model="form.remark"
                                type="textarea"
                                placeholder=""
                                maxlength="150"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <!-- <el-col :span="8">
            <el-form-item label="维修员" prop="dictName">
              <el-input v-model="form.dictName" placeholder="" />
            </el-form-item>
          </el-col> -->
                </el-row>

                <!--        <el-form-item label="状态" prop="status">-->
                <!--          <el-radio-group v-model="form.status">-->
                <!--            <el-radio-->
                <!--                v-for="dict in dict.type.sys_normal_disable"-->
                <!--                :key="dict.value"-->
                <!--                :label="dict.value"-->
                <!--            >{{dict.label}}</el-radio>-->
                <!--          </el-radio-group>-->
                <!--        </el-form-item>-->
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <el-dialog
            :title="title"
            :visible.sync="uploadOpen"
            width="500px"
            append-to-body
        >
            <div style="text-align: center">
                <div class="uploadImg">
                    <div id="qrcode" class="qrcode" ref="codeItem"></div>
                    <!--        <img src="" alt="">-->
                </div>
                <div class="maCode">二维码编号：{{ rowObj.qrCode }}</div>
            </div>
            <div slot="footer" class="dialog-footer" style="text-align: center">
                <!-- <el-button type="primary" @click="downloadCode">下 载</el-button> -->
            </div>
        </el-dialog>
        <MapDialog
            v-if="mapDialogVisible"
            :deviceName="deviceName"
            :deviceType="deviceType"
            :iotCode="iotCode"
            @handelCloseDialog="handelCloseDialog"
        />
    </div>
    <div v-else>
        <BindIOT :props="props" />
    </div>
</template>

<script>
import {
    addMachine,
    delMachine,
    getMachine,
    listMachine,
    updateMachine,
    supplierInfoList,
    getListByMaType,
} from '@/api/store/tools'
import { getProLists } from '@/api/base/base'
import { imgUpLoad } from '@/api/system/upload'
import { getTypeList } from '@/api/store/warehousing'
import { listHouseTree } from '@/api/store/shelves'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import QRCode from 'qrcodejs2'

import BindIOT from './component/BindIOT'
import MapDialog from './component/MapDIalog'

export default {
    name: 'Devices',
    dicts: ['sys_normal_disable'],
    components: { Treeselect, BindIOT, MapDialog },
    data() {
        return {
            openMap: false,
            isShow: false,
            props: {
                isShow: false,
                typeId: '',
                maCode: '',
            },
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            //资产类型数据
            propList: null,
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 字典表格数据
            devicesList: [],
            // 弹出层标题
            title: '',
            uploadOpen: false,
            qrCode: '',
            qrUrl: this.globalUrl.qrUrl,
            rowObj: {},
            // 是否显示弹出层
            open: false,
            // 日期范围
            dateRange: [],
            supplierList: [],
            itemList: [],
            typeList: [],
            modelList: [],
            deptOptions: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                keyWord: '',
                itemId: '',
                deviceId: '',
                typeId: '',
                propId: '',
                maType: '1',
                // dictName: undefined,
                // dictType: undefined,
                // status: undefined
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                dictName: [
                    {
                        required: true,
                        message: '字典名称不能为空',
                        trigger: 'blur',
                    },
                ],
                dictType: [
                    {
                        required: true,
                        message: '字典类型不能为空',
                        trigger: 'blur',
                    },
                ],
            },
            mapDialogVisible: false,
            deviceName: '',
            deviceType: '',
            iotCode: '',
        }
    },
    created() {
        this.getList()
        this.getPropData()
        this.getTypeList()
        this.supplierInfoList()
        this.getHouseTree()
    },
    methods: {
        /** 查询仓库下拉树结构 */
        getHouseTree() {
            listHouseTree().then((response) => {
                this.deptOptions = response.data
            })
        },
        //获取厂家
        supplierInfoList() {
            supplierInfoList().then((response) => {
                this.supplierList = response.rows
            })
        },
        //设备类型
        getTypeList() {
            getTypeList({ level: '2' }).then((response) => {
                this.itemList = response.data
            })
            // getTypeList({ level: '3' }).then((response) => {
            //     this.typeList = response.data
            // })
            // getTypeList({ level: '4' }).then((response) => {
            //     this.modelList = response.data
            // })
        },
        //选择物品种类
        selectItem(id) {
            console.log(id)
            this.queryParams.deviceId = ''
            this.queryParams.typeId = ''
            getListByMaType({ typeId: id }).then((response) => {
                this.typeList = response.data
            })
        },
        //选择设备类型
        selectDevice(id) {
            console.log(id)
            this.queryParams.typeId = ''
            getListByMaType({ typeId: id }).then((response) => {
                this.modelList = response.data
            })
        },
        /** 查询资产属性下拉 */
        getPropData() {
            getProLists().then((response) => {
                this.propList = response.rows
            })
        },
        /** 查询列表 */
        getList() {
            this.loading = true
            this.queryParams.beginTime = this.dateRange[0]
            this.queryParams.endTime = this.dateRange[1]
            listMachine(this.queryParams).then((response) => {
                this.devicesList = response.rows
                // this.devicesList[0].qrCode = "11212asdasd"
                this.total = response.total
                this.loading = false
            })
        },
        showQrCode(row) {
            console.log(row)
            if (row.qrCode == null) {
                this.$message.error('当前设备没有二维码')
                return
            }
            // this.labelCodeName = ''
            this.rowObj = row
            this.uploadOpen = true
            this.title = '二维码查看'
            this.qrCode = row.qrCode
            let str = this.qrUrl + row.qrCode
            this.$nextTick(() => {
                this.$refs.codeItem.innerHTML = ''
                var qrcode = new QRCode(this.$refs.codeItem, {
                    text: str, //二维码内容
                    width: 256,
                    height: 256,
                    colorDark: '#000000',
                    colorLight: '#ffffff',
                    correctLevel: QRCode.CorrectLevel.H,
                })
            }, 500)
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                maId: undefined,
                dictName: undefined,
                dictType: undefined,
                status: '0',
                remark: undefined,
            }
            this.resetForm('form')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = []
            this.typeList = []
            this.modelList = []
            this.resetForm('queryForm')
            this.handleQuery()
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset()
            this.open = true
            this.title = '新建'
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.maId)
            this.single = selection.length != 1
            this.multiple = !selection.length
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            const maId = row.maId || this.ids
            getMachine(maId).then((response) => {
                this.form = response.data
                this.open = true
                this.title = '编辑'
            })
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    if (this.form.maId != undefined) {
                        updateMachine(this.form).then((response) => {
                            this.$modal.msgSuccess('修改成功')
                            this.open = false
                            this.getList()
                        })
                    } else {
                        addMachine(this.form).then((response) => {
                            this.$modal.msgSuccess('新增成功')
                            this.open = false
                            this.getList()
                        })
                    }
                }
            })
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const maIds = row.maId
            this.$modal
                .confirm('是否确认删除所选择的数据项？')
                .then(function () {
                    return delMachine(maIds)
                })
                .then(() => {
                    this.getList()
                    this.$modal.msgSuccess('删除成功')
                })
                .catch(() => {})
        },
        /** 导出按钮操作 */
        handleExport() {
            // this.download('system/dict/type/export', {
            //   ...this.queryParams
            // }, `type_${new Date().getTime()}.xlsx`)
        },

        // iot设备绑定
        handleBindIOT(row) {
            console.log('🚀 ~ handleBindIOT ~ row:', row)
            this.props = {
                isShow: true,
                typeId: row.typeId,
                maCode: row.maCode,
            }
        },
        // 查看设备地图
        async handleMap(row) {
            this.deviceName = row.specificationType
            this.deviceType = row.maStatusName
            this.iotCode = row.iotCode

            this.mapDialogVisible = true
        },

        /** 关闭地图弹框 */
        handelCloseDialog() {
            this.mapDialogVisible = false
        },
    },
}
</script>
<style lang="scss" scoped>
.uploadImg {
    display: flex;
    align-items: center;
    justify-content: center;
}
.maCode {
    margin-top: 15px;
    font-size: 18px;
}

.location-icon {
    font-size: 20px;
    cursor: pointer;
    color: #409eff;
}
</style>
