<template>
  <div class="NCC-common-layout">
    <div class="NCC-common-layout-center">
      <el-row class="NCC-common-search-box" :gutter="16">
        <el-form
          class="NCC-common-search-form"
          @submit.native.prevent
          label-position="right"
          label-width="90px"
        >
          <el-col :span="6">
            <el-form-item label="拓客时间">
              <el-date-picker v-model="query.expansionTime" type="daterange" value-format="timestamp"
                format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="拓客活动">
              <el-select v-model="query.eventId" placeholder="请选择拓客活动" clearable filterable :loading="eventListLoading">
                <el-option v-for="event in eventList" :key="event.id"
                  :label="`${event.eventNumber} - ${event.eventName}`" :value="event.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="拓客人员">
              <userSelect v-model="query.expansionUserId" placeholder="请选择拓客人员" />
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="showAll">
            <el-form-item label="所属门店">
              <el-select v-model="query.storeId" placeholder="请选择门店" clearable filterable>
                <el-option v-for="(item, index) in storeOptions" :key="index" :label="item.fullName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <template v-if="showAll">
            <el-col :span="6">
              <el-form-item label="顾客姓名">
                <el-input v-model="query.customerName" placeholder="顾客姓名" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="电话号码">
                <el-input v-model="query.customerPhone" placeholder="电话号码" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="购买张数">
                <el-input v-model="query.buyNumber" placeholder="购买张数" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="支付方式">
                <el-select v-model="query.paymentMethod" placeholder="支付方式" clearable>
                  <el-option v-for="(item, index) in zffsOptions" :key="index" :label="item.fullName"
                    :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="是否加微信">
                <el-select v-model="query.isAddWeChat" placeholder="是否加微信" clearable>
                  <el-option v-for="(item, index) in sfjwxOptions" :key="index" :label="item.fullName"
                    :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="所属战队">
                <el-input v-model="query.teamName" placeholder="请输入战队名称" clearable />
              </el-form-item>
            </el-col>
          </template>
          <el-col :span="6" class="NCC-search-actions">
            <el-form-item label-width="0">
              <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
              <el-button icon="el-icon-refresh-right" @click="reset()">重置</el-button>
              <el-button type="text" icon="el-icon-arrow-down" @click="showAll = true" v-if="!showAll">展开</el-button>
              <el-button type="text" icon="el-icon-arrow-up" @click="showAll = false" v-else>收起</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="NCC-common-layout-main NCC-flex-main">
        <div class="NCC-common-head">
          <div>
            <el-button type="text" icon="el-icon-download" @click="exportData()">导出</el-button>
            <el-button type="success" icon="el-icon-s-data" @click="goToReport()">拓客报表</el-button>
          </div>
          <div class="NCC-common-head-right">
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link icon="icon-ym icon-ym-Refresh NCC-common-head-icon" :underline="false" @click="reset()" />
            </el-tooltip>
            <screenfull isContainer />
          </div>
        </div>
        <NCC-table v-loading="listLoading" :data="list">
          <!-- <el-table-column prop="id" label="拓客编号" align="left" width="160" show-overflow-tooltip /> -->
          <el-table-column prop="eventName" label="拓客活动" align="left" show-overflow-tooltip min-width="160" />
          <el-table-column prop="expansionUserName" label="拓客人员" align="left" show-overflow-tooltip min-width="120" />
          <el-table-column prop="storeName" label="所属门店" align="left" show-overflow-tooltip min-width="140" />
          <el-table-column prop="expansionTime" label="拓客时间" align="left" :formatter="ncc.tableDateFormat"
            width="160" show-overflow-tooltip />
          <el-table-column prop="customerName" label="顾客姓名" align="left" show-overflow-tooltip min-width="120" />
          <el-table-column prop="customerPhone" label="电话号码" align="left" show-overflow-tooltip min-width="140" />
          <el-table-column prop="buyNumber" label="购买张数" align="left" show-overflow-tooltip min-width="100" />
          <el-table-column label="支付方式" prop="paymentMethod" align="left" min-width="120" show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.paymentMethod | dynamicText(zffsOptions) }}</template>
          </el-table-column>
          <el-table-column label="是否加微信" prop="isAddWeChat" align="left" min-width="110" show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.isAddWeChat | dynamicText(sfjwxOptions) }}</template>
          </el-table-column>
          <el-table-column prop="teamName" label="所属战队" align="left" show-overflow-tooltip min-width="140" />
          <el-table-column prop="remarks" label="备注" align="left" width="360" show-overflow-tooltip />
          <el-table-column label="操作" align="left" width="120">
            <template slot-scope="scope">
              <el-link type="danger" :underline="false" class="NCC-table-delBtn"
                @click="handleDelete(scope.row)">删除</el-link>
            </template>
          </el-table-column>
        </NCC-table>
        <pagination :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize"
          @pagination="initData" />
      </div>
    </div>
    <ExportBox v-if="exportBoxVisible" ref="ExportBox" @download="download" />
  </div>
