<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="用户昵称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入用户昵称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入电话"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          size="small"
          @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"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['store:storeProductUserRecord:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="recordList">
      <el-table-column label="用户昵称" align="center" prop="nickName" show-overflow-tooltip />
      <el-table-column label="电话" align="center" prop="phone" width="130" />
      <el-table-column label="姓名" align="center" prop="name" show-overflow-tooltip />
      <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['store:storeProductUserRecord:query']"
          >详情</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-drawer
      :visible.sync="detailOpen"
      :with-header="false"
      size="60%"
      append-to-body
    >
      <div v-loading="detailLoading" class="record-detail">
        <div class="record-detail-header">采集记录详情</div>

        <div class="detail-section">
          <div class="section-title">基础信息</div>
          <el-descriptions :column="3" border>
            <el-descriptions-item label="用户昵称">{{ detail.nickName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="电话">{{ detail.phone || '-' }}</el-descriptions-item>
            <el-descriptions-item label="姓名">{{ detail.name || '-' }}</el-descriptions-item>
            <el-descriptions-item label="提交时间">{{ detail.createTime || '-' }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="detail-section">
          <div class="section-title">采集信息</div>
          <el-descriptions :column="2" border class="mb16">
            <el-descriptions-item label="模板标题">{{ detail.tempName || detail.templateTitle || '-' }}</el-descriptions-item>
            <el-descriptions-item label="关联商品">{{ detail.productName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="备注" :span="2">{{ detail.remark || '-' }}</el-descriptions-item>
          </el-descriptions>

          <div class="section-subtitle">填写项</div>
          <el-descriptions v-if="fieldValueList.length" :column="1" border>
            <el-descriptions-item
              v-for="(field, index) in fieldValueList"
              :key="field.id || field.tempFieldId || index"
              :label="getFieldLabel(field)"
            >
              <span v-if="getTextValue(field)">{{ getTextValue(field) }}</span>
              <template v-else-if="getChoiceTags(field).length">
                <el-tag
                  v-for="tag in getChoiceTags(field)"
                  :key="tag"
                  size="mini"
                  type="info"
                  class="choice-tag"
                >{{ tag }}</el-tag>
              </template>
              <span v-else class="empty-value">-</span>
            </el-descriptions-item>
          </el-descriptions>
          <el-empty v-else description="暂无采集项" :image-size="80" />
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  listFsStoreProductUserRecord,
  getFsStoreProductUserRecord,
  exportFsStoreProductUserRecord
} from '@/api/hisStore/storeProductUserRecord'

export default {
  name: 'FsStoreProductUserRecord',
  data() {
    return {
      loading: true,
      exportLoading: false,
      detailLoading: false,
      showSearch: true,
      total: 0,
      recordList: [],
      detailOpen: false,
      detail: {},
      fieldValueList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nickName: null,
        phone: null,
        name: null
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      listFsStoreProductUserRecord(this.queryParams).then(response => {
        this.recordList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleDetail(row) {
      this.detailOpen = true
      this.detailLoading = true
      this.detail = { ...row }
      this.fieldValueList = []
      getFsStoreProductUserRecord(row.id).then(response => {
        const data = response.data || {}
        this.detail = { ...row, ...data }
        this.fieldValueList = this.extractFieldValueList(data)
        this.detailLoading = false
      }).catch(() => {
        this.detailLoading = false
      })
    },
    extractFieldValueList(data) {
      const list = data.fieldValueList
        || data.valueList
        || data.recordValueList
        || data.fieldList
        || []
      return Array.isArray(list) ? list : []
    },
    getFieldLabel(field) {
      return field.fieldName || field.field_name || '未命名选项'
    },
    getTextValue(field) {
      const value = field.fieldValue != null && field.fieldValue !== ''
        ? field.fieldValue
        : field.field_value
      return value != null && String(value).trim() !== '' ? value : ''
    },
    getChoiceTags(field) {
      const raw = field.valueJson != null && field.valueJson !== ''
        ? field.valueJson
        : field.value_json
      if (raw == null || raw === '') {
        return []
      }
      let parsed = raw
      if (typeof raw === 'string') {
        try {
          parsed = JSON.parse(raw)
        } catch (e) {
          return [raw]
        }
      }
      if (Array.isArray(parsed)) {
        return parsed.filter(item => item != null && String(item).trim() !== '')
      }
      if (typeof parsed === 'object') {
        if (Array.isArray(parsed.values)) {
          return parsed.values.filter(item => item != null && String(item).trim() !== '')
        }
        if (parsed.value != null && String(parsed.value).trim() !== '') {
          return [parsed.value]
        }
        if (parsed.label != null && String(parsed.label).trim() !== '') {
          return [parsed.label]
        }
      }
      return [String(parsed)]
    },
    handleExport() {
      this.$confirm('是否确认导出商品信息采集记录?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.exportLoading = true
        return exportFsStoreProductUserRecord(this.queryParams)
      }).then(response => {
        this.download(response.msg)
        this.exportLoading = false
      }).catch(() => {
        this.exportLoading = false
      })
    }
  }
}
</script>

<style scoped lang="scss">
.record-detail {
  padding: 20px;
  min-height: 100%;
  background: #f0f2f5;
}

.record-detail-header {
  margin-bottom: 16px;
  padding: 16px 20px;
  background: #fff;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.detail-section {
  margin-bottom: 16px;
  padding: 16px 20px 20px;
  background: #fff;
}

.section-title {
  margin-bottom: 12px;
  font-size: 15px;
  font-weight: 600;
  color: #303133;
}

.section-subtitle {
  margin: 16px 0 10px;
  font-size: 14px;
  font-weight: 500;
  color: #606266;
}

.mb16 {
  margin-bottom: 16px;
}

.choice-tag {
  margin-right: 6px;
  margin-bottom: 4px;
}

.empty-value {
  color: #c0c4cc;
}
</style>
