<template>
  <layout
    :title="layoutTitle"
    subtitle="每日10:10 定时抓取商城分类排名数据"
  >
    <template #icon>
      <el-tooltip content="抓取分类管理" placement="top">
        <i class="el-icon-setting" @click="handleCategoryManage" />
      </el-tooltip>
    </template>
    <template v-if="showSearch" #search>
      <el-form
        ref="queryForm"
        :model="queryParams"
        size="small"
        :inline="true"
        :rules="queryRules"
        label-width="68px"
      >
        <el-form-item label="分类" prop="category">
          <el-select
            v-model="queryParams.category"
            placeholder="请选择分类"
            :clearable="false"
          >
            <el-option
              v-for="category in categoryList"
              :key="category.id"
              :value="category.id"
              :label="category.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="日期" prop="createDate">
          <el-date-picker
            v-model="queryParams.createDate"
            value-format="yyyy-MM-dd"
            placeholder="请选择日期"
            type="date"
            :picker-options="pickerOptions"
            :default-value="defaultDate"
            :clearable="false"
          />
        </el-form-item>
        <el-form-item label="关键字" prop="keyword">
          <el-input
            v-model="queryParams.keyword"
            placeholder="请输入编号/名称"
            clearable
            style="width: 300px"
            @keyup.enter="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>
    </template>

    <template #toolbar>
      <toolbar
        :show-search.sync="showSearch"
        :excel="true"
        @excel="handleExport"
        @queryTable="getList"
      />
    </template>

    <template #table>
      <el-table v-loading="loading" :data="rankingList">
        <el-table-column width="100" label="排名" align="center" prop="rank" />
        <el-table-column width="420" label="商品" align="left" prop="name">
          <template #default="scope">
            <div style="display: flex; align-items: center; gap: 10px">
              <el-image
                :src="scope.row.img"
                fit="contain"
                style="width: 40px; height: 40px"
              />
              <a
                :href="scope.row.url"
                target="_blank"
                style="
                  flex-grow: 1;
                  width: 0;
                  margin: 0;
                  font-size: 13px;
                  color: var(--primary-color);
                "
              >{{ scope.row.name }}</a>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="价格(円)" prop="price" />
        <el-table-column label="货号" prop="sn" />
        <el-table-column label="评价数" align="center" prop="comments" />
        <el-table-column label="店铺" prop="shop" />
        <el-table-column label="最后更新时间" prop="createtime" />
        <el-table-column
          label="操作"
          align="center"
          width="150"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-s-data"
              @click="handleTrend(scope.row)"
            >历史趋势</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!-- 分类管理弹出层 -->
    <el-dialog
      title="分类管理"
      :visible.sync="categoryVisible"
      width="960px"
      :before-close="handleCategoryCancel"
      custom-class="app-container--dialog"
    >
      <div class="app-container--toolbar">
        <div class="app-container--toolbar-left">
          <div class="toolbar-title">
            <span>数据列表</span>
          </div>
        </div>
        <div class="app-container--toolbar-right">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >新增</el-button>
        </div>
      </div>

      <el-table :data="categoryList">
        <el-table-column width="100" label="平台" align="center" prop="type">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.zs_mall_platform"
              :value="scope.row.type"
            />
          </template>
        </el-table-column>
        <el-table-column
          width="200"
          label="分类名称"
          align="center"
          prop="name"
        />
        <el-table-column label="URL" align="center" prop="url" />
        <el-table-column
          width="100"
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            >修改</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 添加或修改分类对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-position="top">
        <el-form-item label="所属平台" prop="type">
          <el-select v-model="form.type" :disabled="true">
            <el-option
              v-for="dict in dict.type.zs_mall_platform"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="分类URL" prop="url">
          <el-input v-model="form.url" placeholder="请输入分类URL" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="历史趋势"
      :visible.sync="trendVisible"
      width="80%"
      append-to-body
    >
      <el-descriptions border :column="1">
        <el-descriptions-item
          label="商品名称"
        ><a :href="trendData.url" target="_blank">{{
          trendData.name
        }}</a></el-descriptions-item>
        <el-descriptions-item
          label="商品价格"
        >{{ trendData.price }}円</el-descriptions-item>
        <el-descriptions-item label="店铺名称">{{
          trendData.shop
        }}</el-descriptions-item>
        <el-descriptions-item label="商品货号">{{
          trendData.sn
        }}</el-descriptions-item>
      </el-descriptions>
      <div
        ref="trendCharts"
        style="
          height: 400px;
          margin-top: 16px;
          border: 1px solid #f0f0f0;
          padding: 16px 0;
        "
      />
    </el-dialog>
  </layout>
</template>