</template>
<script>
import request from '@/utils/request'
import {
  getDictionaryDataSelector
} from '@/api/systemData/dictionary'
import ExportBox from './ExportBox'
import {
  previewDataInterface
} from '@/api/systemData/dataInterface'
import { getLqEventList } from '@/api/extend/lqevent'
export default {
  components: {
    ExportBox
  },
  data() {
    return {
      showAll: false,
      eventList: [],
      eventListLoading: false,
      query: {
        id: undefined,
        expansionUserId: undefined,
        expansionTime: undefined,
        customerName: undefined,
        customerPhone: undefined,
        buyNumber: undefined,
        paymentMethod: undefined,
        isAddWeChat: undefined,
        remarks: undefined,
        eventId: undefined,
        storeId: undefined,
        teamName: undefined,
      },
      list: [],
      listLoading: true,
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 10,
        sort: "desc",
        sidx: "",
      },
      exportBoxVisible: false,
      columnList: [{
        prop: 'id',
        label: '拓客编号'
      },
      {
        prop: 'eventName',
        label: '拓客活动'
      },
      {
        prop: 'expansionUserName',
        label: '拓客人员'
      },
      {
        prop: 'storeName',
        label: '所属门店'
      },
      {
        prop: 'expansionTime',
        label: '拓客时间'
      },
      {
        prop: 'customerName',
        label: '顾客姓名'
      },
      {
        prop: 'customerPhone',
        label: '电话号码'
      },
      {
        prop: 'buyNumber',
        label: '购买张数'
      },
      {
        prop: 'paymentMethod',
        label: '支付方式'
      },
      {
        prop: 'isAddWeChat',
        label: '是否加微信'
      },
      {
        prop: 'teamName',
        label: '所属战队'
      },
      {
        prop: 'remarks',
        label: '备注'
      },
      ],
      zffsOptions: [{
        "fullName": "微信",
        "id": "微信"
      }, {
        "fullName": "支付宝",
        "id": "支付宝"
      }, {
        "fullName": "现金",
        "id": "现金"
      }, {
        "fullName": "银行转账",
        "id": "银行转账"
      }],
      sfjwxOptions: [{
        "fullName": "是",
        "id": "是"
      }, {
        "fullName": "否",
        "id": "否"
      }],
      storeOptions: [],
    }
  },
  computed: {},
  created() {
    this.getEventList()
    this.getStoreOptions()
    if (this.$route.query.id) {
      this.query.id = this.$route.query.id
    }
    this.initData()
  },
  methods: {
    // 获取门店选项
    getStoreOptions() {
      previewDataInterface('730960205902251269').then(res => {
        this.storeOptions = res.data
      });
    },
    // 获取拓客活动列表
    async getEventList() {
      this.eventListLoading = true
      try {
        const response = await getLqEventList({
          currentPage: 1,
          pageSize: 1000 // 获取所有活动
        })
        if (response.code === 200 && response.data && response.data.list) {
          this.eventList = response.data.list.map(event => ({
            id: event.id,
            eventNumber: event.eventNumber,
            eventName: event.eventName
          }))
        } else {
          this.eventList = []
        }
      } catch (error) {
        console.error('获取活动列表失败:', error)
        this.eventList = []
      } finally {
        this.eventListLoading = false
      }
    },
    initData() {
      this.listLoading = true;
      let _query = {
        ...this.listQuery,
        ...this.query
      };
      let query = {}
      for (let key in _query) {
        if (Array.isArray(_query[key])) {
          query[key] = _query[key].join()
        } else {
          query[key] = _query[key]
        }
      }
      request({
        url: `/api/Extend/LqTkjlb`,
        method: 'GET',
        data: query
      }).then(res => {
        this.list = res.data.list
        this.total = res.data.pagination.total
        this.listLoading = false
      })
    },
    exportData() {
      this.exportBoxVisible = true
      this.$nextTick(() => {
        this.$refs.ExportBox.init()
      })
    },
    download(data) {
      // 使用简化的参数
      let query = {
        eventId: data.eventId,
        endTime: data.endTime
      }

      request({
        url: `/api/Extend/LqTkjlb/Actions/Export`,
        method: 'GET',
        data: query
      }).then(res => {
        if (res.data.url) {
          window.location.href = this.define.comUrl + res.data.url
          this.$message({
            type: 'success',
            message: '导出成功！'
          })
        } else if (res.data.message) {
          this.$message({
            type: 'error',
            message: res.data.message
          })
        }
        this.$refs.ExportBox.visible = false
        this.exportBoxVisible = false
      }).catch(error => {
        this.$message({
          type: 'error',
          message: '导出失败：' + (error.message || '未知错误')
        })
        this.$refs.ExportBox.visible = false
        this.exportBoxVisible = false
      })
    },
    search() {
      this.listQuery = {
        currentPage: 1,
        pageSize: 10,
        sort: "desc",
        sidx: "",
      }
      this.initData()
    },
    reset() {
      for (let key in this.query) {
        this.query[key] = undefined
      }
      this.listQuery = {
        currentPage: 1,
        pageSize: 10,
        sort: "desc",
        sidx: "",
      }
      this.initData()
    },
    // 删除拓客信息
    handleDelete(row) {
      if (!row || !row.id) {
        this.$message.error('未获取到要删除的拓客记录');
        return;
      }
      this.$confirm(
        '确定要删除该拓客信息吗？删除后将一并删除关联会员及其女神卡开单记录，且不可恢复。',
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          closeOnClickModal: false
        }
      )
        .then(() => {
          this.listLoading = true;
          request({
            url: `/api/Extend/LqTkjlb/${row.id}`,
            method: 'delete'
          })
            .then(res => {
              if (res && (res.code === 200 || res.success)) {
                this.$message.success(res.msg || '删除成功');
                this.initData();
              } else {
                this.$message.error((res && res.msg) || '删除失败');
                this.listLoading = false;
              }
            })
            .catch(error => {
              this.$message.error(
                (error && (error.msg || error.message)) || '删除失败'
              );
              this.listLoading = false;
            });
        })
        .catch(() => {
          // 用户取消删除，无需处理
        });
    },
    // 跳转到拓客报表页面
    goToReport() {
      this.$router.push('/lqTkjlb/report')
    }
  }
}
</script>

