<template>
	<div class="page bg page-full">
		<div class="content">
			<div class="cont_box" style="align-items: center;">
				<!-- 产品 -->
				<div class="title">{{ `${$t('message.device.product')}：${detail.name}` }}</div>
				<!-- <el-tag :type="developer_status == 1 ? 'success' : 'danger'" style="margin:0 20px;">{{ developer_status == 1 ? '已发布' : '未发布' }}</el-tag> -->
				<el-switch v-auth="'startOrStop'" style="margin:0 20px;" v-model="developer_status" inline-prompt :active-value="1" :inactive-value="0" :active-text="$t('message.device.productDetail.enable')" :inactive-text="$t('message.device.productDetail.disable')" @change="CkOption"></el-switch>
			</div>
		</div>

		<el-tabs v-model="activeName" style="padding: 0 20px;" @tab-click="handleClick">
			<!-- 产品信息 -->
			<el-tab-pane :label="$t('message.device.productDetail.productInfo')" name="1">
				<div class="pro-box">
					<div class="protitle">{{$t('message.device.productDetail.productInfo')}}</div>
					<!-- 编辑 -->
					<el-button type="" :icon="Edit" class="buttonedit" v-auth="'edit'" @click="onOpenEditDic(detail)">{{ $t('message.tableI18nAction.edit') }}</el-button>
				</div>

				<el-descriptions class="margin-top" :column="3" border>
					<!-- 产品标识 -->
					<el-descriptions-item :label="$t('message.device.productDetail.productIdentifier')"><copy :text="detail.key"></copy></el-descriptions-item>
					<!-- 产品分类 -->
					<el-descriptions-item :label="$t('message.device.productDetail.productCategory')">{{ detail.categoryName }}</el-descriptions-item>
					<!-- 设备类型 -->
					<el-descriptions-item :label="$t('message.device.productDetail.deviceType')">{{ detail.deviceType }}</el-descriptions-item>
					<!-- 产品图片 -->
					<el-descriptions-item :label="$t('message.device.productDetail.productImage')">
						<el-image style="width: 80px; height: 80px" :src="detail.icon" :previewSrcList="[detail.icon]" fit="contain">
							<template #error>
								<div class="image-slot">
									<ele-Picture style="width: 30px;" />
									<!-- 加载失败 -->
									{{ $t('message.device.productDetail.loadFailed') }}
								</div>
							</template>
						</el-image>
					</el-descriptions-item>
					<!-- 消息协议 -->
					<el-descriptions-item :label="$t('message.device.productDetail.messageProtocol')">{{ detail.messageProtocol }}</el-descriptions-item>
					<!-- 接入方式 -->
					<el-descriptions-item :label="$t('message.device.tableI18nColumn.transportProtocol')">{{ detail.transportProtocol }}</el-descriptions-item>
					<!-- 描述 -->
					<el-descriptions-item :label="$t('message.tableI18nColumn.des')">{{ detail.desc }}</el-descriptions-item>
				</el-descriptions>
			</el-tab-pane>
			<!-- 物模型 -->
			<el-tab-pane :label="$t('message.device.productDetail.thingModel')" name="2">
				<el-tabs type="border-card" v-model="activetab" @tab-click="wuhandleClick">
					<!-- 属性定义 -->
					<el-tab-pane :label="$t('message.device.productDetail.propertyDefinition')" name="attr">
						<div class="wu-title">
							<div class="title">{{$t('message.device.productDetail.propertyDefinition')}}</div>
							<!-- 新增 -->
							<div>
								<el-button size="small" type="primary" v-auth="'edit'" @click="onOpenEditAttr()">{{$t('message.tableI18nAction.add')}}</el-button>
							</div>
						</div>

						<el-table style="width: 100%" :data="tableData.data" v-loading="tableData.loading" v-if="activetab == 'attr'">
							<!-- 属性标识 -->
							<el-table-column :label="$t('message.device.productDetail.propertyIdentifier')" align="center" prop="key" />
							<!-- 属性名称 -->
							<el-table-column :label="$t('message.device.productDetail.propertyName')" prop="name" show-overflow-tooltip />
							<!-- 数据类型 -->
							<el-table-column prop="valueType" :label="$t('message.device.productDetail.dataType')" width="100" align="center">
								<template #default="scope">
									<span>{{ scope.row.valueType.type }}</span>
								</template>
							</el-table-column>
							<!-- 精度 -->
							<el-table-column prop="decimals" :label="$t('message.device.productDetail.precision')" :width="currentLang == 'en' ? '100' : '60'" align="center">
								<template #default="scope">
									<span>{{ scope.row.valueType.decimals }}</span>
								</template>
							</el-table-column>
							<!-- 单位 -->
							<el-table-column prop="unit" :label="$t('message.device.productDetail.unit')" width="60" align="center">
								<template #default="scope">
									<span>{{ scope.row.valueType.unit }}</span>
								</template>
							</el-table-column>
							<!-- 是否只读 -->
							<el-table-column prop="accessMode" :label="$t('message.device.productDetail.readOnly')" width="120" align="center">
								<template #default="scope">
									<!-- 只读 -->
									<el-tag type="info" size="small" v-if="scope.row.accessMode">{{ $t('message.device.productDetail.readonly') }}</el-tag>
									<!-- 读写 -->
									<el-tag type="success" size="small" v-else>{{ $t('message.device.productDetail.readWrite') }}</el-tag>
								</template>
							</el-table-column>
							<!-- 说明 -->
							<el-table-column :label="$t('message.device.productDetail.remark')" prop="desc" show-overflow-tooltip />
							<!-- 操作 -->
							<el-table-column :label="$t('message.tableI18nColumn.operation')" width="120" align="center" fixed="right">
								<template #default="scope">
									<el-button size="small" text type="warning" v-auth="'edit'" @click="onEditAttr(scope.row)">{{ $t('message.tableI18nAction.edit') }}</el-button>
									<el-button size="small" text type="danger" v-auth="'del'" @click="onRowDel(scope.row.key, 'attr')">{{ $t('message.tableI18nAction.delete') }}</el-button>
								</template>
							</el-table-column>
						</el-table>
					</el-tab-pane>
					<!-- 功能定义 -->
					<el-tab-pane :label="$t('message.device.productDetail.functionDefinition')" name="fun">
						<div class="wu-title">
							<div class="title">{{$t('message.device.productDetail.functionDefinition')}}</div>
							<!-- 新增 -->
							<div>
								<el-button size="small" type="primary" v-auth="'add'" @click="onOpenEditFun()">{{$t('message.tableI18nAction.add')}}</el-button>
							</div>
						</div>

						<el-table style="width: 100%" :data="tableData.data" v-if="activetab == 'fun'">
							<el-table-column :label="$t('message.device.productDetail.functionIdentifier')" align="center" prop="key" />
							<el-table-column :label="$t('message.device.productDetail.name')" prop="name" show-overflow-tooltip />
							<!-- 描述 -->
							<el-table-column :label="$t('message.tableI18nColumn.des')" prop="desc" show-overflow-tooltip />
							<!-- 操作 -->
							<el-table-column :label="$t('message.tableI18nColumn.operation')" width="120" align="center" fixed="right">
								<template #default="scope">
									<!-- 编辑 -->
									<el-button size="small" text type="warning" v-auth="'edit'" @click="onEditFun(scope.row)">{{ $t('message.tableI18nAction.edit') }}</el-button>
									<!-- 删除 -->
									<el-button size="small" text type="danger" v-auth="'del'" @click="onRowDel(scope.row.key, 'fun')">{{ $t('message.tableI18nAction.delete') }}</el-button>
								</template>
							</el-table-column>
						</el-table>
					</el-tab-pane>
					<!-- 事件定义 -->
					<el-tab-pane :label="$t('message.device.productDetail.eventDefinition')" name="event">
						<div class="wu-title">
							<div class="title">{{$t('message.device.productDetail.eventDefinition')}}</div>
							<div>
								<el-button size="small" type="primary" v-auth="'add'" @click="onOpenEditEvent()">{{$t('message.tableI18nAction.add')}}</el-button>
							</div>
						</div>

						<el-table style="width: 100%" :data="tableData.data" v-if="activetab == 'event'">
							<!-- 事件标识 -->
							<el-table-column :label="$t('message.device.productDetail.eventIdentifier')" align="center" prop="key" />
							<!-- 事件名称 -->
							<el-table-column :label="$t('message.device.productDetail.name')" prop="name" show-overflow-tooltip />
							<!-- 事件级别 -->
							<el-table-column prop="level" :label="$t('message.device.productDetail.eventLevel')" width="120" align="center">
								<template #default="scope">
									<!-- 普通 -->
									<el-tag size="small" v-if="scope.row.level == 0">{{ $t('message.device.productDetail.normal') }}</el-tag>
									<!-- 警告 -->
									<el-tag type="warning" size="small" v-if="scope.row.level == 1">{{ $t('message.device.productDetail.warning') }}</el-tag>
									<!-- 紧急 -->
									<el-tag type="danger" size="small" v-if="scope.row.level == 2">{{ $t('message.device.productDetail.urgent') }}</el-tag>
								</template>
							</el-table-column>
							<!-- 描述 -->
							<el-table-column :label="$t('message.tableI18nColumn.des')" prop="desc" show-overflow-tooltip />
							<!-- 操作 -->
							<el-table-column :label="$t('message.tableI18nColumn.operation')" width="120" align="center" fixed="right">
								<template #default="scope">
									<!-- 编辑 -->
									<el-button size="small" text type="warning" v-auth="'edit'" @click="onEditEvent(scope.row)">{{ $t('message.tableI18nAction.edit') }}</el-button>
									<!-- 删除 -->
									<el-button size="small" text type="danger" v-auth="'del'" @click="onRowDel(scope.row.key, 'event')">{{ $t('message.tableI18nAction.delete') }}</el-button>
								</template>
							</el-table-column>
						</el-table>
					</el-tab-pane>
					<!-- 标签定义 -->
					<el-tab-pane :label="$t('message.device.productDetail.tagDefinition')" name="tab">
						<div class="wu-title">
							<!-- 标签定义 -->
							<div class="title">{{ $t('message.device.productDetail.tagDefinition') }}</div>
							<!-- 添加 -->
							<div>
								<el-button size="small" type="primary" v-auth="'add'" @click="onOpenEditTab()">{{ $t('message.tableI18nAction.add') }}</el-button>
							</div>
						</div>

						<el-table style="width: 100%" :data="tableData.data" v-if="activetab == 'tab'">
							<!-- 标签标识 -->
							<el-table-column :label="$t('message.device.productDetail.propertyIdentifier')" align="center" prop="key" />
							<!-- 属性名称 -->
							<el-table-column :label="$t('message.device.productDetail.propertyName')" prop="name" show-overflow-tooltip />
							<!-- 数据类型 -->
							<el-table-column prop="valueType" :label="$t('message.device.productDetail.dataType')" width="120" align="center">
								<template #default="scope">
									<span>{{ scope.row.valueType.type }}</span>
								</template>
							</el-table-column>
							<!-- 是否只读 -->
							<el-table-column prop="accessMode" :label="$t('message.device.productDetail.readOnly')" width="120" align="center">
								<template #default="scope">
									<!-- 只读 -->
									<el-tag type="info" size="small" v-if="scope.row.accessMode">{{ $t('message.device.productDetail.readonly') }}</el-tag>
									<!-- 读写 -->
									<el-tag type="success" size="small" v-else>{{ $t('message.device.productDetail.readWrite') }}</el-tag>
								</template>
							</el-table-column>
							<!-- 描述 -->
							<el-table-column :label="$t('message.tableI18nColumn.des')" prop="desc" show-overflow-tooltip />
							<!-- 操作 -->
							<el-table-column :label="$t('message.tableI18nColumn.operation')" width="120" align="center" fixed="right">
								<template #default="scope">
									<!-- 编辑 -->
									<el-button size="small" text type="warning" v-auth="'edit'" @click="onEditTag(scope.row)">{{ $t('message.tableI18nAction.edit') }}</el-button>
									<!-- 删除 -->
									<el-button size="small" text type="danger" v-auth="'del'" @click="onRowDel(scope.row.key, 'tab')">{{ $t('message.tableI18nAction.delete') }}</el-button>
								</template>
							</el-table-column>
						</el-table>
					</el-tab-pane>
				</el-tabs>
				<div class="import">
					<div class="row_bet">
						<el-upload accept="json" :show-file-list="false" :limit="1" :data="{ productKey: detail.key }" :headers="headers" :action="uploadUrl" :on-success="updateImg">
							<!-- 导入物模型 -->
							<el-button size="small">
								<el-icon> <ele-Upload /> </el-icon>
								{{ $t('message.device.productDetail.importModel') }}
							</el-button>
						</el-upload>
						<!-- 导出物模型 -->
						<el-button size="small" type="default" class="ml10" @click="onRowExport()">
							<el-icon>
								<ele-Download />
							</el-icon>
							{{ $t('message.device.productDetail.exportModel') }}
						</el-button>
					</div>
				</div>
				<pagination v-show="tableData.total > 0" :total="tableData.total" v-model:page="tableData.param.pageNum" v-model:limit="tableData.param.pageSize" @pagination="getList()" />
			</el-tab-pane>
			<!-- 设备接入 -->
			<el-tab-pane :label="$t('message.device.productDetail.deviceAccess')" name="3">
				<deviceIn></deviceIn>
			</el-tab-pane>
			<!-- 数据解析 -->
			<el-tab-pane :label="$t('message.device.productDetail.dataParsing')" name="4" lazy>
				<dataParse v-if="activeName === '4'" :script="detail.scriptInfo" @updateScript="updateScript">
				</dataParse>
			</el-tab-pane>
		</el-tabs>
		<EditDic ref="editDicRef" @typeList="productDetail" />
		<EditAttr ref="editAttrRef" @typeList="getproperty" />
		<EditFun ref="editFunRef" @typeList="getfunction" />
		<EditEvent ref="editEventRef" @typeList="getevent" />
		<EditTab ref="editTabRef" @typeList="gettab" />
	</div>
