<template>
    <div class="app-container">
        <!-- 标签页 -->
        <el-tabs value="first" type="border-card" @tab-click="handleClick">
            <el-tab-pane label="基本信息" name="first">
                <el-row type="flex" justify="space-between">
                    <!-- 左侧内容 -->
                    <el-col :span="5">
                        <!-- 充电设备 -->
                        <div class="advContent">
                            <el-card class="box-card" shadow="hover" v-loading="pileDetailLoading">
                                <div slot="header" class="clearfix">
                                    <span>充电设备(<span style="color: #bf1c1c">{{ status }}</span>)</span>
                                    <el-button icon="el-icon-refresh-right" style="float: right; padding: 3px 0"
                                        type="text" @click="getPileDetail">刷新
                                    </el-button>
                                </div>
                                <!--二维码-->
                                <div class="hello">
                                    <vue-qr ref="Qrcode" :text="pileDetail.qrCodeURL" qid="testQrId" :width="150"
                                        style="margin-left: 25%" />
                                </div>

                                <!-- 表格 -->
                                <div style="margin-bottom: 10px">
                                    <el-descriptions :column="1" border>
                                        <el-descriptions-item label="SN" labelStyle="width: 120px"
                                            contentStyle="width: 150px">{{ pileDetail.pileSn }}
                                        </el-descriptions-item>
                                        <el-descriptions-item>
                                            <template slot="label">
                                                别名
                                                <el-button type="text" icon="el-icon-edit" size="medium" circle
                                                    @click="openEditName" v-hasPermi="['pile:basic:edit']" />
                                            </template>
                                            <el-input v-model="pileDetail.name" size="medium" clearable
                                                :disabled="clearableFlag" type="number" :min="1"
                                                oninput="if(value<1)value=''" style="line-height: 36px;">
                                                <template slot="suffix"> 号桩</template>
                                                <template slot="append">
                                                    <el-button type="text" size="medium" circle @click="updateName">保存
                                                    </el-button>
                                                </template>
                                            </el-input>
                                        </el-descriptions-item>

                                        <el-descriptions-item v-for="(item, index) in snRelationList" :key="index">
                                            <template slot="label">
                                                <span style="font-weight: 600;">{{ item.thirdPartyName }}</span> sn编号
                                                <el-button type="text" icon="el-icon-edit" size="medium" circle
                                                    @click="openEditSnRelation(index)"
                                                    v-hasPermi="['pile:basic:edit']" />
                                            </template>
                                            <el-input v-model="item.thirdPartySn" size="medium" clearable
                                                :disabled="item.disabled" type="text" oninput="if(value<1)value=''">
                                                <template slot="append">
                                                    <el-button type="text" size="medium" circle
                                                        @click="updateThirdPartySn(item)">保存
                                                    </el-button>
                                                </template>
                                            </el-input>
                                        </el-descriptions-item>

                                        <el-descriptions-item label="运营商">{{ pileDetail.merchantName }}
                                        </el-descriptions-item>
                                        <el-descriptions-item label="站点">{{ pileDetail.stationName }}
                                        </el-descriptions-item>
                                        <el-descriptions-item label="设备型号">{{ pileDetail.modelName }}
                                        </el-descriptions-item>
                                        <el-descriptions-item label="额定功率(kW)">{{ pileDetail.ratedPower }}
                                        </el-descriptions-item>
                                        <!--<el-descriptions-item label="额定电压(V)">{{pileDetail.sn}}</el-descriptions-item>-->
                                        <el-descriptions-item label="额定电流(A)">{{ pileDetail.ratedCurrent }}
                                        </el-descriptions-item>

                                        <el-descriptions-item label="iccid">{{ pileDetail.iccid }}
                                        </el-descriptions-item>

                                        <el-descriptions-item label="sim卡商">
                                            <dict-tag :options="dict.type.sim_supplier"
                                                :value="pileDetail.simSupplier" />
                                        </el-descriptions-item>

                                        <el-descriptions-item label="卡运营商">
                                            <dict-tag :options="dict.type.sim_operator" :value="pileDetail.operator" />
                                        </el-descriptions-item>

                                        <!--                    <el-descriptions-item label="桩类型">-->
                                        <!--                      桩类型 数据-->
                                        <!--                    </el-descriptions-item>-->
                                        <el-descriptions-item label="故障原因">
                                        </el-descriptions-item>
                                        <el-descriptions-item label="故障时间">
                                        </el-descriptions-item>
                                    </el-descriptions>
                                </div>



                                <!-- <div ></div> -->
                            </el-card>
                            <div class="advContent" v-if="personalPileInfoList"
                                v-for="personalPileInfo in personalPileInfoList">
                                <el-card class="box-card" shadow="hover">
                                    <div slot="header" class="clearfix">
                                        <span>个人桩信息</span>
                                    </div>
                                    <!-- 表格 -->
                                    <div style="margin: 10px 0">
                                        <el-descriptions :column="1" border>
                                            <el-descriptions-item label="所属会员 id">
                                                {{ personalPileInfo.memberId }}
                                            </el-descriptions-item>
                                            <el-descriptions-item label="身份类型">
                                                <span v-if="personalPileInfo.type == 1">管理员</span>
                                                <span v-if="personalPileInfo.type == 2">普通用户</span>

                                            </el-descriptions-item>
                                        </el-descriptions>
                                    </div>
                                </el-card>
                            </div>
                        </div>
                    </el-col>
                    <!-- 右侧内容 -->
                    <el-col :span="19" style="margin-left: 15px">
                        <el-card class="box-card" shadow="hover">
                            <div style="margin: 12px 0">
                                <span>接口列表</span>
                                <el-button icon="el-icon-refresh-right" style="float: right; padding: 3px 0" type="text"
                                    @click="refreshPileConnectorList">刷新
                                </el-button>
                            </div>
                            <!--<div style="margin-top: 20px">
                                            &lt;!&ndash; 刷新按钮 &ndash;&gt;
                                            <el-button
                                              size="medium"
                                              type="primary"
                                              @click="refreshPileConnectorList"
                                            >
                                              刷新
                                            </el-button>
                                          </div>-->
                            <div class="sideNav" id="app">
                                <!-- 接口列表表单 -->
                                <el-table :data="connectorList" style="width: 100%" v-loading="pileListLoading">
                                    <el-table-column prop="pileConnectorCode" label="枪口编号" width="180px"
                                        align="center" />
                                    <el-table-column prop="connectorQrCodeUrl" label="充电二维码" width="180px"
                                        align="center">
                                        <template slot-scope="scope">
                                            <el-link @click="qrcodeClick(scope.row)">
                                                <vue-qr ref="Qrcode" :text="scope.row.connectorQrCodeUrl"
                                                    qid="scope.row.connectorId" :width="qrWidth" />
                                            </el-link>
                                        </template>
                                    </el-table-column>
                                    <el-table-column width="118px" align="center" prop="status" label="状态">
                                        <template slot-scope="scope">
                                            <div style="display: flex; align-items: center;justify-content: center;" v-if="scope.row.status === 255">
                                                <el-tooltip class="item" effect="dark"
                                                    :content="'故障原因：' + scope.row.faultReason" placement="top">
                                                    <dict-tag :options="dict.type.connector_status"
                                                        :value="scope.row.status" />
                                                </el-tooltip>
                                                <i class="el-icon-warning" style="margin-left: 2px;"></i>
                                            </div>
                                            <dict-tag :options="dict.type.connector_status" :value="scope.row.status"
                                                v-else />
                                        </template>
                                    </el-table-column>
                                    <el-table-column width="80px" align="center" prop="type" label="类型">
                                        <template slot-scope="scope">
                                            <dict-tag :options="dict.type.connector_type" :value="scope.row.type" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column width="118px" align="center" prop="instantPower"
                                        label="即时功率（kW）" />
                                    <el-table-column prop="soc" label="SOC(°C)" align="center" />
                                    <el-table-column prop="equipmentOrderNum" label="设备订单号" align="center"
                                        width="200" />
                                    <el-table-column prop="orderCode" label="平台订单" align="center" width="200" />
                                    <!--                  <el-table-column prop="businessType" label="桩类型" align="center" >-->
                                    <!--                    <template slot-scope="scope">-->
                                    <!--                      <span>{{scope.row.businessType === '1' ? '运营桩':'个人桩'}}</span>-->
                                    <!--                    </template>-->
                                    <!--                  </el-table-column>-->
                                    <el-table-column label="地锁操作" align="center" v-hasRole="['admin', 'common']"
                                        class-name="small-padding fixed-width">
                                        <template slot-scope="scope">
                                            <el-button size="mini" type="text" icon="el-icon-caret-bottom"
                                                @click="remoteControlGroundLock(scope.row, '0')">降锁
                                            </el-button>
                                            <el-button size="mini" type="text" icon="el-icon-caret-top"
                                                @click="remoteControlGroundLock(scope.row, '1')">升锁
                                            </el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </el-card>
                        <el-card style="margin-top: 20px" shadow="hover">
                            <div style="margin: 12px 0">
                                <span>充电桩通信日志</span>
                                <el-button icon="el-icon-refresh-right" style="float: right; padding: 3px 0" type="text"
                                    @click="getFeedList">刷新
                                </el-button>
                            </div>
                            <el-table :data="feedList" stripe style="width: 100%" v-loading="feedListLoading">
                                <el-table-column prop="createTime" label="时间" align="center" width="150" />
                                <el-table-column prop="frameTypeStr" label="帧类型名称" align="center" width="150" />
                                <el-table-column prop="description" label="描述" align="center" width="800" />
                                <el-table-column prop="originalMsg" label="原始报文" align="center">
                                    <template slot-scope="scope">
                                        <el-popover placement="top" width="400" trigger="click">
                                            <p>{{ scope.row.originalMsg }}</p>
                                            <el-button slot="reference">查看</el-button>
                                        </el-popover>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <!--分页-->
                            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                                :limit.sync="queryParams.pageSize" @pagination="getFeedList"
                                style="margin-bottom: 20px" />
                        </el-card>
                    </el-col>
                </el-row>
            </el-tab-pane>
            <el-tab-pane label="配置管理" name="second">
                <remoteUpgrade :pileSn="pileSn" ref="second"></remoteUpgrade>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>

