<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="MAC" prop="mac">
        <el-input
          v-model="queryParams.mac"
          placeholder="请输入设备Mac"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <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="设备名称" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          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="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 label="使用状态" prop="isUsing">
        <el-select v-model="queryParams.isUsing" placeholder="请选择使用状态" clearable @change="handleQuery">
          <el-option :value="true" label="使用中"/>
          <el-option :value="false" label="待使用"/>
        </el-select>
      </el-form-item>
      <el-form-item :label="FieldName.AGENT" prop="agentName">
        <el-input
          v-model="queryParams.agentName"
          :placeholder="`请输入${FieldName.AGENT}名称`"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="FieldName.BIZ" prop="bizManName">
        <el-input
          v-model="queryParams.bizManName"
          :placeholder="`请输入${FieldName.BIZ}名称`"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="FieldName.INVESTOR" prop="userName">
        <el-input
          v-model="queryParams.userName"
          :placeholder="`请输入${FieldName.INVESTOR}名称`"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="FieldName.STORE" prop="storeName" v-if="notHasView(views.store)">
        <el-input
          v-model="queryParams.storeName"
          placeholder="请输入经营场所名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:device:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:device:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:device:export']"
        >导出</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          @click="handleBatchModel"-->
<!--          :disabled="multiple"-->
<!--          v-hasPermi="['system:device:edit']"-->
<!--        >批量修改型号</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备ID" align="center" prop="deviceId" width="80"/>
      <el-table-column label="图片" align="center" prop="picture" width="100">
        <template slot-scope="scope">
          <image-preview v-if="isEmpty(scope.row.customPicture)" :src="scope.row.picture" :width="50" :height="50"/>
          <image-preview v-else :src="scope.row.customPicture" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="二维码" align="center" width="80">
        <template slot-scope="d">
          <el-popover
            placement="top"
            width="180"
            trigger="hover">
            <div class="qr-code-box">
              <qr-code :text="qrCodeText(d.row)" :width="150" :height="150" />
              <p style="text-align: center">设备二维码</p>
            </div>
            <el-button slot="reference" type="text" icon="el-icon-picture">查看</el-button>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="设备Mac" align="center" prop="mac" min-width="100">
        <device-link slot-scope="d" :text="d.row.mac" :id="d.row.deviceId"/>
      </el-table-column>
      <el-table-column label="设备SN" align="center" prop="deviceNo" min-width="100">
        <template slot-scope="d">
          <el-link type="danger" v-if="d.row.deviceNo == null" @click="handleBindSn(d.row)">点击绑定</el-link>
          <device-link v-else :text="d.row.deviceNo" :id="d.row.deviceId"/>
        </template>
      </el-table-column>
      <el-table-column label="设备名称" align="center" prop="deviceName" >
        <device-link slot-scope="d" :text="d.row.deviceName" :id="d.row.deviceId"/>
      </el-table-column>
      <el-table-column label="型号" align="center" prop="model" />
      <el-table-column label="在线状态" align="center" prop="onlineStatus" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sm_device_online_status" :value="scope.row.onlineStatus"/>
        </template>
      </el-table-column>
