<template>
    <div class="iot-product">
        <!-- 搜索栏 -->
        <el-card v-show="showSearch" class="card-search">
            <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px" class="search-form">
                <!-- 产品名称 -->
                <el-form-item prop="productName">
                    <el-input v-model="queryParams.productName" :placeholder="$t('product.index.091251-1')" clearable @keyup.enter.native="handleQuery" />
                </el-form-item>
                <!-- 分类名称 -->
                <el-form-item prop="categoryName">
                    <el-input v-model="queryParams.categoryName" :placeholder="$t('product.index.091251-3')" clearable @keyup.enter.native="handleQuery" />
                </el-form-item>
                <!-- 状态 -->
                <el-form-item prop="status">
                    <el-select v-model="queryParams.status" :placeholder="$t('product.index.091251-5')" clearable @keyup.enter.native="handleQuery">
                        <el-option v-for="dict in dict.type.iot_product_status" :key="dict.value" :label="dict.label" :value="dict.value" />
                    </el-select>
                </el-form-item>
                <div style="float: right">
                    <!-- 搜索，重置 -->
                    <el-button type="primary" icon="el-icon-search" @click="handleQuery">{{ $t('search') }}</el-button>
                    <el-button icon="el-icon-refresh" @click="resetQuery">{{ $t('reset') }}</el-button>
                </div>
            </el-form>
        </el-card>

        <el-card class="product-card">
            <el-row :gutter="10" class="product-header">
                <el-col :span="1.5">
                    <el-button type="primary" plain icon="el-icon-plus" size="small" @click="handleAddProduct" v-hasPermi="['iot:product:add']">{{ $t('add') }}</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button plain icon="el-icon-document-copy" size="small" @click="selectProduct" v-hasPermi="['iot:product:edit']">{{ $t('product.product-things-model.142341-92') }}</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button plain icon="el-icon-upload2" size="small" @click="handleImport" v-hasPermi="['iot:product:add']">{{ $t('import') }}</el-button>
                </el-col>
                <el-col :span="1.5" class="product-checkbox">
                    <el-checkbox v-model="queryParams.showSenior" @change="handleQuery">
                        <div class="el-checkbox__label">{{ $t('product.index.091251-8') }}</div>
                    </el-checkbox>
                    <el-tooltip :content="$t('product.index.091251-9')" placement="top"><i class="el-icon-question"></i></el-tooltip>
                </el-col>
                <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
            <!-- 产品卡片 -->
            <el-row :gutter="20" v-loading="loading">
                <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6" v-for="(item, index) in productList" :key="index" class="product-item">
                    <el-card :body-style="{ padding: '0px' }" shadow="always" style="border-radius: 8px" class="card-item">
                        <div class="item-title">
                            <div>
                                <el-image class="img" lazy :preview-src-list="[baseUrl + item.imgUrl]" :src="baseUrl + item.imgUrl" fit="cover" v-if="item.imgUrl != null && item.imgUrl != ''"></el-image>
                                <el-image class="img" :preview-src-list="[require('@/assets/images/gateway.png')]" :src="require('@/assets/images/gateway.png')" fit="cover" v-else-if="item.deviceType == 2"></el-image>
                                <el-image class="img" :preview-src-list="[require('@/assets/images/video.png')]" :src="require('@/assets/images/video.png')" fit="cover" v-else-if="item.deviceType == 3"></el-image>
                                <el-image class="img" :preview-src-list="[require('@/assets/images/product.png')]" :src="require('@/assets/images/product.png')" fit="cover" v-else></el-image>
                            </div>
                            <div class="title">
                                <div class="name" @click="handleEditProduct(item)">{{ item.productName }}</div>
                                <div class="tag">
                                    <el-tag type="info" size="mini" v-if="item.isSys == 1">{{ $t('product.index.091251-11') }}</el-tag>
                                    <el-tag type="info" size="mini" v-else>{{ item.tenantName }}</el-tag>
                                </div>
                            </div>
                            <div style="width: 45px"></div>
                            <div class="status">
                                <el-tooltip effect="dark" :content="$t('product.index.091251-12')" placement="top-start" v-if="item.status == 2">
                                    <el-button plain size="mini" class="btn-published" :disabled="item.isOwner === 0" @click="changeProductStatus(item.productId, 1, item.deviceType)">
                                        <svg-icon icon-class="check-circle-solid" />
                                        {{ $t('product.index.091251-13') }}
                                    </el-button>
                                </el-tooltip>
                                <el-tooltip class="item" effect="dark" :content="$t('product.index.091251-14')" placement="top-start" v-if="item.status == 1">
                                    <el-button type="info" size="mini" class="btn-unpublished" :disabled="item.isOwner === 0" @click="changeProductStatus(item.productId, 2, item.deviceType)">
                                        <svg-icon icon-class="exclamation-circle-solid" />
                                        {{ $t('product.index.091251-15') }}
                                    </el-button>
                                </el-tooltip>
                            </div>
                        </div>

                        <el-row :gutter="10">
                            <!-- 所属分类 -->
                            <el-col :span="12" class="card-item-desc" style="padding-left: 24px">
                                <el-descriptions :column="1" size="small" class="card-item-desc-item">
                                    <el-descriptions-item :label="$t('product.index.091251-16')">
                                        <el-link type="primary" :underline="false" class="product-category">
                                            {{ item.categoryName }}
                                        </el-link>
                                    </el-descriptions-item>
                                </el-descriptions>
                            </el-col>
                            <!-- 联网方式 -->
                            <el-col :span="12" class="card-item-desc" style="padding-right: 24px">
                                <el-descriptions :column="1" size="small" class="card-item-desc-item">
                                    <el-descriptions-item :label="$t('product.index.091251-18')">
                                        <dict-tag :options="dict.type.iot_network_method" :value="item.networkMethod" />
                                    </el-descriptions-item>
                                </el-descriptions>
                            </el-col>
                        </el-row>
                        <!-- 产品类型 -->
                        <el-row :gutter="10">
                            <el-col :span="12" style="padding-left: 24px">
                                <el-descriptions :column="1" size="small" class="card-item-desc-item">
                                    <el-descriptions-item :label="$t('product.index.091251-17')">
                                        <dict-tag :options="dict.type.iot_device_type" :value="item.deviceType" />
                                    </el-descriptions-item>
                                </el-descriptions>
                            </el-col>
                            <!-- 设备授权 -->
                            <el-col :span="12" style="padding-right: 24px">
                                <el-descriptions :column="1" size="small" class="card-item-desc-item">
                                    <el-descriptions-item :label="$t('product.index.091251-19')">
                                        <el-tag size="mini" v-if="item.isAuthorize == 1" class="tag-item-success">
                                            {{ $t('product.index.091251-20') }}
                                        </el-tag>
                                        <el-tag size="mini" v-else class="tag-item-error" style="color: #c0c4cc; border-radius: 2px; border: 1px solid #c0c4cc; background-color: #ffffff">
                                            {{ $t('product.index.091251-21') }}
                                        </el-tag>
                                    </el-descriptions-item>
                                </el-descriptions>
                            </el-col>
                        </el-row>
                        <!-- 分割线 -->
                        <el-divider class="divider" />

                        <div class="card-item-btns">
                            <!-- 查看详情-->
                            <el-button size="mini" type="text" @click="handleEditProduct(item)" v-hasPermi="['iot:product:query']">{{ $t('product.index.091251-22') }}</el-button>
                            <span class="btn-item-line" v-hasPermi="['iot:product:query']">|</span>
                            <!-- 查看设备-->
                            <el-button size="mini" type="text" @click="handleViewDevice(item.productId)" v-hasPermi="['iot:device:query']">{{ $t('product.index.091251-24') }}</el-button>
                            <span class="btn-item-line" v-hasPermi="['scada:center:share']" v-if="item.deviceType !== 3 && isShowScada == true">|</span>
                            <!-- 组态分享-->
                            <el-button v-if="item.deviceType !== 3 && isShowScada == true" size="mini" type="text" @click="handleScadaShare(item)" v-hasPermi="['scada:center:share']">
                                {{ $t('product.index.091251-42') }}
                            </el-button>
                            <span class="btn-item-line" v-hasPermi="['scada:center:edit']" v-if="item.deviceType !== 3 && isShowScada == true">|</span>
                            <!-- 组态设计 -->
                            <el-button v-if="item.deviceType !== 3 && isShowScada == true" size="mini" type="text" @click="handleGoToScada(item)" v-hasPermi="['scada:center:edit']">
                                {{ $t('product.index.091251-40') }}
                            </el-button>
                            <span class="btn-item-line" v-hasPermi="['iot:product:remove']" v-if="item.status == 1 && item.isOwner != 0">|</span>
                            <!-- 删除 -->
                            <el-button size="mini" type="text" @click="handleDelete(item)" v-hasPermi="['iot:product:remove']" v-if="item.status == 1 && item.isOwner != 0">
                                {{ $t('del') }}
                            </el-button>
                        </div>
                    </el-card>
                </el-col>
            </el-row>

            <el-empty :description="$t('product.index.091251-25')" v-if="total == 0"></el-empty>
            <pagination style="margin: 0 0 20px 0" v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" :pageSizes="[12, 24, 36, 60]" @pagination="getList" />
        </el-card>
        <!-- 下载SDK -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-link type="danger" style="padding-left: 10px" :underline="false">{{ $t('product.index.091251-26') }}</el-link>
            <el-form label-width="80px">
                <el-form-item :label="$t('product.index.091251-27')">
                    <el-radio-group v-model="form.datatype">
                        <el-radio v-for="dict in dict.type.iot_device_chip" :key="dict.value" :label="dict.value" style="margin-top: 15px; width: 160px">{{ dict.label }}</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="downloadSdk" disabled>{{ $t('product.index.091251-28') }}</el-button>
                <el-button @click="cancel">{{ $t('product.index.091251-29') }}</el-button>
            </div>
        </el-dialog>

        <el-dialog :title="uploadImport.title" :visible.sync="uploadImport.open" width="500px" append-to-body>
            <el-upload
                ref="uploadImport"
                :limit="1"
                accept=".json"
                :headers="uploadImport.headers"
                :action="uploadImport.url"
                :disabled="uploadImport.isUploading"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
                :before-upload="handleBeforeUpload"
                :auto-upload="false"
                drag
            >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                    {{ $t('dragFileTips') }}
                    <em>{{ $t('clickFileTips') }}</em>
                </div>
                <div class="el-upload__tip" style="color: red" slot="tip">{{ $t('scada.topoMain.320129-1') }}</div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">{{ $t('confirm') }}</el-button>
                <el-button @click="uploadImport.open = false">{{ $t('cancel') }}</el-button>
            </div>
        </el-dialog>
        <!-- 新增产品弹出层 -->
        <product-add ref="productAdd" />
        <!-- 产品列表弹出层 -->
        <product-list ref="productList" :productId="form.productId" :showSenior="queryParams.showSenior" @productEvent="getProductData($event)" />
        <!-- 组态分享对话框，组态特有 -->
        <!-- <scada-share-dialog ref="scadaShareDialog" :guid="scadaGuid" :type="1" :productId="productId" :visible.sync="isScadaShare"></scada-share-dialog> -->
    </div>
