<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="SN" prop="deviceNo">
        <el-input
          v-model="queryParams.deviceNo"
          placeholder="请输入设备SN"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="MAC" prop="mac">
        <el-input
          v-model="queryParams.mac"
          placeholder="请输入设备Mac"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="型号" prop="model">
        <el-input
          v-model="queryParams.model"
          placeholder="请输入型号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备名称" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="店铺名称" prop="storeName">
        <el-input
          v-model="queryParams.storeName"
          placeholder="请输入店铺名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="在线状态" prop="onlineStatus">
        <el-select v-model="queryParams.onlineStatus" placeholder="请选择在线状态" clearable @change="handleQuery">
          <el-option
            v-for="dict in dict.type.sm_device_online_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable @change="handleQuery">
          <el-option
            v-for="dict in dict.type.sm_device_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <device-table :loading="loading" :data="deviceList" @selection-change="handleSelectionChange" :view="agentViews.agent">
      <template v-slot:operate="scope">
        <el-button
          size="mini"
          type="text"
          icon="el-icon-view"
          @click="handleSee(scope.row)"
        >详情</el-button>
        <el-button
          size="mini"
          type="text"
          icon="el-icon-edit"
          @click="handleUpdate(scope.row)"
        >修改</el-button>
        <el-button
          size="mini"
          type="text"
          icon="el-icon-delete"
          v-if="scope.row.userId != null"
          @click="handleUnbind(scope.row)"
        >解绑商户</el-button>
      </template>
    </device-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <sn-input :show.sync="showBindSn" @submit="onSubmitSn"></sn-input>

    <!-- 添加或修改设备对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="400px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="5em">
        <el-row :gutter="gutter">
          <form-col :span="span" label="服务费" prop="agentServiceRate">
            <el-input v-model="form.agentServiceRate" placeholder="请输入服务费" >
              <template #append>%</template>
            </el-input>
          </form-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--型号选择弹窗-->
    <model-dialog
      :show.sync="showCheckModel"
      @select="onSubmitBatchModel"
    />

  </div>
</template>

<script>
import {
  updateDeviceSn,
  batchUpdateModel, updateDeviceServiceRate
} from '@/api/system/device'
import ModelSelect from "@/components/Business/Model/modelSelect.vue";
import SmUserSelect from "@/components/Business/SmUser/smUserSelect.vue";
import QrCode from "@/components/QrCode/index.vue";
import {getWxIndexUrl} from "@/utils/wx";
import SnInput from '@/components/SnInput/index.vue'
import StoreInput from '@/components/Business/Store/StoreInput.vue'
import UserInput from '@/components/Business/SmUser/UserInput.vue'
import { isEmpty } from '@/utils'
import ModelDialog from '@/components/Business/Model/modelDialog.vue'
import UserLink from '@/components/Business/SmUser/UserLink.vue'
import StoreLink from '@/components/Business/Store/StoreLink.vue'
import DeviceLink from '@/components/Business/Device/DeviceLink.vue'
import { $serviceType } from '@/utils/mixins'
import { mchGetDevice, mchUpdateDevice } from '@/api/mch/device'
import DeviceTable from '@/views/system/device/components/DeviceTable.vue'
import { agentListDevice, agentUnbindDeviceMch, agentUpdateDevice } from '@/api/agent/device'
import { agentViews, views } from '@/utils/constants'

export default {
  name: "MyDevice",
  mixins: [$serviceType],
  components: { DeviceTable, DeviceLink, StoreLink, UserLink, ModelDialog, UserInput, StoreInput, SnInput, QrCode, SmUserSelect, ModelSelect},
  dicts: ['sm_device_online_status', 'sm_device_status', 'sm_device_outage_way','sm_device_notice_way', 'service_type', 'time_unit'],
  data() {
    return {
      // 是否展示选择型号弹窗
      showCheckModel: false,
      span: 24,
      gutter: 8,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备表格数据
      deviceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        storeName: null,
        deviceName: null,
        model: null,
        mac: null,
        deviceNo: null,
        onlineStatus: null,
        status: null,
        userName: null,
        tenantName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        modelId: [
          { required: true, message: "型号不能为空", trigger: "change" }
        ],
        mac: [
          { required: true, message: "设备MAC不能为空", trigger: "change" }
        ],
      },
      // 房租提醒日期选项配置
      expireDatePickerOptions: {
        disabledDate(date) {
          return date.getTime() <= Date.now();
        }
      },
      showBindSn: false,
      snLoading: false,
    };
  },
  computed: {
    agentViews() {
      return agentViews
    },
    views() {
      return views
    },
    isEdit() {
      return this.title === "修改设备";
    },
    // 二维码文本
    qrCodeText() {
      return (device) => {
        return getWxIndexUrl({ s: device.deviceNo});
      }
    },
  },
  created() {
    this.getList();
  },
  methods: {
    // 选中型号后
    onSubmitBatchModel(model) {
      if (model == null) {
        return;
      }
      batchUpdateModel(this.ids, model.modelId).then(res => {
        if (res.code === 200) {
          this.$message.success("操作成功");
          this.showCheckModel = false;
          this.getList();
        }
      })
    },
    isEmpty,
    handleBindSn(row) {
      this.form.deviceId = row.deviceId;
      this.showBindSn = true;
    },
    // 绑定SN
    onSubmitSn(data) {
      this.snLoading = true;
      updateDeviceSn(this.form.deviceId, data.sn).then(res => {
        if (res.code !== 200) {
          return this.$message.error(res.msg);
        }
        this.$message.success("操作成功");
        this.showBindSn = false;
        this.getList();
      }).finally(()=> {
        this.snLoading = false;
      })
    },
    // 选中店铺后
    onSubmitGroup(group) {
      this.form.groupId = group?.groupId;
      this.form.groupName = group?.groupName;
    },
    // 选中型号后
    onSubmitModel(model) {
      this.form.model = model?.modelName;
      // 若是新增，则填入默认的服务费
      if (this.form.deviceId == null) {
        this.form.serviceType = model?.serviceType;
        this.form.serviceRate = model?.serviceRate;
      }
    },
    /** 查询设备列表 */
    getList() {
      this.loading = true;
      agentListDevice(this.queryParams).then(response => {
        this.deviceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deviceId: null,
        picture: null,
        modelId: null,
        mac: null,
        deviceNo: null,
        deviceName: null,
        serviceType: '1',
        serviceRate: null,
        remark: null,
        startTime: null,
        startUnit: "3",
        startPrice: null,
        overTime: null,
        overUnit: "3",
        overPrice: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deviceId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 查看按钮操作
    handleSee(row) {
      this.$router.push({path: `/device/${row.deviceId}`})
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备";
    },
    // 重置服务费
    handleResetService(row) {
      this.$confirm(`确定重置设备${row.deviceNo}的服务费吗？`, '重置服务费', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        updateDeviceServiceRate(row.deviceId, null).then(res => {
          if (res.code === 200) {
            this.$message.success("重置成功")
          }
        }).finally(() => {
          this.getList();
        })
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const deviceId = row.deviceId || this.ids
      mchGetDevice(deviceId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.deviceId != null) {
            agentUpdateDevice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleBatchModel() {
      this.showCheckModel = true;
    },
    /** 解绑按钮操作 */
    handleUnbind(row) {
      this.$modal.confirm(`是否确认解绑设备【${row.deviceName}(${row.deviceNo})】的商户？`).then(function() {
        return agentUnbindDeviceMch(row.deviceId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("解绑成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/device/export', {
        ...this.queryParams
      }, `device_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
