<template>
  <van-nav-bar
    title="远程管控"
    left-arrow
    @click-left="onClickLeft"
    safe-area-inset-top
  />
  <div class="page_check">
    <div class="search_pannel">
      <div class="pannel_left" @click="showRepairPositionPicker = true">
        <van-image
          :src="require('@/assets/position.svg')"
          width="16"
          height="16"
          fit="contain"
        />
        <span>{{ name }}</span>
        <van-image
          :src="require('@/assets/arrow-right.svg')"
          width="24"
          height="24"
          fit="contain"
        />
      </div>
      <div class="pannel_right" @click="toPath">
        <van-image
          :src="require('@/assets/search.svg')"
          width="16"
          height="16"
          fit="contain"
        />
      </div>
    </div>
    <div class="drop_down">
      <van-dropdown-menu active-color="#1989fa">
        <van-dropdown-item
          v-model="deviceType"
          @change="
            handelChange(
              'deviceType',
              'deviceTypeTitle',
              'deviceTypeList',
              deviceType
            )
          "
          :title="deviceTypeTitle"
          :options="deviceTypeList"
        />
        <van-dropdown-item
          v-model="deviceStatus"
          @change="
            handelChange(
              'deviceStatus',
              'deviceStatusTitle',
              'deviceStatusList',
              deviceStatus
            )
          "
          :title="deviceStatusTitle"
          :options="deviceStatusList"
        />
      </van-dropdown-menu>
    </div>
    <div class="list_total">
      <span>共有</span>
      <v-count-up
        :end-val="total"
        class="count_up"
        options="{ separator: ',' }"
      />
      <span>条记录</span>
    </div>
    <div class="check_info">
      <div class="info_list">
        <!-- <van-pull-refresh v-model="refreshing" @refresh="onRefresh"> -->
          <van-list
            v-model:loading="loading"
            :finished="finished"
            :error="error"
            error-text="请求失败，点击重新加载"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <div v-for="(item, index) in list" :key="item.id" class="list_item">
              <template v-if="deviceType == 'AirConditioner'">
                <!-- <div
                v-if="item.attributeList[2]"
                  class="reduce_type"
                  :style="{
                    'background-color': `${
                      deviceStatus_filter(item.attributeList[3].value)['color']
                    }`,
                  }"
                >
                  <span>{{
                    `${
                      deviceStatus_filter(item.attributeList[3].value)["label"]
                    }`
                  }}</span>
                </div> -->
                <template v-if="item.attributeList">
                  <van-switch
                    v-model="item.attributeList[3].value"
                    :active-value="1"
                    :inactive-value="0"
                    class="isSwitch"
                    inactive-color="#dddddd"
                    @change="
                      changeSwitch(
                        item.attributeList[3].value,
                        index,
                        item.deviceId
                      )
                    "
                  />
                </template>
                <span class="header">{{ item.airConditionerName }}</span>
                <span
                  >空间信息：{{ item.installSite }}{{ item.roomNumbers }}</span
                >
                <!-- <span>设备编号：{{ item.airConditionerNo }}</span> -->
                <span v-if="item.attributeList"
                  >室温：{{ item.attributeList[4].value }}</span
                >
                <!-- <span>所属租户：{{ item.rentNum }}</span> -->
                <!-- <div class="list_btn" v-if="item.attributeList">
                  <van-button plain type="primary" size="small">{{
                    item.attributeList[3].value == 1 ? "开启" : "关闭"
                  }}</van-button>
                </div> -->
                <van-row class="operation" v-if="item.attributeList">
                  <van-col
                    span="8"
                    @click="
                      chooseMs(
                        'moshitxt',
                        item.attributeList[2].value,
                        index,
                        item.deviceId
                      )
                    "
                    >{{ ms(item.attributeList[2].value)
                    }}<van-icon name="arrow-down" class="xl"
                  /></van-col>
                  <div class="line" style="left: 32%"></div>
                  <van-col
                    span="8"
                    @click="
                      chooseMs(
                        'wendu',
                        item.attributeList[5].value,
                        index,
                        item.deviceId
                      )
                    "
                    >{{ item.attributeList[5].value }}℃<van-icon
                      name="arrow-down"
                      class="xl"
                  /></van-col>
                  <div class="line" style="left: 65%"></div>
                  <van-col
                    span="8"
                    @click="
                      chooseMs(
                        'fengs',
                        item.attributeList[0].value,
                        index,
                        item.deviceId
                      )
                    "
                    >{{ fs(item.attributeList[0].value)
                    }}<van-icon name="arrow-down" class="xl"
                  /></van-col>
                </van-row>
              </template>
              <template v-if="deviceType == 'Ammeter'">
                <!-- <div
                  v-if="item.attributeList"
                  class="reduce_type"
                  :style="{
                    'background-color': `${
                      deviceStatus_filter(item.status)['color']
                    }`,
                  }"
                >
                  <span>{{
                    `${deviceStatus_filter(item.status)["label"]}`
                  }}</span>
                </div> -->
                <span class="header">{{ item.controlName }}</span>
                <span>空间信息：{{ item.installSite }}</span>
                <!-- <span>设备编号：{{ item.deviceId }}</span>
                <span>实时读数：{{ item.status }}</span> -->
                <!-- <span>所属租户：{{ item.rentNum }}</span> -->
                <van-switch
                  v-model="item.status"
                  active-value="1"
                  inactive-value="0"
                  class="isSwitch"
                  inactive-color="#dddddd"
                  @change="changeElecSwitch(item.status, item.deviceId)"
                />
              </template>
            </div>
          </van-list>
        <!-- </van-pull-refresh> -->
      </div>
    </div>
    <van-popup v-model:show="showRepairPositionPicker" round position="bottom">
      <van-picker
        title="标题"
        :columns="positionList"
        :columns-field-names="fieldNames"
        @cancel="showRepairPositionPicker = false"
        @confirm="confirmPosition"
      />
    </van-popup>
    <van-popup v-model:show="showControl" round position="bottom">
      <van-picker
        v-model="checkedMs"
        title="请选择"
        :columns="controlList"
        @confirm="onConfirmMs"
        @cancel="showControl = false"
      />
    </van-popup>
  </div>
