<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <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
          v-model="queryParams.priceMin"
          placeholder="最低面值"
          style="width: 100px; margin-right: 10px;"
          type="number"
          min="0"
          clearable
        />
        <span style="margin: 0 5px;">-</span>
        <el-input
          v-model="queryParams.priceMax"
          placeholder="最高面值"
          style="width: 100px;"
          type="number"
          min="0"
          clearable
        />
      </el-form-item>

      <el-form-item label="最低消费" prop="minPriceRange">
        <el-input
          v-model="queryParams.minPriceMin"
          placeholder="最低消费"
          style="width: 100px; margin-right: 10px;"
          type="number"
          min="0"
          clearable
        />
        <span style="margin: 0 5px;">-</span>
        <el-input
          v-model="queryParams.minPriceMax"
          placeholder="最高消费"
          style="width: 100px;"
          type="number"
          min="0"
          clearable
        />
      </el-form-item>
      <el-form-item label="数量" prop="countRange">
        <el-input
          v-model="queryParams.countMin"
          placeholder="最少"
          style="width: 100px; margin-right: 10px;"
          type="number"
          min="0"
          clearable
        />
        <span style="margin: 0 5px;">-</span>
        <el-input
          v-model="queryParams.countMax"
          placeholder="最多"
          style="width: 100px;"
          type="number"
          min="0"
          clearable
        />
      </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-input
          v-model="queryParams.cateId"
          placeholder="请输入指定分类ID"
          clearable
        />
      </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">搜索</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="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:Coupons:add']"
        >新增</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>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:Coupons:export']"
        >导出</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="left"  prop="price" >
        <template slot-scope="scope">
          <span >￥{{scope.row.price.toFixed(2)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="最低消费" width="120px" align="left"  prop="price" >
        <template slot-scope="scope">
          <span >￥{{scope.row.minPrice.toFixed(2)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="数量" align="center" prop="count" />
      <el-table-column label="有效期" align="center" prop="couponTime" />
      <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" />
      <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)"
          ></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)"
          >{{ scope.row.couponUserList ? scope.row.couponUserList.length : 0 }}条记录</el-button>
        </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="updatedAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</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']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:Coupons:remove']"
          >删除</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"
    />



    <!-- 添加或修改优惠券对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="jiluform" :model="jiluform" :rules="rules" label-width="80px">
        <el-table :data="couponUserList" :row-class-name="rowCouponUserIndex" @selection-change="handleCouponUserSelectionChange" ref="couponUser">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="用户" prop="uid" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.uid" placeholder="请输入用户" />
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="couponTitle" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.couponTitle" placeholder="请输入名称" />
            </template>
          </el-table-column>
          <el-table-column label="面值" prop="couponPrice" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.couponPrice" placeholder="请输入面值" />
            </template>
          </el-table-column>
          <el-table-column label="最低消费" prop="minPrice" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.minPrice" placeholder="请输入最低消费" />
            </template>
          </el-table-column>
          <el-table-column label="领取时间" prop="addTime" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.addTime" placeholder="请输入领取时间" />
            </template>
          </el-table-column>
          <el-table-column label="失效时间" prop="loseTime" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.loseTime" placeholder="请输入失效时间" />
            </template>
          </el-table-column>
          <el-table-column label="使用时间" prop="useTime" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.useTime" placeholder="请输入使用时间" />
            </template>
          </el-table-column>
          <el-table-column label="指定分类" prop="cateId" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.cateId" placeholder="请输入指定分类" />
            </template>
          </el-table-column>
          <el-table-column label="指定商品" prop="productId" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.productId" placeholder="请输入指定商品" />
            </template>
          </el-table-column>
          <el-table-column label="1:通用券 2：品类券 3：指定商品" prop="receiveType" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.receiveType" placeholder="请选择1:通用券 2：品类券 3：指定商品">
                <el-option label="请选择字典生成" value="" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="1：未使用 2：已使用 3:已失效" prop="status" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.status" placeholder="请选择1：未使用 2：已使用 3:已失效">
                <el-option label="请选择字典生成" value="" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="$comment" prop="createdAt" width="240">
            <template slot-scope="scope">
              <el-date-picker clearable v-model="scope.row.createdAt" type="date" value-format="yyyy-MM-dd" placeholder="请选择$comment" />
            </template>
          </el-table-column>
          <el-table-column label="$comment" prop="updatedAt" width="240">
            <template slot-scope="scope">
              <el-date-picker clearable v-model="scope.row.updatedAt" type="date" value-format="yyyy-MM-dd" placeholder="请选择$comment" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 领取记录弹窗 -->
    <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" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.addTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

        <el-table-column label="失效时间" prop="loseTime" align="center" />           
        <el-table-column label="使用时间" align="center" prop="useTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.useTime, '{y}-{m}-{d}') }}</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'">未使用</el-tag>
            <el-tag type="success" v-else-if="scope.row.status === '2'">已使用</el-tag>
            <el-tag type="info" v-else>已失效</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { listCoupons, getCoupons, delCoupons, addCoupons, updateCoupons,changetypeStatus } 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: [],
      // 子表选中数据
      checkedCouponUser: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 优惠券表格数据
      CouponsList: [],
      // 优惠券领取记录表格数据
      couponUserList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        priceMin: null,
        priceMax: null,
        minPriceMin: null,
        minPriceMax: null,
        countMin: null,
        countMax: null,
        isPermanent: null,
        status: null,
        productId: null,
        type: null,
        cateId: null,
        sort: null,
      },
      // 表单参数
      form: {},

      // 表单参数
      jiluform: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "面值不能为空", trigger: "blur" }
        ],
        minPrice: [
          { required: true, message: "最低消费不能为空", trigger: "blur" }
        ],
        isPermanent: [
          { required: true, message: "是否无限领取不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "1 正常 0 关闭不能为空", trigger: "change" }
        ],
        couponTime: [
          { required: true, message: "有效期不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "1：新人券 2：手动领取 3：系统赠送不能为空", trigger: "change" }
        ],
        sort: [
          { required: true, message: "排序不能为空", trigger: "blur" }
        ],
      },
      // 领取记录弹窗显示状态
      recordDialogVisible: false,
      // 领取记录列表
      recordList: [],
      serviceGoodsList: [],
    }
  },
  created() {
    this.getList()
    this.getServiceGoodsList()
  },
  methods: {
    getServiceGoodsList() {
      // 获取服务商品下拉数据
      this.$api ? this.$api.system.ServiceGoods.listServiceGoods({}).then(res => {
        this.serviceGoodsList = res.rows || []
      }) :
      import('@/api/system/ServiceGoods').then(module => {
        module.listServiceGoods({}).then(res => {
          this.serviceGoodsList = res.rows || []
        })
      })
    },
    /** 查询优惠券列表 */
    getList() {
      this.loading = true
      const params = { ...this.queryParams }
      if (params.priceMin !== null && params.priceMin !== '') params.priceMin = Number(params.priceMin)
      if (params.priceMax !== null && params.priceMax !== '') params.priceMax = Number(params.priceMax)
      if (params.minPriceMin !== null && params.minPriceMin !== '') params.minPriceMin = Number(params.minPriceMin)
      if (params.minPriceMax !== null && params.minPriceMax !== '') params.minPriceMax = Number(params.minPriceMax)
      if (params.countMin !== null && params.countMin !== '') params.countMin = Number(params.countMin)
      if (params.countMax !== null && params.countMax !== '') params.countMax = Number(params.countMax)
      listCoupons(params).then(response => {
        this.CouponsList = response.rows.map(item => {
          // 如果后端没有直接返回couponUserList，需要单独获取
          if (!item.couponUserList) {
            getCoupons(item.id).then(res => {
              item.couponUserList = res.data.couponUserList || [];
              this.$set(item, 'couponUserList', res.data.couponUserList || []);
            })
          }
          return item;
        });
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    reset1() {
      this.couponUserList = []
      this.resetForm("form")
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        price: null,
        minPrice: null,
        startTime: null,
        endTime: null,
        count: null,
        isPermanent: null,
        status: null,
        couponTime: null,
        productId: null,
        type: null,
        receiveType: null,
        sort: null,
        cateId: null,
        userIds: null,
        createdAt: null,
        updatedAt: null,
        deletedAt: null
      }
      this.couponUserList = []
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },

    // 任务状态修改
    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
      getCoupons(id).then(response => {
        this.form = response.data
        this.couponUserList = response.data.couponUserList
        this.open = true
        this.title = "修改优惠券"
      })
    },

    /** 修改按钮操作 */
    handjiluleUpdate(row) {
      this.reset1()
      const id = row.id || this.ids
      getCoupons(id).then(response => {
        this.couponUserList = response.data.couponUserList
        this.open = true
        this.title = "优惠券领取记录"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.couponUserList = this.couponUserList
          if (this.form.id != null) {
            updateCoupons(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addCoupons(this.form).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(() => {})
    },
    /** 优惠券领取记录序号 */
    rowCouponUserIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** 优惠券领取记录添加按钮操作 */
    handleAddCouponUser() {
      let obj = {}
      obj.uid = ""
      obj.couponTitle = ""
      obj.couponPrice = ""
      obj.minPrice = ""
      obj.addTime = ""
      obj.loseTime = ""
      obj.useTime = ""
      obj.cateId = ""
      obj.productId = ""
      obj.receiveType = ""
      obj.status = ""
      obj.createdAt = ""
      obj.updatedAt = ""
      this.couponUserList.push(obj)
    },
    /** 优惠券领取记录删除按钮操作 */
    handleDeleteCouponUser() {
      if (this.checkedCouponUser.length == 0) {
        this.$modal.msgError("请先选择要删除的优惠券领取记录数据")
      } else {
        const couponUserList = this.couponUserList
        const checkedCouponUser = this.checkedCouponUser
        this.couponUserList = couponUserList.filter(function(item) {
          return checkedCouponUser.indexOf(item.index) == -1
        })
      }
    },
    /** 复选框选中数据 */
    handleCouponUserSelectionChange(selection) {
      this.checkedCouponUser = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    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 || [];
      });
    },
  }
}
</script>
