<template>
  <el-dialog :title="!dataForm.id ? '新增开单活动' : '编辑开单活动'" :close-on-click-modal="false" :visible.sync="visible"
    width="800px" @close="closeDialog">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
      label-width="120px">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="活动名称" prop="activityName">
            <el-input v-model="dataForm.activityName" placeholder="请输入活动名称" clearable />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="活动描述" prop="activityDesc">
            <el-input v-model="dataForm.activityDesc" type="textarea" :rows="3" placeholder="请输入活动描述" clearable />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker v-model="dataForm.startTime" type="datetime" placeholder="选择开始时间"
              format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-ddTHH:mm:ss.sssZ" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker v-model="dataForm.endTime" type="datetime" placeholder="选择结束时间" format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-ddTHH:mm:ss.sssZ" style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="最小项目数量" prop="minItemQuantity">
            <el-input-number v-model="dataForm.minItemQuantity" :min="1" :max="2147483647" placeholder="最小项目数量"
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="排序" prop="sortOrder">
            <el-input-number
              v-model="dataForm.sortOrder"
              :min="0"
              placeholder="排序"
              style="width: 100%"
            />
          </el-form-item>
        </el-col> -->
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="活动规则" prop="activityRules">
            <el-input v-model="dataForm.activityRules" type="textarea" :rows="3" placeholder="请输入活动规则" clearable />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="活动图片" prop="activityImages">
            <el-input
              v-model="dataForm.activityImages"
              placeholder="请输入活动图片URL"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row> -->

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="活动项目" prop="activityItems">
            <div class="item-selection-container">
              <el-button type="primary" size="small" @click="showItemSelector = true">
                选择项目
              </el-button>
              <span class="selected-count" v-if="selectedItems.length > 0">
                已选择 {{ selectedItems.length }} 个项目
              </span>
            </div>

            <!-- 已选择的项目列表 -->
            <div class="selected-items" v-if="selectedItems.length > 0">
              <el-tag v-for="item in selectedItems" :key="item.itemId" closable @close="removeItem(item)" class="item-tag">
                {{ item.itemName }} ({{ item.itemId }})
              </el-tag>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 项目选择弹窗 -->
    <el-dialog title="选择项目" :visible.sync="showItemSelector" width="900px" append-to-body>
      <div class="item-selector">
        <!-- 搜索框 -->
        <el-row :gutter="20" style="margin-bottom: 20px;">
          <el-col :span="8">
            <el-input v-model="itemSearchQuery.xmmc" placeholder="项目名称" clearable />
          </el-col>
          <el-col :span="8">
            <el-button type="primary" @click="searchItems">搜索</el-button>
            <el-button @click="resetItemSearch">重置</el-button>
          </el-col>
        </el-row>

        <!-- 项目列表 -->
        <el-table :data="itemList" v-loading="itemListLoading" @selection-change="handleItemSelectionChange"
          max-height="400">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="项目编号" align="left" />
          <el-table-column prop="xmmc" label="项目名称" align="left" />
        </el-table>

        <!-- 分页 -->
        <pagination v-show="itemTotal > 0" :total="itemTotal" :page.sync="itemQuery.currentPage"
          :limit.sync="itemQuery.pageSize" @pagination="getItemList" />
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="showItemSelector = false">取消</el-button>
        <el-button type="primary" @click="confirmItemSelection">确定</el-button>
      </span>
    </el-dialog>

    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import request from '@/utils/request'

  export default {
    name: 'PackageInfoForm',
    data() {
      return {
        visible: false,
        dataForm: {
          id: '',
          activityName: '',
          activityDesc: '',
          startTime: '',
          endTime: '',
          minItemQuantity: 1,
          activityRules: '',
          activityImages: '',
          sortOrder: 0,
          activityItems: []
        },
        dataRule: {
          activityName: [{
            required: true,
            message: '活动名称不能为空',
            trigger: 'blur'
          }],
          activityDesc: [{
            required: true,
            message: '活动描述不能为空',
            trigger: 'blur'
          }],
          startTime: [{
            required: true,
            message: '开始时间不能为空',
            trigger: 'change'
          }],
          endTime: [{
            required: true,
            message: '结束时间不能为空',
            trigger: 'change'
          }],
          minItemQuantity: [{
            required: true,
            message: '最小项目数量不能为空',
            trigger: 'blur'
          }],
          activityItems: [{
            required: true,
            message: '请至少选择一个项目',
            trigger: 'change'
          }]
        },
        // 项目选择相关
        showItemSelector: false,
        selectedItems: [],
        itemList: [],
        itemListLoading: false,
        itemTotal: 0,
        itemQuery: {
          currentPage: 1,
          pageSize: 10
        },
        itemSearchQuery: {
          xmbh: '',
          xmmc: ''
        },
        tempSelectedItems: [] // 临时选择的项目
      }
    },
    methods: {
      init(id) {
        this.dataForm.id = id || ''
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            // 编辑模式，加载数据
            this.loadData()
          } else {
            // 新增模式，重置表单
            this.resetForm()
          }
        })
      },

      // 加载数据（编辑模式）
      loadData() {
        // 这里可以根据需要加载现有数据
        request({
          url: `/api/Extend/lqpackageinfo/GetPackageInfoDetailAsync?id=${this.dataForm.id}`,
          method: 'GET'
        }).then(res => {
          this.dataForm = {
            ...this.dataForm,
            ...res.data
          }
          // 处理已选择的项目
          if (res.data.activityItems) {
            this.selectedItems = res.data.activityItems
            // 转换时间戳为日期字符串格式
            console.log(res.data)
            if (res.data.startTime) {
              this.dataForm.startTime = this.formatTimestamp(res.data.startTime)
            }
            if (res.data.endTime) {
              this.dataForm.endTime = this.formatTimestamp(res.data.endTime)
            }
          }
        })
      },
      // 时间戳转日期字符串
      formatTimestamp(timestamp) {
        if (!timestamp) return ''
        const date = new Date(timestamp)
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      },

      // 重置表单
      resetForm() {
        this.dataForm = {
          id: '',
          activityName: '',
          activityDesc: '',
          startTime: '',
          endTime: '',
          minItemQuantity: 1,
          activityRules: '',
          activityImages: '',
          sortOrder: 0,
          activityItems: []
        }
        this.selectedItems = []
      },

      // 获取项目列表
      getItemList() {
        this.itemListLoading = true
        let query = {
          ...this.itemQuery,
          ...this.itemSearchQuery
        }

        request({
          url: '/api/Extend/LqXmzl',
          method: 'GET',
          data: query
        }).then(res => {
          this.itemList = res.data.list || []
          this.itemTotal = (res.data.pagination && res.data.pagination.total) || 0
          this.itemListLoading = false
        }).catch(() => {
          this.itemListLoading = false
        })
      },

      // 搜索项目
      searchItems() {
        this.itemQuery.currentPage = 1
        this.getItemList()
      },

      // 重置项目搜索
      resetItemSearch() {
        this.itemSearchQuery = {
          xmbh: '',
          xmmc: ''
        }
        this.searchItems()
      },

      // 处理项目选择变化
      handleItemSelectionChange(selection) {
        this.tempSelectedItems = selection
      },

    // 确认项目选择
    confirmItemSelection() {
      // 合并已选择的项目，避免重复
      const existingIds = this.selectedItems.map(item => item.itemId)
      const newItems = this.tempSelectedItems.filter(item => !existingIds.includes(item.id))
      
      // 直接转换为目标格式
      const formattedNewItems = newItems.map(item => ({
        itemId: item.id,
        itemName: item.xmmc,
        itemCategory: item.qt2 || '',
        itemRemark: item.qt1 || ''
      }))
      
      this.selectedItems = [...this.selectedItems, ...formattedNewItems]
      this.showItemSelector = false
      
      // 更新表单数据
      this.updateActivityItems()
    },

    // 移除项目
    removeItem(item) {
      const index = this.selectedItems.findIndex(selected => selected.itemId === item.itemId)
      if (index > -1) {
        this.selectedItems.splice(index, 1)
        this.updateActivityItems()
      }
    },

    // 更新活动项目数据
    updateActivityItems() {
      this.dataForm.activityItems = this.selectedItems
    },

      // 表单提交
      dataFormSubmit() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            // 验证时间
            if (new Date(this.dataForm.startTime) >= new Date(this.dataForm.endTime)) {
              this.$message.error('结束时间必须大于开始时间')
              return
            }

            // 验证项目选择
            if (this.selectedItems.length === 0) {
              this.$message.error('请至少选择一个项目')
              return
            }

            // 更新活动项目数据
            this.updateActivityItems()

            const requestData = {
              ...this.dataForm,
              minItemQuantity: parseInt(this.dataForm.minItemQuantity),
              sortOrder: parseInt(this.dataForm.sortOrder)
            }

            if (this.dataForm.id) {
              request({
                url: '/api/Extend/lqpackageinfo/UpdatePackageInfoAsync',
                method: 'PUT',
                data: requestData
              }).then(res => {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              }).catch(err => {
                this.$message.error(err.msg || '操作失败')
              })
            } else {
              request({
                url: '/api/Extend/lqpackageinfo/CreatePackageInfoAsync',
                method: 'POST',
                data: requestData
              }).then(res => {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              }).catch(err => {
                this.$message.error(err.msg || '操作失败')
              })
            }
          }
        })
      },

      // 关闭弹窗
      closeDialog() {
        this.resetForm()
        this.showItemSelector = false
        this.tempSelectedItems = []
      }
    },

    watch: {
      showItemSelector(val) {
        if (val) {
          this.getItemList()
        }
      }
    }
  }
</script>

<style scoped>
  .item-selection-container {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 10px;
  }

  .selected-count {
    color: #409EFF;
    font-size: 14px;
  }

  .selected-items {
    margin-top: 10px;
  }

  .item-tag {
    margin-right: 8px;
    margin-bottom: 8px;
  }

  .item-selector {
    /* max-height: 500px;
    overflow-y: auto; */
  }

  .dialog-footer {
    text-align: right;
  }
</style>