<!--      <el-table-column label="状态" align="center" prop="status" width="80">-->
<!--        <template slot-scope="scope">-->
<!--          <dict-tag :options="dict.type.sm_device_status" :value="scope.row.status"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="使用状态" align="center" prop="status" width="80">
        <template slot-scope="scope">
          <device-using-status-tag :is-using="scope.row.isUsing"/>
        </template>
      </el-table-column>
      <el-table-column :label="FieldName.AGENT" align="center" prop="agentName" >
        <user-link slot-scope="d" :id="d.row.agentId" :name="d.row.agentName"/>
      </el-table-column>
      <el-table-column :label="FieldName.BIZ" align="center" prop="bizManName" >
        <user-link slot-scope="d" :id="d.row.bizManId" :name="d.row.bizManName"/>
      </el-table-column>
      <el-table-column :label="FieldName.INVESTOR" align="center" prop="userName" >
        <user-link slot-scope="d" :id="d.row.userId" :name="d.row.userName"/>
      </el-table-column>
      <el-table-column :label="FieldName.STORE" align="center" prop="storeName" >
        <store-link slot-scope="d" :id="d.row.storeId" :name="d.row.storeName"/>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
      <el-table-column label="创建时间" align="center" prop="createTime" width="100"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleSee(scope.row)"
            v-hasPermi="['system:device:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:device:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:device:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-link"
            @click="handleBindInvestor(scope.row)"
            v-show="scope.row.userId == null"
            v-hasPermi="['system:device:bindInvestor']"
          >绑定{{FieldName.INVESTOR}}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-link"
            v-show="scope.row.userId != null"
            @click="handleUnBindInvestor(scope.row)"
            v-hasPermi="['system:device:unbindInvestor']"
          >解绑{{FieldName.INVESTOR}}</el-button>
        </template>
      </el-table-column>
    </el-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="800px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="6em">
        <el-row :gutter="gutter">
          <form-col :span="span * 2"  label="自定义图片" prop="customPicture">
              <image-upload v-model="form.customPicture" :limit="1"/>
          </form-col>
          <form-col :span="span"  label="型号" prop="modelId">
              <model-select v-model="form.modelId" :show-value.sync="form.model" @submit="onSubmitModel"/>
          </form-col>
          <form-col :span="span"  label="设备MAC" prop="mac">
              <el-input v-model="form.mac" placeholder="请输入设备MAC" :disabled="isEdit"/>
          </form-col>
          <form-col :span="span"  label="设备SN" prop="deviceNo">
              <el-input v-model="form.deviceNo" placeholder="请输入设备SN" />
          </form-col>
          <form-col :span="span"  label="设备名称" prop="deviceName">
              <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
          </form-col>
          <form-col :span="span"  :label="FieldName.AGENT" prop="agentId">
            <user-input v-model="form.agentId" :query="{type: SmUserType.AGENT}" @change="onChangeSale"/>
          </form-col>
<!--          <form-col :span="span"  :label="FieldName.INVESTOR" prop="userId">-->
<!--            <user-input v-model="form.userId" :before-open="beforeOpenUser" :query="userQuery(form)" @change="onChangeInvestor"/>-->
<!--          </form-col>-->
          <form-col :span="span"  :label="FieldName.STORE" prop="storeId">
            <store-input v-model="form.storeId" :before-open="beforeOpenStore" :query="storeQuery"/>
          </form-col>
          <form-col :span="span" label="所属房间" prop="room">
            <el-input v-model="form.room" placeholder="请输入所属房间" maxlength="200" show-word-limit/>
          </form-col>
          <form-col :span="span" label="尺寸" prop="size">
              <el-input v-model="form.size" placeholder="请输入尺寸" maxlength="200" show-word-limit/>
          </form-col>
          <form-col :span="span" label="面料" prop="fabric">
              <el-input v-model="form.fabric" placeholder="请输入面料" maxlength="200" show-word-limit/>
          </form-col>
          <form-col :span="span" label="填充物" prop="fill">
              <el-input v-model="form.fill" placeholder="请输入填充物" maxlength="200" show-word-limit/>
          </form-col>
          <form-col :span="span * 2" label="功能介绍" prop="funcInfo">
            <editor v-model="form.funcInfo" :min-height="200"/>
          </form-col>
          <form-col :span="span * 2" label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" maxlength="200" show-word-limit/>
          </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"
    />

    <device-bind-investor
      ref="bindInvestor"
      :show.sync="showCheckBindInvestor"
      :row="row"
      @success="getList"
    />

  </div>
</template>

<script>
import {
  listDevice,
  getDevice,
  addDevice,
  updateDevice,
  logicDelDevice,
  updateDeviceSn,
  batchUpdateModel, updateDeviceServiceRate, unbindInvestor
} 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, $view } from '@/utils/mixins'
import { FieldName, SmUserType } from '@/utils/constants'
import DeviceUsingStatusTag from '@/views/system/device/components/DeviceUsingStatusTag.vue'
import SmUserDialog from '@/components/Business/SmUser/smUserDialog.vue'
import DeviceBindInvestor from '@/views/system/device/components/DeviceBindInvestor.vue'

