<template>
    <div class="product normal-form" style="padding: 6px">
        <el-card style="margin: 20px">
            <el-form ref="queryForm" :inline="true" :model="queryParams" label-width="68px"
                style="margin-bottom: -20px">
                <el-form-item :label="$t('product.index.091251-0')" prop="productName">
                    <el-input v-model="queryParams.productName" :placeholder="$t('product.index.091251-1')" clearable
                        size="small" @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item :label="$t('product.index.091251-2')" prop="categoryName">
                    <el-input v-model="queryParams.categoryName" :placeholder="$t('product.index.091251-3')" clearable
                        size="small" @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item :label="$t('product.index.091251-4')" prop="status">
                    <el-select v-model="queryParams.status" :placeholder="$t('product.index.091251-5')" clearable
                        size="small">
                        <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>
                <el-form-item>
                    <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">{{
                        $t('product.index.091251-6') }}</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('product.index.091251-7')
                        }}</el-button>
                    <el-checkbox v-model="queryParams.showSenior" style="margin: 0px 10px" @change="handleQuery">{{
                        $t('product.index.091251-8') }}</el-checkbox>
                    <el-tooltip :content="$t('product.index.091251-9')" placement="top"><i
                            class="el-icon-info"></i></el-tooltip>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card class="main-card" shadow="never" style="margin: 20px">
            <div class="card-toolbar mb8">
                <el-button v-hasPermi="['iot:product:add']" type="primary" size="mini" icon="el-icon-plus"
                    @click="handleEditProduct(0)">{{ $t('add') }}</el-button>
                <el-radio-group v-model="showType" class="fr ml10" plain size="mini">
                    <el-radio-button label="card"><i class="el-icon-menu"></i></el-radio-button>
                    <el-radio-button label="list"><i class="el-icon-s-fold"></i></el-radio-button>
                </el-radio-group>
            </div>
            <template v-if="total > 0">
                <el-row v-if="showType == 'card'" v-loading="loading" type="flex" :gutter="30" style="flex-wrap: wrap">
                    <el-col v-for="(item, index) in productList" :key="index" :xs="24" :sm="12" :md="8" :lg="6" :xl="6"
                        style="margin-bottom: 30px; text-align: center">
                        <el-card :body-style="{ padding: '20px' }" shadow="hover" class="card-item">
                            <el-row type="flex" :gutter="10" justify="space-between">
                                <el-col :span="16" style="text-align: left">
                                    <el-link type="" :underline="false"
                                        style="font-weight: bold; font-size: 16px; line-height: 32px"
                                        @click="handleProductDetail(item)">
                                        <el-tooltip class="item" effect="dark" :content="$t('device.index.105953-38')"
                                            placement="top-start">
                                            <svg-icon v-if="item.isOwner != 1" class="mr5" icon-class="share"
                                                style="font-size: 20px; vertical-align: -6px" />
                                        </el-tooltip>
                                        <svg-icon v-if="item.isOwner == 1" icon-class="device" />
                                        <b class="card-item__title" @click="handleProductDetail(item)">{{
                                            item.productName }}</b>
                                        <el-tag type="info">{{ item.tenantName }}</el-tag>
                                    </el-link>
                                </el-col>
                                <el-col type="flex" :span="8">
                                    <li v-if="item.status == 2" class="table-status success" style="text-align: right">
                                        <span class="status-content">{{ $t('product.index.091251-13') }}</span>
                                    </li>
                                    <li v-else class="table-status" style="text-align: right"><span
                                            class="status-content">{{ $t('product.index.091251-15') }}</span></li>
                                </el-col>
                            </el-row>
                            <el-row :gutter="10">
                                <el-col :span="17">
                                    <el-descriptions :column="1" size="small"
                                        style="margin-top: 10px; white-space: nowrap">
                                        <el-descriptions-item :label="$t('product.index.091251-16')">
                                            <el-link type="primary" :underline="false">{{ item.categoryName }}</el-link>
                                        </el-descriptions-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-item :label="$t('product.product-edit.473153-16')">
                                            <dict-tag :options="dict.type.iot_network_method"
                                                :value="item.networkMethod" />
                                        </el-descriptions-item>
                                        <el-descriptions-item :label="$t('product.index.091251-19')">
                                            <el-tag v-if="item.isAuthorize == 1" type="success" size="mini">{{
                                                $t('product.index.091251-20') }}</el-tag>
                                            <el-tag v-else type="info" size="mini">{{ $t('product.index.091251-21')
                                                }}</el-tag>
                                        </el-descriptions-item>
                                    </el-descriptions>
                                </el-col>
                                <el-col :span="7">
                                    <div style="margin-top: 10px">
                                        <el-image v-if="item.imgUrl != null && item.imgUrl != ''"
                                            style="width: 100%; height: auto" lazy
                                            :preview-src-list="[baseUrl + item.imgUrl]" :src="baseUrl + item.imgUrl"
                                            fit="cover" />
                                        <el-image v-else-if="item.deviceType == 2" style="width: 100%; height: auto"
                                            :preview-src-list="[require('@/assets/images/gateway.svg')]"
                                            :src="require('@/assets/images/gateway.svg')" fit="cover" />
                                        <el-image v-else-if="item.deviceType == 3" style="width: 100%; height: auto"
                                            :preview-src-list="[require('@/assets/images/video.svg')]"
                                            :src="require('@/assets/images/video.svg')" fit="cover" />
                                        <el-image v-else style="width: 100%; height: auto"
                                            :preview-src-list="[require('@/assets/images/product.svg')]"
                                            :src="require('@/assets/images/product.svg')" fit="cover" />
                                    </div>
                                </el-col>
                            </el-row>
                            <div class="card-item__footer">
                                <el-button v-hasPermi="['iot:product:query']" size="mini" class="detail-btn"
                                    @click="handleEditProduct(item)">{{ $t('product.index.091251-22') }}</el-button>
                                <el-button v-if="item.status == 1 && item.isOwner != 0"
                                    v-hasPermi="['iot:product:remove']" size="mini" class="delete-btn"
                                    @click="handleDelete(item)">{{ $t('product.index.091251-23') }}</el-button>
                                <el-button v-if="item.status == 2 && item.isOwner != 0"
                                    v-hasPermi="['iot:product:edit']" size="mini" class="success-btn"
                                    :disabled="item.isAuthorize != 1" @click="handleDeviceAuthorize(item)">
                                    {{ $t('product.index.091251-19') }}
                                </el-button>
                                <el-button v-hasPermi="['iot:device:query']" size="mini" type="warning"
                                    @click="handleViewDevice(item.productId)">{{ $t('product.index.091251-24')
                                    }}</el-button>
                            </div>
                        </el-card>
                    </el-col>
                </el-row>
                <el-table v-else v-loading="loading" class="base-table" :data="productList" :border="false">
                    <el-table-column :label="$t('index.protocol.20250324-05')" align="center" header-align="center"
                        prop="productId" width="72">
                        <template #default="{ row }">
                            <el-image v-if="row.imgUrl != null && row.imgUrl != ''" style="width: 24px; height: 24px"
                                lazy :preview-src-list="[baseUrl + row.imgUrl]" :src="baseUrl + row.imgUrl"
                                fit="cover" />
                            <el-image v-else-if="row.deviceType == 2" style="width: 24px; height: 24px"
                                :preview-src-list="[require('@/assets/images/gateway.svg')]"
                                :src="require('@/assets/images/gateway.svg')" fit="cover" />
                            <el-image v-else-if="row.deviceType == 3" style="width: 24px; height: 24px"
                                :preview-src-list="[require('@/assets/images/video.svg')]"
                                :src="require('@/assets/images/video.svg')" fit="cover" />
                            <el-image v-else style="width: 24px; height: 24px"
                                :preview-src-list="[require('@/assets/images/product.svg')]"
                                :src="require('@/assets/images/product.svg')" fit="cover" />
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('index.protocol.20250324-04')" align="left" header-align="left"
                        prop="productName" min-width="120" />
                    <el-table-column :label="$t('product.index.091251-16')" align="left" prop="categoryName"
                        min-width="120" />
                    <el-table-column :label="$t('index.protocol.20250324-03')" align="left" prop="deviceType"
                        min-width="120">
                        <template #default="{ row }">
                            <dict-tag :options="dict.type.iot_device_type" :value="row.deviceType" />
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('product.index.091251-18')" align="left" prop="networkMethod"
                        min-width="120">
                        <template #default="{ row }">
                            <dict-tag :options="dict.type.iot_network_method" :value="row.networkMethod" />
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('product.index.091251-19')" align="center" prop="isAuthorize"
                        min-width="120">
                        <template #default="{ row }">
                            <el-tag v-if="row.isAuthorize == 1" type="success" size="mini">{{
                                $t('product.index.091251-20') }}</el-tag>
                            <el-tag v-else type="info" size="mini">{{ $t('product.index.091251-21') }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('index.protocol.20250324-02')" align="center" prop="status"
                        min-width="120">
                        <template #default="{ row }">
                            <li v-if="row.status == 2" class="table-status success"><span class="status-content">{{
                                $t('product.index.091251-13') }}</span></li>
                            <li v-else class="table-status"><span class="status-content">{{
                                $t('product.index.091251-15') }}</span></li>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('opation')" align="left" class-name="small-padding fixed-width"
                        fixed="right" width="300">
                        <template #default="{ row }">
                            <el-button v-hasPermi="['iot:product:query']" type="primary" plain style="padding: 5px"
                                @click="handleEditProduct(row)">{{ $t('product.index.091251-22') }}</el-button>
                            <el-button v-hasPermi="['iot:device:query']" type="primary" plain style="padding: 5px"
                                @click="handleViewDevice(row.productId)">{{ $t('product.index.091251-24') }}</el-button>
                            <el-button v-if="row.status == 2 && row.isOwner != 0" v-hasPermi="['iot:product:edit']"
                                type="success" plain style="padding: 5px" @click="handleDeviceAuthorize(row)">{{
                                    $t('product.index.091251-19') }}</el-button>
                            <el-button v-if="row.status == 1 && row.isOwner != 0" v-hasPermi="['iot:product:remove']"
                                type="danger" plain style="padding: 5px" @click="handleDelete(row)">{{
                                    $t('product.index.091251-23') }}</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </template>
            <el-empty v-else :description="$t('product.index.091251-25')"></el-empty>
            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize" :page-sizes="[12, 24, 36, 60]" @pagination="getList" />
            <!-- 下载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" disabled @click="downloadSdk">{{ $t('scada.echart.209302-6')
                        }}</el-button>
                    <el-button @click="cancel">{{ $t('product.product-edit.473153-71') }}</el-button>
                </div>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
