<template>
  <div>
    <el-card :body-style="cardBodyStyle">
      <el-form :model="query" label-width="auto" label-position="right">
        <el-row :gutter="10">
          <el-col :span="5">
            <el-form-item label="客户名称" style="margin-bottom: 0px;">
              <el-select v-model="query.customerName" filterable placeholder="请选择客户" clearable style="width:100%;" size="small">
                <el-option v-for="item in optionsCust" :key="item.id" :label="item.customerNm" :value="item.customerNm" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="" style="margin-bottom: 0px; margin-top: 5px;">
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button type="success" @click="handleAdd">新增</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card :body-style="cardBodyStyle">
      <el-table :data="tableData" border highlight-current-row v-loading="loading">
        <el-table-column type="index" label="序号" align="center" width="60">
          <template #default="scope">
            <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="customer.customerNm" label="客户名称" width="180" show-overflow-tooltip />
        <el-table-column prop="materialName" label="品名简称" width="180" show-overflow-tooltip />
        <el-table-column prop="keepDay" label="免堆时间（天）" width="150" show-overflow-tooltip />
        <el-table-column prop="ordPrice" label="免堆期价格（元/吨）" width="150" show-overflow-tooltip align="right">
          <template #default="scope">
            <span>{{ scope.row.ordPrice ? scope.row.ordPrice.toFixed(2) : '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="outOrdPrice" label="超期价格（元/天/吨）" width="150" show-overflow-tooltip align="right">
          <template #default="scope">
            <span>{{ scope.row.outOrdPrice ? scope.row.outOrdPrice.toFixed(2) : '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="payWay" label="支付方式" width="120" show-overflow-tooltip />
        <el-table-column prop="addName" label="添加人" width="120" show-overflow-tooltip />
        <el-table-column prop="addTime" label="添加时间" width="180" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ formatDate(scope.row.addTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button plain type="warning" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button plain type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card :body-style="cardBodyStyle">
      <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="pageSizes" :total="totalRows"
                     background layout="total, sizes, prev, pager, next, jumper"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange" />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px" :close-on-click-modal="false">
      <el-form :model="form" label-width="120px" label-position="right" :rules="rules" ref="ruleFormRef">
        <el-form-item label="客户名称" prop="customerId">
          <el-select v-model="form.customerId" filterable placeholder="请选择客户" clearable style="width: 100%;">
            <el-option v-for="item in optionsCust" :key="item.id" :label="item.customerNm" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="品名" prop="materialName">
          <el-input v-model="form.materialName" placeholder="请输入品名" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="免堆时间" prop="keepDay">
          <el-input v-model="form.keepDay" type="number" placeholder="请输入免堆时间" style="width: 100%;">
            <template slot="append">天</template>
          </el-input>
        </el-form-item>
        <el-form-item label="免堆期单价" prop="ordPrice">
          <el-input v-model="form.ordPrice" type="number" placeholder="请输入免堆期单价" style="width: 100%;">
            <template slot="append">元/吨</template>
          </el-input>
        </el-form-item>
        <el-form-item label="超期单价" prop="outOrdPrice">
          <el-input v-model="form.outOrdPrice" type="number" placeholder="请输入超期单价" style="width: 100%;">
            <template slot="append">元/天/吨</template>
          </el-input>
        </el-form-item>
        <el-form-item label="支付方式" prop="payWay">
          <el-radio-group v-model="form.payWay">
            <el-radio label="月结">月结</el-radio>
            <el-radio label="现金">现金</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" plain @click="handleSave">保存</el-button>
          <el-button type="danger" plain @click="handleCancelSave">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from '@/axios'

export default {
  data() {
    return {
      cardBodyStyle: { padding: '10px' },
      // 查询条件
      query: {
        customerName: '',
      },
      // 表格数据
      tableData: [],
      loading: false,
      // 对话框控制
      dialogVisible: false,
      dialogTitle: '新增价格',
      // 客户选项
      optionsCust: [],
      // 表单数据
      form: {
        id: '',
        customerId: '',
        materialName: '',
        keepDay: '',
        ordPrice: '',
        outOrdPrice: '',
        payWay: '月结'
      },
      // 分页相关
      currentPage: 1,
      totalRows: 0,
      pageSizes: [10, 20, 50, 100],
      pageSize: 10,
      // 表单验证规则
      rules: {
        customerId: [
          { required: true, message: '请选择客户', trigger: 'change' }
        ],
        materialName: [
          { required: true, message: '请输入品名', trigger: 'blur' }
        ],
        keepDay: [
          { required: true, message: '请输入免堆时间', trigger: 'blur' }
        ],
        ordPrice: [
          { required: true, message: '请输入免堆期单价', trigger: 'blur' }
        ],
        outOrdPrice: [
          { required: true, message: '请输入超期单价', trigger: 'blur' }
        ],
        payWay: [
          { required: true, message: '请选择支付方式', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    this.getTableData()
    this.getAllCustomer()
  },
  methods: {
    // 查询
    handleSearch() {
      this.currentPage = 1
      this.getTableData()
    },

    // 新增按钮
    handleAdd() {
      this.dialogTitle = '新增价格'
      this.form = {
        id: '',
        customerId: '',
        materialName: '',
        keepDay: '',
        ordPrice: '',
        outOrdPrice: '',
        payWay: '月结'
      }
      this.dialogVisible = true
      // 清除表单验证
      if (this.$refs.ruleFormRef) {
        this.$refs.ruleFormRef.clearValidate()
      }
    },

    // 编辑按钮
    handleEdit(row) {
      this.dialogTitle = '编辑价格'
      this.form = {
        id: row.id,
        customerId: row.customerId,
        materialName: row.materialName,
        keepDay: row.keepDay,
        ordPrice: row.ordPrice,
        outOrdPrice: row.outOrdPrice,
        payWay: row.payWay || '月结'
      }
      this.dialogVisible = true
      // 清除表单验证
      if (this.$refs.ruleFormRef) {
        this.$refs.ruleFormRef.clearValidate()
      }
    },

    // 保存
    handleSave() {
      this.$refs.ruleFormRef.validate((valid) => {
        if (valid) {
          const url = 'sto/Price/save'
          const param = {
            json: JSON.stringify(this.form)
          }
          axios.post(url, param).then(response => {
            if (response.data.code == 0) {
              this.$message({
                message: '保存成功',
                type: 'success',
              })
              this.dialogVisible = false
              this.getTableData()
            } else {
              this.$message({
                type: 'error',
                message: '保存失败：' + response.data.msg
              })
            }
          }).catch(error => {
            this.$message({
              type: 'error',
              message: '请求失败：' + error
            })
          })
        } else {
          this.$message({
            type: 'warning',
            message: '请完善表单信息'
          })
          return false
        }
      })
    },

    // 取消保存
    handleCancelSave() {
      this.dialogVisible = false
    },

    // 删除
    handleDelete(row) {
      this.$confirm('确定删除本条记录?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
      }).then(() => {
        const url = 'sto/Price/remove'
        const param = { id: row.id }
        axios.post(url, param).then(response => {
          if (response.data.code == 0) {
            this.$message({
              type: 'success',
              message: '删除成功！',
            })
            this.getTableData()
          } else {
            this.$message.error('操作失败！' + response.data.msg)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消',
        })
      })
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val
      this.getTableData()
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val
      this.getTableData()
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString()
    },

    // 获取表格数据
    getTableData() {
      this.loading = true
      const url = 'sto/Price/query'
      const param = {
        page: this.currentPage,
        rows: this.pageSize,
        customerName: this.query.customerName
      }
      axios.get(url, param).then(response => {
        if (response.data.code == 0) {
          this.tableData = response.data.data.records || response.data.data.list
          this.totalRows = response.data.data.total
        } else {
          this.$message.error('操作失败！' + response.data.msg)
        }
        this.loading = false
      }).catch(error => {
        this.loading = false
        this.$message.error('请求失败：' + error)
      })
    },

    // 获取所有客户
    getAllCustomer() {
      const url = 'sto/Customer/query'
      const param = {
        page: 1,
        rows: 1000
      }
      axios.get(url, param).then(response => {
        if (response.data.code == 0) {
          this.optionsCust = response.data.data.records || response.data.data.list
        }
      }).catch(error => {
        this.$message.error('获取客户列表失败：' + error)
      })
    }
  }
}
</script>

<style scoped>
::v-deep .el-dialog__body {
  background-color: #F2F6FC;
}
</style>