<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <el-form :model="queryParams" :inline="true" label-width="90px">
        <el-form-item label="租户ID">
          <el-input v-model="queryParams.tenantId" clearable placeholder="请输入租户ID" style="width: 180px" />
        </el-form-item>
        <el-form-item label="申请人">
          <el-input v-model="queryParams.applyUser" clearable placeholder="请输入申请人" style="width: 180px" />
        </el-form-item>
        <el-form-item label="申请电话">
          <el-input v-model="queryParams.applyPhone" clearable placeholder="请输入申请电话" style="width: 180px" />
        </el-form-item>
        <el-form-item label="同事姓名">
          <el-input v-model="queryParams.colleagueName" clearable placeholder="请输入同事姓名" style="width: 180px" />
        </el-form-item>
        <el-form-item label="组长姓名">
          <el-input v-model="queryParams.teamLeader" clearable placeholder="请输入组长姓名" style="width: 180px" />
        </el-form-item>
        <el-form-item label="申请日期">
          <el-date-picker
            v-model="queryParams.applyDate"
            type="date"
            value-format="yyyy-MM-dd"
            clearable
            placeholder="请选择申请日期"
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-delete" @click="resetQuery">清空</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="action-container" shadow="never">
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
    </el-card>

    <el-card class="table-container" shadow="never">
      <el-table v-loading="loading" :data="list" style="width: 100%">
        <el-table-column label="租户ID" prop="tenantId" min-width="140" show-overflow-tooltip />
        <el-table-column label="申请人" prop="applyUser" min-width="120" />
        <el-table-column label="申请电话" prop="applyPhone" min-width="130" />
        <el-table-column label="同事姓名" prop="colleagueName" min-width="120" />
        <el-table-column label="组长姓名" prop="teamLeader" min-width="120" />
        <el-table-column label="申请日期" prop="applyDate" min-width="120" />
        <el-table-column label="创建时间" prop="createTime" min-width="170">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间" prop="updateTime" min-width="170">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="140">
          <template slot-scope="scope">
            <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" style="color:#F56C6C;" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :current-page="queryParams.current"
        :page-size="queryParams.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="720px" @close="resetForm">
      <el-form ref="dataForm" :model="form" :rules="formRules" label-width="110px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="租户ID" prop="tenantId">
              <el-input v-model="form.tenantId" placeholder="请输入租户ID" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请人" prop="applyUser">
              <el-input v-model="form.applyUser" placeholder="请输入申请人" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="申请电话" prop="applyPhone">
              <el-input v-model="form.applyPhone" placeholder="请输入申请电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="同事姓名" prop="colleagueName">
              <el-input v-model="form.colleagueName" placeholder="请输入同事姓名" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="组长姓名" prop="teamLeader">
              <el-input v-model="form.teamLeader" placeholder="请输入组长姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请日期" prop="applyDate">
              <el-date-picker
                v-model="form.applyDate"
                type="date"
                value-format="yyyy-MM-dd"
                clearable
                placeholder="请选择申请日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addLbPurchaseApply,
  deleteLbPurchaseApply,
  getLbPurchaseApplyList,
  updateLbPurchaseApply
} from '@/api/lb-purchase-apply'

