<template>
  <div class="app-container" v-loading="loading" >
    <div v-if="deviceData">
      <el-row :gutter="12">
        <el-col :lg="deviceData.userId === userId ? 18 : 24" :xs="24">
          <el-card class="box-card">
            <el-descriptions title="归属信息" :column="4">
              <template slot="extra">
                <el-popover
                  placement="left"
                  width="180"
                  trigger="click">
                  <div class="qr-code-box">
                    <qr-code :text="qrCodeText(deviceData)" :width="150" :height="150" />
                    <p>扫描二维码进行设备绑定</p>
                  </div>
                  <el-button slot="reference" type="primary" icon="el-icon-picture">设备二维码</el-button>
                </el-popover>
              </template>
              <el-descriptions-item label="设备名称">{{deviceData.deviceName | defaultValue}}</el-descriptions-item>
              <el-descriptions-item label="店铺名称">
                <store-link :name="deviceData.storeName" :id="deviceData.storeId"/>
              </el-descriptions-item>
              <el-descriptions-item label="服务费">
                <template v-if="deviceData.serviceRate == null || deviceData.serviceType == null">跟随用户</template>
                <template v-else>
                  <dict-tag :options="dict.type.service_type" :value="deviceData.serviceType" size="mini"/>
                  {{deviceData.serviceRate}} {{serviceUnit(deviceData.serviceType)}}
                </template>
              </el-descriptions-item>
              <el-descriptions-item label="备注">{{deviceData.remark | defaultValue}}</el-descriptions-item>
            </el-descriptions>
          </el-card>

          <el-card class="box-card" >
            <el-descriptions title="设备详情" :column="4">
              <el-descriptions-item label="MAC">{{deviceData.mac | defaultValue}}
                <dict-tag :options="dict.type.sm_device_status" :value="deviceData.status" size="mini"/>
              </el-descriptions-item>
              <el-descriptions-item label="SN">{{deviceData.deviceNo | defaultValue}}</el-descriptions-item>
              <el-descriptions-item label="在线状态">
                <dict-tag :options="dict.type.sm_device_online_status" :value="deviceData.onlineStatus" size="mini"/>
              </el-descriptions-item>
              <el-descriptions-item label="开关状态">
                <el-tag :type="isOpen ? 'success' : 'danger'" size="mini">{{isOpen ? '已开启' : '已关闭'}}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="型号">{{deviceData.model | defaultValue}}</el-descriptions-item>
              <el-descriptions-item label="型号功能">
                <dict-tag :options="dict.type.sm_model_tag" :value="deviceData.modelTags" size="mini"/>
              </el-descriptions-item>
              <el-descriptions-item label="设备租期">{{deviceData.rentTime | defaultValue}}</el-descriptions-item>
              <el-descriptions-item label="WIFI">{{deviceData.wifi | defaultValue}}</el-descriptions-item>
              <el-descriptions-item label="剩余时长">{{surplusTimeDesc(surplusTime).text}}</el-descriptions-item>
            </el-descriptions>
          </el-card>
        </el-col>
        <el-col :lg="deviceData.userId === userId ? 6 : 24" :xs="24" >
          <el-card class="box-card" header="设备操作" v-if="deviceData.userId === userId">
            <el-row :gutter="12" style="min-height: 225px;overflow: auto;">
              <el-col :span="12">
                <div class="control-item clickable" @click="handleAddElectricity">
                  <svg-icon  icon-class="time"/> 增加时长
                </div>
              </el-col>
              <el-col :span="12">
                <div class="control-item clickable" @click="handleReset">
                  <svg-icon  icon-class="time-range"/> 时长归零
                </div>
              </el-col>
              <el-col :span="12">
                <div class="control-item clickable" v-if="!isOpen" @click="handleSwitch(1)">
                  <svg-icon  icon-class="switch"/> 开启设备
                </div>
              </el-col>
              <el-col :span="12">
                <div class="control-item clickable" v-if="isOpen" @click="handleSwitch(0)">
                  <svg-icon  icon-class="switch"/> 关闭设备
                </div>
              </el-col>
              <el-col :span="12">
                <div class="control-item clickable" @click="refreshIot(deviceId, true)">
                  <svg-icon  icon-class="refresh"/> 刷新设备信息
                </div>
              </el-col>
              <el-col :span="24">
                <div class="control-item clickable" @click="handleUnbind" style="color: #ff4242">
                  <svg-icon  icon-class="system"/> 解除绑定
                </div>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>
      <el-card class="box-card">
        <el-tabs>
          <el-tab-pane label="套餐列表" :lazy="true" v-if="deviceData.userId === userId">
            <mch-suit v-if="deviceData.deviceId != null" :query="{deviceId: deviceData.deviceId}"/>
          </el-tab-pane>
          <el-tab-pane label="订单列表" :lazy="true">
            <mch-recharge v-if="deviceData.deviceId != null"  :query="{deviceId: deviceData.deviceId}" :view="views.device"/>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    <el-empty v-else description="设备已被删除或不存在"/>

    <!--添加时长-->
    <el-dialog title="增加时长" :visible.sync="showAddElectricity" center width="400px">
      <el-form :model="addElectricityForm" :rules="addRules">
        <el-form-item label="时长" prop="amount">
          <el-input-number v-model="addElectricityForm.amount" style="width: 250px" controls-position="right" :step="1" step-strictly :min="0"/> 分钟
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" plain @click="submitAddElectricity">确认</el-button>
        <el-button plain @click="showAddElectricity = false">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>

