<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="90px">
            <el-form-item label="传感器名称" prop="sensorName">
                <el-input v-model="queryParams.sensorName" placeholder="请输入传感器名称" clearable
                    @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索
                </el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
				<el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
				<el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
            </el-form-item>
			
        </el-form>
        <!-- <el-row :gutter="10" class="mb8">
            <el-col :span="1.5" v-hasPermi="['certificate:certificate:add']">
                <el-button type="primary" plain icon="Plus" @click="handleAdd">新增
                </el-button>
            </el-col>
            <el-col :span="1.5" v-hasPermi="['certificate:certificate:edit']">
                <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改
                </el-button>
            </el-col>
            <el-col :span="1.5" v-hasPermi="['certificate:certificate:remove']">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除
                </el-button>
            </el-col>
            <el-col :span="1.5" v-hasPermi="['certificate:certificate:export']">
                <el-button type="warning" plain icon="Download" @click="handleExport">导出
                </el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row> -->

        <el-card shadow="never" :body-style="{padding: '0px'}">
            <el-table v-loading="loading" :data="sensorList" 
				:header-cell-style="{ color: 'var(--white)',background: '#30B08E' }"
				@selection-change="handleSelectionChange">
                <el-table-column label="序号" align="center" type="index" width="50" />
				<el-table-column type="expand" width="30">
				    <template #default="scope">
				        <div class="padding">
							<template  v-for="(siten,sind) in scope.row.measurements" :key="sind">
								<el-descriptions :column="4" border>
									<el-descriptions-item label="类型名称：" width="12.5%">
										{{scope.row.measurementsDescription[sind]}}
									</el-descriptions-item>
									<el-descriptions-item label="字符类型：" width="12.5%">
										{{scope.row.measurementsDataType[sind]}}
									</el-descriptions-item>
									<el-descriptions-item label="字段名称：" width="12.5%">
										{{siten}}
									</el-descriptions-item>
									<el-descriptions-item label="单位：" width="12.5%">
										{{scope.row.unit[sind]}}
									</el-descriptions-item>
								</el-descriptions>
							</template>
						</div>
					</template>
				</el-table-column>
                <el-table-column label="编号" align="center" prop="sensorId" show-overflow-tooltip />
				<el-table-column label="传感器名称" align="center" prop="sensorName" width="100"></el-table-column>
                <el-table-column label="传感器路径" align="center" prop="sensorPath"/>
				<el-table-column label="传感器全路径" align="center" prop="sensorFullPath"/>
				<el-table-column label="单位" align="center" prop="unit">
					 <template #default="scope">
						{{scope.row.unit[0]}}
					</template>
				</el-table-column>
                <el-table-column label="焚烧炉" align="center" prop="incineratorSn">
					<template #default="scope">
						<TextTag :options="incineOptions" column="incineratorSn" label="incineratorName" :value="scope.row.incineratorSn" />
					</template>
				</el-table-column>
                <el-table-column label="备注" align="center" prop="remark" />
					
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200"
                    fixed="right">
                    <template #default="scope">
                        <el-button link type="success" icon="Edit" @click="handleUpdate(scope.row)">
							修改
                        </el-button>
                        <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">
							删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

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

        <!-- 添加或修改证书对话框 -->
        <el-dialog :title="title" v-model="open" width="50%" append-to-body>
            <el-form ref="sensorRef" :model="form" :rules="rules" label-width="120px">
				<el-form-item label="焚烧炉" prop="incineratorSn">
					<el-select v-model="form.incineratorSn" placeholder="请选择" @change="changeIncine" style="width:100%;">
						<template v-for="item in incineOptions" :key="item.id">
							<el-option :label="item.incineratorName" :value="item.incineratorSn"></el-option>
						</template>
					</el-select>
				</el-form-item>
                <el-form-item label="传感器名称" prop="sensorName">
                    <el-input v-model="form.sensorName" placeholder="请输入传感器名称" />
                </el-form-item>
				<el-form-item label="传感器路径" prop="sensorPath">
				    <el-input v-model="form.sensorPath" placeholder="请输入传感器路径" />
				</el-form-item>
				<el-form-item label="传感器全路径" prop="sensorFullPath">
					<template #label>
						<span>
							<el-tooltip content="路径根据焚烧炉查询" placement="top">
								<el-icon>
									<question-filled />
								</el-icon>
							</el-tooltip>传感器路径
						</span>
					</template>
					<el-select v-model="form.sensorFullPath" placeholder="请选择传感器全路径" @change="changeFullPath" style="width:100%;">
						<template v-for="item in pathOptions" :key="item">
							<el-option :label="item" :value="item"></el-option>
						</template>
					</el-select>
				</el-form-item>
				<!-- <el-form-item label="单位" prop="unit" v-if="form.measurements.length<2">
				    <el-input v-model="form.unit[0]" placeholder="请输入单位" />
				</el-form-item> -->
				<el-form-item label="参数" prop="unit">
					<template v-for="(fiten,find) in form.measurementsDataType" :key="find">
						<div class="grid col-4 margin-bottom-xs">
							<el-input class="padding-right-sm" v-model="form.measurementsDescription[find]" placeholder="请输入名称" />
							<div>
								<el-select v-model="form.measurementsDataType[find]" placeholder="请选择" style="width:100%;">
									<el-option :label="citem.label" :value="citem.value" v-for="citem in character_type" :key="citem.value"></el-option>
								</el-select>
							</div>
							<!-- <el-input v-model="form.measurementsDataType[find]" placeholder="字符类型" /> -->
							<el-input class="padding-lr-sm" v-model="form.measurements[find]" placeholder="字段名称" />
							<el-input v-model="form.unit[find]" placeholder="请输入单位" />
						</div>
					</template>
				</el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Certificate">
