<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户id" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户id"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入用户昵称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="批次单号" prop="outBatchNo">
        <el-input
          v-model="queryParams.outBatchNo"
          placeholder="请输入批次单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单号" prop="batchId">
        <el-input
          v-model="queryParams.batchId"
          placeholder="请输入微信批次单号(订单号)"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="提现金额(元)" label-width="100px">
        <div class="amount-range">
          <el-input
            v-model="queryParams.minAmount"
            placeholder=""
            clearable
            size="small"
            style="width: 140px"
            @keyup.enter.native="handleQuery"
            @input="handleAmountInput('minAmount', $event)"
          />
          <span class="separator">-</span>
          <el-input
            v-model="queryParams.maxAmount"
            placeholder=""
            clearable
            size="small"
            style="width: 140px"
            @keyup.enter.native="handleQuery"
            @input="handleAmountInput('maxAmount', $event)"
          />
        </div>
      </el-form-item>
      <!-- 提现时间范围 -->
      <el-form-item label="提现时间">
        <el-date-picker
          v-model="timeRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :default-time="['00:00:00', '23:59:59']"
          value-format="yyyy-MM-dd HH:mm:ss"
          size="small"
          style="width: 510px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option label="发送成功" :value="1" />
          <el-option label="领取中" value="0" />
          <el-option label="已取消" :value="-2" />
          <el-option label="发送失败" :value="-1" />

        </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-form :model="queryParams" ref="totalMoney" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="可提现总金额" prop="totalMayWithdraw">
        <el-input
          v-model="totalMoney.totalMayWithdraw"
          placeholder=""
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
          disabled
        />
      </el-form-item>

      <el-form-item label="已提现总金额" prop="totalWithdrawFinish">
        <el-input
          v-model="totalMoney.totalWithdrawFinish"
          placeholder=""
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
          disabled
        />
      </el-form-item>
      <el-form-item label="领取中金额" prop="withdrawMoney">
        <el-input
          v-model="totalMoney.withdrawMoney"
          placeholder=""
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
          disabled
        />
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['his:integralRedPacketLog:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="logList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="日志Id" align="center" prop="logId" />
      <el-table-column label="用户id" align="center" prop="userId" />
      <el-table-column label="用户昵称" align="center" prop="nickName" />
      <el-table-column label="提现金额" align="center" prop="amount" />
      <el-table-column label="提现时间" align="center" prop="createTime" />
      <el-table-column label="批次单号" align="center" prop="outBatchNo" width="250px"/>
      <el-table-column label="微信批次单号" align="center" prop="batchId" />
      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="{ row }">
          <el-tag :type="getStatusType(row.status)" size="small">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="退佣状态" align="center" prop="returnedStatus" >
        <template slot-scope="{ row }">
          <span :class="row.returnedStatus === 1 ? 'status-yes' : 'status-no'">
            {{ row.returnedStatus === 1 ? '是' : '否' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

  </div>
</template>

<script>
import {
  listProfit,
  getProfit,
  delProfit,
  addProfit,
  updateProfit,
  exportProfit,
  getWithFinishAndMayWithdraw
} from "@/api/his/withdrawDetail";
import { listLog, getLog, delLog, addLog, updateLog, exportLog } from "@/api/his/integralRedPacketLog";

export default {
  name: "Profit",
  data() {
    return {
      minAmount: undefined,
      maxAmount: undefined,
      timeRange: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 广告分佣表格数据
      logList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      firstLoginTime: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        nickName: null,
        beginTime:null,
        endTime:null,
        minAmount: null,
        maxAmount: null,
        outBatchNo: null,
        batchId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        adTransId: [
          { required: true, message: "广告回调唯一交易ID不能为空", trigger: "blur" }
        ],
      },
      // 可提现总金额 和 已提现总金额
      totalMoney: {
        totalWithdrawFinish: null,
        totalMayWithdraw: null,
        withdrawMoney: null
      },
    };
  },
  created() {
    this.getList();
    this.selectMoney();
  },
  methods: {
    // 金额输入校验（只允许数字和小数点，最多两位小数）
    handleAmountInput(field, value) {
      // 移除非数字和非小数点字符
      let newValue = value.replace(/[^\d.]/g, '')

      // 只允许一个小数点
      const parts = newValue.split('.')
      if (parts.length > 2) {
        newValue = parts[0] + '.' + parts.slice(1).join('')
      }

      // 限制最多两位小数
      if (parts[1] && parts[1].length > 2) {
        newValue = parts[0] + '.' + parts[1].substring(0, 2)
      }

      // 以0开头但不是0.的情况处理
      if (newValue.startsWith('0') && newValue.length > 1 && !newValue.startsWith('0.')) {
        newValue = newValue.substring(1)
      }

      this.queryParams[field] = newValue === '' ? null : newValue
    },


    getStatusText(status) {
      const map = {
        1: '发送成功',
        '-3': '取消中',
        '-2': '已取消',
        '-1': '发送失败',
        0: '领取中'
      }
      return map[status] || '领取中' // 其余状态默认显示领取中
    },
    getStatusType(status) {
      const map = {
        1: 'success',      // 绿色
        '-3': 'warning',   // 黄色
        '-2': 'info',      // 灰色
        '-1': 'danger'     // 红色
      }
      return map[status] || '' // 领取中为默认蓝色/白色
    },
    changeLoginTime(){
      if(this.firstLoginTime!=null){
        this.queryParams.sTime=this.firstLoginTime[0];
        this.queryParams.eTime=this.firstLoginTime[1];
      }else{
        this.queryParams.sTime=null;
        this.queryParams.eTime=null;
      }
    },
    /** 查询广告分佣列表 */
    getList() {
      this.loading = true;
      const params = this.queryParams
      const minAmount = this.queryParams.minAmount ? parseFloat(this.queryParams.minAmount) : null
      const maxAmount = this.queryParams.maxAmount ? parseFloat(this.queryParams.maxAmount) : null

      // 校验范围逻辑
      if (minAmount !== null && maxAmount !== null && minAmount > maxAmount) {
        this.$message.warning('最小金额不能大于最大金额')
        return
      }

      if (minAmount !== null) {
        params.minAmount = minAmount
      }
      if (maxAmount !== null) {
        params.maxAmount = maxAmount
      }
      // 时间范围处理
      if (this.timeRange && this.timeRange.length>0) {
        params.beginTime = this.timeRange[0]
        params.endTime = this.timeRange[1]
      } else {
        this.timeRange= []
      }
      listLog(params).then(response => {
        this.logList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询可提现总金额 和 已提现总金额 */
    selectMoney() {
      getWithFinishAndMayWithdraw().then(response => {
        this.totalMoney.totalMayWithdraw = response.totalMayWithdraw;
        this.totalMoney.totalWithdrawFinish = response.totalWithdrawFinish;
        this.totalMoney.withdrawMoney = response.withdrawMoney;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        adTransId: null,
        adTaskId: null,
        sumMoney: null,
        userId: null,
        userMoney: null,
        companyId: null,
        companyMoney: null,
        huyiMoney: null,
        yunlianMoney: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.selectMoney();
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        userId : null,
        nickName : null,
        beginTime : null,
        endTime : null,
        minAmount : null,
        maxAmount : null,
        outBatchNo : null,
        batchId : null,
        pageNum : 1,
        pageSize : 10,
      }
      this.timeRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加广告分佣";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProfit(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改广告分佣";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProfit(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProfit(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除广告分佣编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delProfit(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {

      const params = this.queryParams
      const minAmount = this.queryParams.minAmount ? parseFloat(this.queryParams.minAmount) : null
      const maxAmount = this.queryParams.maxAmount ? parseFloat(this.queryParams.maxAmount) : null

      // 校验范围逻辑
      if (minAmount !== null && maxAmount !== null && minAmount > maxAmount) {
        this.$message.warning('最小金额不能大于最大金额')
        return
      }

      if (minAmount !== null) {
        params.minAmount = minAmount
      }
      if (maxAmount !== null) {
        params.maxAmount = maxAmount
      }
      // 时间范围处理
      if (this.timeRange && this.timeRange.length>0) {
        params.beginTime = this.timeRange[0]
        params.endTime = this.timeRange[1]
      } else {
        this.timeRange= []
      }
      this.$confirm('是否确认导出所有提现数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportLog(params);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    }
  }
};
</script>
<style scoped>
.amount-range {
  display: flex;
  align-items: center;
}
.separator {
  margin: 0 8px;
  color: #909399;
}
</style>
