<template>
  <div>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
      <el-form-item label="订单号" prop="orderId">
        <el-input
          v-model="queryParams.orderId"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收支类别" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择收支类别" clearable>
          <el-option
            v-for="dict in dict.type.worker_money_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="收益状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状收益状态" clearable>
          <el-option
            v-for="dict in dict.type.worker_money_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-lock"
          size="mini"
          :disabled="!canLock"
          @click="handleLockMoney"
          v-hasPermi="['system:workerMoneyLog:lock']"
        >锁住收益</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-unlock"
          size="mini"
          :disabled="!canLock"
          @click="handleUnlockMoney"
          v-hasPermi="['system:workerMoneyLog:unlock']"
        >解锁收益</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-edit-outline"
          size="mini"
          :disabled="!canAdjust"
          @click="handleAdjustMoney"
          v-hasPermi="['system:workerMoneyLog:adjust']"
        >调整收益</el-button>
      </el-col>
      <el-col :span="16.5"></el-col>
      <el-col :span="1.5" style="text-align:right;">
        <el-button @click="$emit('close')">关闭</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="workerMoneyLogList" @selection-change="handleSelectionChange" element-loading-text="正在加载师傅佣金明细数据...">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="订单号" align="center" prop="orderId" />
      <el-table-column label="金额" align="center" prop="price">
        <template slot-scope="scope">
          <span style="color: #E6A23C; font-weight: bold; font-size: 14px;">
            ¥{{ formatMoney(scope.row.price) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="收支类别" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.worker_money_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="服务金额" align="center" prop="servicePrice">
        <template slot-scope="scope">
          <span v-if="scope.row.servicePrice" style="color: #E6A23C; font-weight: bold;">
            ¥{{ formatMoney(scope.row.servicePrice) }}
          </span>
          <span v-else style="color: #C0C4CC;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="优惠金额" align="center" prop="reductionPrice">
        <template slot-scope="scope">
          <span v-if="scope.row.reductionPrice" style="color: #F56C6C; font-weight: bold;">
            ¥{{ formatMoney(scope.row.reductionPrice) }}
          </span>
          <span v-else style="color: #C0C4CC;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="提成比例" align="center" prop="cr" />
      <el-table-column label="质保金" align="center" prop="mergin">
        <template slot-scope="scope">
          <span v-if="scope.row.mergin" style="color: #E6A23C; font-weight: bold;">
            ¥{{ formatMoney(scope.row.mergin) }}
          </span>
          <span v-else style="color: #C0C4CC;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="上门费" align="center" prop="doorPrice">
        <template slot-scope="scope">
          <span v-if="scope.row.doorPrice" style="color: #E6A23C; font-weight: bold;">
            ¥{{ formatMoney(scope.row.doorPrice) }}
          </span>
          <span v-else style="color: #C0C4CC;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收益状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.worker_money_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="锁单类型" align="center" prop="statusType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.worker_money_status_type" :value="scope.row.statusType"/>
        </template>
      </el-table-column>
      <el-table-column label="锁单开始时间" align="center" prop="beginlook" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.beginlook, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="锁单结束时间" align="center" prop="endlook" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endlook, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="锁单天数" align="center" prop="lookday" />
      <el-table-column label="锁单金额" align="center" prop="lookMoney" />
      <el-table-column label="调整金额" align="center" prop="adminUpPrice" />
      <el-table-column label="锁单调整原由" align="center" prop="adminUpReamk" />
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 空数据提示 -->
    <div v-if="!loading && workerMoneyLogList.length === 0" style="text-align: center; padding: 40px; color: #909399;">
      <i class="el-icon-warning" style="font-size: 48px; margin-bottom: 16px;"></i>
      <p>暂无师傅佣金明细数据</p>
      <p v-if="queryParams.workerId">师傅ID: {{ queryParams.workerId }}</p>
    </div>

    <!-- 操作提示 -->
    <div v-if="!loading && workerMoneyLogList.length > 0 && ids.length === 0" style="text-align: center; padding: 20px; color: #909399; background: #f8f9fa; border-radius: 4px; margin-bottom: 20px;">
      <i class="el-icon-info" style="margin-right: 8px;"></i>
      请选择一条记录进行操作。锁住收益：未锁定状态 | 解锁收益：已锁定状态 | 调整收益：已锁定状态
    </div>

    <!-- 锁住收益弹窗 -->
    <el-dialog title="锁住收益" :visible.sync="lockDialogVisible" width="500px" append-to-body>
      <el-form ref="lockForm" :model="lockForm" :rules="lockRules" label-width="100px">
        <el-form-item label="锁住金额">
          <el-input v-model="lockForm.price" disabled>
            <template slot="prepend">¥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="锁住类型" prop="lockType">
          <el-radio-group v-model="lockForm.lockType">
            <el-radio label="forever">永久锁住</el-radio>
            <el-radio label="days">按天数锁住</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="lockForm.lockType === 'days'" label="锁住天数" prop="lockday">
          <el-input-number v-model="lockForm.lockday" :min="1" :max="365" />
        </el-form-item>
        <el-form-item label="锁住原因" prop="remark">
          <el-input
            v-model="lockForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入锁住原因"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-form-item>
          <div style="color: #909399; font-size: 12px;">
            将锁住 {{ lockForm.count }} 条记录，总金额 ¥{{ formatMoney(lockForm.total) }}
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelLockDialog">取消</el-button>
        <el-button type="primary" @click="confirmLockMoney" :loading="lockLoading">确认锁住</el-button>
      </div>
    </el-dialog>

    <!-- 解锁收益弹窗 -->
    <el-dialog title="解锁收益" :visible.sync="unlockDialogVisible" width="500px" append-to-body>
      <el-form ref="unlockForm" :model="unlockForm" :rules="unlockRules" label-width="100px">
        <el-form-item label="解锁原因" prop="remark">
          <el-input
            v-model="unlockForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入解锁原因"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-form-item>
          <div style="color: #909399; font-size: 12px;">
            将解锁 {{ unlockForm.count }} 条记录，总金额 ¥{{ formatMoney(unlockForm.total) }}
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelUnlockDialog">取消</el-button>
        <el-button type="primary" @click="confirmUnlockMoney" :loading="unlockLoading">确认解锁</el-button>
      </div>
    </el-dialog>

    <!-- 调整收益弹窗 -->
    <el-dialog title="调整收益" :visible.sync="adjustDialogVisible" width="500px" append-to-body>
      <el-form ref="adjustForm" :model="adjustForm" :rules="adjustRules" label-width="100px">
        <el-form-item label="调整类型" prop="type">
          <el-radio-group v-model="adjustForm.type">
            <el-radio label="reward">奖励</el-radio>
            <el-radio label="deduct">扣除</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="调整金额" prop="amount">
          <el-input-number
            v-model="adjustForm.amount"
            :min="0.01"
            :max="adjustForm.type === 'deduct' ? adjustForm.maxPrice : 99999"
            :precision="2"
            :step="0.01"
            placeholder="请输入调整金额"
            style="width: 100%;"
          />
          <div v-if="adjustForm.type === 'deduct'" style="color: #909399; font-size: 12px; margin-top: 5px;">
            当前金额: ¥{{ formatMoney(adjustForm.maxPrice) }}，最大可扣除: ¥{{ formatMoney(adjustForm.maxPrice) }}
          </div>
          <div v-else style="color: #909399; font-size: 12px; margin-top: 5px;">
            当前金额: ¥{{ formatMoney(adjustForm.maxPrice) }}，奖励后金额: ¥{{ formatMoney(adjustForm.maxPrice + (adjustForm.amount || 0)) }}
          </div>
        </el-form-item>
        <el-form-item label="调整原因" prop="remark">
          <el-input
            v-model="adjustForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入调整原因"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAdjustDialog">取消</el-button>
        <el-button type="primary" @click="confirmAdjustMoney" :loading="adjustLoading">确认调整</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listWorkerMoneyLog, lockWorkerMoney, unlockWorkerMoney, adjustWorkerMoney } from '@/api/system/workerMoneyLog'
export default {
  name: 'WorkerMoneyLogTable',
  props: {
    workerId: {
      type: [String, Number],
      required: true
    }
  },
  dicts: ['worker_money_type', 'worker_money_status_type', 'worker_money_status'],
  data() {
    return {
      loading: false,
      total: 0,
      workerMoneyLogList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        workerId: null,
        orderId: null,
        type: null,
        status: null
      },
      ids: [],
      single: true,
      multiple: true,
      canAdjust: false,
      canLock: false,
      canUnlock: false,
      lockDialogVisible: false,
      lockForm: {
        price: 0,
        lockType: 'forever',
        lockday: 1,
        ids: [],
        count: 0,
        total: 0,
        remark: ''
      },
      unlockDialogVisible: false,
      unlockForm: {
        count: 0,
        total: 0,
        ids: [],
        remark: ''
      },
      adjustDialogVisible: false,
      adjustForm: {
        id: null,
        type: 'reward',
        amount: null,
        remark: '',
        maxPrice: 0
      },
      lockLoading: false,
      unlockLoading: false,
      adjustLoading: false,
      lockRules: {
        lockType: [
          { required: true, message: '请选择锁住类型', trigger: 'change' }
        ],
        lockday: [
          {
            validator: (rule, value, callback) => {
              if (this.lockForm.lockType === 'days' && (!value || value < 1)) {
                callback(new Error('按天锁住时必须输入锁住天数'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        remark: [
          { required: true, message: '请输入锁住原因', trigger: 'blur' }
        ]
      },
      unlockRules: {
        remark: [
          { required: true, message: '请输入解锁原因', trigger: 'blur' }
        ]
      },
      adjustRules: {
        type: [
          { required: true, message: '请选择调整类型', trigger: 'change' }
        ],
        amount: [
          { required: true, message: '请输入调整金额', trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '请输入调整原因', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    workerId: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          this.queryParams.workerId = newVal;
          this.getList();
        }
      }
    }
  },
  methods: {
    getList() {
      console.log('开始加载师傅佣金明细数据，workerId:', this.queryParams.workerId);
      if (!this.queryParams.workerId) {
        console.warn('workerId为空，无法加载数据');
        this.$message.warning('师傅ID不能为空');
        return;
      }
      this.loading = true;
      listWorkerMoneyLog(this.queryParams).then(response => {
        console.log('师傅佣金明细数据加载成功:', response);
        this.workerMoneyLogList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(error => {
        console.error('师傅佣金明细数据加载失败:', error);
        this.loading = false;
        if (error.response && error.response.status === 403) {
          this.$message.error('没有权限查看师傅佣金明细');
        } else {
          this.$message.error('数据加载失败: ' + (error.message || '未知错误'));
        }
      });
    },
    formatMoney(money) {
      if (!money) return '0.00';
      return parseFloat(money).toFixed(2);
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.queryParams.orderId = null;
      this.queryParams.type = null;
      this.queryParams.status = null;
      this.handleQuery();
    },
    parseTime(time, pattern) {
      if (!time) return '';
      const date = new Date(time);
      const y = date.getFullYear();
      const m = ('0' + (date.getMonth() + 1)).slice(-2);
      const d = ('0' + date.getDate()).slice(-2);
      if (pattern === '{y}-{m}-{d}') return `${y}-${m}-${d}`;
      return `${y}-${m}-${d}`;
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length

      if (selection.length === 1) {
        const selectedItem = selection[0];
        // 调整收益：只能操作已锁定的数据（status === 1）
        this.canAdjust = selectedItem.status === 1;
        // 锁住收益：只能操作未锁定的数据（status !== 1）
        this.canLock = selectedItem.status !== 1;
        // 解锁收益：只能操作已锁定的数据（status === 1）
        this.canUnlock = selectedItem.status === 1;
      } else {
        this.canAdjust = false;
        this.canLock = false;
        this.canUnlock = false;
      }
    },
    handleLockMoney() {
      if (this.ids.length !== 1) {
        this.$message.warning('请选择一条要锁住收益的数据');
        return;
      }
      const row = this.workerMoneyLogList.find(item => item.id === this.ids[0]);
      if (!row || row.status === 1) {
        this.$message.warning('只能锁住未锁定状态的数据');
        return;
      }
      this.lockForm.count = 1;
      this.lockForm.total = row.price;
      this.lockForm.price = row.price;
      this.lockForm.lockType = 'forever';
      this.lockForm.lockday = 1;
      this.lockForm.ids = [row.id];
      this.lockForm.remark = '';
      this.lockDialogVisible = true;
    },
    handleUnlockMoney() {
      if (this.ids.length !== 1) {
        this.$message.warning('请选择一条要解锁收益的数据');
        return;
      }
      console.log('开始解锁收益数据，ids:', this.ids)
      const row = this.workerMoneyLogList.find(item => item.id === this.ids[0]);
      console.log('开始解锁收益数据，ids:', row.status)
      if (!row || row.status === 1) {
        this.$message.warning('只能操作冻结中的数据');
        return;
      }
      this.unlockForm.count = 1;
      this.unlockForm.total = row.price;
      this.unlockForm.ids = [row.id];
      this.unlockForm.remark = '';
      this.unlockDialogVisible = true;
    },
    handleAdjustMoney() {
      if (this.ids.length !== 1) {
        this.$message.warning('请选择一条要调整的数据');
        return;
      }
      const row = this.workerMoneyLogList.find(item => item.id === this.ids[0]);
      if (!row || row.status !== 1) {
        this.$message.warning('只能调整冻结中的数据');
        return;
      }
      this.adjustForm.id = row.id;
      this.adjustForm.type = 'reward';
      this.adjustForm.amount = null;
      this.adjustForm.remark = '';
      this.adjustForm.maxPrice = parseFloat(row.price) || 0;
      this.adjustDialogVisible = true;
    },
    // 确认锁住收益
    confirmLockMoney() {
      this.$refs.lockForm.validate(valid => {
        if (valid) {
          this.lockLoading = true;
          const lockData = {
            ids: this.lockForm.ids,
            lockType: this.lockForm.lockType,
            lockday: this.lockForm.lockType === 'days' ? this.lockForm.lockday : null,
            remark: this.lockForm.remark
          };

          lockWorkerMoney(lockData).then(response => {
            this.$message.success('锁住收益成功');
            this.lockDialogVisible = false;
            this.getList(); // 刷新列表
            // 重置表单
            this.$nextTick(() => {
              if (this.$refs.lockForm) {
                this.$refs.lockForm.resetFields();
              }
            });
          }).catch(error => {
            console.error('锁住收益失败:', error);
            this.$message.error('锁住收益失败: ' + (error.message || '未知错误'));
          }).finally(() => {
            this.lockLoading = false;
          });
        }
      });
    },
    // 确认解锁收益
    confirmUnlockMoney() {
      this.$refs.unlockForm.validate(valid => {
        if (valid) {
          this.unlockLoading = true;
          const unlockData = {
            ids: this.unlockForm.ids,
            remark: this.unlockForm.remark
          };

          unlockWorkerMoney(unlockData).then(response => {
            this.$message.success('解锁收益成功');
            this.unlockDialogVisible = false;
            this.getList(); // 刷新列表
            // 重置表单
            this.$nextTick(() => {
              if (this.$refs.unlockForm) {
                this.$refs.unlockForm.resetFields();
              }
            });
          }).catch(error => {
            console.error('解锁收益失败:', error);
            this.$message.error('解锁收益失败: ' + (error.message || '未知错误'));
          }).finally(() => {
            this.unlockLoading = false;
          });
        }
      });
    },
    // 确认调整收益
    confirmAdjustMoney() {
      this.$refs.adjustForm.validate(valid => {
        if (valid) {
          this.adjustLoading = true;
          const adjustData = {
            id: this.adjustForm.id,
            type: this.adjustForm.type,
            amount: this.adjustForm.amount,
            remark: this.adjustForm.remark
          };

          adjustWorkerMoney(adjustData).then(response => {
            this.$message.success('调整收益成功');
            this.adjustDialogVisible = false;
            this.getList(); // 刷新列表
            // 重置表单
            this.$nextTick(() => {
              if (this.$refs.adjustForm) {
                this.$refs.adjustForm.resetFields();
              }
            });
          }).catch(error => {
            console.error('调整收益失败:', error);
            this.$message.error('调整收益失败: ' + (error.message || '未知错误'));
          }).finally(() => {
            this.adjustLoading = false;
          });
        }
      });
    },
    // 取消锁住收益弹窗
    cancelLockDialog() {
      this.lockDialogVisible = false;
      this.$nextTick(() => {
        if (this.$refs.lockForm) {
          this.$refs.lockForm.resetFields();
        }
      });
    },
    // 取消解锁收益弹窗
    cancelUnlockDialog() {
      this.unlockDialogVisible = false;
      this.$nextTick(() => {
        if (this.$refs.unlockForm) {
          this.$refs.unlockForm.resetFields();
        }
      });
    },
    // 取消调整收益弹窗
    cancelAdjustDialog() {
      this.adjustDialogVisible = false;
      this.$nextTick(() => {
        if (this.$refs.adjustForm) {
          this.$refs.adjustForm.resetFields();
        }
      });
    }
  }
}
</script>