import { listProduct, delProduct, changeProductStatus, deviceCount } from '@/api/iot/product';
import { delSipconfigByProductId } from '@/api/iot/sipConfig';
import { checkPermi } from '@/utils/permission';
import defaultSettings from '@/settings';
import { getToken } from "@/utils/auth";
import auth from '@/plugins/auth';
export default {
    name: 'Product',
    dicts: ['iot_yes_no', 'iot_product_status', 'iot_device_type', 'iot_network_method', 'iot_vertificate_method', 'iot_device_chip'],
    data() {
        return {
            openTemp: false,
            // 导入参数
            upload: {
                // 是否显示弹出层
                open: false,
                // 弹出层标题
                title: '',
                // 设置上传的请求头部
                headers: {
                    Authorization: 'Bearer ' + getToken(),
                },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + '/iot/product/temp',
            },
            // 遮罩层
            loading: true,
            // 总条数
            total: 0,
            // 产品表格数据
            productList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            //组态相关按钮是否显示，true显示，false不显示
            isShowScada: defaultSettings.isShowScada,
            showType: 'card',
            // 查询参数
            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,
            },
            // 表单参数
            form: {},
            baseUrl: process.env.VUE_APP_BASE_API,

        };
    },
    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: {
        /*导入模板*/
        importTemplate() {
            this.download('iot/product/temp-json', {}, `产品模板${new Date().getTime()}.xlsx`);
        },
        // 提交上传文件
        submitFileForm() {
            this.$refs.upload.submit();
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false;
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
            this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {
                dangerouslyUseHTMLString: true,
            });
            this.getList();
        },
        /** 查询产品列表 */
        getList() {
            this.loading = true;
            listProduct(this.queryParams).then((response) => {
                this.productList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        /**同步获取产品下的设备数量**/
        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-36'),
                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(() => {
                });
        },
        handleTemp() {
            this.openTemp = true;
        },
        /** 查看设备按钮操作 */
        handleViewDevice(productId) {
            this.$router.push({
                path: '/iotdev/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,
                    },
                });
            }
        },
        // 取消按钮
        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, 'yanfan-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: '/iotdev/iot/product-edit',
                query: {
                    productId: productId,
                    pageNum: this.queryParams.pageNum,
                },
            });
        },
        /** 设备授权操作 */
        // handleDeviceAuthorize(row) {
        //     let productId = row.productId;
        //     this.$router.push({
        //         path: '/iot/product-edit',
        //         query: {
        //             productId: productId,
        //             tabPanelName: 'productAuthorize',
        //             pageNum: this.queryParams.pageNum,
        //         },
        //     });
        // },
        // 点击名称查看
        handleProductDetail(item) {
            if (auth.hasPermi('iot:product:query')) {
                this.handleEditProduct(item);
            }
        },
    },
};
</script>