</template>
<script>
import api from "../utils/api";
import { ref } from "vue";
import { isEmpty } from "@/utils/index.js";
import VCountUp from "./CountUp";
import { Notify, Dialog, showConfirmDialog } from "vant";
export default {
  components: {
    "v-count-up": VCountUp,
  },
  setup() {
    //指令下发
    const controlList = ref([]);
    const showControl = ref(false);
    const deviceId = ref("");
    const module = ref("");
    //切换模式start
    const checkedMs = ref([]);
    const msCurrentIndex = ref(0);
    const moshitxt = ref([
      { text: "制热", value: 1 },
      { text: "制冷", value: 2 },
      { text: "送风", value: 4 },
      { text: "除湿", value: 8 },
    ]);
    //切换模式end
    //切换温度start
    const checkedWd = ref("");
    const wdCurrentIndex = ref(0);
    const wendu = ref([]);
    //切换温度end
    const checkedFs = ref("");
    const fsCurrentIndex = ref(0);
    const fengs = ref([
      { text: "自动", value: 0 },
      { text: "低速", value: 1 },
      { text: "中速", value: 2 },
      { text: "高速", value: 3 },
    ]);
    const fieldNames = ref({
      text: "orgName",
      value: "orgId",
      children: "childrenList",
    });
    const storeyId=ref('');
    const buildingId=ref('');
    const positionList = ref([]); //定位
    const page=ref('1');

    function ms(data) {
      let text = "";
      let node = this.moshitxt.filter((item) => {
        return item.value == data;
      });
      if (node[0]) {
        text = node[0].text;
      }
      return text;
    }
    function fs(data) {
      let text = "";
      let node = this.fengs.filter((item) => {
        return item.value == data;
      });
      if (node[0]) {
        text = node[0].text;
      }
      return text;
    }
    return {
      page,
      module,
      deviceId,
      controlList,
      showControl,
      ms,
      moshitxt,
      checkedMs,
      msCurrentIndex,
      wendu,
      checkedWd,
      wdCurrentIndex,
      fs,
      fengs,
      checkedFs,
      fsCurrentIndex,
      fieldNames,
      positionList,
      buildingId,
      storeyId,
    };
  },
  data() {
    return {
      showRepairPositionPicker: false,
      loading: false,
      name: "电商园四期",
      deviceType: "AirConditioner",
      deviceStatus: "",
      deviceTypeTitle: "空调",
      deviceStatusTitle: "设备状态",
      deviceTypeList: [
        { text: "空调", value: "AirConditioner" },
        { text: "水表", value: "WaterMeter" },
        { text: "电表", value: "Ammeter" },
      ],
      deviceStatusList: [
        { text: "连接中", value: 1 },
        { text: "断连中", value: 0 },
      ],
      total:0,
      list: [],
      loading: false,
      refreshing: false,
      finished: false,
    };
  },
  watch: {
    positionList(newval, oldval) {
      if (newval) {
        let json = {
          category: "s",
          childrenList: null,
          orgId: "",
          orgName: "全部",
        };
        for (let i = 0; i < newval.length; i++) {
          newval[i].childrenList.push(json);
        }
      }
    },
  },
  created() {
    this.getBuildList();
    this.setwendu();
    //this.getAircond();
  },
  methods: {
    //定位完成
    confirmPosition(val) {
      this.buildingId=val[0].orgId;
      this.storeyId=val[1].orgId;
      let storeyName=val[1].orgName=='全部'?'':val[1].orgName+'-';
      this.name="电商园四期-"+val[0].orgName+storeyName;
      this.showRepairPositionPicker=false;
    },
    //继电器下发指令开关
    changeElecSwitch(val, deviceId) {
      api
        .setControlElec({
          keyword: "setRelay",
          param: val ? 0 : 1,
          deviceId: deviceId,
        })
        .then((res) => {
          if (res.code == 0) {
            Notify({ type: "success", message: "操作成功" });
          }
        });
    },
    //空调下发指令开关
    changeSwitch(val, index, deviceId) {
      api
        .setControl({
          keyword: "setPower",
          param: val ? 0 : 1,
          deviceId: deviceId,
        })
        .then((res) => {
          if (res.code == 0) {
            Notify({ type: "success", message: "操作成功" });
          }
        });
    },
    onConfirmMs(data) {
      let deviceCommandDTO = {};
      switch (this.module) {
        case "moshitxt":
          this.checkedMs[0] = data.value;
          this.list[this.msCurrentIndex].attributeList[2].value = data.value;
          this.showControl = false;
          deviceCommandDTO = {
            keyword: "setMode",
            param: data.value,
            deviceId: this.deviceId,
          };
          break;
        case "wendu":
          console.log(data);
          this.checkedMs[0] = data;
          this.list[this.msCurrentIndex].attributeList[5].value = data;
          this.showControl = false;
          deviceCommandDTO = {
            keyword: "setTemp",
            param: data,
            deviceId: this.deviceId,
          };
          break;
        case "fengs":
          this.checkedMs[0] = data.value;
          this.list[this.msCurrentIndex].attributeList[0].value = data.value;
          this.showControl = false;
          deviceCommandDTO = {
            keyword: "setFan",
            param: data.value,
            deviceId: this.deviceId,
          };
          break;
      }
      api.setControl(deviceCommandDTO).then((res) => {
        if (res.code == 0) {
          Notify({ type: "success", message: "操作成功" });
        }
      });
    },
    chooseMs(name, val, index, deviceId) {
      this.deviceId = deviceId;
      this.msCurrentIndex = index;
      this.showControl = true;
      this.controlList = this[name];
      this.module = name;
    },
    setwendu() {
      this.wendu = [];
      for (let i = 16; i < 33; i++) {
        this.wendu.push(i);
      }
    },
    elecControl(id, state) {
      console.log(id, state);
      Dialog.confirm({
        title: "标题",
        message: "确定执行该操作？",
      })
        .then(() => {
          api
            .elecControl({
              keyword: "setRelay",
              deviceId: id,
              param: state ? "1" : "0",
            })
            .then((res) => {
              console.log(res);
              if (res.code == 0) {
                this.getElec();
              }
            });
        })
        .catch(() => {
          // on cancel
        });
    },
    getElec() {
      console.log(this.page)
      api
        .getElec({
          buildingId:this.buildingId,
          storeyId:this.storeyId,
          page:this.page,
          limit: 10,
          status: this.deviceStatus,
          controlCategory: "CommonLighting",
        })
        .then((res) => {
          console.log(res)
          if (res.code == 0) {
            this.total = res.data.total;
            this.list=this.list.concat(res.data.list);
            this.loading = false;
            if( res.data.list.length<10){
              this.finished=true;
            }else{
              this.page++;
            }
            console.log(this.list)
            // for(let i=0;i<res.data.list.length;i++){
            //   if(res.data.list[i].attributeList&&res.data.list[i].attributeList.length!=0){
            //     this.list.push(res.data.list[i])
            //   }
            // }
          }
        });
    },
    getAircond() {
      api
        .airconditioner({
          page:this.page,
          limit: 10,
          buildingId:this.buildingId,
          storeyId:this.storeyId,
        })
        .then((res) => {
          if (res.code == 0) {
            this.total = res.data.total;
            for (let i = 0; i < res.data.list.length; i++) {
              if (
                res.data.list[i].attributeList &&
                res.data.list[i].attributeList.length != 0
              ) {
                this.list.push(res.data.list[i]);
              }
            }
            if( res.data.list.length<10){
              this.finished=true;
            }else{
              this.page++;
            }
            this.loading = false;
          }
        });
    },
    deviceStatus_filter(val) {
      if (isEmpty(val)) {
        return {};
      }
      if (val == 1) {
        return {
          label: "连接中",
          color: "#09C700",
          btn: "断闸",
        };
      }
      if (val == 0) {
        return {
          label: "断连中",
          color: "#FA5555",
          btn: "开闸",
        };
      }
    },
    //获取楼栋
    getBuildList() {
      api.getBuildInfo().then((res) => {
        if (res.code == 0) {
          this.positionList = res.data[0].childrenList;
          if (this.positionList) {
            let json = {
              category: "s",
              childrenList: null,
              orgId: "",
              orgName: "全部",
            };
            for (let i = 0; i < this.positionList.length; i++) {
              this.positionList[i].childrenList.unshift(json);
            }
          }
        }
      });
    },
    onLoad() {
      this.loading = true;
      if(this.deviceType=='AirConditioner'){
        this.getAircond()
      }else{
         this.getElec();
      }
    },
    // onRefresh() {
    //  // 清空列表数据
    //   finished.value = false;
    //   // 重新加载数据
    //   // 将 loading 设置为 true，表示处于加载状态
    //   loading.value = true;
    //   this.onLoad();
    // },
    // change事件可以拿到的是value
    handelChange(type, lackTypeTitle, lackTypeList, val) {
      this[type] = val;
      console.log(this.deviceType)
      this.list=[];
      this.page=1;
      this.finished=true;
      if (this.deviceType == "Ammeter") this.getElec();
      if (this.deviceType == "AirConditioner") this.getAircond();
      // 显示中文名字
      this[lackTypeTitle] = this[lackTypeList].filter(
        (item) => item.value === val
      )[0].text;
    },
    onClickLeft() {
      this.$router.back();
    },
  },
};
</script>
<style lang="scss" scoped>
.page_check {
  height: 100%;
  .search_pannel {
    padding: 10px 16px;
    background: #5c8fff;
    box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.04);
    display: flex;
    align-items: center;
    .pannel_left {
      display: flex;
      align-items: center;
      span {
        height: 24px;
        font-size: 16px;
        font-weight: 400;
        color: #ffffff;
        line-height: 24px;
        text-shadow: 0px 2px 4px rgba(0, 0, 0, 0.04);
        text-indent: 4px;
      }
    }
    .pannel_left,
    .pannel_right {
      flex: 1;
    }
    .pannel_right {
      text-align: right;
    }
  }
  .drop_down {
    /deep/ {
      --van-gray-4: #999999;
      --van-dropdown-menu-title-text-color: #0c1935;
    }
  }
  .list_total {
    padding: 0 16px;
    margin: 8px 0;
    display: flex;
    text-align: left;
    span {
      height: 16px;
      font-size: 12px;
      font-weight: 400;
      color: #999999;
      line-height: 16px;
    }
    .count_up {
      font-size: 16px;
      font-weight: 500;
      color: #fa5555;
      margin: 0 2px;
    }
  }
  .check_info {
    padding: 0 16px;
    height: calc(
      100% - var(--van-nav-bar-height) - var(--van-dropdown-menu-height) - 76px
    );
    .info_list {
      height: 100%;
      overflow-y: auto;
      .list_item {
        background: #ffffff;
        box-shadow: 0px 0px 10px 0px rgba(153, 153, 153, 0.15);
        border-radius: 4px;
        margin-bottom: 12px;
        padding: 12px 16px;
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        position: relative;
        &:nth-last-child(1) {
          margin-bottom: 0;
        }
        .header {
          height: 22px;
          font-size: 16px;
          font-weight: 600;
          color: #313836;
          line-height: 22px;
          margin-bottom: 8px;
        }
        span {
          height: 18px;
          font-size: 14px;
          font-weight: 400;
          color: #999999;
          line-height: 18px;
          margin-bottom: 4px;
          &:nth-last-child(1) {
            margin-bottom: 0;
          }
        }
        .reduce_type {
          position: absolute;
          top: 0;
          right: 0;
          width: 48px;
          height: 24px;
          border-radius: 0px 4px 0px 10px;
          span {
            height: 16px;
            font-size: 12px;
            font-weight: 400;
            color: #ffffff;
            line-height: 16px;
          }
        }
        // .list_btn {
        //   position: absolute;
        //   bottom: 15px;
        //   right: 12px;
        //   .van-button {
        //     &:nth-child(2) {
        //       margin: 0 12px;
        //     }
        //   }
        // }
        .isSwitch {
          position: absolute;
          right: 10px;
          font-size: 18px;
          top: auto;
          z-index: 1;
        }
        .operation {
          width: 100%;
          position: relative;
          font-size: 13px;
          margin-top: 10px;
          .xl {
            margin-left: 4px;
          }
          .line {
            position: absolute;
            top: 15%;
            width: 2px;
            height: 16px;
            background: #d6d6d6;
          }
        }
      }
    }
  }
}
</style>