<script>
import remoteUpgrade from "./components/remoteUpgrade.vue";
import {
    getPersonalPileList,
    getPileDetailById,
    getPileFeedList, getThirdPartySnRelation,
    listBasic,
    updateBasic,
    updatePileName, updateThirdPartySnRelation,
} from "@/api/pile/basic";
import { queryConnectorListByParams } from "@/api/pile/connector";
// 二维码组件
import VueQr from "vue-qr";
import { remoteControlGroundLock } from "@/api/pile/pileRemote";
import Template from "@/views/billing/template";

export default {
    components: { Template, VueQr, remoteUpgrade },
    name: "pile-detail",
    dicts: ["connector_status", "connector_type", "sim_supplier", "sim_operator"],
    data() {
        return {
            visible: false,
            clearableFlag: true,
            clearableFlagSnRelation: true,
            resCode: null,
            msg: null,
            pileDetailLoading: false,
            pileListLoading: false,
            pileId: this.$route.params.pileId,
            // 右侧数据数组
            connectorList: [],
            stationId: 1,
            // 充电桩详情 竖向 表格渲染的数据
            pileDetail: { url: "" },
            feedListLoading: false,
            snRelationList: [],
            personalPileInfoList: [],
            qrWidth: 60,
            flag: true,
            // 充电桩通信日志
            feedList: [],
            // 总条数
            total: 0,
            // 查询参数
            queryParams: {
                pileSn: null,
                pageNum: 1,
                pageSize: 5,
            },
            pileSn: null,
        };
    },
    computed: {
        status() {
            const status = this.pileDetail.status;
            // 0-未知；1-在线；2-离线；3-故障
            let str = "";
            if (status === "1") {
                str = "在线";
            } else if (status === "2") {
                str = "离线";
            } else if (status === "3") {
                str = "故障";
            } else {
                str = "未知";
            }
            return str;
        },
    },
    created() {
        // 查询充电桩详情
        this.getPileDetail();
        // 查询充电桩接口列表
        this.queryPileConnectorList();
        // 查询桩绑定的用户列表
        this.getMemberInfoBySn();
    },
    mounted() {
        setTimeout(() => {
        }, 300);
    },
    methods: {
        // 遥控地锁
        remoteControlGroundLock(row, operate) {
            console.log("row:", row);
            const pileSn = row.pileSn;
            const pileConnectorCode = row.pileConnectorCode;
            const connectorCode = pileConnectorCode.replace(pileSn, "");
            var data = {
                pileSn: pileSn,
                connectorCode: connectorCode,
                operate: operate,
            };
            remoteControlGroundLock(data).then((response) => {
                console.log("后管遥控地锁结果：", response);
            });
        },

        //点击二维码事件
        qrcodeClick(row) {
            if (this.flag) {
                this.flag = false;
                this.qrWidth = 150;
            } else {
                this.flag = true;
                this.qrWidth = 60;
            }
        },
        // 查询接口列表
        queryPileConnectorList() {
            const data = {
                pileIds: [this.pileId],
            };
            queryConnectorListByParams(data)
                .then((response) => {
                    console.log("response", response);
                    this.connectorList = response.rows;
                    console.log("接口列表", this.connectorList);
                })
                .catch((error) => {
                    console.log("错误日志", error);
                });
        },
        // test(dataUrl, id){
        //   console.log(dataUrl)
        //   console.log(id)
        // },
        test() {
            console.log("测试");
        },
        // 开放编辑按钮
        openEditName() {
            this.clearableFlag = this.clearableFlag === false;
        },
        openEditSnRelation(index) {
            const updatedSnRelationList = this.snRelationList.map((item, currentIndex) => {
                // 只对当前点击的项进行状态切换
                if (currentIndex === index) {
                    return {
                        ...item,
                        disabled: !item.disabled
                    };
                }
                return item;
            });
            // 更新snRelationList
            this.snRelationList = updatedSnRelationList;
        },
        // 修改充电桩别名
        updateName() {
            const params = {
                id: this.pileDetail.pileId,
                name: this.pileDetail.name,
                sn: this.pileDetail.pileSn,
                stationId: this.pileDetail.stationId,
            };
            console.log("params", params);
            updatePileName(params).then((response) => {
                console.log("response", response);
                this.resCode = response.resCode;
                this.msg = response.msg;
                if (this.resCode !== "00100000") {
                    this.$message({
                        type: "error",
                        message: this.msg,
                    });
                }
                this.clearableFlag = true;
                this.getPileDetail();
            });
        },
        // 修改第三方平台对应编号
        updateThirdPartySn(item) {
            const params = {
                thirdPartyType: item.thirdPartyType,
                pileSn: item.pileSn,
                thirdPartySn: item.thirdPartySn,
            }
            console.log("修改第三方平台对应编号 params:", params)
            updateThirdPartySnRelation(params).then((response) => {
                console.log("修改第三方平台对应编号 response:", response)
            });
        },
        // 查询充电桩详情接口
        getPileDetail() {
            this.pileDetailLoading = true;
            // console.log(this.pileId);
            const queryForm = {
                pileId: this.pileId,
            };
            getPileDetailById(queryForm).then((response) => {
                this.pileDetail = response.data;
                this.pileSn = this.pileDetail.pileSn;
                this.pileDetailLoading = false;
                console.log("getPileDetailById结果：", this.pileDetail);
                this.getThirdPartySnRelationList();
                this.getMemberInfoBySn();
            });
        },
        getThirdPartySnRelationList() {
            const params = {
                pileSn: this.pileDetail.pileSn
            }
            // console.log("params", params)
            getThirdPartySnRelation(params).then((response) => {
                this.snRelationList = response.rows;
                //默认添加一个状态
                this.snRelationList = this.snRelationList.map(item => {
                    return {
                        ...item,
                        disabled: true
                    };
                });
                // console.log("snRelationList:", this.snRelationList)
            });
        },
        getMemberInfoBySn() {
            const param = {
                pileSn: this.pileDetail.pileSn,
            }
            getPersonalPileList(param).then((response) => {
                console.log("getMemberInfoBySn :", response);
                this.personalPileInfoList = response.rows;
                //默认添加一个状态
                this.personalPileInfoList = this.personalPileInfoList.map(item => {
                    return {
                        ...item,
                        disabled: true
                    };
                });
            });
        },
        handleClick(tab) {
            // console.log(tab.name, event);
            if (tab.name === "second") {
                this.$refs.second.getList();
            }
            // this.initializeData(tab.name);
        },
        // 刷新按钮重新获取数据
        refreshPileConnectorList() {
            this.pileListLoading = true;
            setTimeout(() => {
                this.queryPileConnectorList();
                this.pileListLoading = false;
            }, 1000);
        },
        /** 查询充电桩通信日志 */
        getFeedList() {
            this.feedListLoading = true;
            this.queryParams.pileSn = this.pileSn;
            getPileFeedList(this.queryParams).then((response) => {
                this.feedListLoading = false;
                console.log("查询充电桩通信日志", response);
                this.feedList = response.data.list;
                this.total = response.data.total;
            });
        },
    },
    watch: {
        pileSn(newValue, oldValue) {
            if (newValue !== null) {
                this.getFeedList();
            }
        },
    },

};
</script>

<style scoped lang="scss">
.advContent {
    background: #fff;
    border-radius: 5px 5px 0px 0px;
}

.sideNav {
    padding: 30px 0 12px;
}

#qrcodeArea img {
    height: 80px;
    width: 80px;
}

::v-deep .el-input-group--append .el-input__inner {
    // background-color: #fff;
    // border-color: #fff;
    color: #606266;
    border-top-right-radius: 5px;
    border-bottom-right-radius: 5px;
}

::v-deep .el-input-group__append,
.el-input-group__prepend {
    background-color: #fff;
    border-color: #fff;
    color: #606266;
}

::v-deep input::-webkit-outer-spin-button,
::v-deep input::-webkit-inner-spin-button {
    -webkit-appearance: none !important;
}

::v-deep input[type="number"] {
    -moz-appearance: textfield !important;
}
</style>
