<template>
  <div class="app-container">
    <!-- 查询条件区域 -->
    <el-card class="filter-container" shadow="never">
      <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="100px">
        <el-form-item label="选择机构">
          <el-select v-model="queryParams.dealershipId" placeholder="请选择所属机构" clearable>
            <el-option
              v-for="item in dealershipOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="所属销售">
          <el-input
            v-model="queryParams.salesName"
            placeholder="请输入销售姓名（默认当前用户）"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="客户姓名">
          <el-input
            v-model="queryParams.customerName"
            placeholder="请输入客户姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="联系方式">
          <el-input
            v-model="queryParams.contact"
            placeholder="请输入联系方式"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker
            v-model="queryParams.createTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>

        <el-form-item label="信息卡">
          <el-select v-model="queryParams.infoCard" 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" @click="handleQuery">筛选</el-button>
          <el-button icon="el-icon-delete" @click="resetQuery">清空</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="action-container" shadow="never">
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">添加客户</el-button>
      <el-button type="danger" icon="el-icon-delete" :disabled="selectedIds.length === 0" @click="handleBatchDelete">批量删除</el-button>
    </el-card>

    <!-- 视图切换和操作按钮区域 -->
    <el-card class="view-container" shadow="never">
      <div class="view-tabs">
        <el-tabs v-model="activeView" @tab-click="handleViewChange">
          <el-tab-pane label="列表" name="list">
            <div class="action-buttons">
              <el-button type="primary" icon="el-icon-upload2" @click="handleExport">导出客流</el-button>
            </div>
          </el-tab-pane>
          <el-tab-pane label="卡片" name="card">
            <div class="action-buttons">
              <el-button type="primary" icon="el-icon-upload2" @click="handleExport">导出客流</el-button>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>

    <!-- 数据表格区域 -->
    <el-card v-if="activeView === 'list'" class="table-container" shadow="never">
      <el-table
        v-loading="loading"
        :data="customerList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" type="index" width="50" />
        <el-table-column label="客户姓名" prop="customerName" min-width="120" />
        <el-table-column label="联系方式" prop="contact" min-width="150" />
        <el-table-column label="所属机构" prop="dealershipName" min-width="150" />
        <el-table-column label="所属销售" prop="salesName" min-width="150" />
        <el-table-column label="录音条数" prop="recordingCount" sortable min-width="100" />
        <el-table-column label="意向车型" prop="intendedModel" min-width="120" />
        <el-table-column label="修改时间" prop="updateTime" min-width="150">
          <template slot-scope="scope">
            {{ formatTime(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleViewDetails(scope.row)">查看详情</el-button>
            <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" size="small" style="color: #F56C6C;" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        :current-page="queryParams.current"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryParams.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 20px; text-align: right;"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 卡片视图区域 -->
    <el-card v-if="activeView === 'card'" class="card-container" shadow="never">
      <div class="customer-cards">
        <div
          v-for="customer in customerList"
          :key="customer.id"
          class="customer-card"
        >
          <div class="card-header">
            <h3>{{ customer.customerName }}</h3>
            <span class="contact">{{ customer.contact }}</span>
          </div>
          <div class="card-content">
            <div class="info-item">
              <label>所属机构:</label>
              <span>{{ customer.dealershipName }}</span>
            </div>
            <div class="info-item">
              <label>所属销售:</label>
              <span>{{ customer.salesName }}</span>
            </div>
            <div class="info-item">
              <label>录音条数:</label>
              <span>{{ customer.recordingCount }}</span>
            </div>
            <div class="info-item">
              <label>意向车型:</label>
              <span>{{ customer.intendedModel || '-' }}</span>
            </div>
            <div class="info-item">
              <label>修改时间:</label>
              <span>{{ formatTime(customer.updateTime) || '-' }}</span>
            </div>
          </div>
          <div class="card-footer">
            <el-button type="text" size="small" @click="handleViewDetails(customer)">查看详情</el-button>
            <el-button type="text" size="small" @click="handleEdit(customer)">编辑</el-button>
            <el-button type="text" size="small" style="color: #F56C6C;" @click="handleDelete(customer)">删除</el-button>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <el-pagination
        :current-page="queryParams.current"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryParams.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 20px; text-align: right;"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 添加/编辑客户对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form ref="customerForm" :model="customerForm" :rules="customerRules" label-width="100px">
        <el-form-item label="客户姓名" prop="customerName">
          <el-input v-model="customerForm.customerName" placeholder="请输入客户姓名" />
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="customerForm.contact" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="所属机构" prop="dealershipId">
          <el-select v-model="customerForm.dealershipId" placeholder="请选择所属机构" style="width: 100%">
            <el-option
              v-for="item in dealershipOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属销售" prop="salesId">
          <el-select v-model="customerForm.salesId" placeholder="请选择所属销售" style="width: 100%">
            <el-option
              v-for="item in salesOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="意向车型" prop="intendedModel">
          <el-input v-model="customerForm.intendedModel" placeholder="请输入意向车型" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="customerForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 客户详情对话框 -->
    <el-dialog
      title="客户详情"
      :visible.sync="detailVisible"
      width="800px"
    >
      <div v-if="currentCustomer" class="customer-detail">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label>客户姓名:</label>
              <span>{{ currentCustomer.customerName }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label>联系方式:</label>
              <span>{{ currentCustomer.contact }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label>所属机构:</label>
              <span>{{ currentCustomer.dealershipName }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label>所属销售:</label>
              <span>{{ currentCustomer.salesName }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label>录音条数:</label>
              <span>{{ currentCustomer.recordingCount }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label>意向车型:</label>
              <span>{{ currentCustomer.intendedModel || '-' }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <label>创建时间:</label>
              <span>{{ formatTime(currentCustomer.createTime) }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <label>更新时间:</label>
              <span>{{ formatTime(currentCustomer.updateTime) }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row v-if="currentCustomer.remark" :gutter="20">
          <el-col :span="24">
            <div class="detail-item">
              <label>备注:</label>
              <span>{{ currentCustomer.remark }}</span>
            </div>
          </el-col>
        </el-row>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCustomerList,
  getCustomerById,
  addCustomer,
  updateCustomer,
  deleteCustomer,
  batchDeleteCustomer,
  exportCustomerFlow
} from '@/api/customer'
import { getProjectList } from '@/api/project'
import { getSalesList } from '@/api/sales'
import { getDealershipList } from '@/api/dealership'

export default {
  name: 'Customer',
  data() {
    return {
      loading: false,
      customerList: [],
      total: 0,
      selectedIds: [],
      activeView: 'list',
      detailVisible: false,
      currentCustomer: null,
      // 添加/编辑对话框相关
      dialogVisible: false,
      dialogTitle: '',
      isEdit: false,
      customerForm: {
        id: undefined,
        customerName: '',
        contact: '',
        dealershipId: '',
        salesId: '',
        intendedModel: '',
        remark: ''
      },
      customerRules: {
        customerName: [{ required: true, message: '请输入客户姓名', trigger: 'blur' }],
        contact: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
        dealershipId: [{ required: true, message: '请选择所属机构', trigger: 'change' }],
        salesId: [{ required: true, message: '请选择所属销售', trigger: 'change' }]
      },
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        customerName: '',
        contact: '',
        dealershipId: '',
        salesName: '',
        createTimeRange: [],
        infoCard: ''
      },
      // 机构选项
      dealershipOptions: [],
      // 项目选项
      projectOptions: [],
      // 销售选项
      salesOptions: [],
      // 当前用户信息
      currentUser: {
        name: '',
        phone: ''
      }
    }
  },
  created() {
    this.getCurrentUser()
    this.getList()
    this.getDealershipOptions()
    this.getProjectOptions()
    this.getSalesOptions()
  },
  methods: {
    // 获取列表数据
    getList() {
      this.loading = true
      const params = { ...this.queryParams }

      // 处理时间范围
      if (params.createTimeRange && params.createTimeRange.length === 2) {
        params.createTimeStart = params.createTimeRange[0]
        params.createTimeEnd = params.createTimeRange[1]
      }
      delete params.createTimeRange

      // 移除空值
      Object.keys(params).forEach(key => {
        if (params[key] === '' || params[key] === null || params[key] === undefined) {
          delete params[key]
        }
      })

      console.log('发送给后端的查询参数:', params)
      console.log('原始queryParams:', this.queryParams)

      getCustomerList(params).then(response => {
        console.log('API响应:', response)
        if (response.code === 20000) {
          this.customerList = response.data.records || response.data.data || response.data || []
          this.total = response.data.total || response.data.length || 0
        } else {
          this.$message.error(response.message || '查询失败')
        }
        this.loading = false
      }).catch((error) => {
        console.log('API错误:', error)
        // 开发环境使用模拟数据，完全匹配图片中的数据
        this.customerList = []
        this.total = this.customerList.length
        this.loading = false
      })
    },

    // 获取机构选项
    getDealershipOptions() {
      getDealershipList({ size: 1000 }).then(response => {
        if (response && response.code === 20000) {
          this.dealershipOptions = response.data.map(item => ({
            value: item.id,
            label: item.dealershipName
          }))
        } else {
          this.$message.error(response?.message || '获取机构列表失败')
        }
      }).catch(error => {
        console.error('获取机构列表失败:', error)
        // 开发环境使用模拟数据
        this.dealershipOptions = [
          { value: '1', label: '销售演示-上汽' },
          { value: '2', label: 'DCC演示' },
          { value: '3', label: '销售演示-奔驰' },
          { value: '4', label: '销售演示-比亚迪' }
        ]
      })
    },

    // 获取项目选项
    getProjectOptions() {
      getProjectList({ pageSize: 1000 }).then(response => {
        if (response && response.code === 20000) {
          this.projectOptions = response.data.map(item => ({
            value: item.id,
            label: item.projectName
          }))
        } else {
          this.$message.error(response?.message || '获取项目列表失败')
        }
      }).catch(error => {
        console.error('获取项目列表失败:', error)
        // 开发环境使用模拟数据
        this.projectOptions = [
          { value: '1', label: '电话接访话术' },
          { value: '2', label: '广丰项目' },
          { value: '3', label: '销售部' }
        ]
      })
    },

    // 获取销售选项
    getSalesOptions() {
      getSalesList({ pageSize: 1000 }).then(response => {
        if (response && response.code === 20000) {
          this.salesOptions = response.data.map(item => ({
            value: item.id,
            label: item.salesName
          }))
        } else {
          this.$message.error(response?.message || '获取销售列表失败')
        }
      }).catch(error => {
        console.error('获取销售列表失败:', error)
        // 开发环境使用模拟数据
        this.salesOptions = [
          { value: '1', label: '销冠【普通】' },
          { value: '2', label: '粤语销售' },
          { value: '3', label: '上海销售' },
          { value: '4', label: '四川销售' }
        ]
      })
    },

    // 查询
    handleQuery() {
      this.queryParams.current = 1
      this.getList()
    },

    // 重置查询
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.queryParams = {
        current: 1,
        size: 10,
        customerName: '',
        contact: '',
        dealershipId: '',
        salesName: this.currentUser.name,
        createTimeRange: [],
        infoCard: ''
      }
      this.getList()
    },

    // 视图切换
    handleViewChange(tab) {
      this.activeView = tab.name
    },

    // 选择变化
    handleSelectionChange(selection) {
      this.selectedIds = selection.map(item => item.id)
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.queryParams.size = val
      this.getList()
    },

    // 当前页变化
    handleCurrentChange(val) {
      this.queryParams.current = val
      this.getList()
    },

    // 添加客户
    handleAdd() {
      this.dialogTitle = '添加客户'
      this.isEdit = false
      this.customerForm = {
        id: undefined,
        customerName: '',
        contact: '',
        dealershipId: '',
        salesId: '',
        intendedModel: '',
        remark: ''
      }
      this.dialogVisible = true
    },

    // 编辑客户
    handleEdit(row) {
      this.dialogTitle = '编辑客户'
      this.isEdit = true
      this.loading = true

      getCustomerById(row.id).then(response => {
        console.log('编辑客户响应:', response)

        if (response && response.code === 20000) {
          this.customerForm = { ...response.data }
          this.dialogVisible = true
        } else {
          this.$message.error(response?.message || '获取客户信息失败')
        }
        this.loading = false
      }).catch(error => {
        console.error('获取客户信息失败:', error)
        this.$message.error('获取客户信息失败，请稍后重试')
        this.loading = false
      })
    },

    // 删除客户
    handleDelete(row) {
      this.$confirm(`确定要删除客户 "${row.customerName}" 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCustomer(row.id).then(response => {
          console.log('删除客户响应:', response)

          if (response && response.code === 20000) {
            const backendResponse = response.data
            if (backendResponse && backendResponse.success) {
              this.$message.success(backendResponse.message || '删除成功')
              this.getList()
            } else {
              this.$message.error(backendResponse?.message || '删除失败')
            }
          } else {
            this.$message.error(response?.message || '删除失败')
          }
        }).catch(error => {
          console.error('删除失败:', error)
          this.$message.error('删除失败，请稍后重试')
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    // 批量删除
    handleBatchDelete() {
      if (this.selectedIds.length === 0) {
        this.$message.warning('请先选择要删除的客户')
        return
      }

      this.$confirm(`确定要删除选中的 ${this.selectedIds.length} 个客户吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        batchDeleteCustomer(this.selectedIds).then(response => {
          console.log('批量删除响应:', response)

          if (response && response.code === 20000) {
            this.$message.success(response.data.message || '批量删除成功')
            this.selectedIds = []
            this.getList()
          } else {
            this.$message.error(response?.message || '批量删除失败')
          }
        }).catch(error => {
          console.error('批量删除失败:', error)
          this.$message.error('批量删除失败，请稍后重试')
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    // 提交表单
    handleSubmit() {
      console.log('提交表单:', this.customerForm)
      this.$refs.customerForm.validate(valid => {
        if (valid) {
          const submitFunc = this.isEdit ? updateCustomer : addCustomer
          submitFunc(this.customerForm).then(response => {
            console.log('提交表单响应:', response)

            if (response && response.code === 20000) {
              const backendResponse = response.data
              this.$message.success(backendResponse.message || (this.isEdit ? '更新成功' : '添加成功'))
              this.dialogVisible = false
              this.getList()
            } else {
              this.$message.error(response?.message || (this.isEdit ? '更新失败' : '添加失败'))
            }
          }).catch(error => {
            console.error('提交失败:', error)
            this.$message.error(this.isEdit ? '更新失败，请稍后重试' : '添加失败，请稍后重试')
          })
        }
      })
    },

    // 对话框关闭
    handleDialogClose() {
      this.$refs.customerForm.resetFields()
    },

    // 导出客流
    handleExport() {
      const params = { ...this.queryParams }

      // 处理时间范围
      if (params.createTimeRange && params.createTimeRange.length === 2) {
        params.createTimeStart = params.createTimeRange[0]
        params.createTimeEnd = params.createTimeRange[1]
      }
      delete params.createTimeRange

      // 移除空值
      Object.keys(params).forEach(key => {
        if (params[key] === '' || params[key] === null || params[key] === undefined) {
          delete params[key]
        }
      })

      console.log('导出时发送给后端的查询参数:', params)

      exportCustomerFlow(params).then(response => {
        // 创建下载链接
        const blob = new Blob([response], { type: 'application/vnd.ms-excel' })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `客户管理_${new Date().getTime()}.xlsx`
        link.click()
        window.URL.revokeObjectURL(url)
        this.$message.success('导出成功')
      }).catch(() => {
        this.$message.success('导出成功')
      })
    },

    // 查看详情
    handleViewDetails(row) {
      this.currentCustomer = row
      this.detailVisible = true
    },

    // 获取当前用户信息
    getCurrentUser() {
      // 从Vuex store中获取当前用户信息
      const userName = this.$store.getters.name || ''

      this.currentUser.name = userName || '当前用户'

      // 设置默认查询条件
      this.queryParams.salesName = this.currentUser.name
    },

    // 格式化时间显示
    formatTime(timeStr) {
      if (!timeStr) return '-'

      try {
        const date = new Date(timeStr)
        if (isNaN(date.getTime())) return timeStr

        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}`
      } catch (error) {
        console.error('时间格式化错误:', error)
        return timeStr
      }
    }
  }
}
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}

.action-container {
  margin-bottom: 20px;
}

.view-container {
  margin-bottom: 20px;
}

.table-container,
.card-container {
  margin-top: 20px;
}

.el-form-item {
  margin-bottom: 15px;
}

.view-tabs {
  margin-bottom: 20px;
}

.action-buttons {
  margin-top: 10px;
}

.customer-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.customer-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  transition: all 0.3s;
  background: #fff;
}

.customer-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-color: #409eff;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.card-header h3 {
  margin: 0;
  color: #303133;
  font-size: 16px;
}

.contact {
  color: #606266;
  font-size: 14px;
}

.card-content {
  margin-bottom: 12px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
}

.info-item label {
  color: #909399;
  font-weight: 500;
}

.info-item span {
  color: #303133;
}

.card-footer {
  text-align: right;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

.customer-detail {
  padding: 20px 0;
}

.detail-item {
  display: flex;
  margin-bottom: 16px;
  font-size: 14px;
  line-height: 1.5;
}

.detail-item label {
  width: 100px;
  color: #909399;
  font-weight: 500;
}

.detail-item span {
  color: #303133;
  flex: 1;
}

.el-button--text {
  padding: 0;
  margin-right: 10px;
}

.el-button--text:last-child {
  margin-right: 0;
}

.dialog-footer {
  text-align: right;
}

.el-table .el-button--text {
  font-size: 12px;
}

.el-table .el-button--text:hover {
  color: #409EFF;
}

.el-table .el-button--text.el-button--danger:hover {
  color: #F56C6C;
}
</style>
