<template>
  <el-dialog
    :title="'补偿记录管理 - ' + requisitionTitle"
    :visible.sync="dialogVisible"
    width="1200px"
    append-to-body :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-row :gutter="10" class="mb8" v-if="canAdd">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增补偿</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="compensationList" border>
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column label="工作量" align="center" prop="workload" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.workload">{{ scope.row.workload }}</span>
          <span v-else style="color: #909399;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="工作量单位" align="center" prop="workloadUnit" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.requisition_workload_unit" :value="scope.row.workloadUnit" />
        </template>
      </el-table-column>
      <el-table-column label="单价" align="center" prop="unitPrice" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.unitPrice">{{ scope.row.currency || 'CNY' }} {{ scope.row.unitPrice }}</span>
          <span v-else style="color: #909399;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="金额" align="center" prop="amount" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.amount">{{ scope.row.currency || 'CNY' }} {{ scope.row.amount }}</span>
          <span v-else style="color: #909399;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="币种" align="center" prop="currency" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.currency" :value="scope.row.currency || 'CNY'" />
        </template>
      </el-table-column>
      <el-table-column label="发票号" align="center" prop="invoiceNo" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="支付时间" align="center" prop="paidAt" width="160">
        <template slot-scope="scope">
          <span v-if="scope.row.paidAt">{{ parseTime(scope.row.paidAt, '{y}-{m}-{d} {h}:{i}') }}</span>
          <span v-else style="color: #909399;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.requisition_compensation_status" :value="scope.row.status || 'pending'" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span v-if="scope.row.createTime">{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
          <span v-else style="color: #909399;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="250" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
            v-if="scope.row.status === 'pending'"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="scope.row.status === 'pending'"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleSettle(scope.row)"
            v-if="scope.row.status === 'pending'"
          >结算</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"
    />

    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">关 闭</el-button>
    </div>

    <!-- 补偿表单弹窗 -->
    <el-dialog :title="compensationTitle" :visible.sync="compensationOpen" width="800px" append-to-body :close-on-click-modal="false">
      <el-form ref="compensationForm" :model="compensationForm" :rules="compensationRules" label-width="140px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工作量" prop="workload">
              <el-input-number
                v-model="compensationForm.workload"
                :min="0"
                :precision="2"
                placeholder="请输入工作量"
                style="width: 100%"
                @change="calculateAmount"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作量单位" prop="workloadUnit">
              <el-select v-model="compensationForm.workloadUnit" placeholder="请选择工作量单位" style="width: 100%">
                <el-option
                  v-for="dict in (dict.type.requisition_workload_unit || [])"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="单价" prop="unitPrice">
              <el-input-number
                v-model="compensationForm.unitPrice"
                :min="0"
                :precision="2"
                placeholder="请输入单价"
                style="width: 100%"
                @change="calculateAmount"
              >
                <template slot="prepend">{{ compensationForm.currency || 'CNY' }}</template>
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="币种" prop="currency">
              <el-select v-model="compensationForm.currency" placeholder="请选择币种" style="width: 100%">
                <el-option
                  v-for="dict in (dict.type.currency || [])"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="金额" prop="amount">
          <el-input-number
            v-model="compensationForm.amount"
            :min="0"
            :precision="2"
            placeholder="金额（自动计算，可手动调整）"
            style="width: 100%"
          >
            <template slot="prepend">{{ compensationForm.currency || 'CNY' }}</template>
          </el-input-number>
          <div style="color: #909399; font-size: 12px; margin-top: 5px;">
            提示：金额 = 工作量 × 单价，可手动调整
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="compensationForm.remark" type="textarea" placeholder="请输入备注" maxlength="500" :rows="2" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCompensationForm">确 定</el-button>
        <el-button @click="compensationOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 结算弹窗 -->
    <el-dialog title="结算补偿" :visible.sync="settleOpen" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="settleForm" :model="settleForm" :rules="settleRules" label-width="120px">
        <el-form-item label="发票号" prop="invoiceNo">
          <el-input v-model="settleForm.invoiceNo" placeholder="请输入发票号" maxlength="100" />
        </el-form-item>
        <el-form-item label="支付时间" prop="paidAt">
          <el-date-picker
            v-model="settleForm.paidAt"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择支付时间"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSettleForm">确 定</el-button>
        <el-button @click="settleOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import {
  listRequisitionCompensations,
  getRequisitionCompensation,
  addRequisitionCompensation,
  updateRequisitionCompensation,
  delRequisitionCompensation,
  settleCompensation
} from '@/api/resource/requisition'