<style lang="scss" scoped>
.product {
    --font-grey: #606266;
    --success-color: #67c23b;
    padding: 20px;
    --primary-color: #0147eb;

    .search-form {
        .el-form-item {
            ::v-deep .el-form-item__label {
                font-weight: normal;
                color: var(--font-grey);
            }
        }
    }

    .el-table {
        ::v-deep .el-table__header th {
            color: #9a9da3;
            border-color: #f6f8fa;
            background-color: #f5f7fa;
        }

        ::v-deep .el-table__body .el-table__cell {
            color: #606266;
            padding: 8px 0;
            border-color: #f6f8fa;

            .el-button {
                border-color: transparent;
                background: transparent;

                &:hover {
                    &.el-button--danger {
                        color: #ff9999;
                    }

                    &.el-button--primary {
                        color: #91a8f8;
                    }
                }

                &.el-button {
                    margin-left: 2px;
                }
            }
        }
    }

    .pagination-container {
        ::v-deep .el-pagination {
            .el-pager li:not(.disabled).active {
                background-color: var(--primary-color);
            }
        }
    }

    .card-item {
        height: 100%;
        border-radius: 4px;
        background-image: linear-gradient(#e9f1fc, #fefefe);

        ::v-deep .el-card__body {
            display: flex;
            height: 100%;
            flex-direction: column;
            justify-content: space-between;
        }

        .card-item__title {
            vertical-align: -2px;
            margin-right: 0.5em;
        }

        .el-descriptions {
            ::v-deep .el-descriptions__body {
                background: transparent;
            }
        }

        .card-item__footer {
            margin-top: 1em;
            text-align: right;

            .el-button {
                background: #f5f7fa;
                border-color: #f5f7fa;
                color: #333;
                font-weight: bold;

                &.detail-btn {
                    color: var(--primary-color);
                }

                &.delete-btn {
                    color: #ff6363;
                }

                &.success-btn {
                    color: var(--success-color);
                }

                &:hover {
                    border-color: var(--primary-color);
                    color: var(--primary-color);
                }
            }
        }
    }
}
</style>