export default {
  name: 'LbPurchaseApply',
  data() {
    return {
      loading: false,
      submitLoading: false,
      list: [],
      total: 0,
      dialogVisible: false,
      dialogTitle: '',
      isEdit: false,
      queryParams: {
        current: 1,
        size: 10,
        tenantId: '',
        applyUser: '',
        applyPhone: '',
        colleagueName: '',
        teamLeader: '',
        applyDate: ''
      },
      form: {
        id: '',
        tenantId: '',
        applyUser: '',
        applyPhone: '',
        colleagueName: '',
        teamLeader: '',
        applyDate: ''
      },
      formRules: {
        tenantId: [{ required: true, message: '请输入租户ID', trigger: 'blur' }],
        applyUser: [{ required: true, message: '请输入申请人', trigger: 'blur' }],
        applyPhone: [{ required: true, message: '请输入申请电话', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.fetchList()
  },
  methods: {
    fetchList() {
      this.loading = true
      getLbPurchaseApplyList(this.buildListParams())
        .then((res) => {
          if (res && (res.code === 20000 || res.code === 200 || res.success === true)) {
            this.list = Array.isArray(res.data) ? res.data : []
            this.total = typeof res.total === 'number'
              ? res.total
              : (res.page && typeof res.page.total === 'number' ? res.page.total : this.list.length)
          } else {
            this.list = []
            this.total = 0
          }
        })
        .catch(() => {
          this.list = []
          this.total = 0
        })
        .finally(() => {
          this.loading = false
        })
    },
    buildListParams() {
      const params = {
        current: this.queryParams.current,
        size: this.queryParams.size,
        tenantId: this.queryParams.tenantId || undefined,
        applyUser: this.queryParams.applyUser || undefined,
        applyPhone: this.queryParams.applyPhone || undefined,
        colleagueName: this.queryParams.colleagueName || undefined,
        teamLeader: this.queryParams.teamLeader || undefined,
        applyDate: this.queryParams.applyDate || undefined
      }
      Object.keys(params).forEach((key) => {
        if (params[key] === undefined || params[key] === '') delete params[key]
      })
      return params
    },
    handleQuery() {
      this.queryParams.current = 1
      this.fetchList()
    },
    resetQuery() {
      this.queryParams = {
        current: 1,
        size: 10,
        tenantId: '',
        applyUser: '',
        applyPhone: '',
        colleagueName: '',
        teamLeader: '',
        applyDate: ''
      }
      this.fetchList()
    },
    handleSizeChange(size) {
      this.queryParams.size = size
      this.fetchList()
    },
    handleCurrentChange(current) {
      this.queryParams.current = current
      this.fetchList()
    },
    handleAdd() {
      this.dialogTitle = '新增进货申请'
      this.isEdit = false
      this.resetFormData()
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.dataForm && this.$refs.dataForm.clearValidate()
      })
    },
    handleEdit(row) {
      this.dialogTitle = '编辑进货申请'
      this.isEdit = true
      this.form = {
        id: row.id || '',
        tenantId: row.tenantId || '',
        applyUser: row.applyUser || '',
        applyPhone: row.applyPhone || '',
        colleagueName: row.colleagueName || '',
        teamLeader: row.teamLeader || '',
        applyDate: row.applyDate || ''
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.dataForm && this.$refs.dataForm.clearValidate()
      })
    },
    handleDelete(row) {
      this.$confirm('确定删除这条进货申请记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return deleteLbPurchaseApply(row.id)
      }).then((res) => {
        this.$message.success((res && res.message) || '删除成功')
        this.fetchList()
      }).catch(() => {})
    },
    handleSubmit() {
      this.$refs.dataForm.validate((valid) => {
        if (!valid) return
        const payload = this.buildPayload()
        this.submitLoading = true
        const req = this.isEdit ? updateLbPurchaseApply(payload) : addLbPurchaseApply(payload)
        req.then((res) => {
          this.$message.success((res && res.message) || (this.isEdit ? '更新成功' : '新增成功'))
          this.dialogVisible = false
          this.fetchList()
        }).finally(() => {
          this.submitLoading = false
        })
      })
    },
    buildPayload() {
      const payload = {
        tenantId: this.form.tenantId,
        applyUser: this.form.applyUser,
        applyPhone: this.form.applyPhone,
        colleagueName: this.form.colleagueName || undefined,
        teamLeader: this.form.teamLeader || undefined,
        applyDate: this.form.applyDate || undefined
      }
      if (this.isEdit) payload.id = this.form.id
      Object.keys(payload).forEach((key) => {
        if (payload[key] === undefined || payload[key] === '') delete payload[key]
      })
      return payload
    },
    resetForm() {
      this.$refs.dataForm && this.$refs.dataForm.resetFields()
      this.resetFormData()
    },
    resetFormData() {
      this.form = {
        id: '',
        tenantId: '',
        applyUser: '',
        applyPhone: '',
        colleagueName: '',
        teamLeader: '',
        applyDate: ''
      }
    },
    formatDateTime(dateTime) {
      if (!dateTime) return '-'
      const date = new Date(String(dateTime).replace('T', ' '))
      if (Number.isNaN(date.getTime())) return String(dateTime)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .filter-container {
    margin-bottom: 20px;
  }

  .action-container {
    margin-bottom: 20px;
  }

  .table-container {
    .el-pagination {
      margin-top: 20px;
      text-align: right;
    }
  }
}
</style>