export default {
  name: "Device",
  mixins: [$serviceType, $view],
  dicts: ['sm_device_online_status', 'sm_device_status', 'sm_device_outage_way','sm_device_notice_way', 'service_type', 'time_unit'],
  components: { DeviceBindInvestor, SmUserDialog, DeviceUsingStatusTag, DeviceLink, StoreLink, UserLink, ModelDialog, UserInput, StoreInput, SnInput, QrCode, SmUserSelect, ModelSelect},
  props: {
    query: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      // 当前选中
      row: {},
      // 是否展示选择绑定投资人
      showCheckBindInvestor: false,
      // 是否展示选择型号弹窗
      showCheckModel: false,
      span: 12,
      gutter: 8,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备表格数据
      deviceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storeName: null,
        deviceName: null,
        model: null,
        mac: null,
        deviceNo: null,
        onlineStatus: null,
        status: null,
        userName: null,
        tenantName: null,
        isArrears: null,
        isUsing: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        modelId: [
          { required: true, message: "型号不能为空", trigger: "change" }
        ],
        mac: [
          { required: true, message: "设备MAC不能为空", trigger: "change" }
        ],
        deviceNo: [
          { required: true, message: "设备SN不能为空", trigger: "blur" }
        ]
      },
      // 房租提醒日期选项配置
      expireDatePickerOptions: {
        disabledDate(date) {
          return date.getTime() <= Date.now();
        }
      },
      showBindSn: false,
      snLoading: false,
    };
  },
  computed: {
    FieldName() {
      return FieldName
    },
    SmUserType() {
      return SmUserType
    },
    isEdit() {
      return this.title === "修改设备";
    },
    // 二维码文本
    qrCodeText() {
      return (device) => {
        return getWxIndexUrl({ s: device.deviceNo});
      }
    },
    // 投资人查询条件
    userQuery() {
      return (row) => {
        return {
          type: SmUserType.INVESTOR,
          agentId: row.agentId
        }
      }
    },
    // 店铺查询条件
    storeQuery() {
      return {
        investorAgentId: this.form.agentId
      }
    }
  },
  created() {
    this.queryParams = {
      ...this.queryParams,
      ...this.query,
      ...this.$route.query
    }
    this.getList();
  },
  methods: {
    onChangeSale(user) {
      if (this.form.userId != null) {
        this.form.userId = null;
        this.$message.info(`由于更改了${FieldName.AGENT}，请重新选择${FieldName.INVESTOR}和${FieldName.STORE}`)
      }
    },
    onChangeInvestor(user) {
      if (this.form.storeId != null) {
        this.form.storeId = null;
        this.$message.info(`由于更改了${FieldName.INVESTOR}，请重新选择${FieldName.STORE}`)
      }
    },
    beforeOpenStore() {
      if (this.form.agentId == null) {
        this.$message.warning(`请先选择${FieldName.AGENT}`);
        return false;
      }
      return true;
    },
    beforeOpenUser() {
      if (this.form.agentId == null) {
        this.$message.warning(`请先选择${FieldName.AGENT}`);
        return false;
      }
      return true;
    },
    // 选中型号后
    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;
      listDevice(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: `/smDevice/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
      getDevice(deviceId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let data = {
            ...this.form,
            funcInfo: encodeURI(this.form.funcInfo)
          }
          if (this.form.deviceId != null) {
            updateDevice(data).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDevice(data).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleBatchModel() {
      this.showCheckModel = true;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deviceIds = row.deviceId || this.ids;
      this.$modal.confirm('是否确认删除设备编号为"' + deviceIds + '"的数据项？').then(function() {
        return logicDelDevice(deviceIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleBindInvestor(row) {
      this.row = row;
      this.showCheckBindInvestor = true;
    },
    handleUnBindInvestor(row) {
      this.$confirm(`确定解绑${row.deviceNo}的${FieldName.INVESTOR}吗？`, '解绑', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        unbindInvestor(row.deviceId).then(res => {
          if (res.code === 200) {
            this.$message.success("操作成功");
            this.getList();
          }
        })
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/device/export', {
        ...this.queryParams
      }, `device_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
