<template>
    <div>
        <el-card>
            <template #header>
                <div class="card-header">
                    <el-form :inline="true" :model="queryParams" @keyup.enter.native="queryList(true)">
                        <el-form-item label="遥测站编码" style="width: 240px;">
                            <el-input v-model="queryParams.stationCode" placeholder="站点编码" clearable maxlength="10"
                                show-word-limit />
                        </el-form-item>
                        <el-form-item label="遥测站名称" style="width: 250px;">
                            <el-input v-model="queryParams.stationName" placeholder="遥测站点" maxlength="100" clearable />
                        </el-form-item>
                        <el-form-item label="设备编号" style="width: 240px;">
                            <el-input v-model="queryParams.deviceSn" placeholder="设备编号" clearable maxlength="11"
                                show-word-limit />
                        </el-form-item>
                        <el-form-item label="使用单位">
                            <el-select v-model="queryParams.unitCode" placeholder="使用单位" filterable clearable>
                                <el-option v-for="item in state.unitData" :key="item.unitCode" :label="item.unitName"
                                    :value="item.unitCode"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="关联单位" v-if="userType === '0'">
                            <el-select v-model="queryParams.visUnitCodes" placeholder="关联单位" filterable clearable>
                                <el-option v-for="item in state.unitData2" :key="item.unitCode" :label="item.unitName"
                                    :value="item.unitCode" />
                            </el-select>
                        </el-form-item>

                        <el-form-item>
                            <el-button type="primary" class="button" :disabled="state.search_disabled"
                                @click="queryList(true)">
                                查询信息
                            </el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" class="button" @click="handleAdd" :disabled="!adminFlag">新增遥测站
                            </el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </template>

            <el-table v-loading="loading" :data="state.tableData" border stripe style="width: 100%,"
                :height="tableHeight" highlight-current-row @current-change="handleCurrentRowChange" size="large"
                :header-cell-style="{ background: '#FF000000', color: '#000000' }">
                <el-table-column fixed prop="stationCode" label="遥测站编码" header-align="center" width="100" />
                <el-table-column fit prop="stationName" label="遥测站名称" header-align="center" width="250" />
                <!-- <el-table-column fit prop="groupName" label="站点组" header-align="center" min-width="90" /> -->
                <el-table-column prop="deviceSn" label="设备编号" header-align="center" align="center" width="120" />
                <el-table-column fit prop="unitName" label="使用单位" header-align="center" min-width="90" width="250"
                    show-overflow-tooltip="unitName" />
                <el-table-column label="当前读数" header-align="center" width="100" />
                <el-table-column prop="stationContacts" label="站点联系信息" header-align="center" width="150" />
                <!-- <el-table-column prop="stationLon" label="遥测站点经度" header-align="center" width="120" /> -->
                <el-table-column prop="stationLat" label="站点经纬度" header-align="center" width="155">
                    <template #default="scope">
                        <el-space direction="horation" alignment="start">
                            <!-- <el-tag size="small">Lon:{{ scope.row.stationLon }}</el-tag>
                            <el-tag size="small">Lat:{{ scope.row.stationLat }}</el-tag> -->
                            <span>{{
                                scope.row.stationLat == null ? " " : scope.row.stationLat + "," + scope.row.stationLat
                            }}</span>
                        </el-space>
                    </template>
                </el-table-column>
                <el-table-column label="状态" header-align="center" align="center" width="80">
                    <template #default="scope">
                        <el-tag :type="UseStateColorMap[scope.row.useFlag]" size="small">{{
                            UseStateMap[scope.row.useFlag]
                        }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="站点安装信息" header-align="center" align="center" width="220">
                    <template #default="scope">
                        <el-space>
                            <el-tag :type="SetupColorMap[scope.row.deviceSetupFlag]" size="small">{{
                                SetupMap[scope.row.deviceSetupFlag]
                            }}</el-tag>
                            <!-- <el-tag size="small">人员：{{ scope.row.deviceSetupMan }}</el-tag> -->
                            <el-tag size="small" style="margin-left: 3px;"> 日期：{{
                                tool.dateFormat(scope.row.deviceSetupDate)
                            }}</el-tag>
                        </el-space>
                    </template>
                </el-table-column>

                <el-table-column prop="memo" label="备注" header-align="center" align="left" min-width="150" />
                <el-table-column fixed="right" label="" align="left" width="190">
                    <template #default="scope">
                        <el-button type="text" @click="showDevCfg(scope.row)">设备参数</el-button>
                        <el-button type="text" @click="handleEdit(scope.row)" :disabled="!adminFlag">编辑</el-button>
                        <el-button type="text" @click="handleDelete(scope.row)" :disabled="!adminFlag">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-config-provider :locale="locale">
                <el-pagination v-model:currentPage="queryParams.page" v-model:page-size="queryParams.rows"
                    :page-sizes="[10, 15, 20, 25, 100]" :small="state.small" :disabled="state.disabled"
                    :background="state.background" layout="total, sizes, prev, pager, next, jumper" :total="state.total"
                    style="text-align: center;margin-top: 10px;height: 30px;" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </el-config-provider>
        </el-card>

        <el-dialog :title="formdialog.title" v-model="formdialog.visible" width="810px" draggable center
            @close="dialogClose">
            <el-form ref="formRef" :model="formData" :rules="state.rules" label-width="100px">
                <el-form-item label="遥测站名称:" prop="stationName">
                    <el-input v-model="formData.stationName" placeholder="遥测站名称" maxlength="50" clearable />
                </el-form-item>
                <el-row :gutter="20">
                    <el-col :span="10">
                        <el-form-item label="遥测站编码:" prop="stationCode">
                            <el-input v-model="formData.stationCode" placeholder="遥测站编码" maxlength="10" clearable
                                style="width: 250px;" show-word-limit />
                        </el-form-item>
                    </el-col>
                    <el-col :span="10" :offset="3">
                        <el-form-item label="遥测站拼音码:">
                            <el-input v-model="formData.stationPy" placeholder="遥测站拼音码" style="width: 240px;"
                                clearable />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="10">
                        <el-form-item label="设备类型:" prop="deviceType">
                            <el-select v-model="formData.deviceType" style="width: 250px;" filterable clearable
                                placeholder="请选择设备类型">
                                <el-option v-for="(key, value) in Dic.deviceTypeMap" :key="key" :label="key"
                                    :value="value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10" :offset="3">
                        <el-form-item label="设备参数:">
                            <el-select v-model="formData.meterFontStyle" style="width: 240px;" filterable clearable
                                v-if="formData.deviceType === '1'||formData.deviceType==='3'" placeholder="请选择设备参数">
                                <el-option v-for="(key, value) in Dic.meterFontStyle" :key="key" :label="key"
                                    :value="value"></el-option>
                                <!-- <el-option v-for="item in Dic.meterFontStyle" :key="item.value" :label="item.value"
                                    :value="item.label" ></el-option> -->
                            </el-select>

                            <el-select v-model="formData.deviceUnit" style="width: 240px;" filterable clearable
                                v-if="formData.deviceType === '2'" placeholder="请选择设备参数">
                                <!-- <el-option v-for="(key, value) in Dic.pgDeviceUnitMap" :key="key" :label="key"
                                    :value="value"></el-option> -->
                                <el-option v-for="item in Dic.pgDeviceUnitMap" :key="item.value" :label="item.label"
                                    :value="item.value" />
                                <!-- <el-option v-for="item in Dic.pgDeviceUnitMap" :key="item.value" :label="item.value"
                                    :value="item.label" ></el-option> -->
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- <el-form-item label="遥测站分组:">
                    <el-cascader :options="groupData" :props="props1" clearable v-model="formData.groupCode"
                        style="width: 550px;" />
                </el-form-item> -->

                <el-row :gutter="20">
                    <el-col :span="10">
                        <el-form-item label="使用单位:">
                            <el-select v-model="formData.unitCode" style="width: 250px;" filterable clearable
                                placeholder="请搜索或选择">
                                <el-option v-for="item in state.unitData" :key="item.unitCode" :label="item.unitName"
                                    :value="item.unitCode"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10" :offset="3">
                        <el-form-item label="关联单位:">
                            <el-select v-model="formData.visUnitCodeList" value-key="unitCode" multiple filterable
                                placeholder="请搜索或选择" style="width: 240px" clearable>
                                <el-option v-for="item in state.unitData2" :key="item.unitCode" :label="item.unitName"
                                    :title="item.unitName" :value="item.unitCode" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="10">
                        <el-form-item label="经度坐标:">
                            <el-input v-model="formData.stationLon" placeholder="遥测站经度坐标" style="width: 250px;"
                                clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="10" :offset="3">
                        <el-form-item label="纬度坐标:">
                            <el-input v-model="formData.stationLat" placeholder="遥测站纬度坐标" style="width: 240px;"
                                clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="10">
                        <el-form-item label="站点联系人:">
                            <el-input v-model="formData.stationContacts" placeholder="站点联系人" style="width: 250px;"
                                clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="10" :offset="3">
                        <el-form-item label="是否安装设备:">
                            <el-switch v-model="formData.deviceSetupFlag" inline-prompt="true" active-value="1"
                                inactive-value="0" active-text="已安装" inactive-text="未安装" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="10">
                        <el-form-item label="设备SN:">
                            <el-input v-model="formData.deviceSn" placeholder="设备SN" style="width: 250px;"
                                maxlength="11" show-word-limit :disabled="formData.deviceSetupFlag !== '1'" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="10" :offset="3">
                        <el-form-item label="安装人员:">
                            <el-input v-model="formData.deviceSetupMan" placeholder="安装人员" style="width: 240px;"
                                maxlength="30" :disabled="formData.deviceSetupFlag !== '1'" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="10">
                        <el-form-item label="在用状态:">
                            <el-switch v-model="formData.useFlag" inline-prompt="true" active-value="1"
                                inactive-value="0" active-text="在用" inactive-text="停用" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="10" :offset="3">
                        <el-form-item label="是否审核:">
                            <el-switch v-model="formData.reviewFlag" inline-prompt="true" active-value="1"
                                inactive-value="0" active-text="是" inactive-text="否" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20" v-if="userType === '0'">
                    <el-col :span="10">
                        <el-form-item label="归属单位:">
                            <el-select v-model="formData.createUnitCode" style="width: 250px;" filterable clearable
                                placeholder="选择站点的归属单位">
                                <el-option v-for="item in state.unitData3" :key="item.unitCode" :label="item.unitName"
                                    :value="item.unitCode"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10" :offset="3">
                        <span style="color: red;">归属单位：内部用户帮运维单位创建站点时选择</span>
                    </el-col>
                </el-row>

                <el-form-item label="备注:">
                    <el-input v-model="formData.memo" type="textarea" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancel">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <el-dialog :title="cfgdialog.title" v-model="cfgdialog.visible" width="1100px" center>
            <DevCfgDialog :stationCode="state.cfgData.stationCode" :deviceSn="state.cfgData.deviceSn"></DevCfgDialog>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { reactive, toRefs, toRef, ref, onMounted } from "vue";
import { ElForm, ElMessage, ElMessageBox } from 'element-plus';
import StationAccAction from '@/api/station/stationacc';
import TAffAction from "@/api/customermanagement/taffiliatedunit";
//import StationGroupApi from '@/api/station/stationgroup';
import { StationAccQueryParam, StationAccModel, Dialog, PageResult, StationGroupModel, StationGroupQueryParam, StationGroupTree, TAffiliatedunitQueryParam, TAffiliatedunitModel } from '@/types';
import zhCn from 'element-plus/lib/locale/lang/zh-cn';
//import arrayToTree from "array-to-tree";
import tool from "@/until/tool"
import DevCfgDialog from "@/components/devcfg/index.vue";
import Dic from "@/dictionary/aicbqcfg";

let locale = ref(zhCn)
const userType = localStorage.getItem("UserType")?.toString();
// const props1 = {
//     checkStrictly: true,
//     emitPath: false,
//     value: "groupCode",
// }
// const deviceUseFlagMap = {
//     0: '停用',
//     1: '在用',
// };

type mapStatee = Record<string, string>;
const UseStateMap: mapStatee = {
    null: '停用',
    0: '停用',
    1: '使用中',
};

const UseStateColorMap: mapStatee = {
    null: 'danger',
    0: 'danger',
    1: 'success',
};

const SetupMap: mapStatee = {
    null: '未安装',
    0: '未安装',
    1: '已安装',
};

const SetupColorMap: mapStatee = {
    null: 'danger',
    0: 'danger',
    1: 'success',
};


const loading = ref(false)
const adminFlag = localStorage.getItem("AdminFlag")?.toString() === '1';
const unitCode = localStorage.getItem("UnitCode")?.toString();

const state = reactive({
    queryParams: { page: 1, rows: 10 } as StationAccQueryParam,
    group_queryParams: { page: 1, rows: 10, customerId: localStorage.getItem("CustomerId") || "" } as StationGroupQueryParam,
    total: 0,
    small: false,
    background: true,
    disabled: false,
    search_disabled: false,
    formdialog: {} as Dialog,
    formData: {} as StationAccModel,
    tableData: [] as StationAccModel[],
    //groupData: [] as StationGroupTree[],
    submittype: 0,//0 新增 1 编辑
    unitData: [] as TAffiliatedunitModel[],      //使用单位
    unitData2: [] as TAffiliatedunitModel[],     //关联单位
    unitData3: [] as TAffiliatedunitModel[],     //创建单位
    cfgdialog: {} as Dialog,
    cfgData: {} as StationAccModel,
    rules: {
        stationCode: [{ required: true, message: "遥测站编码不能为空", trigger: "blur", },
        { min: 10, max: 10, message: "遥测站编码长度不合法", trigger: "blur" },],
        stationName: [{ required: true, message: "遥测站名称不能为空", trigger: "blur", },],
    },
});

const {
    queryParams,
    total,
    formdialog,
    formData,
    tableData,
    cfgdialog,
    cfgData
    //groupData,
} = toRefs(state);

const tableHeight = ref(document.documentElement.clientHeight - 200);

const currentRow = ref()

const handleCurrentRowChange = (val: StationAccModel | undefined) => {
    currentRow.value = val
}

async function handleAdd() {
    //await queryTreeList();
    state.submittype = 0;
    state.formData = {} as StationAccModel;
    state.formData.deviceType = '1';              //默认水表
    state.formData.meterFontStyle = '1';          //默认白底黑字

    if (userType === '1' && localStorage.getItem("CreateUnitFalg") === '1' && unitCode !== undefined) {
        state.formData.visUnitCodeList = [] as string[];
        state.formData.visUnitCodeList.push(unitCode);
    }

    state.formdialog = {
        title: '新增遥测站信息',
        visible: true,
        disabled: false,
    };
}

const handleSizeChange = (val: number) => {
    queryParams.value.rows = val;
    queryList(false);
};

const handleCurrentChange = (val: number) => {
    queryParams.value.page = val;
    queryList(false);
};

async function handleEdit(row: any) {
    //await queryTreeList();
    state.submittype = 1;
    state.formData = JSON.parse(JSON.stringify(row));
    //console.log(state.formData);

    state.formdialog = {
        title: '编辑遥测站信息',
        visible: true,
        disabled: false,
    };
}

const cancel = () => {
    state.submittype = 0;
    state.formData = {} as StationAccModel;
    state.formdialog.visible = false;
}

const formRef: any = ref(null);
const submitForm = () => {
    formRef.value.validate((valid: any) => {
        if (valid) {
            if (state.formData.visUnitCodeList !== null && state.formData.visUnitCodeList !== undefined) {
                state.formData.visUnitCodes = state.formData.visUnitCodeList.join(',');
            }

            if (state.submittype === 0) {
                if (state.formData.deviceSetupFlag !== "1") {
                    state.formData.deviceSn = "";
                    state.formData.deviceSetupMan = "";
                }
                //state.formData.customerId = localStorage.getItem("CustomerId") || "";
                state.formData.createMan = localStorage.getItem("UserName") || "";
                let userType = localStorage.getItem("UserType") || "";

                //如果是用户创建的站点,自动绑定
                if (userType === '1') {
                    state.formData.createUnitCode = localStorage.getItem("UnitCode") || "";
                }

                StationAccAction.AddStationAcc(state.formData).then(result => {
                    if (result.status == 200) {
                        const { res, flag, error } = result.data;
                        if (flag === "1") {
                            ElMessage.success("新增成功");
                            cancel();
                            queryList(false);
                        }
                        else {
                            ElMessage.error(error || "未知异常...");
                        }
                    }
                });
            }
            else if (state.submittype === 1) {
                if (state.formData.deviceSetupFlag !== "1") {
                    state.formData.deviceSn = "";
                    state.formData.deviceSetupMan = "";
                }
                StationAccAction.EditStationAcc(state.formData).then(result => {
                    if (result.status == 200) {
                        const { res, flag, error } = result.data;
                        if (flag === "1") {
                            ElMessage.success('编辑成功');
                            cancel();
                            queryList(false);
                        } else {
                            ElMessage.error(error || "未知异常...");
                        }
                    }
                });
            }
        }
    });
};

const handleDelete = (row: any) => {
    ElMessageBox.confirm(
        ' 是否删除遥测站[' + row.stationName + ']? ',
        '提示',
        {
            cancelButtonText: '取消',
            confirmButtonText: '确认',
            type: 'warning',
            center: true,
        }
    )
        .then(() => {
            StationAccAction.DeleteStationAcc(row.id).then(result => {
                if (result.status === 200) {
                    const { res, flag, error } = result.data;
                    if (flag === "1") {
                        ElMessage.success('删除成功');
                        queryList(true);
                    }
                }
            }
            );
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除成功!',
            })
        })
};


