<template>
  <div class="app-container">
    <!-- 搜索条件 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="股票代码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入股票代码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="股票名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入股票名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="交易日期" prop="tradeDate">
        <el-date-picker
          v-model="queryParams.tradeDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择交易日期"
          clearable
        />
      </el-form-item>
      <el-form-item label="涨跌幅" prop="changeRate">
        <el-input
          v-model="queryParams.changeRate"
          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-button type="warning" icon="el-icon-upload2" size="mini" @click="handleImport">导入</el-button>
        <el-button type="info" icon="el-icon-s-operation" size="mini" @click="handleAnalyze">分析</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['stocksystem:newstocks:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['stocksystem:newstocks:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['stocksystem:newstocks:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['stocksystem:newstocks:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据列表 -->
    <el-table
      v-loading="loading"
      :data="stocksList"
      @selection-change="handleSelectionChange"
      border
      fit
      highlight-current-row
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="股票代码" align="center" prop="code" />
      <el-table-column label="股票名称" align="center" prop="name" />
      <el-table-column label="交易日期" align="center" prop="tradeDate" width="120" />
      <el-table-column label="开盘价" align="center" prop="open" />
      <el-table-column label="收盘价" align="center" prop="close" />
      <el-table-column label="涨跌幅" align="center" prop="changeRate" />
      <el-table-column label="成交量" align="center" prop="volume" />
      <el-table-column label="成交额" align="center" prop="amount" />
      <el-table-column label="总市值" align="center" prop="totalMarketValue" />
      <el-table-column 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)"
            v-hasPermi="['stocksystem:newstocks:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['stocksystem:newstocks:remove']"
          >删除</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-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="{ Authorization: getToken() }"
        :action="upload.url"
        :data="upload.data"
        :auto-upload="false"
        :on-change="handleFileChange"
        :on-success="handleSuccess"
        :on-error="handleError"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <el-checkbox v-model="upload.updateSupport">是否更新已存在的数据</el-checkbox>
        </div>
      </el-upload>
      <el-form :model="upload" style="margin-top: 15px;">
        <el-form-item label="交易日期" prop="tradeDate">
          <el-date-picker
            v-model="upload.tradeDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择交易日期"
            style="width: 100%;"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确定</el-button>
        <el-button @click="upload.open = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 分析结果对话框 -->
    <el-dialog :title="'分析结果'" :visible.sync="analyzeDialogVisible" width="800px">
      <el-form :model="analyzeResult" label-width="120px">
        <el-form-item label="总股票数">
          <el-input v-model="analyzeResult.totalStocks" disabled />
        </el-form-item>
        <el-form-item label="平均涨跌幅">
          <el-input v-model="analyzeResult.avgChangeRate" disabled />
        </el-form-item>
        <el-form-item label="上涨股票数">
          <el-input v-model="analyzeResult.upCount" disabled />
        </el-form-item>
        <el-form-item label="下跌股票数">
          <el-input v-model="analyzeResult.downCount" disabled />
        </el-form-item>
        <el-form-item label="平盘股票数">
          <el-input v-model="analyzeResult.flatCount" disabled />
        </el-form-item>
        <el-form-item label="上涨比例">
          <el-input v-model="analyzeResult.upRatio" disabled />
        </el-form-item>
        <el-form-item label="下跌比例">
          <el-input v-model="analyzeResult.downRatio" disabled />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="analyzeDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 新增/修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="股票代码" prop="code">
          <el-input v-model="form.code" placeholder="请输入股票代码" />
        </el-form-item>
        <el-form-item label="股票名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入股票名称" />
        </el-form-item>
        <el-form-item label="交易日期" prop="tradeDate">
          <el-date-picker
            v-model="form.tradeDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择交易日期"
          />
        </el-form-item>
        <el-form-item label="开盘价" prop="open">
          <el-input v-model="form.open" placeholder="请输入开盘价" />
        </el-form-item>
        <el-form-item label="收盘价" prop="close">
          <el-input v-model="form.close" placeholder="请输入收盘价" />
        </el-form-item>
        <el-form-item label="涨跌幅" prop="changeRate">
          <el-input v-model="form.changeRate" placeholder="请输入涨跌幅" />
        </el-form-item>
        <el-form-item label="成交量" prop="volume">
          <el-input v-model="form.volume" placeholder="请输入成交量" />
        </el-form-item>
        <el-form-item label="成交额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入成交额" />
        </el-form-item>
        <el-form-item label="总市值" prop="totalMarketValue">
          <el-input v-model="form.totalMarketValue" placeholder="请输入总市值" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="open = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { parseTime } from '@/utils/ruoyi'
import request from '@/utils/request'
import newstocksApi from '@/api/stocksystem/newstocks'

export default {
  name: 'NewStocks',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 行情数据表格数据
      stocksList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 分析结果对话框
      analyzeDialogVisible: false,
      // 分析结果
      analyzeResult: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        name: null,
        tradeDate: null,
        changeRate: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: [
          { required: true, message: '股票代码不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '股票名称不能为空', trigger: 'blur' }
        ],
        tradeDate: [
          { required: true, message: '交易日期不能为空', trigger: 'blur' }
        ],
        close: [
          { required: true, message: '收盘价不能为空', trigger: 'blur' }
        ]
      },
      // 上传参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: '',
        // 是否更新已存在的数据
        updateSupport: 0,
        // 交易日期
        tradeDate: new Date().toISOString().split('T')[0],
        // 查询参数
        url: '/stocksystem/newstocks/importData'
      },
      // 文件上传
      fileList: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 获取token */
    getToken() {
      return getToken()
    },
    /** 消息提示 */
    msgSuccess(message) {
      this.$message({ showClose: true, message: message, type: "success" })
    },
    /** 错误提示 */
    msgError(message) {
      this.$message({ showClose: true, message: message, type: "error" })
    },
    /** 下载文件 */
    download(fileName) {
      window.location.href = process.env.VUE_APP_BASE_API + "/common/download?fileName=" + encodeURI(fileName) + "&delete=" + true
    },
    /** 查询行情数据列表 */
    getList() {
      this.loading = true
      newstocksApi.listNewStocksB(this.queryParams).then(response => {
        this.stocksList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.resetForm()
    },
    // 表单重置
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields()
      }
      this.form = {}
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.resetForm()
      this.open = true
      this.title = '新增行情数据'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.resetForm()
      const id = row.id || this.ids
      newstocksApi.getNewStocks(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改行情数据'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            newstocksApi.updateNewStocks(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              }
            })
          } else {
            newstocksApi.addNewStocks(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除行情数据编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(function() {
        return newstocksApi.deleteNewStocks(ids)
      }).then(response => {
        if (response.code === 200) {
          this.msgSuccess('删除成功')
          this.getList()
        }
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有行情数据数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return newstocksApi.exportNewStocks(queryParams)
      }).then(response => {
        this.download(response.msg)
      }).catch(() => {})
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '导入行情数据'
      this.upload.open = true
    },
    /** 文件上传前处理 */
    handleFileChange(file) {
      this.fileList = [file]
    },
    /** 文件上传提交 */
    submitFileForm() {
      if (this.fileList.length === 0) {
        this.msgError('请选择文件')
        return
      }
      const formData = new FormData()
      formData.append('file', this.fileList[0].raw)
      formData.append('updateSupport', this.upload.updateSupport ? 1 : 0)
      formData.append('tradeDate', this.upload.tradeDate)
      this.upload.open = false
      this.loading = true
      // 上传文件
      request({
        url: this.upload.url,
        method: 'post',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data',
          'Authorization': getToken()
        }
      }).then(response => {
        this.loading = false
        this.msgSuccess(response.msg)
        this.getList()
      }).catch(() => {
        this.loading = false
      })
    },
    /** 文件上传成功处理 */
    handleSuccess(response, file, fileList) {
      this.upload.open = false
      this.loading = false
      this.msgSuccess('导入成功')
      this.getList()
    },
    /** 文件上传失败处理 */
    handleError() {
      this.upload.open = false
      this.loading = false
      this.msgError('导入失败')
    },
    /** 分析按钮操作 */
    handleAnalyze() {
      newstocksApi.analyzeNewStocks(this.queryParams).then(response => {
        this.analyzeResult = response.data
        this.analyzeDialogVisible = true
      })
    },
    /** 表格选中操作 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 15px;
}

.mb8 {
  margin-bottom: 8px;
}

.small-padding {
  padding: 0 5px;
}

.fixed-width {
  width: 150px;
}
</style>
