<template>
  <div class="app-container" v-loading="loading" >
    <div v-if="deviceData">
      <el-row :gutter="12">
        <el-col :lg="18" :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 style="text-align: center">设备二维码</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="MAC">{{deviceData.mac | defaultValue}}</el-descriptions-item>
              <el-descriptions-item label="SN">{{deviceData.deviceNo | defaultValue}}</el-descriptions-item>
              <el-descriptions-item label="型号">{{deviceData.model | defaultValue}}</el-descriptions-item>
              <el-descriptions-item label="状态">
                <dict-tag :options="dict.type.sm_device_status" :value="deviceData.status" size="mini"/>
              </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="型号功能" :span="2">
                <dict-tag :options="dict.type.sm_model_tag" :value="deviceData.modelTags" size="mini"/>
              </el-descriptions-item>
              <el-descriptions-item label="剩余时长">{{surplusTimeDesc(surplusTime).text}}</el-descriptions-item>
              <el-descriptions-item label="备注" :span="3">{{deviceData.remark | defaultValue}}</el-descriptions-item>
              <el-descriptions-item label="尺寸">{{deviceData.size | defaultValue}}</el-descriptions-item>
              <el-descriptions-item label="面料">{{deviceData.fabric | defaultValue}}</el-descriptions-item>
              <el-descriptions-item label="填充物">{{deviceData.fill | defaultValue}}</el-descriptions-item>
            </el-descriptions>
          </el-card>

          <el-card class="box-card">
            <el-row type="flex">
              <el-statistic :title="FieldName.BIZ" v-if="[SmUserType.AGENT].includes(this.smUserType)">
                <template #formatter>
                  <user-link :name="deviceData.bizManName" :id="deviceData.bizManId" :is-link="[SmUserType.BIZ, SmUserType.AGENT].includes(smUserType)" class="statistic-link"/>
                </template>
              </el-statistic>
              <el-statistic :title="FieldName.INVESTOR"  v-if="[SmUserType.AGENT, SmUserType.BIZ].includes(this.smUserType)">
                <template #formatter>
                  <user-link :name="deviceData.userName" :id="deviceData.userId" :is-link="[SmUserType.BIZ, SmUserType.AGENT].includes(smUserType)" class="statistic-link"/>
                </template>
              </el-statistic>
              <el-statistic :title="FieldName.STORE">
                <template #formatter>
                  <store-link :name="deviceData.storeName" :id="deviceData.storeId" :is-link="false" class="statistic-link"/>
                </template>
              </el-statistic>
              <el-statistic title="房间号">
                <template #formatter>
                  {{deviceData.room | defaultValue}}
                </template>
              </el-statistic>
              <el-statistic title="订单总数" :value="deviceData.orderCount" :precision="0" suffix="单"/>
              <el-statistic title="订单金额" :value="deviceData.orderAmount" :precision="2" suffix="元"/>
            </el-row>
          </el-card>
        </el-col>
        <el-col :lg="6" :xs="24">
          <el-card class="box-card" header="分成详情">
            <div style="height: 228px;overflow: auto;">
              <el-result v-if="isEmpty(deviceData.bonusList)" sub-title="暂无分成信息"/>
              <line-field v-for="item of deviceData.bonusList" :label="item.arrivalName">
                <template #label>
                  <div style="display: flex">
                    <dict-tag :options="dict.type.bonus_arrival_type" :value="item.arrivalType" size="mini"/>
                    <div style="margin-left: 0.5em">
                      <user-link v-if="BonusArrivalType.userList().includes(item.arrivalType)" :id="item.arrivalId" :name="item.arrivalName" />
                      <template v-else>{{item.arrivalName}}</template>
                    </div>
                  </div>
                </template>
                {{item.point | money | defaultValue}} %
              </line-field>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-card class="box-card">
        <el-tabs>
          <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 { BonusArrivalType, FieldName, SmUserType, views } from '@/utils/constants'
import { agentGetDevice } from '@/api/agent/device'
import LineField from '@/components/LineField/index.vue'
import { isEmpty } from '@/utils'
import smUser from '@/views/system/smUser/index.vue'
import SmUser from '@/views/system/smUser/index.vue'
import { bizGetDevice } from '@/api/biz/device'

export default {
  name: 'MyDeviceDetail',
  mixins: [$serviceType],
  components: {
    LineField,
    MchRecharge,
    MchSuit,
    UserLink,
    StoreLink,
    QrCode,
    LineChart
  },
  dicts: ['sm_device_status', 'sm_model_tag', 'sm_device_online_status', 'bonus_arrival_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: {
    SmUser() {
      return SmUser
    },
    ...mapGetters(['userId', 'smUserType']),
    SmUserType() {
      return SmUserType
    },
    smUser() {
      return smUser
    },
    BonusArrivalType() {
      return BonusArrivalType
    },
    FieldName() {
      return FieldName
    },
    views() {
      return views
    },
    qrCodeText() {
      return (device) => {
        return getWxIndexUrl({ s: device.deviceNo});
      }
    },
    surplusTimeDesc() {
      return (second) => {
        return toDescriptionFromSecond(second);
      }
    },
    isOpen() {
      return this.deviceData != null && this.deviceData.powerStatus === '1';
    },
    // 详情API
    detailApi() {
      if (this.smUserType === SmUserType.AGENT) {
        return agentGetDevice;
      } else if (this.smUserType === SmUserType.BIZ) {
        return bizGetDevice;
      } else {
        return mchGetDevice;
      }
    }
  },
  created() {
    this.deviceId = this.$route.params.deviceId;
    this.refreshIot(this.deviceId);
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
  methods: {
    isEmpty,
    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;
      this.detailApi(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>