</template>
<script lang="ts" setup>
import { toRefs, reactive, onMounted, ref, defineComponent, computed } from 'vue';
import { Edit } from '@element-plus/icons-vue';
import { ElMessageBox, ElMessage, FormInstance } from 'element-plus';
import downloadFile from '/@/utils/download';
import getOrigin from '/@/utils/origin';
import { useI18n } from 'vue-i18n';

import EditDic from './component/editPro.vue';
import deviceIn from './component/deviceIn.vue';
import dataParse from './component/dataParse.vue';
import EditAttr from './component/editAttr.vue';
import EditFun from './component/editFun.vue';
import EditEvent from './component/editEvent.vue';
import EditTab from './component/editTab.vue';
import { getToken } from "/@/utils/auth";
import { useRoute } from 'vue-router';

import api from '/@/api/device';

const { locale } = useI18n();

const currentLang = computed(() => locale.value);

// interface TableDataState {
// 	isShowDialog: boolean;
// 	detail: any;
// 	developer_status: number;
// 	activeName: string;
// 	activetab: string;
// 	tableData: {
// 		data: [];
// 		total: number;
// 		loading: boolean;
// 		param: {
// 			pageNum: number;
// 			pageSize: number;
// 			name: string;
// 			productKey: string | string[];
// 			deviceType: string;
// 			status: string;
// 			dateRange: string[];
// 		} | any;
// 	};
// }
// export default defineComponent({
// 	name: 'deviceEditPro',
// 	components: { EditDic, EditAttr, EditFun, EditEvent, EditTab, deviceIn, dataParse },