/* const queryTreeList = () => {
    StationGroupApi.QueryStationGroupList(state.group_queryParams).then(result => {
        if (result.status === 200) {
            const { res, flag, error } = result.data;
            if (flag === "1") {
                let treeModel = res as StationGroupModel[];
                let treeArray = [] as StationGroupTree[];
                treeModel.forEach(element => {
                    let treeNode = {} as StationGroupTree;
                    treeNode.id = (element as StationGroupModel).id;
                    treeNode.label = (element as StationGroupModel).groupName;
                    treeNode.groupCode = (element as StationGroupModel).groupCode;
                    treeNode.parentCode = (element as StationGroupModel).parentCode;
                    treeNode.data = element;
                    treeArray.push(treeNode);
                });

                state.groupData = arrayToTree(treeArray, {
                    parentProperty: "parentCode",
                    customID: "groupCode",
                    childrenProperty: "children",
                });

            }
            else { }
        }
    }).catch(error => {
        //请求失败时的操作     
        ElMessage.error(error);
    })
}; */

//加条件firstPage,是否回到第一页(当前在第2页,输入了遥测站名称,同样有多页时,当前页数会停留在2上) 2022-07-13 guozhao
const queryList = (firstPage: boolean) => {
    state.queryParams.page = firstPage ? 1 : state.queryParams.page;
    loading.value = true;
    state.search_disabled = true;

    if (userType === '1') {
        state.queryParams.createUnitCode = unitCode;
    }
    if (state.queryParams.stationCode) {
        state.queryParams.stationCode = state.queryParams.stationCode.padStart(10, '0');     //不足10位前面自动补0
    }
    if (state.queryParams.deviceSn) {
        state.queryParams.deviceSn = state.queryParams.deviceSn.padStart(11, '0');     //不足10位前面自动补0
    }

    StationAccAction.QueryStationAccList(state.queryParams).then(result => {
        if (result.status === 200) {
            const { res, flag, error } = result.data;

            if (flag === "1") {
                const pageData = res as PageResult<StationAccModel[]>;
                state.tableData = pageData.list;
                state.tableData.forEach(ele => {
                    if (ele.visUnitCodes) {
                        ele.visUnitCodeList = ele.visUnitCodes.split(',');
                    }
                });
                state.total = pageData.total;
            }
            else {
                ElMessage.success(error);
            }
            loading.value = false;
            state.search_disabled = false;
        }
    }).catch(error => {
        //请求失败时的操作     
        ElMessage.error(error);
        loading.value = false;
        state.search_disabled = false;
    })
};