<script>
import {
  listRanking,
  getRankingCategory,
  listRankingCategory,
  getRankingTrend,
  addRankingCategory,
  updateRankingCategory
} from '@/api/operational/tools'
import * as echarts from 'echarts'
export default {
  name: 'Post',
  dicts: ['zs_mall_platform'],
  data() {
    const today = new Date()
    const formattedToday = today.toISOString().split('T')[0] // 获取 YYYY-MM-DD 格式的今天日期
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 分类表格数据
      rankingList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        createDate: formattedToday,
        keyword: ' ',
        website: this.$route.query.platform,
        category: ''
      },
      queryRules: {
        category: [{ required: true, message: '请选择分类', trigger: 'change' }]
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now() // 禁用大于今天的日期
        }
      },
      // 日期组件默认值
      defaultDate: formattedToday, // 设置组件默认值
      // 分类弹出层
      categoryVisible: false,
      // 分类列表
      categoryList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: '分类名称不能为空', trigger: 'blur' }
        ],
        url: [{ required: true, message: '分类URL不能为空', trigger: 'blur' }]
      },
      trendData: {},
      trendVisible: false
    }
  },
  computed: {
    layoutTitle() {
      const { platform } = this.$route.query
      let title = ''
      if (platform === '1') {
        title = 'Rakuten 商城排行分析工具'
      } else if (platform === '2') {
        title = 'Yahoo! 商城排行分析工具'
      }
      return title
    }
  },
  created() {
    this.getCategoryList()
  },
  methods: {
    getList() {
      this.$refs['queryForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          listRanking(this.queryParams).then((response) => {
            this.rankingList = response
            this.total = response.total
            this.loading = false
          })
        }
      })
    },
    /** 查询分类列表 */
    getCategoryList() {
      listRankingCategory({
        type: this.$route.query.platform,
        pageNum: 1,
        pageSize: 10000
      }).then((response) => {
        this.categoryList = response.rows
      })
    },
    handleTrend(row) {
      this.trendVisible = true
      this.trendData = row
      getRankingTrend({
        sn: row.sn,
        website: row.website,
        category: row.category,
        shop: row.shop
      }).then((response) => {
        const data = response

        const rankData = []
        const priceData = []
        const createdateData = []

        data.forEach((d) => {
          rankData.push(d.rank)
          priceData.push(d.price)
          createdateData.push(d.createdate)
        })

        console.log(rankData, priceData, createdateData)

        const trendCharts = echarts.init(this.$refs.trendCharts)
        trendCharts.setOption({
          backgroundColor: '#fff', // 设置背景色
          textStyle: {
            color: '#333' // 设置文字颜色
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['价格', '排名'],
            textStyle: {
              color: '#333' // 设置图例文字颜色
            }
          },
          grid: {
            left: '30',
            right: '20',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            axisLabel: {
              interval: 0,
              rotate: 45,
              textStyle: {
                color: '#333' // 设置 x 轴标签文字颜色
              }
            },
            data: createdateData,
            axisPointer: {
              type: 'shadow'
            },
            min: 0,
            axisLine: {
              lineStyle: {
                color: '#333'
              }
            }
          },
          yAxis: [
            {
              type: 'value',
              name: '价格',
              position: 'left',
              axisLine: {
                lineStyle: {
                  color: '#333'
                }
              },
              axisLabel: {
                textStyle: {
                  color: '#333' // 设置 y 轴标签文字颜色
                }
              }
            },
            {
              type: 'value',
              name: '排名',
              position: 'right',
              splitLine: {
                show: false // 隐藏排名的参考线
              },
              axisLine: {
                lineStyle: {
                  color: '#333'
                }
              },
              axisLabel: {
                textStyle: {
                  color: '#333' // 设置 y 轴标签文字颜色
                }
              }
            }
          ],
          dataZoom: [
            {
              type: 'slider',
              start: 0,
              end: 100, // 设置为 100，确保显示所有数据
              showDetail: true
            }
          ],
          series: [
            {
              name: '价格',
              type: 'line',
              smooth: true,
              data: priceData,
              yAxisIndex: 0, // 对应左侧的 Y 轴
              label: {
                show: true,
                position: 'top',
                color: '#333' // 设置标签文字颜色
              }
            },
            {
              name: '排名',
              type: 'line',
              smooth: true,
              data: rankData,
              yAxisIndex: 1, // 对应右侧的 Y 轴
              label: {
                show: true,
                position: 'top',
                color: '#333' // 设置标签文字颜色
              }
            }
          ]
        })
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        type: undefined,
        name: undefined,
        url: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 分类弹出层操作 */
    handleCategoryManage() {
      this.categoryVisible = true
    },
    /** 分类弹出层取消 */
    handleCategoryCancel() {
      this.categoryVisible = false
    },
    /** 分类新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增分类'
      this.form.type = this.$route.query.platform
    },
    /** 分类修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id
      getRankingCategory(id).then((response) => {
        this.form = response.data
        this.open = true
        this.title = '修改分类'
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.id !== undefined) {
            updateRankingCategory(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getCategoryList()
            })
          } else {
            addRankingCategory(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getCategoryList()
            })
          }
        }
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$refs['queryForm'].validate((valid) => {
        if (valid) {
          this.download(
            'productranking/exportExcel',
            {
              ...this.queryParams
            },
            `ranking_${new Date().getTime()}.xlsx`
          )
        }
      })
    }
  }
}
</script>