// 	setup(prop, context) {

		const uploadUrl: string = getOrigin("/product/tsl/import");
		const headers = {
			Authorization: 'Bearer ' + getToken(),
		};
		const route = useRoute();
		const editDicRef = ref();
		const editAttrRef = ref();
		const editFunRef = ref();
		const editEventRef = ref();
		const editTabRef = ref();
		const activeName = ref('1');// 分类数据
		const activetab = ref('attr');// 分类数据
		const detail = ref<any>({});
		const developer_status = ref(0);
		const tableData = ref({
			data: [],
			total: 0,
			loading: false,
			param: {
				pageNum: 1,
				productKey: route.params?.id,
				pageSize: 20,
				status: '',
				dateRange: [],
			},
		});

		onMounted(() => {
			productDetail()
			//第一次加载
			api.model.property(tableData.value.param).then((res: any) => {
				tableData.value.data = res.Data;
				tableData.value.total = res.Total;
			});
		});
		function productDetail() {
			const productKey = route.params?.id;
			api.product.detail(productKey).then((res: any) => {
				detail.value = res.data;
				developer_status.value = res.data.status
			});
		}


		//编辑属性
		const onEditAttr = (row: any) => {
			editAttrRef.value.openDialog(row, route.params.id);
		};

		//编辑功能
		const onEditFun = (row: any) => {
			editFunRef.value.openDialog(row, route.params.id);
		}


		//编辑事件
		const onEditEvent = (row: any) => {
			editEventRef.value.openDialog(row, route.params.id);
		}

		//编辑标签
		const onEditTag = (row: any) => {
			editTabRef.value.openDialog(row, route.params.id);
		}

		//打开添加属性弹窗
		const onOpenEditAttr = () => {
			editAttrRef.value.openDialog({ productKey: route.params.id, id: 0, accessMode: 1 });
		};

		//打开添加功能弹窗
		const onOpenEditFun = () => {
			editFunRef.value.openDialog({ productKey: route.params.id, id: 0 });
		};
		//打开添加事件弹窗
		const onOpenEditEvent = () => {
			editEventRef.value.openDialog({ productKey: route.params.id, id: 0, level: 0 });
		};

		//打开添加事件弹窗
		const onOpenEditTab = () => {
			editTabRef.value.openDialog({ productKey: route.params.id, id: 0, accessMode: 1 });
		};

		// 打开修改产品弹窗
		const onOpenEditDic = (row: any) => {
			editDicRef.value.openDialog(row);
		};


		// 删除产品
		const onRowDel = (key: string, type: string) => {
			let msg = `此操作将永久删除该数据，是否继续?`;

			if (key.length === 0) {
				ElMessage.error('请选择要删除的数据。');
				return;
			}
			ElMessageBox.confirm(msg, '提示', {
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(() => {
					const productKey = route.params?.id as string
					if (type == 'attr') {
						api.model.propertydel(productKey, key).then(() => {
							ElMessage.success('删除成功');
							getproperty();
						});
					}
					if (type == 'fun') {
						api.model.functiondel(productKey, key).then(() => {
							ElMessage.success('删除成功');
							getfunction();
						});
					}
					if (type == 'event') {
						api.model.eventdel(productKey, key).then(() => {
							ElMessage.success('删除成功');
							getevent();
						});
					}
					if (type == 'tab') {
						api.model.tagdel(productKey, key).then(() => {
							ElMessage.success('删除成功');
							gettab();
						});
					}
				})
				.catch(() => { });
		};


		//根据不同类型获取列表
		const getList = () => {
			switch (activetab.value) {
				case 'attr':
					getproperty();
					break;
				case 'fun':
					getfunction();
					break;
				case 'event':
					getevent();
					break;
				case 'tab':
					gettab();
					break;
			}
		};

		const getproperty = () => {
			api.model.property(tableData.value.param).then((res: any) => {
				tableData.value.data = res.Data;
				tableData.value.total = res.Total;
			});
		};

		const getfunction = () => {
			api.model.function(tableData.value.param).then((res: any) => {
				tableData.value.data = res.Data;
				tableData.value.total = res.Total;
			});
		};
		const getevent = () => {
			api.model.event(tableData.value.param).then((res: any) => {
				tableData.value.data = res.Data;
				tableData.value.total = res.Total;
			});
		};

		const gettab = () => {
			api.model.tag(tableData.value.param).then((res: any) => {
				tableData.value.data = res.Data;
				tableData.value.total = res.Total;
			});
		};

		const wuhandleClick = (tab: any) => {
			activetab.value = tab.props.name;
			switch (tab.props.name) {
				case 'attr':
					getproperty();
					break;
				case 'fun':
					getfunction();
					break;
				case 'event':
					getevent();
					break;
				case 'tab':
					gettab();
					break;
			}
		};

		const handleClick = (tab: any, event: Event) => {
		};

		const updateScript = (scriptInfo: string) => {
			detail.value.scriptInfo = scriptInfo
		};

		const CkOption = (developerStatus: number) => {
			if (developerStatus == 0) {
				api.product.undeploy(route.params.id).then((res: any) => {
					ElMessage.success('操作成功');
					developer_status.value = 0;
				}).catch(() => developer_status.value = 1)
			} else {
				api.product.deploy(route.params.id).then((res: any) => {
					ElMessage.success('操作成功');
					developer_status.value = 1;
				}).catch(() => developer_status.value = 0)
			}
		}

		// 导出
		const onRowExport = () => {

			api.product.export({ productKey: detail.value.key }).then((res: any) => downloadFile(res, "TSL-" + detail.value.key + "-" + getCurrentTime() + ".json"))
		};


		const getCurrentTime = () => {
			const date = new Date();
			const year = date.getFullYear().toString();
			const month = (date.getMonth() + 1).toString().padStart(2, '0');
			const day = date.getDate().toString().padStart(2, '0');
			const hours = date.getHours().toString().padStart(2, '0');
			const minutes = date.getMinutes().toString().padStart(2, '0');
			return year + month + day + hours + minutes;
		}
		const updateImg = (res: any) => {
			if (res.code === 0) {
				getList();
				ElMessage.success('物模型导入成功');
			} else {
				ElMessage.error(res.message);
			}
		};

// 		return {
// 			updateImg,
// 			headers,
// 			uploadUrl,
// 			getCurrentTime,
// 			onRowExport,
// 			Edit,
// 			updateScript,
// 			editDicRef,
// 			editAttrRef,
// 			editFunRef,
// 			editEventRef,
// 			editTabRef,
// 			CkOption,
// 			onRowDel,
// 			onEditFun,
// 			onEditEvent,
// 			onEditTag,
// 			onEditAttr,
// 			getList,
// 			getproperty,
// 			getfunction,
// 			getevent,
// 			gettab,
// 			wuhandleClick,
// 			onOpenEditTab,
// 			onOpenEditEvent,
// 			productDetail,
// 			onOpenEditAttr,
// 			onOpenEditFun,
// 			onOpenEditDic,
// 			handleClick,
// 			...toRefs(state),
// 		};
// 	},
// });
</script>
<style scoped>
.import {
	position: absolute;
	top: 8px;
	right: 12px;
}

.import .row_bet {
	display: flex;
	flex-direction: row;
	align-items: center;
	flex: 1;
}

.content {
	width: 100%;
	padding: 20px;
}

.cont_box {
	display: flex;
}

.cont_box .title {
	font-size: 24px;
}

.cont_box .pro-status {
	line-height: 40px;
	margin-left: 30px;
}

.cont_box .pro-status .on {
	background: #52c41a;
}

.cont_box .pro-status .off {
	background: #c41a1a;
}

.cont_box .pro-status span {
	position: relative;
	top: -1px;
	display: inline-block;
	width: 6px;
	height: 6px;
	vertical-align: middle;
	border-radius: 50%;
	margin-right: 5px;
}

.cont_box .pro-option {
	line-height: 40px;
	margin-left: 10px;
	color: #1890ff;
	cursor: pointer;
}

.pro-box {
	display: flex;
	padding: 10px;
	align-items: center;
}

.pro-box .protitle {
	font-size: 18px;
	font-weight: bold;
	line-height: 35px;
}

.pro-box .buttonedit {
	border: 0px;
	color: #1890ff;
}

.wu-title {
	display: flex;
	flex-direction: row;
	justify-content: space-between;
	padding: 20px;
	border-bottom: #e8e8e8 1px solid;
}

.wu-title .title {
	font-size: 18px;
}
</style>


