<template>
  <div class='app-container'>
    <el-form inline>
      <el-form-item label="设备名称：">
        <el-input v-model="data.form.name" placeholder="请输入设备名称" clearable />
      </el-form-item>
      <el-form-item label="所属企业：">
        <el-select v-model="data.form.tenantId" placeholder="请选择所属企业" clearable>
          <el-option v-for="item in businessData.options" :key="item.id" :value="item.id" :label="item.name" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备状态：">
        <el-select v-model="data.form.deviceStatus" placeholder="请选择当前状态" clearable>
          <el-option v-for="item in dev_change_status" :key="item.value" :value="item.value" :label="item.label" />
        </el-select>
      </el-form-item>
      <el-form-item label="绑定状态：">
        <el-select v-model="data.form.status" placeholder="请选择当前状态" clearable>
          <el-option v-for="item in sys_change_status" :key="item.value" :value="item.value" :label="item.label" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="getSearch">搜索</el-button>
        <el-button icon="Refresh" @click="getRefresh">重置</el-button>
        <el-button type="primary" plain icon="Plus" @click="getDialog()"
          v-hasPermi="['store:devices:add']">关联设备</el-button>
      </el-form-item>
      <el-form-item>
        <el-button :type="grid ? 'primary' : ''" icon="Grid" title="九宫格" @click="grid = true" />
        <el-button :type="grid ? '' : 'primary'" icon="Expand" title="列表" @click="grid = false" />
      </el-form-item>
    </el-form>
    <!-- 列表 -->
    <el-table v-show="!grid" :data="data.tableData" v-loading="loading">
      <el-table-column label="设备名称" prop="deviceName" align="center" />
      <el-table-column label="设备型号" prop="clientType" align="center" />
      <el-table-column label="设备Mac" prop="deviceMac" align="center" />
      <el-table-column label="设备图片" align="center" width="100px">
        <template #default="scope">
          <el-image :src="scope.row.devicePic" />
        </template>
      </el-table-column>
      <el-table-column label="设备分类" prop="deviceCategoryName" align="center" />
      <el-table-column label="所属门店" prop="storeName" align="center" />
      <el-table-column label="所属城市" align="center">
        <template #default="scope">
          <span>{{ scope.row.provinceName }}</span>
          <span v-if="scope.row.cityName"> - {{ scope.row.cityName }}</span>
          <span v-if="scope.row.areaName"> - {{ scope.row.areaName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="设备状态" prop="status" align="center">
        <template #default="scope">
          <dict-tag :options="dev_change_status" :value="scope.row.deviceStatus" />
        </template>
      </el-table-column>
      <el-table-column label="绑定状态" prop="status" align="center">
        <template #default="scope">
          <dict-tag :options="sys_change_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="getDialog(scope.row.id)"
            v-hasPermi="['store:devices:edit']">编辑</el-button>
          <el-button v-if="scope.row.status == 1" type="primary" link @click="getChange(scope.row.id, '上架', 0)"
            v-hasPermi="['store:devices:on']">上架</el-button>
          <el-button v-else type="primary" link @click="getChange(scope.row.id, '下架', 1)"
            v-hasPermi="['store:devices:off']">下架</el-button>
          <el-button type="danger" link @click="getDelete(scope.row)"
            v-hasPermi="['store:devices:delete']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="grid" class="card_box">
      <div class="card" v-for="item in data.tableData" :key="item">
        <div class="card-header">
          <i class="state" :style="{ 'backgroundColor': item.deviceStatus === 0 ? '#8aff5b' : '#ff0000' }" />
          <el-dropdown v-hasPermi="['store:devices:edit', 'store:devices:delete']">
            <el-icon>
              <MoreFilled />
            </el-icon>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-if="checkPermi(['store:devices:edit'])" @click="getDialog(item.id)">
                  编辑
                </el-dropdown-item>
                <el-dropdown-item v-if="checkPermi(['store:devices:delete'])" @click="getDelete(item)">
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <el-image class="icon" :src="item.devicePic" />
        <span class="name">{{ item.deviceName }}</span>
      </div>
    </div>
    <pagination v-show="total > 0" :total="total" v-model:page="data.form.pageNum" v-model:limit="data.form.pageSize"
      @pagination="getList" />

    <!-- 弹窗 -->
    <el-dialog v-model="dialogVisible" :title="title" width="500" :before-close="getClose">
      <el-form :model="data.dialogForm" ref="dialogForm" :rules="data.rules" label-width="auto">
        <el-form-item label="设备型号：" prop="clientType">
          <el-select v-model="data.dialogForm.clientType" filterable placeholder="请输入设备型号">
            <el-option v-for="item in deviceOptions" :key="item.clientTypeId" :value="item.clientTypeId"
              :label="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备序列号：" prop="deviceMac">
          <el-input v-model="data.dialogForm.deviceMac" placeholder="请输入设备序列号" />
        </el-form-item>
        <el-form-item label="所属企业：" prop="tenantId">
          <el-select v-model="data.dialogForm.tenantId" placeholder="请输入所属企业" filterable remote
            :remote-method="businessRemote" remote-show-suffix>
            <el-option v-for="item in businessData.options" :key="item.id" :value="item.id" :label="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属门店：" prop="storeId">
          <el-select v-model="data.dialogForm.storeId" placeholder="请选择所属门店" filterable remote
            :remote-method="storeRemote" remote-show-suffix>
            <el-option v-for="item in storeData.options" :key="item.id" :value="item.id" :label="item.name" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="getClose">取消</el-button>
        <el-button type="primary" @click="getSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { list, detail, submit, edit, change, remove } from "@/api/store/devices"
import { useBusinessSelect, useStoreSelect, useDeviceList } from "@/hooks/index"
import { checkPermi } from "@/utils/permission";

const { businessData, getBusiness, businessRemote } = useBusinessSelect(true)
getBusiness()
const { storeData, getStore, storeRemote } = useStoreSelect()
const { deviceOptions } = useDeviceList()

const { proxy } = getCurrentInstance()

const { sys_change_status, dev_change_status } = proxy.useDict("sys_change_status", "dev_change_status");
// 遮罩层
const loading = ref(false)

const data = reactive({
  // 表单
  form: {
    pageNum: 1,
    pageSize: 10
  },
  // 列表
  tableData: [],
  // 弹窗表单
  dialogForm: {},
  // 校验
  rules: {
    clientType: [{
      required: true, message: '请选择设备型号', trigger: 'change'
    }],
    deviceMac: [{
      required: true, message: '请输入设备序列号', trigger: 'blur'
    }],
    tenantId: [{
      required: true, message: '请选择所属企业', trigger: 'change'
    }],
    storeId: [{
      required: true, message: '请选择所属门店', trigger: 'change'
    }]
  }
})

const total = ref(0)

const grid = ref(true)

// 列表
const getList = () => {
  loading.value = true
  list(data.form).then(res => {
    if (res.code === 0) {
      data.tableData = res.data
      total.value = res.total
      loading.value = false
    }
  })
}
getList()

// 搜索
const getSearch = () => {
  data.form.pageNum = 1
  getList()
}

// 重置
const getRefresh = () => {
  data.form = {
    pageNum: 1,
    pageSize: 10
  }
  getList()
}

// 弹窗
const dialogVisible = ref(false)
// 弹窗标题
const title = ref('')
// 打开弹窗
function getDialog(id) {
  dialogVisible.value = true
  title.value = '关联'
  if (id) {
    getDetail(id)
  }
}

// 详情
const getDetail = (id) => {
  title.value = '编辑'
  detail({ id: id }).then(res => {
    if (res.code === 0) {
      data.dialogForm = res.data
    }
  })
}

// 取消
const getClose = () => {
  dialogVisible.value = false
  data.dialogForm = {}
  proxy.$refs.dialogForm.resetFields()
}

// 提交
const getSubmit = () => {
  proxy.$refs.dialogForm.validate(async valid => {
    if (valid) {
      if (data.dialogForm.id) {
        await edit(data.dialogForm).then(res => {
          if (res.code !== 0) {
            return false
          }
        })
      } else {
        await submit(data.dialogForm).then(res => {
          if (res.code !== 0) {
            return false
          }
        })
      }
      proxy.$modal.msgSuccess('提交成功！')
      getClose()
      getList()
    } else {
      return false
    }
  })
}

// 修改状态
const getChange = (id, title, status) => {
  change({ id: id, status: status }).then(res => {
    if (res.code === 0) {
      proxy.$modal.msgSuccess(`${title}成功！`)
      getList()
    }
  })
}

// 删除
const getDelete = (row) => {
  proxy.$modal.confirm(`是否删除设备名称为：${row.deviceName}的数据?`).then(() => {
    remove({ id: row.id }).then(res => {
      if (res.code === 0) {
        proxy.$modal.msgSuccess('删除成功！')
        getList()
      }
    })
  })
}

// 监听
watch(() => data.dialogForm.tenantId, (val) => {
  if (val) {
    storeData.form.tenantId = val
    getStore()
  }
})
</script>

<style lang="scss" scoped>
.card_box {
  display: flex;
  flex-wrap: wrap;
}

.card {
  display: flex;
  flex-direction: column;
  padding: 10px 10px 20px;
  width: 200px;
  border-radius: 10px;
  box-shadow: 0px 0px 12px rgba(0, 0, 0, .12);
  margin-right: 40px;
  margin-bottom: 30px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .state {
      width: 10px;
      height: 10px;
      border-radius: 50%;
      display: inline-block;
    }
  }

  .icon {
    padding: 0 20px;
    margin: 15px 0;
    text-align: center;

    :deep(.el-image__inner) {
      width: 80%;
      height: 100%;
    }
  }

  .name {
    font-size: 14px;
    text-align: center;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    padding: 0 20px;
  }
}
</style>