<template>
  <div class="app-container">
    <div v-if="isShowUpdate">
      <div class="head">
        编辑设备
        <el-button
          type="primary"
          size="mini"
          style="margin-left: 20px"
          @click="back"
        >返回</el-button>
        <el-button
          type="primary"
          size="mini"
          style="margin-left: 20px"
          @click="chooseTemplate"
        >选用模板</el-button>
      </div>
      <edit-device
        :is-dis="true"
        :obj="updateData"
        :template-data="templateData"
        style="margin-left: 16px"
        @finish="back"
        @back="back"
      />
      <el-dialog
        title="选用模板"
        :visible.sync="dialogVisible"
        width="500px"
        :close-on-click-modal="false"
      >
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-width="80px"
          label-position="left"
        >
          <el-form-item label="模板名称" prop="id" required>
            <el-select
              v-model="form.id"
              placeholder="请选择模板名称"
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in templateDataList"
                :key="index"
                :label="item.templateName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false"> 取消 </el-button>
          <el-button type="primary" @click="sure"> 确定 </el-button>
        </div>
      </el-dialog>
    </div>
    <div v-show="!isShowUpdate">
      <uploadModal
        ref="uploadModal"
        :template-data-list="templateDataList"
        @finish="modalSuccess(false)"
      />
      <div class="search-layout" style="margin-bottom: 0px; margin-top: -10px">
        <el-input
          v-model="form.sn"
          placeholder="设备sn"
          class="filter-item input"
        />
        <el-select
          v-model="form.purchaserId"
          class="filter-item"
          placeholder="购买方公司"
          clearable
          filterable
        >
          <el-option
            v-for="(item, index) in buyList"
            :key="index"
            :label="item.companyName"
            :value="item.purchaserId"
          />
        </el-select>
        <el-select
          v-model="form.applicationTypeId"
          class="filter-item"
          placeholder="应用类型"
          clearable
          filterable
        >
          <el-option
            v-for="(item, index) in applicationList"
            :key="index"
            :label="item.applicationType"
            :value="item.applicationTypeId"
          />
        </el-select>
        <el-select
          v-model="form.deviceModelHardwareId"
          class="filter-item"
          placeholder="设备型号(硬件)"
          clearable
          filterable
        >
          <el-option
            v-for="(item, index) in devicelList"
            :key="index"
            :label="item.deviceModel"
            :value="item.deviceModelId"
          />
        </el-select>
        <el-select
          v-model="form.deviceModelEnvironmentId"
          class="filter-item"
          placeholder="设备型号(环境)"
          clearable
          filterable
        >
          <el-option
            v-for="(item, index) in devicelList"
            :key="index"
            :label="item.deviceModel"
            :value="item.deviceModelId"
          />
        </el-select>
        <el-select
          v-model="form.systemTypeCode"
          class="filter-item"
          placeholder="系统类型"
          clearable
          filterable
        >
          <el-option
            v-for="(item, index) in systemType"
            :key="index"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-select
          v-model="form.status"
          class="filter-item"
          placeholder="状态"
          clearable
        >
          <el-option
            v-for="(item, index) in statusLists"
            :key="index"
            :label="item.value"
            :value="item.key"
          />
        </el-select>
      </div>
      <div class="search-layout">
        <el-button
          class="filter-item"
          style="margin-right: 0"
          type="primary"
          icon="el-icon-search"
          @click="query(1)"
        >
          搜索
        </el-button>
        <el-button
          class="filter-item"
          style="margin-right: 0"
          type="primary"
          icon="el-icon-plus"
          @click="handleCreate"
        >
          添加
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          @click="download"
        >下载模板</el-button>
        <el-button
          type="primary"
          plain
          @click="addOrUpdate"
        >批量导入</el-button>
      </div>
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        element-loading-text="加载中..."
        border
        fit
        highlight-current-row
      >
        <el-table-column align="center" label="序号" width="95">
          <template slot-scope="scope">
            {{
              (pagination.page - 1) * pagination.pageSize + (scope.$index + 1)
            }}
          </template>
        </el-table-column>
        <el-table-column label="设备sn">
          <template slot-scope="scope">
            {{ scope.row.sn }}
          </template>
        </el-table-column>
        <el-table-column label="购买方公司">
          <template slot-scope="scope">
            {{ scope.row.companyName }}
          </template>
        </el-table-column>
        <el-table-column label="应用类型">
          <template slot-scope="scope">
            {{ scope.row.applicationType }}
          </template>
        </el-table-column>
        <el-table-column label="设备型号(硬件)">
          <template slot-scope="scope">
            {{ scope.row.deviceModelHardware }}
          </template>
        </el-table-column>
        <el-table-column label="设备型号(环境)">
          <template slot-scope="scope">
            {{ scope.row.deviceModelEnvironment }}
          </template>
        </el-table-column>
        <el-table-column label="系统类型">
          <template slot-scope="scope">
            {{ scope.row.systemType }}
          </template>
        </el-table-column>
        <el-table-column
          label="状态"
          align="center"
          class-name="status-col"
          width="120"
        >
          <template slot-scope="{ row }">
            <el-tag :type="row.status | statusFilter">
              {{ row.status | statusFilterStr }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="250"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="{ row, $index }">
            <el-button type="primary" size="mini" @click="handleUpdate(row)">
              编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(row, $index)"
            >
              删除
            </el-button>
            <template>
              <el-button
                v-if="row.status"
                size="mini"
                type="danger"
                @click="handleAuth(row, false)"
              >取消授权</el-button>
              <el-button
                v-else
                size="mini"
                type="danger"
                @click="handleAuth(row, true)"
              >获取授权</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        :total="pagination.total"
        :page.sync="pagination.page"
        :limit.sync="pagination.pageSize"
        :page-sizes="pagination.pageSizeOptions"
        :layout="pagination.layout"
        @pagination="handleSizeChange"
      />
    </div>
  </div>
</template>

<script>
import EditDevice from './components/edit'
import UploadModal from './components/UploadModal.vue'
import tableMixins from '@/mixins/tableMixins'
import {
  getList,
  deleteById,
  autoById,
  autoCancelById,
  templateList,
  templateDetail
} from '@/api/FKJ'
import Pagination from '@/components/Pagination'
import {
  applicationTypeList,
  deviceModelList,
  purchaserList
} from '@/api/configuration'
export default {
  components: { Pagination, UploadModal, EditDevice },
  filters: {
    statusFilter(status) {
      return status ? 'success' : 'info'
    },
    statusFilterStr(status) {
      return status ? '已授权' : '未授权'
    }
  },
  mixins: [tableMixins],
  data() {
    return {
      merchantLists: [],
      modeLists: [
        {
          key: 'public',
          value: '开放'
        },
        {
          key: 'close',
          value: '封闭'
        },
        {
          key: 'elasticity',
          value: '弹性'
        }
      ],
      statusLists: [
        {
          key: false,
          value: '未授权'
        },
        {
          key: true,
          value: '已授权'
        }
      ],
      form: {},
      isShowUpdate: false,
      updateData: {},
      templateData: {},
      pagination: {
        page: 1,
        current: 1
      },
      applicationList: [],
      devicelList: [],
      buyList: [],
      systemType: [
        { id: 1, name: '蚂蚁OS' },
        { id: 2, name: '非蚂蚁OS' }
      ],
      ampeDataList: [],
      templateDataList: [],
      dialogVisible: false,
      form: {
        id: null
      },
      rules: {
        id: [
          {
            required: true,
            message: '不能为空!',
            trigger: ['change', 'blur']
          }
        ]
      }
    }
  },
  methods: {
    initData() {
      this.getTableList()
      this.applicationTypeList()
      this.deviceModelList()
      this.purchaserList()
      this.templateList()
    },
    // 获取表格数据
    async getTableList() {
      this.pagination.current = this.pagination.page
      this.tableLoading = true
      try {
        const result = await getList(this.getFilterParams())
        this.setDataList(result.data)
      } catch (e) {
        console.log(e)
      } finally {
        this.tableLoading = false
      }
    },
    // 获取筛选信息
    query(type) {
      if (type) {
        this.pagination.page = 1
        this.pagination.current = 1
      }
      this.clearPageParams()
      this.getTableList()
    },
    // 增加筛选条件
    transformFilterForm() {
      return {
        company: this.form.company || null,
        purchaserId: this.form.purchaserId || null,
        applicationTypeId: this.form.applicationTypeId || null,
        deviceModelHardwareId: this.form.deviceModelHardwareId || null,
        deviceModelEnvironmentId: this.form.deviceModelEnvironmentId || null,
        systemTypeCode: this.form.systemTypeCode || null,
        sn: this.form.sn || null,
        company: this.form.company || null,
        tenantId: this.form.tenantId || null,
        sceneId: this.form.sceneId || null,
        mode: this.form.mode || null,
        userLibId: this.form.userLibId || null,
        status: this.form.status === '' ? null : this.form.status
      }
    },
    // 下载模板
    download() {
      window.location.href =
        process.env.VUE_APP_BASE_API + '/static/deviceListExcel.xlsx'
    },
    addOrUpdate() {
      this.$refs.uploadModal.open()
    },
    modalSuccess(isEdit) {
      if (!isEdit) {
        this.clearPageParams()
      }
      this.getTableList()
    },
    handleCreate() {
      this.$router.push({ path: '/FKJDeviceList/add' })
    },
    handleUpdate(row) {
      this.isShowUpdate = true
      this.updateData = JSON.parse(JSON.stringify(row))
    },
    back() {
      this.isShowUpdate = false
      this.query()
    },
    chooseTemplate() {
      this.form.id = null
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    templateList() {
      templateList().then((res) => {
        this.templateDataList = res.data
      })
    },
    sure() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          templateDetail(this.form.id).then((res) => {
            this.dialogVisible = false
            this.templateData = JSON.parse(JSON.stringify(res.data))
          })
        }
      })
    },
    handleAuth(row, needAuth) {
      const that = this
      this.$confirm(
        `确定 ${needAuth ? '获取授权' : '取消授权'} 操作吗?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          showClose: false,
          type: 'warning',
          beforeClose: async(action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true
              instance.cancelButtonLoading = true
              instance.confirmButtonText = '提交中...'
              try {
                if (needAuth) {
                  await autoById(row.id)
                } else {
                  await autoCancelById(row.id)
                }
                this.$message({
                  type: 'success',
                  message: '操作成功!'
                })
                that.getTableList()
              } catch (e) {
                // this.$message({
                //   type: 'error',
                //   message: '删除失败!'
                // })
              } finally {
                done()
                setTimeout(() => {
                  instance.confirmButtonLoading = false
                  instance.cancelButtonLoading = false
                }, 300)
              }
            } else {
              done()
            }
          }
        }
      )
        .then(() => {})
        .catch(() => {})
    },
    handleDelete(row, index) {
      const that = this
      this.$confirm('确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showClose: false,
        type: 'warning',
        beforeClose: async(action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.cancelButtonLoading = true
            instance.confirmButtonText = '提交中...'
            try {
              await deleteById(row.id)
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              that.getTableList()
            } catch (e) {
              // this.$message({
              //   type: 'error',
              //   message: '删除失败!'
              // })
            } finally {
              done()
              setTimeout(() => {
                instance.confirmButtonLoading = false
                instance.cancelButtonLoading = false
              }, 300)
            }
          } else {
            done()
          }
        }
      })
        .then(() => {})
        .catch(() => {})
    },
    // 获取应用类型列表
    applicationTypeList() {
      applicationTypeList().then((res) => {
        this.applicationList = res.data
      })
    },
    // 设备型号列表
    deviceModelList() {
      deviceModelList().then((res) => {
        this.devicelList = res.data
      })
    },
    // 购买方列表
    purchaserList() {
      purchaserList().then((res) => {
        this.buyList = res.data
      })
    }
  }
}
</script>

<style scoped>
.search-layout {
  margin-bottom: 20px;
}
.search-layout .filter-item {
  margin-right: 20px;
  margin-top: 10px;
}
.search-layout .filter-item:last-of-type {
  margin-right: 0;
}
.head {
  margin-left: 16px;
  font-weight: 600;
  font-size: 18px;
  color: #333333;
}
.input {
  width: 200px;
  margin-right: 15px;
}
.m-r {
  margin-right: 15px;
}
</style>
