<template>
   <div class="app-container">
      <table-search-card  :model="queryParams" @getList="getList" @handleQuery="handleQuery" @resetQuery="resetQuery">
         <template #left>
            <table-search-date ref="searchDateRef" v-model:dateRange="dateRange" @dateChange="handleQuery" v-model:operateTimeType="operateTimeType"></table-search-date>
            <el-form-item :label="t('商户账号')" prop="tenantKey">
               <el-input
                  v-model="queryParams.tenantKey"
                  :placeholder="t('请输入商户账号')"
                  clearable
                  style="width: 200px"
                  @keyup.enter="handleQuery"
               />
            </el-form-item>
            <el-form-item :label="t('代理账号')" prop="agentName">
               <el-input
                  v-model="queryParams.agentName"
                  :placeholder="t('请输入代理账号')"
                  clearable
                  style="width: 200px"
                  @keyup.enter="handleQuery"
               />
            </el-form-item>
         </template>
         <template #right>
         </template>
      </table-search-card>

      <el-table v-loading="loading" :data="commissionList" stripe border class="c-table-main" height="672px">
         <!-- <el-table-column type="selection" width="55" align="center" /> -->
         <el-table-column :label="t('佣金来源')" width="100" align="center" prop="sourceType" >
            <template #default="scope">
               <span v-if="scope.row.sourceType === 1">返佣</span>
               <!-- <dict-tag :options="ff_tenant_agent_approval_status" :value="String(scope.row.sourceType)" /> -->
            </template>
         </el-table-column>
         <el-table-column :label="t('佣金类型')" align="center" prop="commissionType" :show-overflow-tooltip="true" >
            <template #default="scope">
               <span>充值</span>
              <!-- <dict-tag :options="ff_tenant_agent_commission_type" :value="String(scope.row.commissionType)" /> -->
            </template>
         </el-table-column>
         <el-table-column :label="t('商户账号')" align="center" prop="tenantKey" :show-overflow-tooltip="true" >
            <template #default="{row}">
               {{ row.tenantKey|| '--' }}
            </template>
         </el-table-column>
         <el-table-column :label="t('代理账号')" align="center" prop="agentName" :show-overflow-tooltip="true" >
            <template #default="{row}">
               {{ row.agentName|| '--' }}
            </template>
         </el-table-column>
         <el-table-column :label="t('佣金比例（%）')" align="center" width="160" prop="profitRatio" :show-overflow-tooltip="true" />
         <!-- <el-table-column :label="t('成本（%）')" align="center" width="110" prop="costBalance" :show-overflow-tooltip="true" />
         <el-table-column :label="t('商户比例（%）')" align="center" width="160" prop="merchantBalance" :show-overflow-tooltip="true" /> -->
         <el-table-column :label="t('币种')" align="center" prop="currencyCode" :show-overflow-tooltip="true" />
         <el-table-column :label="t('充值额度')" align="center" prop="balance" :show-overflow-tooltip="true" />
         <el-table-column :label="t('支付金额(USDT)')" align="center" width="130" prop="usdtBalance"></el-table-column>
         <el-table-column :label="t('佣金(USDT)')" align="center"  prop="commissionBalance" :show-overflow-tooltip="true" />

         <el-table-column :label="t('时间')" align="center" prop="createTime" :show-overflow-tooltip="true">
            <template #default="scope">{{ parseTime(scope.row.createTime) }}</template>
         </el-table-column>
      </el-table>
    <pagination
         v-show="total > 0"
         :total="total"
         v-model:page="queryParams.pageNum"
         v-model:limit="queryParams.pageSize"
         @pagination="getList"
      />
      <div class="flooter" >
         <el-tag>{{ t('未提现佣金') }}: {{ unwithdrawn }}</el-tag>
         <el-tag>{{ t('已提现佣金') }}: {{ withdrawn }}</el-tag>
         <el-tag>{{ t('佣金总额') }}: {{ total }}</el-tag>
         <el-tag>{{ t('抽成佣金') }}: {{ take }}</el-tag>
      </div>

  

      <!-- 添加或修改定时任务对话框 -->
      <el-dialog :title="title" align-center v-model="open" width="820px" append-to-body>
         <el-form ref="agentRef" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="商户账号" prop="account">
               <el-input v-model="form.account" placeholder="请输入商户账号" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
               <el-input v-model="form.password" auto-complete="off" type="password" placeholder="请输入商户账号" />
            </el-form-item>
            <el-form-item label="商户模式" prop="tenantType">
               <el-radio-group v-model="form.tenantType">
                  <el-radio-button v-for="item in ff_tenant_type" :key="item.value" :value="item.value">{{ item.label }}</el-radio-button>
               </el-radio-group>
            </el-form-item>
            <el-form-item label="买分比例" prop="scoreRatio">
               <el-input-number v-model="form.scoreRatio" :precision="1" :min="0.9" :step="0.1" :max="2"></el-input-number>
               &nbsp;
               (万法定货币=1万通用额度)
            </el-form-item>
            <div class="label-scoreRatio">
               <span>平台比例</span>
               <div> 
                  <el-button type="danger" @click="queryCode('del')" :disabled="!form.tenantAgentPlatforms.length">-0.5</el-button>
                  <el-button type="primary" @click="queryCode('add')" :disabled="!form.tenantAgentPlatforms.length">+0.5</el-button>
               </div>
            </div>
            <el-table :data="form.tenantAgentPlatforms" class="scoreRatioTable">
               <el-table-column label="平台" align="center" prop="platformCode" />
               <el-table-column label="币种" align="center" prop="currencyCode" />
               <el-table-column label="成本比例（%）" align="center" prop="cost">
                  <template #default="scope">
                     {{ scope.row.cost }}%
                  </template>
               </el-table-column>
               <el-table-column label="商户通用比例（%）" align="center" prop="useCost">
                  <template #default="scope">
                     {{ scope.row.useCost }}%
                  </template>
               </el-table-column>
            </el-table>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm" :loading="loadingButton">{{ t('确 定') }}</el-button>
               <el-button @click="cancel">{{ t('取 消') }}</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup name="Commission">
