<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="filter-container" shadow="never">
      <div class="filter-item">
        <el-form :inline="true" :model="listQuery" size="small">
          <el-form-item label="审核状态">
            <el-select v-model="listQuery.status" placeholder="请选择审核状态" clearable>
              <el-option v-for="item in statusOptions" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-container" shadow="never">
      <div class="table-header">
        <span class="table-title">分销商申请列表</span>
        <div class="table-operations">
          <el-button v-if="hasWaitingApproval" type="primary" size="mini" @click="handlePassAll">
            一键通过
          </el-button>
        </div>
      </div>

      <el-table v-loading="listLoading" :data="list" border style="width: 100%"
        :header-cell-style="{ background: '#F5F7FA', color: '#606266' }">
        <el-table-column prop="userName" label="申请人" align="center"></el-table-column>
        <el-table-column prop="createTime" label="申请时间" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime | formatDate }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="auditTime" label="审核时间" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.auditTime | formatDate }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="审核状态" align="center">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="refuseReason" label="拒绝理由" align="center" width="200">
          <template slot-scope="scope">
            <span v-if="scope.row.status === -1">{{ scope.row.refuseReason }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template slot-scope="scope">
            <el-button v-if="scope.row.status === 0" size="mini" type="success"
              @click="handleApprove(scope.row)">通过</el-button>
            <el-button v-if="scope.row.status === 0" size="mini" type="danger"
              @click="handleReject(scope.row)">拒绝</el-button>
            <el-button v-else size="mini" type="primary" @click="handleDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page.sync="listQuery.pageNumber" :page-sizes="[10, 20, 30, 50]" :page-size="listQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 拒绝原因对话框 -->
    <el-dialog title="拒绝申请" :visible.sync="rejectDialogVisible" width="30%">
      <el-form :model="rejectForm" :rules="rejectRules" ref="rejectForm" label-width="100px">
        <el-form-item label="拒绝理由" prop="reason">
          <el-input type="textarea" :rows="4" placeholder="请输入拒绝理由" v-model="rejectForm.reason">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rejectDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmReject">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog title="申请详情" :visible.sync="detailDialogVisible" width="50%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="申请人">{{ detailData.userName }}</el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ detailData.createTime | formatDate }}</el-descriptions-item>
        <el-descriptions-item label="审核时间">{{ detailData.auditTime | formatDate }}</el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <el-tag :type="getStatusType(detailData.status)">
            {{ getStatusText(detailData.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="拒绝理由" v-if="detailData.status === -1" :span="2">
          {{ detailData.refuseReason }}
        </el-descriptions-item>
      </el-descriptions>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mer_admin } from '@/api/modules/mer_admin';
import { mapState } from 'vuex';

export default {
  name: 'DistributorApplyList',
  data() {
    return {
      brandId: '',
      isBrand: false,
      listLoading: false,
      list: [],
      total: 0,
      listQuery: {
        pageNumber: 1,
        pageSize: 10,
        status: null
      },
      statusOptions: [
        { label: '待审核', value: 0 },
        { label: '已通过', value: 1 },
        { label: '已拒绝', value: -1 }
      ],
      rejectDialogVisible: false,
      detailDialogVisible: false,
      currentRow: null,
      rejectForm: {
        id: null,
        reason: ''
      },
      rejectRules: {
        reason: [
          { required: true, message: '请输入拒绝理由', trigger: 'blur' },
          { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
        ]
      },
      detailData: {}
    };
  },
  computed: {
    ...mapState("userData", [
      "isMerchant",
      "marketList",
      "storeList",
      "marketId",
      "shopId",
    ]),
    // 判断是否有待审核的申请
    hasWaitingApproval() {
      return this.list.some(item => item.status === 0);
    }
  },
  created() {
    if (
      JSON.parse(sessionStorage.getItem("userInfo")).role ===
      "ROLE_BRAND_MANAGER"
    ) {
      this.brandId = JSON.parse(
        sessionStorage.getItem("userInfo")
      ).brandId;
      this.isBrand = true;
    } else {
      this.brandId = JSON.parse(
        sessionStorage.getItem("userInfo")
      ).agentId;
      this.isBrand = false;
    }
    this.getList();
  },
  methods: {
    getList() {
      this.listLoading = true;
      const params = {
        pageNumber: this.listQuery.pageNumber,
        pageSize: this.listQuery.pageSize
      };
      
      if (this.listQuery.status !== null && this.listQuery.status !== '') {
        params.status = this.listQuery.status;
      }
      
      // 判断当前是品牌、市场还是店铺，添加相应参数
      if (this.isBrand) {
        // 如果是品牌管理员
        params.brandId = this.brandId;
      } else if (this.isMerchant) {
        // 如果是商户
        if (this.shopId) {
          // 如果是店铺
          params.marketId = this.marketId;
          params.shopId = this.shopId;
        } else if (this.marketId) {
          // 如果是市场
          params.marketId = this.marketId;
        }
      }
      
      mer_admin.getApplyRecord(params)
        .then(response => {
          console.log(response);
          this.list = response.data.data.data || [];
          this.total = response.data.data.total || 0;
          this.listLoading = false;
        })
        .catch(() => {
          this.listLoading = false;
        });
    },
    handleFilter() {
      this.listQuery.pageNumber = 1;
      this.getList();
    },
    resetQuery() {
      this.listQuery = {
        pageNumber: 1,
        pageSize: 10,
        status: null
      };
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.pageNumber = val;
      this.getList();
    },
    getStatusType(status) {
      switch (parseInt(status)) {
        case 0:
          return 'warning';
        case 1:
          return 'success';
        case -1:
          return 'danger';
        default:
          return 'info';
      }
    },
    getStatusText(status) {
      switch (parseInt(status)) {
        case 0:
          return '待审核';
        case 1:
          return '已通过';
        case -1:
          return '已拒绝';
        default:
          return '未知状态';
      }
    },
    handleApprove(row) {
      this.$confirm('确定通过该分销商申请?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        const params = {
          id: row.id,
          distributorId: row.distributorId,
          status: 1 // 通过
        };
        
        // 调用审核接口
        mer_admin.auditApplyRecord(params)
          .then(() => {
            this.$message({
              type: 'success',
              message: '审核通过成功!'
            });
            this.getList();
          })
          .catch(() => {
            this.listLoading = false;
          });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });          
      });
    },
    handleReject(row) {
      this.currentRow = row;
      this.rejectForm.id = row.id;
      this.rejectForm.reason = '';
      this.rejectDialogVisible = true;
    },
    confirmReject() {
      this.$refs.rejectForm.validate((valid) => {
        if (valid) {
          this.listLoading = true;
          const params = {
            id: this.rejectForm.id,
            distributorId: this.currentRow.distributorId,
            status: -1, // 拒绝
            refuseReason: this.rejectForm.reason
          };
          
          // 调用审核接口
          mer_admin.auditApplyRecord(params)
            .then(() => {
              this.$message({
                type: 'success',
                message: '已拒绝该申请'
              });
              this.rejectDialogVisible = false;
              this.getList();
            })
            .catch(() => {
              this.listLoading = false;
            });
        }
      });
    },
    // 添加一键通过功能
    handlePassAll() {
      this.$confirm('确定要一键通过所有待审核的分销商申请?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true,
        message: '<strong>一键通过操作将批量审核所有待审核申请，此操作不可撤销，请谨慎操作！</strong>'
      }).then(() => {
        this.listLoading = true;
        const params = {};
        
        // 添加品牌或市场店铺参数
        if (this.isBrand) {
          params.brandId = this.brandId;
        } else if (this.isMerchant) {
          if (this.shopId) {
            params.marketId = this.marketId;
            params.shopId = this.shopId;
          } else if (this.marketId) {
            params.marketId = this.marketId;
          }
        }
        
        // 调用一键通过接口
        mer_admin.passAllApplyRecord(params)
          .then(response => {
            this.$message({
              type: 'success',
              message: `成功通过 ${response.data || 0} 条申请记录!`
            });
            this.getList();
          })
          .catch(() => {
            this.listLoading = false;
          });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    },
    handleDetail(row) {
      this.detailData = {...row};
      this.detailDialogVisible = true;
    }
  },
  filters: {
    formatDate(time) {
      if (!time) return '';
      return new Date(time).toLocaleString();
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.table-container {
  margin-bottom: 20px;
}

.table-header {
  padding: 0 0 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  font-size: 16px;
  font-weight: bold;
}

.table-operations {
  display: flex;
  gap: 10px;
}

.pagination-container {
  padding: 15px 0;
  display: flex;
  justify-content: flex-end;
}
</style>