<template>
  <!-- 基础页面 -->
  <div class="app-container">
    <el-form v-show="showSearch" :model="queryParams" ref="queryForm" size="small" inline @submit.native.prevent>
      <el-form-item label="关键字" prop="keyWord">
        <el-input
          v-model="queryParams.keyWord"
          placeholder="请输入关键字"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 240px"
        />
      </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="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出数据</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="index => (queryParams.pageNum - 1) * queryParams.pageSize + index + 1"
      />
      <!-- :index="indexContinuous(queryParams.pageNum, queryParams.pageSize)" -->
      <el-table-column
        v-for="(column, index) in tableColumns"
        show-overflow-tooltip
        :key="index"
        :label="column.label"
        :prop="column.prop"
        align="center"
      ></el-table-column>
      <!-- 操作 -->
      <el-table-column label="操作" align="center" width="150">
        <template slot-scope="{ row }">
          <el-button type="text" size="mini" icon="el-icon-edit" @click="handleEdit(row)">编辑</el-button>
          <el-button type="text" size="mini" icon="el-icon-delete" style="color: #f56c6c" @click="handleDelete(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="departName">
          <el-input v-model="dialogForm.departName" placeholder="请输入内容" clearable />
        </el-form-item>
        <el-form-item label="所属分公司" prop="deptId">
          <el-select v-model="dialogForm.deptId" placeholder="请选择" clearable style="width: 100%">
            <el-option
              v-for="(item, index) in unitsNameList"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="headUser">
          <el-input v-model="dialogForm.headUser" placeholder="请输入内容" clearable />
        </el-form-item>
        <el-form-item label="联系电话" prop="headUserPhone">
          <el-input v-model="dialogForm.headUserPhone" placeholder="请输入内容" clearable maxlength="11" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getBmProDepartApi,
  addBmProDepartApi,
  editBmProDepartApi,
  delBmProDepartApi,
  impUnitTypeList
} from '@/api/materialsStation'

export default {
  data() {
    return {
      showSearch: true,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyWord: '' // 关键字
      },

      total: 0, // 总条数
      // 表头
      tableColumns: [
        { label: '项目部名称', prop: 'departName' },
        { label: '所属组织', prop: 'deptName' },
        { label: '联系人', prop: 'headUser' },
        { label: '联系电话', prop: 'headUserPhone' }
      ],
      // 表格数据
      tableList: [],
      dialogTitle: '新增',
      dialogVisible: false,
      unitsNameList: [], // 所属单位
      isEdit: false, // 是否编辑
      dialogForm: {
        departName: '', // 项目部名称
        deptId: '', // 所属单位
        headUser: '', // 联系人
        headUserPhone: '' // 联系电话
      },
      dialogRules: {
        departName: [{ required: true, message: '请输入项目部名称', trigger: 'blur' }],
        deptId: [{ required: true, message: '请选择所属单位', trigger: 'change' }],
        headUser: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
        headUserPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 查询
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置
    handleReset() {
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.$refs.queryForm.resetFields()
      this.getList()
    },
    // 获取列表
    async getList() {
      console.log('列表-查询', this.queryParams)
      const loading = this.$loading({ text: '加载中...' })
      try {
        const params = { ...this.queryParams }
        const res = await getBmProDepartApi(params)
        console.log('🚀 ~ 获取列表 ~ res:', res)
        this.tableList = res.data.rows
        this.total = res.data.total
        loading.close()
      } catch (error) {
        console.log('🚀 ~ 获取列表 ~ error:', error)
        this.tableList = []
        this.total = 0
        loading.close()
      }
    },
    // 多选
    selectionChange(val) {
      console.log('selectionChange', val)
    },
    // 获取单位列表
    async getUnitsNameList() {
      try {
        const res = await impUnitTypeList()
        console.log('🚀 ~ 获取单位列表 ~ res:', res)
        let matTypeRes = res.data
        let result = []
        matTypeRes.forEach(item => {
          const parts = item.ancestors.split(',')
          if (parts.length == 2) {
            result.push({
              label: item.deptName,
              value: item.deptId
            })
          }
        })
        this.unitsNameList = result
      } catch (error) {
        console.log('获取单位列表失败', error)
      }
    },
    handleAdd() {
      console.log('新增')
      this.dialogTitle = '新增'
      this.dialogVisible = true
      this.isEdit = false
      this.getUnitsNameList()
      setTimeout(() => {
        this.$refs.dialogForm.resetFields()
      }, 100)
    },
    // 编辑
    handleEdit(row) {
      console.log('编辑', row)
      this.dialogTitle = '编辑'
      this.dialogVisible = true
      this.isEdit = true
      this.getUnitsNameList()
      setTimeout(() => {
        this.$refs.dialogForm.resetFields()
        this.dialogForm = { ...row }
      }, 100)
    },
    // 删除
    handleDelete(row) {
      console.log('删除', row)
      this.$confirm('是否删除该数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await delBmProDepartApi({ id: row.id })
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getList()
        } catch (error) {
          console.log('删除失败', error)
        }
      })
    },
    // 导出数据
    handleExport() {
      try {
        let fileName = `项目管理部_${new Date().getTime()}.xLsx`
        let url = 'material/bmProDepart/export'
        const params = { ...this.queryParams }
        console.log('🚀 ~ 导出 ~ params:', params)
        this.download(url, params, fileName)
      } catch (error) {
        console.log('导出数据失败', error)
      }
    },
    // 弹框确认
    dialogConfirm() {
      console.log('dialogConfirm')
      this.$refs.dialogForm.validate(async valid => {
        if (valid) {
          try {
            const params = { ...this.dialogForm }
            console.log('🚀 ~ dialogConfirm ~ params:', params)
            if (this.isEdit) {
              const res = await editBmProDepartApi(params)
            } else {
              const res = await addBmProDepartApi(params)
            }
            this.dialogVisible = false
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.getList()
          } catch (error) {
            console.log('新增失败', error)
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>

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