onMounted(() => {
    window.onresize = function () {
        tableHeight.value = document.documentElement.clientHeight - 200;
    }
    queryList(false);
    queryUnit();
})

const queryUnit = () => {
    let queryModel = {} as TAffiliatedunitQueryParam;
    TAffAction.QueryTAffiliatedunitList(queryModel).then(result => {
        if (result.status === 200) {
            const { res, flag, error } = result.data;
            if (flag === "1") {
                const pageData = res as PageResult<TAffiliatedunitModel[]>;
                if (userType === '0') {
                    state.unitData = pageData.list.filter(s => s.unitType === '4');
                    state.unitData3 = pageData.list.filter(s => s.createUnitFalg === '1');
                } else {
                    state.unitData = pageData.list.filter(s => s.unitType === '4' && (s.createUnitCode === unitCode || s.createUnitCode == null || s.createUnitCode === '1'));
                }

                state.unitData2 = pageData.list.filter(s => s.unitType !== '4');
            } else {
                ElMessage.error(error);
            }
        }
        loading.value = false;
    }).catch(error => {
        //请求失败时的操作     
        ElMessage.error(error);
        loading.value = false;
    })
}

const showDevCfg = (row: any) => {
    state.cfgData = row as StationAccModel;

    state.cfgdialog = {
        title: "设备参数预览[" + state.cfgData.deviceSn + "]",
        visible: true,
        disabled: false,
    };
}

const dialogClose = () => {
    formRef.value.resetFields();
    cancel();
}
</script>

<style lang="scss" scoped>
.button {
    margin: 10px 0;
}

.card-header {
    display: flexbox;
    justify-content: space-between;
    align-items: center;
    vertical-align: center;
    justify-content: center;
    background-color: #E8EDF0;
    height: 55px;
    margin: -10px;
    padding: 5px 10px;
}


.el-card ::v-deep .el-card__header {
    padding: 10px 10px;
    background-color: white;
}

.el-card ::v-deep .el-card__body {
    padding: 1px;
    background-color: #E8EDF0;
}

.el-table .warning-row {
    --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
    --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>