import LineChart from "@/views/dashboard/LineChart.vue";
import QrCode from "@/components/QrCode/index.vue";
import {getWxIndexUrl} from "@/utils/wx";
import { toDescriptionFromSecond } from '@/utils/date'
import StoreLink from '@/components/Business/Store/StoreLink.vue'
import UserLink from '@/components/Business/SmUser/UserLink.vue'
import { $serviceType } from '@/utils/mixins'
import {
  mchAddTime,
  mchGetDevice,
  mchRefreshIot,
  mchResetDevice,
  mchSwitchDevice,
  mchUnbindDevice
} from '@/api/mch/device'
import { mapGetters } from 'vuex'
import MchSuit from '@/views/mch/suit/index.vue'
import MchRecharge from '@/views/mch/recharge/index.vue'
import { SmUserType, views } from '@/utils/constants'

export default {
  name: 'MyDeviceDetail',
  mixins: [$serviceType],
  components: {
    MchRecharge,
    MchSuit,
    UserLink,
    StoreLink,
    QrCode,
    LineChart
  },
  dicts: ['sm_device_status', 'sm_device_outage_way', 'sm_device_notice_way', 'sm_model_tag', 'sm_device_online_status', 'service_type'],
  data() {
    return {
      loading: false,
      deviceData: {},
      timer: null,
      surplusTime: 0, // 剩余时长
      addElectricityForm: {
        amount: 0
      },
      showAddElectricity: false,
      addRules: {
        amount: [
          { required: true, message: '请输入电量', trigger: 'blur' }
        ]
      },
      // 设备ID
      deviceId: null,
    }
  },
  computed: {
    SmUserType() {
      return SmUserType
    },
    views() {
      return views
    },
    ...mapGetters(['userId', 'smUserType']),
    qrCodeText() {
      return (device) => {
        return getWxIndexUrl({ s: device.deviceNo});
      }
    },
    surplusTimeDesc() {
      return (second) => {
        return toDescriptionFromSecond(second);
      }
    },
    isOpen() {
      return this.deviceData != null && this.deviceData.powerStatus === '1';
    }
  },
  created() {
    this.deviceId = this.$route.params.deviceId;
    this.refreshIot(this.deviceId);
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
  methods: {
    handleUnbind() {
      this.$confirm('是否强制解绑该设备？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        mchUnbindDevice(this.deviceData.deviceId).then(res => {
          if (res.code === 200) {
            this.$message.success("操作成功");
          }
        }).finally(() => {
          this.getDevice();
        })
      })
    },
    handleSwitch(status) {
      this.$confirm(`是否确认强制${status === 1 ? '开启' : '关闭'}设备？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        mchSwitchDevice(this.deviceData.deviceId, status).then(res => {
          if (res.code === 200) {
            this.$message.success("操作成功");
            this.deviceData.powerStatus = status === 1 ? '1' : '0';
          }
        }).finally(() => {
          this.loading = false;
        })
      })
    },
    // 计算剩余时长
    computeSurplusTime() {
      if (this.deviceData.expireTime == null) {
        return 0;
      }
      let expireTime = new Date(this.deviceData.expireTime).getTime();
      let now = new Date().getTime();
      if (expireTime < now) {
        return 0;
      }
      return ((expireTime - now) / 1000).toFixed(2);
    },
    handleReset() {
      this.$confirm('是否确认归零设备？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        mchResetDevice(this.deviceData.deviceId).then(res => {
          if (res.code === 200) {
            this.$message.success('操作成功');
            this.getDevice();
          }
        })
      })
    },
    handleAddElectricity() {
      this.resetAddElectricityForm();
      this.showAddElectricity = true;
    },
    submitAddElectricity() {
      mchAddTime(this.deviceData.deviceId, this.addElectricityForm.amount).then(res => {
        if (res.code === 200) {
          this.$message.success('操作成功');
          this.showAddElectricity = false;
          this.getDevice();
        }
      })
    },
    resetAddElectricityForm() {
      this.addElectricityForm = {
        amount: 0
      }
    },
    // 刷新设备信息
    refreshIot(deviceId, notice = false) {
      this.loading = true;
      mchRefreshIot(deviceId).then(res => {
        if (res.code !== 200) {
          return this.$message.error(res.msg);
        }
        if (notice) {
          this.$message.success('操作成功');
        }
      }).finally(() => {
        this.getDevice();
      })
    },
    getDevice() {
      this.loading = true;
      mchGetDevice(this.deviceId).then(response => {
        this.deviceData = response.data;
        this.surplusTime = this.computeSurplusTime();
        if (this.timer == null) {
          this.timer = setInterval(() => {
            this.surplusTime = this.computeSurplusTime();
          }, 1000)
        }
      }).finally(() => {
        this.loading = false;
      })
    },
  }
}
</script>

<style scoped>
.remark-text {
  color: #ccc;
  margin-left: 1em;
}
.control-item {
  padding: 1em;
  border-radius: 16px;
  text-align: center;
  margin-bottom: 1em;
}
</style>
