<template>
  <!-- 违章类型管理 -->
  <div class="app-container">
    <el-form v-show="showSearch" :model="queryParams" ref="queryForm" size="small" inline>
      <el-form-item label="违章类型" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入违章类型" clearable @keyup.enter.native="handleQuery"  v-no-whitespace/>
      </el-form-item>
      <el-form-item label="创建人" prop="createUserName">
        <el-input
          v-model="queryParams.createUserName"
          placeholder="请输入创建人"
          clearable v-no-whitespace
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- 日期范围 -->
      <el-form-item label="创建日期" prop="createTimeRange">
        <el-date-picker
          v-model="queryParams.createTimeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          clearable
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出数据</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table :data="tableList" fit highlight-current-row style="width: 100%">
      <!-- 多选 -->
      <el-table-column type="selection" width="55" align="center" @selection-change="selectionChange" />
      <el-table-column
        type="index"
        width="55"
        label="序号"
        align="center"
        :index="indexContinuous(queryParams.pageNum, queryParams.pageSize)"
      />
      <el-table-column
        v-for="(column, index) in tableColumns"
        show-overflow-tooltip
        :key="column.prop"
        :label="column.label"
        :prop="column.prop"
        align="center"
      >
        <!-- 插槽 -->
        <!-- <template v-slot="scope" v-if="column.prop == 'checkingInStatus'">
          <span>
            <el-switch v-model="scope.row.checkingInStatus" @change="changeSwitch(scope.row)"></el-switch>
          </span>
        </template> -->
      </el-table-column>
      <!-- 操作 -->
      <el-table-column label="操作" align="center" width="150">
        <template slot-scope="scope">
          <el-button type="text" size="mini" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            type="text"
            size="mini"
            icon="el-icon-delete"
            style="color: #f56c6c"
            @click="handleDelete(scope.row)"
          >
            删除
          </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"
    />

    <!-- 弹框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="40%">
      <el-form ref="dialogForm" :model="dialogForm" label-width="120px" :rules="dialogRules">
        <el-form-item label="违章类型名称" prop="name">
          <el-input v-model="dialogForm.name" placeholder="请输入类型名称" clearable maxlength="30" show-word-limit v-no-whitespace />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogConfirm" v-preventReClick="5000">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  selectHiddenDangerType,
  addHiddenDangerTypeForm,
  updateHiddenDangerTypeForm,
  deleteHiddenDangerTypeForm,
  getHiddenDangerTypeList,
  exportHiddenDangerTypeList,
} from '@/api/hiddenDangerManagement'