export default {
  name: 'RequisitionCompensationDialog',
  dicts: ['requisition_workload_unit', 'requisition_compensation_status', 'currency'],
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    requisitionId: {
      type: Number,
      default: null
    },
    requisitionTitle: {
      type: String,
      default: ''
    },
    requisitionStatus: {
      type: String,
      default: 'draft'
    }
  },
  data() {
    return {
      dialogVisible: this.visible,
      loading: false,
      compensationList: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      compensationOpen: false,
      compensationTitle: '',
      compensationForm: {},
      settleOpen: false,
      settleForm: {},
      currentCompensationId: null,
      compensationRules: {
        workload: [
          { required: true, message: '工作量不能为空', trigger: 'blur' }
        ],
        workloadUnit: [
          { required: true, message: '工作量单位不能为空', trigger: 'change' }
        ],
        unitPrice: [
          { required: true, message: '单价不能为空', trigger: 'blur' }
        ],
        amount: [
          { required: true, message: '金额不能为空', trigger: 'blur' }
        ],
        currency: [
          { required: true, message: '币种不能为空', trigger: 'change' }
        ],
        remark: [
          { max: 500, message: '备注长度不能超过500个字符', trigger: 'blur' }
        ]
      },
      settleRules: {
        invoiceNo: [
          { required: true, message: '发票号不能为空', trigger: 'blur' },
          { max: 100, message: '发票号长度不能超过100个字符', trigger: 'blur' }
        ],
        paidAt: [
          { required: true, message: '支付时间不能为空', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    canAdd() {
      return this.requisitionStatus === 'active'
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
      if (val && this.requisitionId) {
        this.getList()
      }
    },
    dialogVisible(val) {
      this.$emit('update:visible', val)
    }
  },
  methods: {
    /** 查询补偿记录列表 */
    getList() {
      this.loading = true
      listRequisitionCompensations(this.requisitionId, this.queryParams).then(response => {
        this.compensationList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 新增补偿 */
    handleAdd() {
      this.resetCompensationForm()
      this.compensationTitle = '新增补偿'
      this.compensationOpen = true
    },
    /** 编辑补偿 */
    handleEdit(row) {
      getRequisitionCompensation(row.id).then(response => {
        const data = response.data || {}
        this.compensationForm = {
          id: data.id,
          requisitionId: this.requisitionId,
          workload: data.workload,
          workloadUnit: data.workloadUnit,
          unitPrice: data.unitPrice,
          amount: data.amount,
          currency: data.currency || 'CNY',
          invoiceNo: data.invoiceNo,
          paidAt: data.paidAt,
          status: data.status || 'pending',
          remark: data.remark
        }
        this.compensationTitle = '编辑补偿'
        this.compensationOpen = true
      })
    },
    /** 删除补偿 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除该补偿记录？').then(() => {
        return delRequisitionCompensation(this.requisitionId, row.id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 结算补偿 */
    handleSettle(row) {
      this.currentCompensationId = row.id
      this.settleForm = {
        invoiceNo: undefined,
        paidAt: undefined
      }
      this.resetForm('settleForm')
      this.settleOpen = true
    },
    /** 提交结算表单 */
    submitSettleForm() {
      this.$refs['settleForm'].validate(valid => {
        if (valid) {
          settleCompensation(
            this.currentCompensationId,
            this.settleForm.invoiceNo,
            this.settleForm.paidAt
          ).then(response => {
            this.$modal.msgSuccess('结算成功')
            this.settleOpen = false
            this.getList()
            this.$emit('success')
          })
        }
      })
    },
    /** 计算金额 */
    calculateAmount() {
      if (this.compensationForm.workload && this.compensationForm.unitPrice) {
        this.compensationForm.amount = parseFloat(
          (this.compensationForm.workload * this.compensationForm.unitPrice).toFixed(2)
        )
      } else {
        this.compensationForm.amount = undefined
      }
    },
    /** 提交补偿表单 */
    submitCompensationForm() {
      this.$refs['compensationForm'].validate(valid => {
        if (valid) {
          if (this.compensationForm.id != undefined) {
            updateRequisitionCompensation(this.requisitionId, this.compensationForm.id, this.compensationForm).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.compensationOpen = false
              this.getList()
              this.$emit('success')
            })
          } else {
            addRequisitionCompensation(this.requisitionId, this.compensationForm).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.compensationOpen = false
              this.getList()
              this.$emit('success')
            })
          }
        }
      })
    },
    /** 重置补偿表单 */
    resetCompensationForm() {
      this.compensationForm = {
        id: undefined,
        requisitionId: this.requisitionId,
        workload: undefined,
        workloadUnit: undefined,
        unitPrice: undefined,
        amount: undefined,
        currency: 'CNY',
        invoiceNo: undefined,
        paidAt: undefined,
        status: 'pending',
        remark: undefined
      }
      this.resetForm('compensationForm')
    },
    /** 关闭对话框 */
    handleClose() {
      this.compensationList = []
      this.total = 0
      this.queryParams = {
        pageNum: 1,
        pageSize: 10
      }
    }
  }
}
</script>

