<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.uperCustomerId" filterable placeholder="请选择上游客户" clearable style="width:100%;" size="small">
                <el-option v-for="item in optionsCustomer" :key="item.id" :label="item.customerNm" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="客户" style="margin-bottom: 0px;">
              <el-select v-model="query.customerId" filterable placeholder="请选择客户" clearable style="width:100%;" size="small">
                <el-option v-for="item in optionsCustomer" :key="item.id" :label="item.customerNm" :value="item.id" />
              </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-button type="info" @click="handleReset">重置</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="uperCustomerName" label="上游客户" width="180" show-overflow-tooltip />
        <el-table-column prop="customerName" label="客户" width="180" show-overflow-tooltip />
        <el-table-column prop="sumWeight" label="可使用量(吨)" width="120" show-overflow-tooltip align="right">
          <template #default="scope">
            <span>{{ scope.row.sumWeight ? scope.row.sumWeight.toFixed(3) : '0.000' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="useWeight" label="已使用量(吨)" width="120" show-overflow-tooltip align="right">
          <template #default="scope">
            <span>{{ scope.row.useWeight ? scope.row.useWeight.toFixed(3) : '0.000' }}</span>
          </template>
        </el-table-column>
        <!-- 启用状态列 -->
<!--        <el-table-column prop="enableStatus" label="启用状态" width="100" align="center">
          <template #default="scope">
            <el-switch
                v-model="scope.row.enableStatus"
                :active-value="'1'"
                :inactive-value="'0'"
                @change="handleEnableStatusChange(scope.row)"
            />
          </template>
        </el-table-column>-->
        <el-table-column label="启用状态操作" width="120" fixed="right">
          <template #default="scope">
            <el-button
                plain
                :type="scope.row.enableStatus === '1' ? 'danger' : 'success'"
                size="mini"
                @click="handleToggleEnableStatus(scope.row)"
                :loading="enableStatusLoading"
            >
              {{ scope.row.enableStatus === '1' ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button plain type="warning" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
        <el-table-column label="日志记录" width="100" fixed="right">
          <template #default="scope">
            <el-button plain type="primary" size="mini" @click="handleLog(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="form.id ? '货权调整' : '新增货权'" 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="uperCustomerId">
          <el-select
              v-model="form.uperCustomerId"
              filterable
              placeholder="请选择上游客户"
              :disabled="!!form.id"
              style="width: 100%;">
            <el-option v-for="item in optionsCustomer" :key="item.id" :label="item.customerNm" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户" prop="customerId">
          <el-select
              v-model="form.customerId"
              filterable
              placeholder="请选择客户"
              :disabled="!!form.id"
              style="width: 100%;">
            <el-option v-for="item in optionsCustomer" :key="item.id" :label="item.customerNm" :value="item.id" />
          </el-select>
        </el-form-item>
        <!-- 编辑时显示启用状态 -->
        <el-form-item v-if="form.id" label="启用状态">
          <el-tag :type="form.enableStatus === '1' ? 'success' : 'info'">
            {{ form.enableStatus === '1' ? '已启用' : '未启用' }}
          </el-tag>
        </el-form-item>
        <el-form-item label="修改内容" prop="subStr">
          <el-select
              v-model="form.subStr"
              placeholder="请选择修改内容"
              :disabled="isReduceDisabled"
              style="width: 100%;">
            <el-option label="增加" value="增加" />
            <el-option label="减少" value="减少" :disabled="isReduceDisabled" />
          </el-select>
          <div v-if="isReduceDisabled" style="color: #f56c6c; font-size: 12px; margin-top: 5px;">
            当前记录已启用且可使用量为0，不能进行减少操作
          </div>
        </el-form-item>
        <el-form-item label="重量" prop="weight">
          <el-input v-model="form.weight" type="number" placeholder="请输入重量" style="width: 100%;">
            <template slot="append">吨</template>
          </el-input>
        </el-form-item>
        <el-form-item label="单号" prop="ordNo">
          <el-input v-model="form.ordNo" placeholder="请输入单号" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" style="width: 100%;" />
        </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>

    <!-- 日志记录对话框 -->
    <el-dialog title="转移数量变动日志" v-model="logDialogVisible" width="900px" :close-on-click-modal="false">
      <!-- 日志查询条件 -->
      <el-form :model="logQuery" label-width="auto" label-position="right">
        <el-row :gutter="10">
          <el-col :span="10">
            <el-form-item label="修改时间" style="margin-bottom: 0px;">
              <el-date-picker
                  v-model="logQuery.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                  style="width:100%;"
                  size="small"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="修改类型" style="margin-bottom: 0px;">
              <el-select v-model="logQuery.subStr" placeholder="请选择" clearable style="width:100%;" size="small">
                <el-option label="增加" value="增加" />
                <el-option label="减少" value="减少" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="修改来源" style="margin-bottom: 0px;">
              <el-select v-model="logQuery.changeFrom" placeholder="请选择" clearable style="width:100%;" size="small">
                <el-option label="手动调整" value="手动调整" />
                <el-option label="货权转移" value="货权转移" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="" style="margin-bottom: 0px; margin-top: 5px;">
              <el-button type="primary" @click="handleLogSearch">查询</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 日志表格 -->
      <el-table :data="logTableData" border highlight-current-row v-loading="logLoading">
        <el-table-column type="index" label="序号" align="center" width="60">
          <template #default="scope">
            <span>{{ scope.$index + (logCurrentPage - 1) * logPageSize + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="modifyTime" label="修改时间" width="180" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ formatDate(scope.row.modifyTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="modifyName" label="修改人员" width="120" show-overflow-tooltip />
        <el-table-column prop="weight" label="修改重量(吨)" width="120" show-overflow-tooltip align="right">
          <template #default="scope">
            <span>{{ scope.row.weight ? scope.row.weight.toFixed(3) : '0.000' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="subStr" label="修改类型" width="100" show-overflow-tooltip />
        <el-table-column prop="changeFrom" label="修改来源" width="120" show-overflow-tooltip />
        <el-table-column prop="ordNo" label="单号" width="150" show-overflow-tooltip />
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
      </el-table>

      <!-- 日志分页 -->
      <div style="margin-top: 15px;">
        <el-pagination :current-page="logCurrentPage" :page-size="logPageSize" :page-sizes="logPageSizes" :total="logTotalRows"
                       background layout="total, sizes, prev, pager, next, jumper"
                       @size-change="handleLogSizeChange"
                       @current-change="handleLogCurrentChange" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from '@/axios'

export default {
  data() {
    return {
      cardBodyStyle: { padding: '10px' },
      // 查询条件
      query: {
        uperCustomerId: '',
        customerId: ''
      },
      // 表格数据
      tableData: [],
      loading: false,
      // 对话框控制
      dialogVisible: false,
      logDialogVisible: false,
      // 客户选项
      optionsCustomer: [],
      // 表单数据
      form: {
        id: '',
        uperCustomerId: '',
        customerId: '',
        subStr: '',
        weight: '',
        ordNo: '',
        remark: '',
        enableStatus: '0',
        sumWeight: 0
      },
      // 分页相关
      currentPage: 1,
      totalRows: 0,
      pageSizes: [10, 20, 50, 100],
      pageSize: 10,
      // 日志查询条件
      logQuery: {
        dateRange: [],
        subStr: '',
        changeFrom: ''
      },
      // 日志表格数据
      logTableData: [],
      logLoading: false,
      // 日志分页相关
      logCurrentPage: 1,
      logTotalRows: 0,
      logPageSizes: [10, 20, 50, 100],
      logPageSize: 10,
      // 当前选中的货权记录（用于日志查询）
      currentCargoRecord: null,
      // 启用状态修改加载状态
      enableStatusLoading: false,
      // 表单验证规则
      rules: {
        uperCustomerId: [
          { required: true, message: '请选择上游客户', trigger: 'change' }
        ],
        customerId: [
          { required: true, message: '请选择客户', trigger: 'change' }
        ],
        subStr: [
          { required: true, message: '请选择修改内容', trigger: 'change' }
        ],
        weight: [
          { required: true, message: '请输入重量', trigger: 'blur' },
          { validator: this.validateWeight, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 计算是否禁用减少操作
    isReduceDisabled() {
      if (!this.form.id) {
        // 新增时，减少操作不可用
        return true
      }
      // 编辑时，如果启用状态为1且可使用量为0，则禁用减少操作
      return this.form.enableStatus === '1' && (this.form.sumWeight === 0 || this.form.sumWeight === null)
    }
  },
  mounted() {
    this.getTableData()
    this.getAllCustomer()
  },
  methods: {
    // 重量验证
    validateWeight(rule, value, callback) {
      if (!value) {
        callback(new Error('请输入重量'))
      } else if (parseFloat(value) <= 0) {
        callback(new Error('重量必须大于0'))
      } else {
        callback()
      }
    },

    // 查询
    handleSearch() {
      this.currentPage = 1
      this.getTableData()
    },

    // 重置查询条件
    handleReset() {
      this.query = {
        uperCustomerId: '',
        customerId: ''
      }
      this.currentPage = 1
      this.getTableData()
    },

    // 新增按钮
    handleAdd() {
      this.form = {
        id: '',
        uperCustomerId: '',
        customerId: '',
        subStr: '增加', // 新增时默认为增加
        weight: '',
        ordNo: '',
        remark: '',
        enableStatus: '0',
        sumWeight: 0
      }
      this.dialogVisible = true
      // 清除表单验证
      if (this.$refs.ruleFormRef) {
        this.$refs.ruleFormRef.clearValidate()
      }
    },

    // 编辑按钮
    handleEdit(row) {
      this.form = {
        id: row.id,
        uperCustomerId: row.uperCustomerId,
        customerId: row.customerId,
        subStr: '增加', // 编辑时默认为增加
        weight: '',
        ordNo: '',
        remark: '',
        enableStatus: row.enableStatus,
        sumWeight: row.sumWeight
      }
      this.dialogVisible = true
      // 清除表单验证
      if (this.$refs.ruleFormRef) {
        this.$refs.ruleFormRef.clearValidate()
      }
    },

    // 查看日志
    handleLog(row) {
      this.currentCargoRecord = row
      this.logQuery = {
        dateRange: [],
        subStr: '',
        changeFrom: ''
      }
      this.logCurrentPage = 1
      this.getLogTableData()
      this.logDialogVisible = true
    },

    // 日志查询
    handleLogSearch() {
      this.logCurrentPage = 1
      this.getLogTableData()
    },

    // 保存
    handleSave() {
      this.$refs.ruleFormRef.validate((valid) => {
        if (valid) {
          // 使用transfer接口进行货权调整
          const url = 'sto/Cargo/transfer'
          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
    },

    // 切换启用状态
    handleToggleEnableStatus(row) {
      const newStatus = row.enableStatus === '1' ? '0' : '1'
      const action = newStatus === '1' ? '启用' : '禁用'

      this.$confirm(`确定要${action}此货权记录吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        this.updateEnableStatus(row.id, newStatus)
      }).catch(() => {})
    },

    // 更新启用状态
    updateEnableStatus(id, enableStatus) {
      this.enableStatusLoading = true
      const url = 'sto/Cargo/updateEnableStatus'
      const param = {
        id: id,
        enableStatus: enableStatus
      }

      axios.post(url, param).then(response => {
        if (response.data.code == 0) {
          this.$message({
            message: '操作成功',
            type: 'success',
          })
          this.getTableData() // 刷新表格数据
        } else {
          this.$message({
            type: 'error',
            message: '操作失败：' + response.data.msg
          })
          // 操作失败，刷新表格以恢复正确的状态
          this.getTableData()
        }
        this.enableStatusLoading = false
      }).catch(error => {
        this.enableStatusLoading = false
        this.$message({
          type: 'error',
          message: '请求失败：' + error
        })
        // 请求失败，刷新表格以恢复正确的状态
        this.getTableData()
      })
    },

    // 开关状态改变事件
    handleEnableStatusChange(row) {
      this.updateEnableStatus(row.id, row.enableStatus)
    },

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

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

    // 日志分页大小改变
    handleLogSizeChange(val) {
      this.logPageSize = val
      this.getLogTableData()
    },

    // 日志当前页改变
    handleLogCurrentChange(val) {
      this.logCurrentPage = val
      this.getLogTableData()
    },

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

    // 获取表格数据
    getTableData() {
      this.loading = true
      const url = 'sto/Cargo/query'
      const param = {
        page: this.currentPage,
        rows: this.pageSize,
        uperCustomerId: this.query.uperCustomerId,
        customerId: this.query.customerId
      }
      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)
      })
    },

    // 获取日志表格数据
    getLogTableData() {
      this.logLoading = true
      const url = 'sto/CargoChangeRecord/query'
      const param = {
        page: this.logCurrentPage,
        rows: this.logPageSize,
        uperCustomerId: this.currentCargoRecord ? this.currentCargoRecord.uperCustomerId : '',
        customerId: this.currentCargoRecord ? this.currentCargoRecord.customerId : '',
        startDate: this.logQuery.dateRange && this.logQuery.dateRange[0] ? this.logQuery.dateRange[0] : '',
        endDate: this.logQuery.dateRange && this.logQuery.dateRange[1] ? this.logQuery.dateRange[1] : '',
        subStr: this.logQuery.subStr,
        changeFrom: this.logQuery.changeFrom
      }
      axios.get(url, param).then(response => {
        if (response.data.code == 0) {
          this.logTableData = response.data.data.records || response.data.data.list
          this.logTotalRows = response.data.data.total
        } else {
          this.$message.error('操作失败！' + response.data.msg)
        }
        this.logLoading = false
      }).catch(error => {
        this.logLoading = 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.optionsCustomer = 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>