export default {
  data() {
    return {
      userId: this.$store.state.user.id,
      userName: this.$store.state.user.userData.nickName,
      showSearch: true,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: '', // 违章类型
        createUserName: '', // 创建人
        createTimeRange: [], // 创建日期范围
      },
      total: 0, // 总条数
      // 表头
      tableColumns: [
        { label: '违章类型', prop: 'name' },
        { label: '创建人', prop: 'createUserName' },
        { label: '创建时间', prop: 'createTime' },
      ],
      // 表格数据
      tableList: [],
      dialogTitle: '新增',
      dialogVisible: false,
      dialogForm: {
        name: '', // 隐患问题类别
      },
      dialogRules: {
        name: [{ required: true, message: '请输入隐患问题类别', trigger: 'blur' }],
      },
      isAdd: true,
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 查询
    handleQuery() {
      console.log('查询')
      this.getList()
    },
    // 重置
    handleReset() {
      console.log('重置')
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.$refs.queryForm.resetFields()
      this.getList()
    },
    // 获取列表
    async getList() {
      try {
        let createStartTime = ''
        let createEndTime = ''
        if (this.queryParams.createTimeRange && this.queryParams.createTimeRange.length) {
          createStartTime = this.queryParams.createTimeRange[0]
          createEndTime = this.queryParams.createTimeRange[1]
        } else {
          createStartTime = ''
          createEndTime = ''
        }
        const params = { ...this.queryParams, createStartTime, createEndTime, type: 2 }
        delete params.createTimeRange // 删除时间范围
        console.log('🚀 ~ getList ~ params:', params)
        const res = await getHiddenDangerTypeList(params)
        console.log('🚀 ~ 获取列表 ~ res:', res)
        this.tableList = res.rows
        this.total = res.total
      } catch (error) {
        console.log('🚀 ~ 获取列表 ~ error:', error)
      }
    },
    // 多选
    selectionChange(val) {
      console.log('selectionChange', val)
    },
    handleAdd() {
      console.log('新增')
      this.isAdd = true
      this.dialogTitle = '新增违章类型'
      this.dialogForm = { name: '' }
      this.dialogVisible = true
      setTimeout(() => {
        this.$refs.dialogForm.clearValidate()
      }, 200)
    },
    // 编辑
    handleEdit(row) {
      console.log('编辑', row)
      this.isAdd = false
      this.dialogForm = { ...row }
      this.dialogTitle = '编辑违章类型'
      this.dialogVisible = true
      setTimeout(() => {
        this.$refs.dialogForm.clearValidate()
      }, 200)
    },
    // 删除
    handleDelete(row) {
      console.log('删除', row)
      this.$confirm('是否删除该数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        try {
          const res = await deleteHiddenDangerTypeForm(row.id)
          console.log('🚀 ~ handleDelete ~ res:', res)
          this.getList()
          this.$message({ type: 'success', message: '删除成功!' })
        } catch (error) {
          console.log('🚀 ~ handleDelete ~ error:', error)
        }
      })
    },
    // 导出数据
    handleExport() {
      try {
        let fileName = `违章类型管理_${new Date().getTime()}.xLsx`
        let url = exportHiddenDangerTypeList()
        let createStartTime = ''
        let createEndTime = ''
        if (this.queryParams.createTimeRange && this.queryParams.createTimeRange.length) {
          createStartTime = this.queryParams.createTimeRange[0]
          createEndTime = this.queryParams.createTimeRange[1]
        } else {
          createStartTime = ''
          createEndTime = ''
        }
        const params = { ...this.queryParams, createStartTime, createEndTime, type: 2 }
        delete params.createTimeRange // 删除时间范围
        console.log('🚀 ~ getList ~ params:', params)
        console.log('🚀 ~ 导出 ~ params:', params)
        this.derive(url, params, fileName)
      } catch (error) {
        console.log('导出数据失败', error)
      }
    },
    // 弹框确认
    dialogConfirm() {
      console.log('dialogConfirm')
      this.$refs.dialogForm.validate(async valid => {
        if (valid) {
          console.log('表单验证通过')
          try {
            this.handleName()
          } catch (error) {
            console.log('🚀 ~ dialogConfirm ~ error:', error)
          }
        }
      })
    },
    async handleName() {
      try {
        const params = { ...this.dialogForm, type: 2 }
        const res = await selectHiddenDangerType(params)
        console.log('🚀 ~ handleName ~ res:', res)
        this.submit()
      } catch (error) {
        console.log('🚀 ~ handleName ~ error:', error)
      }
    },
    async submit() {
      const params = {
        id: this.dialogForm.id, // 隐患问题类别id
        name: this.dialogForm.name, // 隐患问题类别
        createUserId: this.userId, // 创建人id
        createUserName: this.userName, // 创建人姓名
        type: 2, // 类型: 1-隐患 2-违章
      }
      console.log('🚀 ~ handleName ~ params:', params)
      let res = undefined
      if (this.isAdd) {
        // 新增
        delete params.id
        res = await addHiddenDangerTypeForm(params)
      } else {
        // 编辑
        res = await updateHiddenDangerTypeForm(params)
      }
      console.log('🚀 ~ dialogConfirm ~ res:', res)
      this.getList()
      this.dialogVisible = false
      this.$message({ type: 'success', message: '操作成功!' })
    },
  },
}
</script>

<style lang="scss" scoped></style>