import { listCommission,getCommissionInfo,updateAgentCommission } from "@/api/commission";
import { superAgentCommissionList,superAgentCommissionSum } from "@/api/super/commissionList";
 import TableSearchDate from '@/components/TableSearchDate'
import Crontab from '@/components/Crontab'
import { parseTime } from '@/utils/ruoyi'; // 时间格式化
import { onMounted } from "vue";
const router = useRouter();
const { proxy } = getCurrentInstance();
const { ff_tenant_type, ff_tenant_status,ff_tenant_agent_approval_status,ff_tenant_agent_commission_type } = proxy.useDict("ff_tenant_type", "ff_tenant_status","ff_tenant_agent_approval_status","ff_tenant_agent_commission_type");

const loadingButton = ref(false);
const commissionList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const title = ref("");
const openView = ref(false);
const openCron = ref(false);
const expression = ref("");
const tenantAgentPlatforms = ref([]);


const unwithdrawn = ref(0);
const withdrawn = ref(0);
const total = ref(0);
const invite = ref(0);
const take = ref(0);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderByColumn:'createTime',
    isAsc:'desc',
    tenantKey: "",
    agentName:'',
  },
  rules: {
      account: [{ required: true, message: proxy.t('商户账号不能为空'), trigger: "blur" }],
      password: [{ required: true, message: proxy.t('密码不能为空'), trigger: "blur" }],
      scoreRatio: [{ required: true, message: proxy.t('买分比例不能为空'), trigger: "blur" }],
      tenantType: [{ required: true, message: proxy.t('商户模式不能为空'), trigger: "change" }],
  }
});

const { queryParams, form, rules } = toRefs(data);
const dateRange = ref([]),operateTimeType = ref("day");
/** 查询列表 */
function getList() {
  loading.value = true;
  
  superAgentCommissionList(proxy.addDateRange(queryParams.value, dateRange.value)).then(response => {
    commissionList.value = response.data.rows;;
    total.value = response.data.total;
    unwithdrawn.value = response.unwithdrawn;
    withdrawn.value = response.withdrawn;
    invite.value = response.invite;
    take.value = response.take;
    loading.value = false;
  });
}

const superAgentCommissionSums = () => {
  loading.value = true;
  superAgentCommissionSum({}).then(response => {
    unwithdrawn.value = response.data.unwithdrawn;
    withdrawn.value = response.data.withdrawn;
    invite.value = response.data.invite;
    take.value = response.data.take;
   loading.value = false;
  })
 }

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    account: "",
    password: "",
    scoreRatio: 1,
    tenantType: 1,
    tenantAgentPlatforms: [],
  };
  proxy.resetForm("agentRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 新增按钮操作 */
function handleApply() {
   proxy.$modal.confirm(proxy.t('提现, 是否继续?')).then(() => {
      loading.value = true;
      updateAgentCommission({}).then(res => {
         loading.value = false;
         proxy.$modal.msgSuccess(proxy.t('提现成功！'));
         handleQuery();
      }).catch(() => {
         loading.value = false;
      });
   }).catch(() => { });
}
const searchDateRef = ref(null);
/** 重置按钮操作 */
function resetQuery() {
   dateRange.value = [];
  operateTimeType.value = "day";
   proxy.resetForm("queryRef");
   searchDateRef.value.timeTypeChange(operateTimeType.value)
}
function queryCode(type) {
   form.value.tenantAgentPlatforms = form.value.tenantAgentPlatforms.map((item, index) => {
      if (type === 'del' && item.cost > tenantAgentPlatforms.value[index].cost) {
         item.cost -= 0.5;
         item.useCost -= 0.5
      } else if (type === 'add') {
         item.cost += 0.5;
         item.useCost += 0.5
      }
      return item
   })
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["agentRef"].validate(valid => {
    if (valid) {
      loadingButton.value = true;
        createAgent(form.value).then(response => {
         loadingButton.value = false;
          proxy.$modal.msgSuccess(proxy.t('新增成功'));
          open.value = false;
          getList();
        });
      
    }
  });
}

//初始化
onMounted(() => { 
   getList();
});
// superAgentCommissionSums();
</script>

<style scoped lang="scss">
 .label-scoreRatio{
   width: 100%;
   display: flex;
   justify-content: space-between;
   align-items: center;
   margin-bottom: 10px;
   span{
      width: 120px;
      text-align: right;
      font-weight: 700;
      padding-right: 12px;
   }
 }
 .scoreRatioTable{
   width: calc(100% - 120px);
   margin-left: 120px;
 }
 .flooter {
   .el-tag{
      margin: 8px;
   }
 }
</style>