import { listSensor, getSensor, getSensorByIncine, updateSensor, addSensor, delSensor, downloadSensor, getTimeSeries } from "@/api/Incinerator/sensorApi";
import { listIncinerator } from "@/api/Incinerator/incineratorApi";
const { proxy } = getCurrentInstance();
const { character_type } = proxy.useDict("character_type");
const sensorList = ref([]);
const open = ref(false);
const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const incineOptions = ref([]);
const pathOptions = ref([]);
const deptList = ref([]);
const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        sensorName: null,
		incineratorSn: null
    },
    rules: {
        incineratorSn: [{
            required: true, message: "焚烧炉不能为空", trigger: "blur"
        }],
        sensorName: [{
            required: true, message: "传感器名称不能为空", trigger: "blur"
        }],
        sensorPath: [{
            required: true, message: "传感器路径不能为空", trigger: "blur"
        }],
    }
})
    ;

const { queryParams, form, rules } = toRefs(data);
const baseUrl = import.meta.env.VITE_APP_BASE_API;

/** 查询证书列表 */


function addList() {
    loading.value = true;
    listSensor(queryParams.value)
        .then(response => {
            sensorList.value.push(...response.rows);
            total.value = response.total;
            if (sensorList.value.length >= total.value) finished.value = true;
            loading.value = false;
        })
        .catch(response => {
            loading.value = false;
        });
}

// 下拉刷新
function handlePullDownRefresh() {
    queryParams.value.pageNum = 1;
    sensorList.value = [];
    addList();
}

// 滚动到底部的事件
function handleReachBottom() {
    queryParams.value.pageNum++;
    addList();
}

// 取消按钮
function cancel() {
    open.value = false;
    reset();
}

// 表单重置
function reset() {
    form.value = {
		sensorId: null,
		incineratorSn: null,
		sensorName: null,
		sensorPath: null,
		remark: null,
		measurementsDescription: [],
		measurementsDataType: [],
		measurements: [],
		unit: [],
    };
    proxy.resetForm("sensorRef");
}
function changeFullPath(val){
	if (form.value.sensorId == null) {
		getTimeSeries({
			sensorPath: val
		}).then(res => {
			form.value.measurementsDataType = res.data.dataType;
			form.value.measurements = res.data.measurements;
		})
	}
}

function changeIncine(val){
	getSensorByIncine({
		incineratorSn: val
	}).then(res=>{
		pathOptions.value = res;
	})
}
/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.sensorId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}
/** 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加传感器";
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    const sensorIds = row.sensorId || ids.value;
	changeIncine(row.incineratorSn);
    getSensor(sensorIds).then(response => {
		let item = response.data;
		item.measurements = JSON.parse(item.measurements);
		item.measurementsDataType = JSON.parse(item.measurementsDataType);
		item.measurementsDescription = JSON.parse(item.measurementsDescription);
		if(item.unit != null){
			if(item.unit.indexOf("[") != -1){
				item.unit = JSON.parse(item.unit);
			}else{
				item.unit = [item.unit];
			}
		}else{
			item.unit = [];
		}
        form.value = item;
        open.value = true;
        title.value = "修改传感器";
    });
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["sensorRef"].validate(valid => {
        if (valid) {
			form.value.measurements = JSON.stringify(form.value.measurements);
			form.value.measurementsDataType = JSON.stringify(form.value.measurementsDataType);
			form.value.measurementsDescription = JSON.stringify(form.value.measurementsDescription);
			form.value.unit = JSON.stringify(form.value.unit);
            if (form.value.sensorId != null) {
                updateSensor(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    open.value = false;
                    getList();
                });
            } else {
                addSensor(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
    const sensorIds = row.sensorId || ids.value;
    proxy.$modal.confirm('是否确认删除传感器为"' + row.sensorName + '"的数据项？').then(function () {
        return delSensor(sensorIds);
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
    downloadSensor(queryParams.value)
}

/** 详细按钮操作 */
function handleView(row) {
}

/** 查询部门下拉树结构 */
function getTreeselect() {
    listIncinerator().then(response => {
        incineOptions.value = response.rows;
    });
};
function getList() {
    loading.value = true;
    listSensor(queryParams.value).then(response => {
		let _obj = response.rows;
		_obj.forEach(item => {
			item.measurements = JSON.parse(item.measurements);
			item.measurementsDataType = JSON.parse(item.measurementsDataType);
			item.measurementsDescription = JSON.parse(item.measurementsDescription);
			if(item.unit != null){
				if(item.unit.indexOf("[") != -1){
					item.unit = JSON.parse(item.unit);
				}else{
					item.unit = [item.unit];
				}
			}else{
				item.unit = [];
			}
			
		});
        sensorList.value = _obj;
        total.value = response.total;
        loading.value = false;
    });
}
function initialData() {
	let _list = proxy.$store.state.data.analogList.filter(item => item.sn == proxy.$store.state.data.curAnalogSn);
	queryParams.value.incineratorSn = _list.length?_list[0].incineratorSn:null;
    getTreeselect();
    getList();
}

watch(() => proxy.$store.state.data.curAnalogSn, (newValue, oldValue) => {
	initialData();
})
onActivated(() => {
    initialData();
})
onMounted(() => {
    initialData();
})
</script>

