<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="开始日期" prop="startDate">
        <el-date-picker
          v-model="queryParams.startDate"
          type="date"
          placeholder="选择开始日期"
          value-format="yyyy-MM-dd"
          clearable
        />
      </el-form-item>
      <el-form-item label="结束日期" prop="endDate">
        <el-date-picker
          v-model="queryParams.endDate"
          type="date"
          placeholder="选择结束日期"
          value-format="yyyy-MM-dd"
          clearable
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wecom:customerExport:export']"
        >同步导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleAsyncExport"
          v-hasPermi="['wecom:customerExport:export']"
        >异步导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-tickets"
          size="mini"
          @click="showExportTaskDialog"
          v-hasPermi="['wecom:customerExport:export']"
        >导出任务</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList" @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="客户名称" align="center" prop="customerName" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="描述" align="center" prop="description" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="性别" align="center" prop="gender" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.gender === 1 ? '男' : scope.row.gender === 2 ? '女' : '未知' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="添加人" align="center" prop="addUserName" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="添加人账号" align="center" prop="addUserAccount" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="添加人所属部门" align="center" prop="addUserDepartment" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="添加时间" align="center" prop="addTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.addTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="来源" align="center" prop="source" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="手机" align="center" prop="mobile" width="120" />
      <el-table-column label="企业" align="center" prop="company" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="邮箱" align="center" prop="email" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="地址" align="center" prop="address" width="200" :show-overflow-tooltip="true" />
      <el-table-column label="职务" align="center" prop="position" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="电话" align="center" prop="phone" width="120" />
      <el-table-column label="标签组1(投放)" align="center" prop="tagGroup1" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="标签组2(公司孵化)" align="center" prop="tagGroup2" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="标签组3(商务)" align="center" prop="tagGroup3" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="标签组4(成交日期)" align="center" prop="tagGroup4" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="标签组5(年级组)" align="center" prop="tagGroup5" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="标签组6(客户属性)" align="center" prop="tagGroup6" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="标签组7(成交)" align="center" prop="tagGroup7" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="标签组8(成交品牌)" align="center" prop="tagGroup8" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="标签组9(线索通标签)" align="center" prop="tagGroup9" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="标签组10(A1组)" align="center" prop="tagGroup10" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="标签组11(B1组)" align="center" prop="tagGroup11" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="标签组12(C1组)" align="center" prop="tagGroup12" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="标签组13(D1组)" align="center" prop="tagGroup13" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="标签组14(E1组)" align="center" prop="tagGroup14" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="标签组15(意向度)" align="center" prop="tagGroup15" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="标签组16(自然流)" align="center" prop="tagGroup16" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="标签组17(F1组)" align="center" prop="tagGroup17" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="标签组18(G1组)" align="center" prop="tagGroup18" width="150" :show-overflow-tooltip="true" />
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 导出任务对话框 -->
    <el-dialog title="导出任务列表" :visible.sync="taskDialogVisible" width="800px" append-to-body>
      <el-table v-loading="taskLoading" :data="taskList">
        <el-table-column label="任务ID" align="center" prop="taskId" width="80" />
        <el-table-column label="任务名称" align="center" prop="taskName" width="150" />
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ getStatusLabel(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="进度" align="center" prop="progress" width="150">
          <template slot-scope="scope">
            <el-progress 
              :percentage="scope.row.progress || 0" 
              :status="scope.row.status === '2' ? 'success' : scope.row.status === '3' ? 'exception' : ''"
            />
          </template>
        </el-table-column>
        <el-table-column label="文件大小" align="center" prop="fileSize" width="100">
          <template slot-scope="scope">
            <span>{{ formatFileSize(scope.row.fileSize) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-download"
              @click="handleDownload(scope.row)"
              :disabled="scope.row.status !== '2'"
            >下载</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDeleteTask(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="taskTotal>0"
        :total="taskTotal"
        :page.sync="taskQueryParams.pageNum"
        :limit.sync="taskQueryParams.pageSize"
        @pagination="getTaskList"
      />
    </el-dialog>
  </div>
</template>

<script>
import { listCustomerExport, exportAsync, getExportStatus, listExportTask, delExportTask } from "@/api/wecom/customerExport"
import { getToken } from "@/utils/auth"
import axios from 'axios'

export default {
  name: "CustomerExport",
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      dataList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        startDate: undefined,
        endDate: undefined,
        customerName: undefined
      },
      taskDialogVisible: false,
      taskLoading: false,
      taskList: [],
      taskTotal: 0,
      taskQueryParams: {
        pageNum: 1,
        pageSize: 10
      },
      pollingTimers: {}
    }
  },
  created() {
    this.getList()
  },
  beforeDestroy() {
    Object.values(this.pollingTimers).forEach(timer => clearTimeout(timer))
  },
  methods: {
    getList() {
      this.loading = true
      listCustomerExport(this.queryParams).then(response => {
        this.dataList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    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
    },
    handleExport() {
      this.download('/wecom/customerExport/export', {
        ...this.queryParams
      }, `客户列表数据_${new Date().getTime()}.xlsx`)
    },
    handleAsyncExport() {
      const params = {
        startDate: this.queryParams.startDate,
        endDate: this.queryParams.endDate,
        customerName: this.queryParams.customerName
      }
      exportAsync(params).then(response => {
        this.$modal.msgSuccess("导出任务已创建，请稍后在导出任务列表中查看")
        const taskId = response.data
        this.startPolling(taskId)
      })
    },
    startPolling(taskId) {
      const poll = () => {
        getExportStatus(taskId).then(response => {
          const task = response.data
          if (task.status === '2') {
            this.$modal.msgSuccess(`导出任务完成，文件：${task.fileName}`)
            delete this.pollingTimers[taskId]
          } else if (task.status === '3') {
            this.$modal.msgError(`导出任务失败：${task.errorMsg}`)
            delete this.pollingTimers[taskId]
          } else {
            this.pollingTimers[taskId] = setTimeout(poll, 2000)
          }
        })
      }
      this.pollingTimers[taskId] = setTimeout(poll, 2000)
    },
    showExportTaskDialog() {
      this.taskDialogVisible = true
      this.getTaskList()
    },
    getTaskList() {
      this.taskLoading = true
      listExportTask(this.taskQueryParams).then(response => {
        this.taskList = response.rows
        this.taskTotal = response.total
        this.taskLoading = false
      })
    },
    getStatusType(status) {
      const map = {
        '0': 'info',
        '1': 'warning',
        '2': 'success',
        '3': 'danger'
      }
      return map[status] || 'info'
    },
    getStatusLabel(status) {
      const map = {
        '0': '待处理',
        '1': '处理中',
        '2': '已完成',
        '3': '失败'
      }
      return map[status] || '未知'
    },
    formatFileSize(bytes) {
      if (!bytes) return '-'
      if (bytes < 1024) return bytes + ' B'
      if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB'
      return (bytes / (1024 * 1024)).toFixed(2) + ' MB'
    },
    handleDownload(row) {
      const url = process.env.VUE_APP_BASE_API + '/wecom/customerExport/export/download/' + row.taskId
      axios({
        method: 'get',
        url: url,
        responseType: 'blob',
        headers: { 'Authorization': 'Bearer ' + getToken() }
      }).then((res) => {
        const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        const link = document.createElement('a')
        link.href = window.URL.createObjectURL(blob)
        link.download = row.fileName || '导出文件.xlsx'
        link.click()
        window.URL.revokeObjectURL(link.href)
      }).catch((error) => {
        console.error('下载失败', error)
        this.$modal.msgError('下载失败，请重试')
      })
    },
    handleDeleteTask(row) {
      this.$modal.confirm('是否确认删除该导出任务？').then(() => {
        return delExportTask(row.taskId)
      }).then(() => {
        this.getTaskList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    }
  }
}
</script>