<style lang="scss" scoped>
.NCC-common-layout {
  .NCC-table {
    .el-table {
      .el-table__header {
        th {
          background-color: #f5f7fa;
          color: #606266;
          font-weight: 600;
        }
      }

      .el-table__body {
        tr:hover {
          background-color: #f5f7fa;
        }
      }
    }
  }

  .NCC-common-search-box {
    padding: 16px 16px 0;
    margin-bottom: 16px;
    background-color: #fff;
    border-radius: 8px;

    .el-form-item {
      margin-bottom: 16px;

      .el-form-item__label {
        font-weight: 500;
        color: #606266;
      }
    }
  }

  .NCC-common-head {
    .el-button {
      margin-right: 8px;

      &.el-button--primary {
        background-color: #409eff;
        border-color: #409eff;
      }

      &.el-button--text {
        color: #409eff;

        &:hover {
          color: #66b1ff;
        }
      }
    }

    .NCC-common-head-right {
      display: flex;
      align-items: center;

      .NCC-common-head-icon {
        cursor: pointer;
        transition: color 0.2s ease, transform 0.2s ease;

        &:hover {
          color: #409eff;
          transform: translateY(-1px);
        }
      }
    }
  }
}

.NCC-search-actions {
  .el-form-item__content {
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }

  .el-button + .el-button {
    margin-left: 8px;
  }
}

// 表格列宽度优化
.el-table {
  .el-table__header-wrapper {
    th {
      padding: 12px 0;
    }
  }

  .el-table__body-wrapper {
    td {
      padding: 12px 0;
      white-space: nowrap;
    }
  }
}

// 操作按钮样式
.NCC-table-delBtn {
  color: #f56c6c !important;
  cursor: pointer;
  transition: color 0.2s ease;

  &:hover {
    color: #f78989 !important;
  }
}

// 响应式优化：窄屏时查询条件两列一行，避免压缩
@media (max-width: 992px) {
  .NCC-common-search-box {
    .el-col {
      width: 50%;
      max-width: 50%;
    }

    .NCC-search-actions {
      .el-form-item__content {
        justify-content: flex-start;
      }
    }
  }
}
</style>
