<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="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.cika"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </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:UserSecondaryCard: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:UserSecondaryCard: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:UserSecondaryCard: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:UserSecondaryCard:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="UserSecondaryCardList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="80" />
      <el-table-column label="订单ID" align="center" prop="orderid" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.orderid || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="title" min-width="150">
        <template slot-scope="scope">
          <el-tooltip :content="scope.row.title || ''" placement="top" :disabled="!scope.row.title || scope.row.title.length <= 20">
            <span>{{ scope.row.title ? (scope.row.title.length > 20 ? scope.row.title.substr(0, 20) + '...' : scope.row.title) : '-' }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="简介" align="center" prop="title" min-width="150">
        <template slot-scope="scope">
          <el-tooltip :content="scope.row.introduction || ''" placement="top" :disabled="!scope.row.introduction || scope.row.title.length <= 50">
            <span>{{ scope.row.introduction ? (scope.row.introduction.length > 50 ? scope.row.introduction.substr(0, 50) + '...' : scope.row.introduction) : '-' }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="服务项目" align="center" prop="goodsname" min-width="150">
        <template slot-scope="scope">
          <el-tooltip :content="scope.row.goodsname || ''" placement="top" :disabled="!scope.row.goodsname || scope.row.goodsname.length <= 20">
            <span>{{ scope.row.goodsname ? (scope.row.goodsname.length > 20 ? scope.row.goodsname.substr(0, 20) + '...' : scope.row.goodsname) : '-' }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="展示价格" align="center" width="120">
        <template slot-scope="scope">
          <span class="price-text">¥ {{ scope.row.showMoney !== undefined && scope.row.showMoney !== null ? parseFloat(scope.row.showMoney).toFixed(2) : '0.00' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实付价格" align="center" width="120">
        <template slot-scope="scope">
          <span class="price-text price-highlight">¥ {{ scope.row.realMoney !== undefined && scope.row.realMoney !== null ? parseFloat(scope.row.realMoney).toFixed(2) : '0.00' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="展示图片" align="center" prop="showimage" width="120">
        <template slot-scope="scope">
          <div v-if="parseImageArray(scope.row.showimage).length" class="image-container">
            <div class="image-row">
              <image-preview
                v-for="(img, idx) in parseImageArray(scope.row.showimage)"
                :key="idx"
                :src="img"
                :width="60"
                :height="60"
                class="table-image"
                @error="handleImageError"
              />
            </div>
            <div class="image-count">{{ parseImageArray(scope.row.showimage).length }}张</div>
          </div>
          <span v-else class="no-image">-</span>
        </template>
      </el-table-column>
      <el-table-column label="轮播图" align="center" prop="carouselImage" width="300">
        <template slot-scope="scope">
          <div v-if="parseImageArray(scope.row.carouselImage).length" class="carousel-container">
            <div class="carousel-row">
              <image-preview
                v-for="(img, idx) in parseImageArray(scope.row.carouselImage)"
                :key="idx"
                :src="img"
                :width="45"
                :height="45"
                class="table-image"
                @error="handleImageError"
              />
            </div>
            <div class="image-count">{{ parseImageArray(scope.row.carouselImage).length }}张</div>
          </div>
          <span v-else class="no-image">-</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <dict-tag v-if="scope.row.status !== undefined && scope.row.status !== null" :options="dict.type.cika" :value="scope.row.status" class="status-tag"/>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="creattime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.creattime ? parseTime(scope.row.creattime, '{y}-{m}-{d}') : '-' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="分类" align="center" prop="typename" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.typename || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="可用/总数" align="center" width="120">
        <template slot-scope="scope">
          <el-tooltip content="可提供服务数/总服务数" placement="top">
            <span class="service-count">
              <span class="available-count">{{ scope.row.num !== undefined && scope.row.num !== null ? scope.row.num : 0 }}</span>
              <span class="count-separator">/</span>
              <span class="total-count">{{ scope.row.allnum !== undefined && scope.row.allnum !== null ? scope.row.allnum : 0 }}</span>
            </span>
          </el-tooltip>
        </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:UserSecondaryCard:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:UserSecondaryCard: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="45" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="简介" prop="introduction">
          <el-input v-model="form.introduction" placeholder="请输入简介" />
        </el-form-item>

        <el-form-item label="服务项目" prop="goodsids">
          <el-select
            v-model="form.goodsids"
            multiple
            filterable
            clearable
            placeholder="请选择服务项目"
            style="width: 100%"
            @change="onGoodsidsChange"
          >
            <el-option
              v-for="item in ServiceGoodsList"
              :key="item.id"
              :label="item.title"
              :value="String(item.id)"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="分类" prop="type">
          <el-select v-model="form.type" placeholder="请选择分类">
            <el-option v-for="cate in serviceCateList" :key="cate.id" :label="cate.title" :value="cate.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="展示价格" prop="showMoney">
          <el-input-number
            v-model="form.showMoney"
            :precision="2"
            :min="0"
            :step="0.01"
            placeholder="请输入展示价格"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="真实付款价格" prop="realMoney">
          <el-input-number
            v-model="form.realMoney"
            :precision="2"
            :min="0"
            :step="0.01"
            placeholder="请输入真实付款价格"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="主图" prop="showimage">
          <image-upload v-model="form.showimage" :multiple="false" />
        </el-form-item>
        <el-form-item label="轮播图" prop="carouselImage">
          <image-upload v-model="form.carouselImage" :multiple="true" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.cika"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="可提供服务数" prop="num">
          <el-input-number
            v-model="form.num"
            :min="1"
            :step="1"
            :precision="0"
            placeholder="请输入可提供服务数"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="总服务数" prop="allnum">
          <el-input-number
            v-model="form.allnum"
            :min="1"
            :step="1"
            :precision="0"
            placeholder="请输入总服务数"
            style="width: 100%"
          />
        </el-form-item>
      </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>
  </div>
</template>

<script>
import { listUserSecondaryCard, getUserSecondaryCard, delUserSecondaryCard, addUserSecondaryCard, updateUserSecondaryCard ,selectList,selectServiceCateList} from "@/api/system/UserSecondaryCard"
import { getGoodsDataList } from "@/api/system/GoodsOrder"
export default {
  name: "UserSecondaryCard",
  dicts: ['cika'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,


      serviceCateList: [],

      ServiceGoodsList: [],
      // 次卡管理表格数据
      UserSecondaryCardList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderid: null,
        title: null,
        goodsids: null,
        showMoney: null,
        realMoney: null,
        showimage: null,
        status: null,
        creattime: null,
        createdAt: null,
        updatedAt: null,
        type: null,
        num: null,
        allnum: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        introduction: [
          { required: true, message: '请输入简介', trigger: 'blur' }
        ],
        goodsids: [
          { required: true, message: '请选择服务项目', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ],
        showMoney: [
          { required: true, message: '请输入展示价格', trigger: 'blur' },
          { pattern: /^(0|[1-9]\d*)(\.\d{1,2})?$/, message: '请输入正确的金额（最多两位小数）', trigger: 'blur' }
        ],
        realMoney: [
          { required: true, message: '请输入真实付款价格', trigger: 'blur' },
          { pattern: /^(0|[1-9]\d*)(\.\d{1,2})?$/, message: '请输入正确的金额（最多两位小数）', trigger: 'blur' }
        ],
        showimage: [
          { required: true, message: '请上传展示图片', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        num: [
          { required: true, message: '请输入可提供服务数', trigger: 'blur' },
          { pattern: /^[1-9]\d*$/, message: '请输入正整数', trigger: 'blur' }
        ],
        allnum: [
          { required: true, message: '请输入总服务数', trigger: 'blur' },
          { pattern: /^[1-9]\d*$/, message: '请输入正整数', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getserviceCateList();
  },
  methods: {
    /** 查询次卡管理列表 */
    getList() {
      this.loading = true
      listUserSecondaryCard(this.queryParams).then(response => {
        this.UserSecondaryCardList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderid: null,
        title: null,
        goodsids: null,
        showMoney: null,
        realMoney: null,
        showimage: '',
        status: null,
        creattime: null,
        createdAt: null,
        updatedAt: null,
        introduction: null,
        type: null,
        num: null,
        allnum: null,
        carouselImage: []
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    getUserSecondaryCard () {
      getGoodsDataList(3).then(response => {
        this.ServiceGoodsList = response.data
      })
    },


    /** 新增按钮操作 */
    handleAdd() {
      this.getUserSecondaryCard();
      this.reset()
      this.open = true
      this.title = "添加次卡管理"
    },


    getserviceCateList(){
      selectServiceCateList(1).then(response => {
        this.serviceCateList = response.data
      })
    },

    parseImageArray(val) {
      if (!val) return [];

      if (Array.isArray(val)) {
        return val.map(item => {
          if (typeof item === 'string') return item;
          if (item && item.url) return item.url;
          return '';
        }).filter(Boolean);
      }

      try {
        const arr = JSON.parse(val);
        if (Array.isArray(arr)) {
          return arr.map(item => {
            if (typeof item === 'string') return item;
            if (item && item.url) return item.url;
            return '';
          }).filter(Boolean);
        }
      } catch (e) {
        // 如果不是JSON，可能是单个图片URL
        if (typeof val === 'string' && val.trim()) {
          return [val.trim()];
        }
      }

      return [];
    },

    handleImageError(event) {
      // 图片加载失败时的处理
      const imgElement = event.target;
      imgElement.style.display = 'none';
      imgElement.onerror = null; // 防止重复触发

      // 在图片位置显示错误提示
      const errorDiv = document.createElement('div');
      errorDiv.className = 'image-error';
      errorDiv.innerHTML = '<i class="el-icon-picture-outline"></i>';
      errorDiv.style.cssText = `
        width: ${imgElement.width}px;
        height: ${imgElement.height}px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #f5f7fa;
        border: 1px dashed #c0c4cc;
        border-radius: 4px;
        color: #909399;
        font-size: 16px;
      `;
      imgElement.parentNode.insertBefore(errorDiv, imgElement);
    },


    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.getUserSecondaryCard();
      const id = row.id || this.ids
      getUserSecondaryCard(id).then(response => {
        this.form = response.data
        // 主图showimage处理
        if (this.form.showimage) {
          if (Array.isArray(this.form.showimage)) {
            this.form.showimage = this.form.showimage.length > 0 ? this.form.showimage[0] : '';
          } else if (typeof this.form.showimage === 'string') {
            // 保持字符串
          } else if (this.form.showimage && this.form.showimage.url) {
            this.form.showimage = this.form.showimage.url;
          }
        } else {
          this.form.showimage = '';
        }
        // 轮播图处理为数组，兼容字符串和数组
        if (this.form.carouselImage) {
          try {
            const arr = JSON.parse(this.form.carouselImage)
            if (Array.isArray(arr)) {
              this.form.carouselImage = arr.map(item => {
                if (typeof item === 'string') return item;
                if (item && item.url) return item.url;
                return '';
              }).filter(Boolean);
            } else {
              this.form.carouselImage = []
            }
          } catch (e) {
            this.form.carouselImage = []
          }
        } else {
          this.form.carouselImage = []
        }
        // 兼容后端返回goodsids为JSON字符串数组或逗号分隔字符串，全部转为字符串数组
        if (this.form.goodsids) {
          if (typeof this.form.goodsids === 'string') {
            try {
              const arr = JSON.parse(this.form.goodsids)
              if (Array.isArray(arr)) {
                this.form.goodsids = arr.map(i => String(i))
              } else {
                this.form.goodsids = this.form.goodsids.split(',').map(i => String(i).trim()).filter(i => i)
              }
            } catch (e) {
              this.form.goodsids = this.form.goodsids.split(',').map(i => String(i).trim()).filter(i => i)
            }
          } else if (Array.isArray(this.form.goodsids)) {
            this.form.goodsids = this.form.goodsids.map(i => String(i))
          }
        } else {
          this.form.goodsids = []
        }
        this.onGoodsidsChange(this.form.goodsids);
        this.open = true
        this.title = "修改次卡管理"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 主图（showimage）只允许一张，取第一个
          let showimageVal = '';
          if (Array.isArray(this.form.showimage)) {
            showimageVal = this.form.showimage.length > 0 ? this.form.showimage[0] : '';
          } else if (typeof this.form.showimage === 'string') {
            showimageVal = this.form.showimage;
          } else if (this.form.showimage && this.form.showimage.url) {
            showimageVal = this.form.showimage.url;
          }
          // 处理轮播图为URL数组
          let carouselArr = [];
          if (Array.isArray(this.form.carouselImage)) {
            carouselArr = this.form.carouselImage.map(item => {
              if (typeof item === 'string') return item;
              if (item && item.url) return item.url;
              return '';
            }).filter(Boolean);
          }

          const submitForm = {
            ...this.form,
            showimage: showimageVal,
            carouselImage: JSON.stringify(carouselArr),
            goodsids: Array.isArray(this.form.goodsids) ? JSON.stringify(this.form.goodsids.map(String)) : this.form.goodsids
          }
          if (this.form.id != null) {
            updateUserSecondaryCard(submitForm).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addUserSecondaryCard(submitForm).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 delUserSecondaryCard(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/UserSecondaryCard/export', {
        ...this.queryParams
      }, `UserSecondaryCard_${new Date().getTime()}.xlsx`)
    },
    // 服务项目选择变化时自动回填总服务数
    onGoodsidsChange(val) {
      this.form.allnum = Array.isArray(val) ? val.length : 0
    }
  }
}
</script>

<style scoped>
.price-text {
  font-family: Arial, sans-serif;
  color: #606266;
  font-weight: bold;
}
.price-highlight {
  color: #f56c6c;
}
.service-count {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}
.available-count {
  color: #67c23a;
  font-weight: bold;
}
.count-separator {
  color: #909399;
}
.total-count {
  color: #606266;
}
.status-tag {
  font-weight: bold;
}
.image-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}
.image-row {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  justify-content: center;
  align-items: center;
}
.carousel-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}
.carousel-row {
  display: flex;
  flex-wrap: nowrap;
  gap: 6px;
  justify-content: flex-start;
  align-items: center;
  overflow-x: auto;
  max-width: 280px;
  padding: 2px;
  scrollbar-width: thin;
  scrollbar-color: #c0c4cc transparent;
}
.carousel-row::-webkit-scrollbar {
  height: 4px;
}
.carousel-row::-webkit-scrollbar-track {
  background: transparent;
}
.carousel-row::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 2px;
}
.carousel-row::-webkit-scrollbar-thumb:hover {
  background: #909399;
}
.table-image {
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
  flex-shrink: 0;
}
.table-image:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}
.no-image {
  color: #909399;
  font-style: italic;
}
.image-count {
  font-size: 12px;
  color: #909399;
  text-align: center;
}
</style>