</template>

<script>
import { listProduct, delProduct, changeProductStatus, deviceCount, copyProduct } from '@/api/iot/product';
import { delSipconfigByProductId } from '@/api/iot/sipConfig';
import { checkPermi } from '@/utils/permission';
import defaultSettings from '@/settings';
import productList from '../device/product-list'; // 产品列表
import productAdd from './product-add'; // 产品列表
import { getToken } from '@/utils/auth';

// import ScadaShareDialog from '@/views/scada/common/ScadaShareDialog/index.vue'; // 组态特有

export default {
    name: 'Product',
    //组态特有
    components: {
        productList,
        productAdd,
        // ScadaShareDialog // 组态特有
    },
    dicts: ['iot_yes_no', 'iot_product_status', 'iot_device_type', 'iot_network_method', 'iot_vertificate_method', 'iot_device_chip'],
    data() {
        return {
            // 遮罩层
            loading: true,
            // 总条数
            total: 0,
            // 产品表格数据
            productList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 显示搜索条件
            showSearch: true,
            //组态相关按钮是否显示，true显示，false不显示
            isShowScada: defaultSettings.isShowScada,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 12,
                showSenior: true,
                productName: null,
                categoryId: null,
                categoryName: null,
                tenantId: null,
                tenantName: null,
                isSys: null,
                status: null,
                deviceType: null,
                networkMethod: null,
            },
            uploadImport: {
                open: false, // 是否显示弹出层（用户导入）
                title: '', // 弹出层标题（用户导入）
                isUploading: false, // 是否禁用上传
                updateSupport: 0, // 是否更新已经存在的用户数据
                headers: { Authorization: 'Bearer ' + getToken() }, // 设置上传的请求头部
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + '/iot/product/importJson',
            },
            fileType: ['json'],
            // 表单参数
            form: {},
            baseUrl: process.env.VUE_APP_BASE_API,
            isScadaShare: false, // 是否分享组态
            productId: null,
            scadaGuid: '', // 组态guid
        };
    },
    created() {
        this.getList();
    },
    activated() {
        const time = this.$route.query.t;
        if (time != null && time != this.uniqueId) {
            this.uniqueId = time;
            this.queryParams.pageNum = Number(this.$route.query.pageNum);
            this.getList();
        }
    },
    methods: {
        /** 查询产品列表 */
        getList() {
            this.loading = true;
            listProduct(this.queryParams).then((response) => {
                this.productList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 导入json
        handleImport() {
            this.uploadImport.title = '导入产品';
            this.uploadImport.open = true;
        },
        // 上传前校检格式
        handleBeforeUpload(file) {
            // 校检文件类型
            if (this.fileType) {
                const fileName = file.name.split('.');
                const fileExt = fileName[fileName.length - 1];
                const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
                if (!isTypeOk) {
                    this.$modal.msgError('文件格式不正确，请上传json文件！');
                    return false;
                } else {
                    return true;
                }
            }
        },
        // 文件上传中处理
        handleFileUploadProgress() {
            this.uploadImport.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess(res, file, fileList) {
            this.uploadImport.open = false;
            this.uploadImport.isUploading = false;
            this.$refs.uploadImport.clearFiles();
            this.$alert(res.msg, '导入结果', { dangerouslyUseHTMLString: true });
            this.importLoading = false;
            this.getList();
        },
        // 提交上传文件
        submitFileForm() {
            this.$refs.uploadImport.submit();
            this.importLoading = true;
        },
        //新增产品
        handleAddProduct() {
            this.$refs.productAdd.open = true;
            this.$refs.productAdd.reset();
        },
        /**选择产品 */
        selectProduct() {
            this.$refs.productList.queryParams.status = '';
            this.$refs.productList.open = true;
            this.$refs.productList.getList();
        },
        /**获取选中的产品 */
        getProductData(product) {
            const productId = product.productId;
            this.handleCopy(productId);
        },
        //选中产品后调用接口
        handleCopy(productId) {
            copyProduct(productId)
                .then((response) => {
                    this.$message.success(response.msg);
                })
                .catch(() => {});
            setTimeout(() => {
                this.getList();
            }, 2000);
        },
        /**同步获取产品下的设备数量**/
        getDeviceCountByProductId(productId) {
            return new Promise((resolve, reject) => {
                deviceCount(productId)
                    .then((res) => {
                        resolve(res);
                    })
                    .catch((error) => {
                        reject(error);
                    });
            });
        },
        /** 更新产品状态 */
        async changeProductStatus(productId, status, deviceType) {
            let message = this.$t('product.index.091251-30');
            if (status == 2) {
                // 发布
                let hasPermission = checkPermi(['iot:product:add']);
                if (!hasPermission) {
                    this.$modal.alertError(this.$t('product.index.091251-31'));
                    return;
                }
                message = this.$t('product.index.091251-32');
            } else if (status == 1) {
                // 取消发布
                let hasPermission = checkPermi(['iot:product:edit']);
                if (!hasPermission) {
                    this.$modal.alertError(this.$t('product.index.091251-31'));
                    return;
                }
                let result = await this.getDeviceCountByProductId(productId);
                if (result.data > 0) {
                    message = this.$t('product.index.091251-33', [result.data]);
                }
            }
            this.$confirm(message, this.$t('product.index.091251-34'), {
                confirmButtonText: this.$t('product.index.091251-35'),
                cancelButtonText: this.$t('product.index.091251-29'),
                type: 'warning',
            })
                .then(() => {
                    let data = {};
                    data.productId = productId;
                    data.status = status;
                    data.deviceType = deviceType;
                    changeProductStatus(data)
                        .then((response) => {
                            this.getList();
                            this.$modal.alertSuccess(response.msg);
                        })
                        .catch(() => {});
                })
                .catch(() => {});
        },
        /** 查看设备按钮操作 */
        handleViewDevice(productId) {
            this.$router.push({
                path: '/iot/device',
                query: {
                    t: Date.now(),
                    productId: productId,
                },
            });
        },
        // 组态设计
        handleGoToScada(row) {
            const { scadaId, guid, productId } = row;
            if (guid) {
                const routeUrl = this.$router.resolve({
                    path: '/scada/topo/editor',
                    query: {
                        id: scadaId,
                        guid: guid,
                        type: 1,
                    },
                });
                window.open(routeUrl.href, '_blank');
            } else {
                this.$router.push({
                    path: '/scada/center/temp',
                    query: {
                        productId: productId,
                    },
                });
            }
        },
        // 组态分享
        handleScadaShare(row) {
            if (row.guid) {
                this.isScadaShare = true;
                this.scadaGuid = row.guid;
                this.productId = row.productId;
            } else {
                this.$message({
                    type: 'warning',
                    message: this.$t('product.index.091251-41'),
                });
            }
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm');
            this.handleQuery();
        },
        /** 生成SDK */
        handleGeneratorSDK(row) {
            this.title = this.$t('product.index.091251-38');
            this.open = true;
        },
        /** 下载SDK */
        downloadSdk() {
            this.$download.zip('/iot/tool/genSdk?deviceChip=' + 1, 'fastbee-sdk');
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const productIds = row.productId || this.ids;
            let msg = '';
            this.$modal
                .confirm(this.$t('product.index.091251-39', [productIds]))
                .then(function () {
                    // 删除SIP配置
                    delSipconfigByProductId(productIds).then((response) => {});
                    return delProduct(productIds).then((response) => {
                        msg = response.msg;
                    });
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess(msg);
                })
                .catch(() => {});
        },
        /** 修改按钮操作 */
        handleEditProduct(row) {
            let productId = 0;
            if (row != 0) {
                productId = row.productId || this.ids;
            }
            this.$router.push({
                path: '/iot/product-edit',
                query: {
                    productId: productId,
                    pageNum: this.queryParams.pageNum,
                },
            });
        },
    },
};
</script>

<style lang="scss" scoped>
$border-color: #dcdfe6;
.iot-product {
    padding: 20px;

    .card-search {
        margin-bottom: 15px;
        width: 100%;
        border-radius: 8px;
        .search-form {
            margin-bottom: -18px;
            padding: 3px 0 0 0;
        }
    }
    .product-card {
        border-radius: 8px;
        .product-header {
            margin-bottom: 20px;

            .add-btn {
                background: rgba(72, 111, 242, 0.1);
                border-radius: 4px;
                border: 1px solid #486ff2;
                font-family: PingFangSC, PingFang SC;
                font-weight: 400;
                font-size: 12px;
                color: #486ff2;
                line-height: 17px;
                text-align: left;
                font-style: normal;
            }
            .product-checkbox {
                line-height: 32px;
                margin: 0px 10px;

                .el-checkbox__label {
                    color: #606266 !important;
                    font-size: 14px;
                    margin: 0px 5px 0 -10px;
                }
                .el-icon-question {
                    color: #909399;
                    font-size: 16px;
                }
            }
        }
    }
    .product-item {
        margin-bottom: 20px;
        text-align: center;
    }
    .card-item {
        background: #ffffff;
        border-radius: 8px;
        border: 1px solid #dcdfe6;

        .item-title {
            display: -webkit-box;
            flex-direction: row;
            align-items: center;
            position: relative;
            padding: 18px;

            .img {
                height: 58px;
                width: 58px;
                border-radius: 10px;
            }

            .title {
                flex: 1;
                text-align: left;
                margin-left: 16px;

                .name {
                    font-weight: 500;
                    font-size: 16px;
                    color: #303133;
                    line-height: 22px;
                    white-space: nowrap; /* 不换行 */
                    overflow: hidden; /* 隐藏超出部分 */
                    text-overflow: ellipsis; /* 使用省略号 */
                    cursor: pointer;
                }

                .tag {
                    margin-top: 5px;

                    span {
                        font-weight: 200;
                        border-radius: 2px;
                        border: 1px solid #c0c4cc;
                        background: #ffffff;
                    }
                }
            }

            .status {
                position: absolute;
                right: -1px;
                top: 24px;

                .btn-published {
                    padding: 3px !important;
                    background: rgba(103, 194, 58, 0.2);
                    color: #67c23a;
                    border-radius: 2px 0px 0px 2px;
                }

                ::v-deep .is-plain:hover {
                    border-color: transparent !important;
                }

                .btn-unpublished {
                    padding: 3px !important;
                    background: rgba(192, 196, 204, 0.2);
                    color: #c0c4cc;
                    border-radius: 2px 0px 0px 2px;
                    border: 1px solid #c0c4cc;
                }
            }
        }

        .card-item-desc {
            // 设备授权
            .card-item-desc-item {
                white-space: nowrap;
                .tag-item-success {
                    color: #67c23a;
                    border-radius: 2px;
                    border: 1px solid #67c23a;
                    background-color: #ffffff;
                }
                .tag-item-error {
                    color: #c0c4cc;
                    border-radius: 2px;
                    border: 1px solid #c0c4cc;
                    background-color: #ffffff;
                }
            }
        }
        // 所属分类
        .product-category {
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 13px;
            color: #486ff2;
            line-height: 18px;
            text-align: left;
            font-style: normal;
        }

        .divider {
            margin: 10px 0 0;
            height: 1px;
            background: #dcdfe6;
        }

        .card-item-btns {
            height: 40px;
            display: flex;
            font-size: 12px;
            align-items: center;
            justify-content: space-evenly;

            .btn-item-line {
                width: 1px;
                font-size: 16px;
                color: #dcdfe6;
            }
        }
    }
}
</style>
