<template>
  <div class="app-container">
    <!-- 页面标题栏 -->


    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="面值" prop="priceRange">
        <el-input-number
          v-model="queryParams.priceMin"
          placeholder="最低面值"
          style="width: 130px; margin-right: 10px;"
          :min="0"
          :step="1"
          controls-position="right"
        />
        <span style="margin: 0 8px; color: #909399; font-weight: 500;">至</span>
        <el-input-number
          v-model="queryParams.priceMax"
          placeholder="最高面值"
          style="width: 130px;"
          :min="0"
          :step="1"
          controls-position="right"
        />
      </el-form-item>

      <el-form-item label="最低消费" prop="minPriceRange">
        <el-input-number
          v-model="queryParams.minPriceMin"
          placeholder="最低消费"
          style="width: 130px; margin-right: 10px;"
          :min="0"
          :step="1"
          controls-position="right"
        />
        <span style="margin: 0 8px; color: #909399; font-weight: 500;">至</span>
        <el-input-number
          v-model="queryParams.minPriceMax"
          placeholder="最高消费"
          style="width: 130px;"
          :min="0"
          :step="1"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item label="数量" prop="countRange">
        <el-input-number
          v-model="queryParams.countMin"
          placeholder="最少数量"
          style="width: 130px; margin-right: 10px;"
          :min="0"
          :step="1"
          clearable
          controls-position="right"
        />
        <span style="margin: 0 8px; color: #909399; font-weight: 500;">至</span>
        <el-input-number
          v-model="queryParams.countMax"
          placeholder="最多数量"
          style="width: 130px;"
          :min="0"
          :step="1"
          controls-position="right"
        />
      </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.coupons_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否无限领取" prop="isPermanent" label-width="auto">
        <el-select v-model="queryParams.isPermanent" placeholder="请选择是否无限领取" clearable>
          <el-option label="是" :value="1" />
          <el-option label="否" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="指定商品" prop="productId">
        <el-select
          v-model="queryParams.productId"
          placeholder="请选择指定商品"
          clearable
          filterable
        >
          <el-option
            v-for="item in serviceGoodsList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="指定分类" prop="cateId">
        <el-select
          v-model="queryParams.cateId"
          placeholder="请选择指定分类"
          clearable
          filterable
        >
          <el-option
            v-for="item in typeDataList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="正常" :value="1" />
          <el-option label="关闭" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          style="background: linear-gradient(135deg, #409eff 0%, #36a3f7 100%); border: none;"
        >搜索</el-button>
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
          style="margin-left: 10px;"
        >重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:Coupons:add']"
          style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border: none;"
        >新增优惠券</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:Coupons:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:Coupons:remove']"
        >删除</el-button>
      </el-col>


      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="CouponsList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" width="55"  prop="id" />
      <el-table-column label="名称" align="center" prop="title" />

      <el-table-column label="面值" width="120px" align="center"  prop="price" >
        <template slot-scope="scope">
          <div class="money-display">
            <span class="money-symbol">￥</span>
            <span class="money-amount-primary">{{scope.row.price ? scope.row.price.toFixed(2) : '0.00'}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="最低消费" width="120px" align="center"  prop="price" >
        <template slot-scope="scope">
          <div class="money-display">
            <span class="money-symbol">￥</span>
            <span class="money-amount-warning">{{scope.row.minPrice ? scope.row.minPrice.toFixed(2) : '0.00'}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="数量" align="center" prop="count">
        <template slot-scope="scope">
          <span class="count-display">{{scope.row.count}}</span>
        </template>
      </el-table-column>
      <el-table-column label="有效期" align="center" prop="couponTime">
        <template slot-scope="scope">
          <div class="validity-display">
            <i class="el-icon-time"></i>
            <span>{{scope.row.couponTime}}天</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="发送方式" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.coupons_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort">
        <template slot-scope="scope">
          <span class="sort-display">{{scope.row.sort}}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态"  width="85"  align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
            class="status-switch"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="领取记录" align="center" prop="num">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="showRecordDialog(scope.row)"
            class="record-button"
          >
            <i class="el-icon-document"></i>
            {{ scope.row.lqjv}}条记录
          </el-button>
        </template>
      </el-table-column>


      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template slot-scope="scope">
          <span>{{ formatDate(scope.row.createdAt) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updatedAt" width="180">
        <template slot-scope="scope">
          <span>{{ formatDate(scope.row.updatedAt) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:Coupons:edit']"
            class="edit-button"
            title="修改"
          ></el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:Coupons:remove']"
            class="delete-button"
            title="删除"
          ></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"
      style="margin-top: 20px;"
    />

    <!-- 添加或修改优惠券抽屉 -->
    <el-drawer
      :title="title"
      :visible.sync="open"
      size="50%"
      :before-close="handleClose"
      direction="rtl"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- 类型选择 -->
        <el-form-item label="类型" prop="receiveType">
          <el-radio-group v-model="form.receiveType">
            <el-radio :label="1">通用券</el-radio>
            <el-radio :label="2">品类券</el-radio>
            <el-radio :label="3">商品券</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 发送方式 -->
        <el-form-item label="发送方式" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio :label="1">新人券</el-radio>
            <el-radio :label="2">手动领取</el-radio>
            <el-radio :label="3">手动赠送</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 名称 -->
        <el-form-item label="名称" prop="title">
          <el-input v-model="form.title" placeholder="朋友券" />
        </el-form-item>

        <!-- 面值 -->
        <el-form-item label="面值" prop="price">
          <div style="display: flex; align-items: center;">
            <el-input-number
              v-model="form.price"
              :min="0"
              :precision="2"
              :step="1"
              controls-position="right"
              style="width: 200px;"
              placeholder="请输入面值"
            />
            <span style="margin-left: 8px; color: #606266; font-size: 14px;">元</span>
          </div>
        </el-form-item>

        <!-- 最低消费 -->
        <el-form-item label="最低消费" prop="minPrice">
          <div style="display: flex; align-items: center;">
            <el-input-number
              v-model="form.minPrice"
              :min="0"
              :precision="2"
              :step="1"
              controls-position="right"
              style="width: 200px;"
              placeholder="请输入最低消费"
            />
            <span style="margin-left: 8px; color: #606266; font-size: 14px;">元</span>
          </div>
        </el-form-item>

        <!-- 领取时间 -->
        <el-form-item label="领取时间">
          <el-col :span="11">
            <el-date-picker
              v-model="form.startTime"
              type="datetime"
              placeholder="选择开始时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              style="width: 100%;"
            />
          </el-col>
          <el-col class="line" :span="2" style="text-align: center;">-</el-col>
          <el-col :span="11">
            <el-date-picker
              v-model="form.endTime"
              type="datetime"
              placeholder="选择结束时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              style="width: 100%;"
            />
          </el-col>
        </el-form-item>

        <!-- 是否无限领取 -->
        <el-form-item label="是否无限领取" prop="isPermanent">
          <el-radio-group v-model="form.isPermanent">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 数量 -->
        <el-form-item label="数量" prop="count">
          <div style="display: flex; align-items: center;">
            <el-input-number
              v-model="form.count"
              :min="0"
              :step="1"
              controls-position="right"
              style="width: 200px;"
              placeholder="请输入数量"
            />
<!--            <span style="margin-left: 8px; color: #909399; font-size: 12px;">领取后至少30天有效</span>-->
          </div>
        </el-form-item>

        <!-- 有效期 -->
        <el-form-item label="有效期" prop="couponTime">
          <div style="display: flex; align-items: center;">
            <el-input-number
              v-model="form.couponTime"
              :min="0"
              :step="1"
              controls-position="right"
              style="width: 200px;"
              placeholder="请输入有效期"
            />
            <span style="margin-left: 8px; color: #606266; font-size: 14px;">天</span>
          </div>
        </el-form-item>

        <!-- 排序 -->
        <el-form-item label="排序" prop="sort">
          <div style="display: flex; align-items: center;">
            <el-input-number
              v-model="form.sort"
              :min="0"
              :step="1"
              controls-position="right"
              style="width: 200px;"
              placeholder="请输入排序"
            />
            <span style="margin-left: 8px; color: #909399; font-size: 12px;">数字越小排序越靠前</span>
          </div>
        </el-form-item>

        <!-- 状态 -->
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </el-form-item>

        <!-- 指定商品 (仅当类型为商品券时显示) -->
        <el-form-item label="指定商品" prop="productId" v-if="form.receiveType === 3">
          <el-select
            v-model="form.productId"
            placeholder="请选择指定商品"
            clearable
            filterable
            style="width: 100%;"
          >
            <el-option
              v-for="item in serviceGoodsList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
              </el-select>
        </el-form-item>

        <!-- 指定分类 (仅当类型为品类券时显示) -->
        <el-form-item label="指定分类" prop="cateId" v-if="form.receiveType === 2">
          <el-select
            v-model="form.cateId"
            placeholder="请选择指定分类"
            clearable
            filterable
            style="width: 100%;"
          >
            <el-option
              v-for="item in typeDataList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
              </el-select>
        </el-form-item>

        <!-- 选择用户 (仅当发送方式为手动赠送时显示) -->
        <el-form-item label="选择用户" prop="selectedUsers" v-if="form.type === 3">
          <el-button
            type="primary"
            icon="el-icon-user"
            @click="showUserDialog"
            style="width: 100%; margin-bottom: 10px;"
          >
            {{ selectedUsers.length > 0 ? `已选择 ${selectedUsers.length} 个用户` : '选择赠送用户' }}
          </el-button>
          <div v-if="selectedUsers.length > 0" class="selected-users-container">
            <el-tag
              v-for="user in selectedUsers"
              :key="user.userId"
              closable
              type="info"
              class="user-tag"
              @close="removeUser(user)"
            >
              <span class="user-tag-content">
                <span class="user-name">{{ user.name || '未命名用户' }}</span>
                <span class="user-phone">{{ user.phone || '无手机号' }}</span>
              </span>
            </el-tag>
          </div>
        </el-form-item>
      </el-form>
      <div  class="dialog-footer">
        <el-button @click="resetForm('form')">重 置</el-button>
        <el-button type="primary" @click="submitForm">{{ form.id ? '保 存' : '确认创建' }}</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-drawer>

    <!-- 领取记录弹窗 -->
    <el-dialog title="优惠券领取记录" :visible.sync="recordDialogVisible" width="70%" append-to-body>
      <el-table :data="recordList" border>
        <el-table-column label="用户" prop="uname" align="center" />
        <el-table-column label="面值" prop="couponPrice" align="center" />
        <el-table-column label="最低消费" prop="minPrice" align="center" />
        <el-table-column label="领取时间" align="center" prop="addTime">
        <template slot-scope="scope">
            <span>{{ formatDate(scope.row.addTime) }}</span>
        </template>
      </el-table-column>
        <el-table-column label="失效时间" align="center" prop="loseTime">
        <template slot-scope="scope">
            <span>{{ formatDate(scope.row.loseTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="使用时间" align="center" prop="useTime">
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.useTime) }}</span>
        </template>
      </el-table-column>
        <el-table-column label="指定分类" prop="catename" align="center" />
        <el-table-column label="指定商品" prop="productname" align="center" />
        <el-table-column label="类型" align="center" prop="receiveType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.coupons_user_type" :value="scope.row.receiveType"/>
        </template>
      </el-table-column>
        <el-table-column label="状态" prop="status" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status === 1" type="warning">未使用</el-tag>
            <el-tag type="success" v-else-if="scope.row.status === 2">已使用</el-tag>

          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 用户选择对话框 -->
    <el-dialog
      title="用户列表"
      :visible.sync="userDialogVisible"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
      destroy-on-close
    >
      <div class="user-dialog-container">
        <!-- 搜索框 -->
        <div class="search-box">
          <el-input
            v-model="userSearchKeyword"
            placeholder="请输入用户名称搜索"
            clearable
            prefix-icon="el-icon-search"
            style="width: 300px;"
            @keyup.enter.native="handleUserSearch"
            @clear="handleUserSearch"
          >
            <el-button slot="append" icon="el-icon-search" @click="handleUserSearch">搜索</el-button>
          </el-input>
        </div>

        <!-- 用户表格 -->
        <el-table
          ref="userTable"
          :data="filteredUserList"
          @select="handleUserSelectionChange"
           @select-all="handleUserSelectionChange"

          height="400"
          border
          v-loading="userTableLoading"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="用户ID" prop="id" width="80" align="center" />
          <el-table-column label="用户名称" prop="name" align="center" />
          <el-table-column label="手机号" prop="phone" align="center" />
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            @size-change="handleUserSizeChange"
            @current-change="handleUserCurrentChange"
            :current-page.sync="userTableParams.pageNum"
            :page-sizes="[10, 20, 30, 50]"
            :page-size.sync="userTableParams.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalUsers"
          />
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="userDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmUserSelection">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCoupons, getCoupons, delCoupons, addCoupons, updateCoupons, changetypeStatus, getTypeList,getUserDataList,getGoodsDataList,getUserListByCoupon} from "@/api/system/Coupons"
import { getUserProfile } from "@/api/system/user"

export default {
  name: "Coupons",
  dicts: ['coupons_type','coupons_user_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      userDataList:[],
      typeDataList: [],
      // 优惠券表格数据
      CouponsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        priceMin: undefined,
        priceMax: undefined,
        minPriceMin: undefined,
        minPriceMax: undefined,
        countMin: undefined,
        countMax: undefined,
        isPermanent: undefined,
        status: undefined,
        productId: undefined,
        type: undefined,
        cateId: undefined,
        sort: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "面值不能为空", trigger: "blur" }
        ],
        minPrice: [
          { required: true, message: "最低消费不能为空", trigger: "blur" }
        ],
        isPermanent: [
          { required: true, message: "是否无限领取不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
        couponTime: [
          { required: true, message: "有效期不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "发送方式不能为空", trigger: "change" }
        ],
        receiveType: [
          { required: true, message: "类型不能为空", trigger: "change" }
        ],
        sort: [
          { required: true, message: "排序不能为空", trigger: "blur" }
        ],
        count: [
          { required: true, message: "数量不能为空", trigger: "blur" }
        ],
      },

      // 领取记录弹窗显示状态
      recordDialogVisible: false,
      // 领取记录列表
      recordList: [],
      serviceGoodsList: [],


      // 用户选择对话框相关
      userDialogVisible: false,
      userSearchKeyword: '',
      filteredUserList: [],
      selectedUsers: [],
      tempSelectedUsers: [],
      userTableParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined
      },
      totalUsers: 0,
      userTableLoading: false,
    }
  },
  created() {
    this.getList()
    this.getGoodsDataList()
    this.getTypeList()
  },





  methods: {

    /** 查询优惠券列表 */
    getList() {
      this.loading = true;
      // 创建新的对象，避免引用传递
      const params = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize
      };

      // 只传递有值的参数
      Object.keys(this.queryParams).forEach(key => {
        if (this.queryParams[key] !== undefined &&
            this.queryParams[key] !== null &&
            this.queryParams[key] !== '' &&
            !['pageNum', 'pageSize'].includes(key)) {
          if (['priceMin', 'priceMax', 'minPriceMin', 'minPriceMax', 'countMin', 'countMax'].includes(key)) {
            params[key] = Number(this.queryParams[key]);
          } else {
            params[key] = this.queryParams[key];
          }
        }
      });

      listCoupons(params).then(response => {
        if (response.code === 200) {
          this.CouponsList = response.rows || [];
          this.total = parseInt(response.total) || 0;
        } else {
          this.CouponsList = [];
          this.total = 0;
          this.$message.error(response.msg || '获取数据失败');
        }
        this.loading = false;
      }).catch(error => {
        console.error('获取优惠券列表失败:', error);
        this.CouponsList = [];
        this.total = 0;
        this.loading = false;
        this.$message.error('获取数据失败');
      });
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        price: null,
        minPrice: null,
        startTime: null,
        endTime: null,
        count: null,
        isPermanent: 1,
        status: 1,
        couponTime: null,
        productId: null,
        type: 1,
        receiveType: 1,
        sort: 1,
        cateId: null,
        userIds: '[]', // 初始化为空数组的JSON字符串
        createdAt: null,
        updatedAt: null,
        deletedAt: null
      }
      this.selectedUsers = []
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // 重置后需要将分页参数也重置
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.getList();
    },
    getDataUserListByCoupon(id){
      getUserListByCoupon(id).then(response => {
        this.selectedUsers = response.data;
        this.tempSelectedUsers=JSON.parse(JSON.stringify(response.data)) ;
      })

    },
    // 任务状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用"
      this.$modal.confirm('确认要"' + text + '""' + row.title + '"状态吗？').then(function() {
        return changetypeStatus(row.id, row.status)
      }).then(() => {
        this.$modal.msgSuccess(text + "成功")
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0"
      })
    },

    // 多选框选中数据
    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;
      //this.getDataUserListByCoupon(id);
      getCoupons(id).then(response => {
        this.form = response.data;
        // 处理日期字段
        if (this.form.startTime) {
          this.form.startTime = this.parseTime(this.form.startTime, '{y}-{m}-{d} {h}:{i}:{s}');
        }
        if (this.form.endTime) {
          this.form.endTime = this.parseTime(this.form.endTime, '{y}-{m}-{d} {h}:{i}:{s}');
        }

        // 处理userIds
        // if (this.form.userIds) {
        //   let userIdArray = [];
        //   try {
        //     // 尝试解析JSON字符串
        //     if (typeof this.form.userIds === 'string') {
        //       userIdArray = JSON.parse(this.form.userIds);
        //     } else if (Array.isArray(this.form.userIds)) {
        //       userIdArray = this.form.userIds;
        //     }
        //   } catch (e) {
        //     // 如果解析失败，尝试按逗号分隔
        //     userIdArray = this.form.userIds.split(',');
        //   }

        //   // 确保所有ID都是数字
        //   userIdArray = userIdArray.map(id => parseInt(id)).filter(id => !isNaN(id));

          // 获取用户列表并初始化选中用户
          // getUserDataList().then(res => {
          //   const userList = res.data || [];
          //   this.selectedUsers = userList.filter(user => userIdArray.includes(user.id))
          //     .map(user => ({
          //       id: user.id,
          //       name: user.name || '未命名用户',
          //       phone: user.phone || '无手机号'
          //     }));
          //   // 更新form中的userIds为标准格式
          //   this.form.userIds = JSON.stringify(this.selectedUsers.map(user => user.id));
          // });
        // }

        this.open = true;
        this.title = "修改优惠券";
      });
    },

    getTypeList() {
      getTypeList().then(response => {
        this.typeDataList = response.data
      })
    },
    getGoodsDataList() {
      getGoodsDataList(2).then(response => {
        this.serviceGoodsList = response.data
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const submitData = { ...this.form };

          // 处理日期格式，转换为10位时间戳（秒）
          if (submitData.startTime) {
            submitData.startTime = typeof submitData.startTime === 'number' && submitData.startTime.toString().length === 10
              ? submitData.startTime
              : Math.floor(new Date(submitData.startTime).getTime() / 1000);
          }
          if (submitData.endTime) {
            submitData.endTime = typeof submitData.endTime === 'number' && submitData.endTime.toString().length === 10
              ? submitData.endTime
              : Math.floor(new Date(submitData.endTime).getTime() / 1000);
          }

          // 确保userIds是JSON字符串格式
          if (submitData.userIds && Array.isArray(this.selectedUsers)) {
            submitData.userIds = JSON.stringify(this.selectedUsers.map(user => String(user.userId)));
          }

          if (submitData.id != null) {
            updateCoupons(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCoupons(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除优惠券编号为"' + ids + '"的数据项？').then(function() {
        return delCoupons(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/Coupons/export', {
        ...this.queryParams
      }, `Coupons_${new Date().getTime()}.xlsx`)
    },
    /** 显示领取记录弹窗 */
    showRecordDialog(row) {
      this.recordDialogVisible = true;
      getCoupons(row.id).then(response => {
        this.recordList = response.data.couponUserList || [];
      });
    },

    // 用户选择相关
    showUserDialog() {
      this.tempSelectedUsers=JSON.parse(JSON.stringify(this.selectedUsers)) ;
      this.userDialogVisible = true;
      // this.tempSelectedUsers = [...this.selectedUsers];
      this.userSearchKeyword = '';
      this.userTableParams.pageNum = 1;

      this.getUserList();
    },

    handleUserSelectionChange(selection) {
      let newSelected=this.tempSelectedUsers.map(r=>r.userId);
      selection.map(r=>{
        if(!newSelected.includes(r.id)){
          this.tempSelectedUsers.push({
          userId: r.id,
          name: r.name ,
          phone: r.phone
         })
        }
      })
      let _ids=[];
      this.filteredUserList.map(r=>{
        if(!selection.map(r=>r.id).includes(r.id)){
          _ids.push(r.id);
        }
      })
      _ids.map(r=>{
        this.tempSelectedUsers.map((s,index)=>{
          if(s.userId==r){
            this.tempSelectedUsers.splice(index,1)
          }
        })
      })
    },

    getUserList() {


      this.userTableLoading = true;
      const params = {
        pageNum: this.userTableParams.pageNum,
        pageSize: this.userTableParams.pageSize,
        userName: this.userSearchKeyword
      };
      import('@/api/system/users').then(module => {
        module.listUsers(params).then(response => {
          if (response.code === 200) {
            this.filteredUserList = response.rows || [];
            this.totalUsers = parseInt(response.total) || 0;
            // 设置已选用户的选中状态
            this.$nextTick(() => {
              if (this.$refs.userTable) {
                console.log(this.tempSelectedUsers,66666)
                this.$refs.userTable.clearSelection();
                const selectedIds = (this.tempSelectedUsers || []).map(u => Number(u.userId));
                this.filteredUserList.forEach(row => {
                  if (selectedIds.includes(row.id)) {
                    this.$refs.userTable.toggleRowSelection(row, true);
                  }
                });
              }
            });
          } else {
            this.$message.error(response.msg || '获取用户列表失败');
          }
          this.userTableLoading = false;
        }).catch(error => {
          this.$message.error('获取用户列表失败');
          this.userTableLoading = false;
        });
      });
    },

    handleUserSearch() {
      this.userTableParams.pageNum = 1;
      this.getUserList();
    },

    handleUserSizeChange(val) {
      this.userTableParams.pageSize = val;
      this.getUserList();
    },

    handleUserCurrentChange(val) {
      this.userTableParams.pageNum = val;
      this.getUserList();
    },

    confirmUserSelection() {
      this.selectedUsers = [...this.tempSelectedUsers];
      this.form.userIds = JSON.stringify(this.selectedUsers.map(user => user.userId));
      this.userDialogVisible = false;
      console.log(this.form.userIds+"#############",this.selectedUsers)
    },

    removeUser(user) {

      this.selectedUsers = this.selectedUsers.filter(u => u.userId !== user.userId);

      this.form.userIds = JSON.stringify(this.selectedUsers.map(user => user.userId));
      if (this.$refs.userTable) {
        const row = this.filteredUserList.find(item => item.userId === user.userId);
        if (row) {
          this.$refs.userTable.toggleRowSelection(row, false);
        }
      }
    },

    /** 关闭抽屉前的回调 */
    handleClose(done) {

          this.reset();
          done();

    },

    /** 表格日期格式化 */
    formatDate(dateStr) {
      if (!dateStr) return '';
      return this.parseTime(dateStr, '{y}-{m}-{d} {h}:{i}:{s}');
    },
  }
}
</script>

<style>
/* 用户选择对话框样式 */
.user-dialog-container .search-box {
  margin-bottom: 15px;
}

.user-dialog-container .pagination-container {
  margin-top: 15px;
  text-align: right;
}

/* 已有的样式保持不变 */
.selected-users-container {
  margin-top: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  max-height: 120px;
  overflow-y: auto;
  padding: 8px;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  background: #FAFAFA;
}

.user-tag {
  display: inline-flex;
  align-items: center;
  margin: 2px;
  max-width: 100%;
  background-color: #f4f4f5;
  border-color: #e9e9eb;
  color: #909399;
  transition: all 0.3s;
}

.user-tag:hover {
  background-color: #ecf5ff;
  border-color: #d9ecff;
  color: #409eff;
}

.user-tag-content {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  max-width: 200px;
  overflow: hidden;
  padding: 0 4px;
}

.user-name {
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 100px;
}

.user-phone {
  color: #909399;
  font-size: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 90px;
}

/* 滚动条样式优化 */
.selected-users-container::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.selected-users-container::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 3px;
}

.selected-users-container::-webkit-scrollbar-track {
  background: #f5f7fa;
  border-radius: 3px;
}
</style>
