<template>
  <div class="app-container">
    <div class="search-con">
      <div class="title">查询条件</div>
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="代码" prop="code">
          <el-input v-model="queryParams.code" placeholder="请输入代码" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="标准合约" prop="standardId">
          <el-select v-model="queryParams.standardId" placeholder="请选择标准合约" clearable>
            <el-option v-for="standard in futureStandardInforList" :key="standard.id" :label="standard.name" :value="standard.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div class="search-btn-con">
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button type="info" icon="Refresh" @click="resetQuery">重置</el-button>
      </div>
    </div>
    <div class="main-con">
      <div class="title-con">
        <div class="title">基本信息</div>
        <div class="operate-btn-con">
          <el-button @click="handleAdd" icon="Plus" v-hasPermi="['invest:futureBaseInfor:add']">新增</el-button>
          <el-button :disabled="multiple" icon="Delete" @click="handleDelete" v-hasPermi="['invest:futureBaseInfor:remove']">删除</el-button>
        </div>
      </div>
      <div class="content-con" v-loading="loading">
        <el-table v-loading="loading" :data="futureBaseInforList" @selection-change="handleSelectionChange" height="calc(100% - 0.65rem)">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column type="index" label="序号" :index="indexMethod" width="50"></el-table-column>
          <el-table-column label="名称" align="center" prop="name" />
          <el-table-column label="代码" width="100" align="center" prop="code" />
          <!-- <el-table-column label="标准合约" align="center" prop="standardName" /> -->
          <el-table-column label="交割月份" align="center" prop="deliveryMonth" width="100"> </el-table-column>
          <el-table-column label="上市基准价" align="center" width="100" prop="referencePrice" />
          <el-table-column label="涨跌副限制(%)" align="center" width="120" prop="priceLimit" />
          <el-table-column label="保证金比例(%)" align="center" width="120" prop="marginRatio" />
          <el-table-column label="最后交易日" align="center" prop="lastTradingDay" width="100"> </el-table-column>
          <el-table-column label="上市交易所" width="200" align="center" prop="exchangeName" />
          <el-table-column label="交易时间" align="center" prop="tradingTimeName" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template v-slot="scope">
              <div class="ctrl-btn d-flex">
                <el-tooltip v-for="item in operateList" :key="item.id" class="item" effect="dark" :content="item.title" placement="top">
                  <el-button :icon="item.icon" :v-hasPermi="item.hasPermi" circle @click="handleOperate(item.id, scope.row)"></el-button>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          small
          background
          layout="total,sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 添加或修改期货基本合约对话框 -->
    <el-dialog :title="title" v-model="open" width="880px" append-to-body>
      <el-form ref="futureBaseInforRef" :model="form" :inline="true" :rules="rules" label-width="120px">
        <el-form-item label="标准合约" prop="standardId">
          <el-select v-model="form.standardId" placeholder="请选择标准合约" @change="handleStandardChange">
            <el-option v-for="standard in futureStandardInforList" :key="standard.id" :label="standard.name" :value="standard.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="交割月份" prop="deliveryMonth">
          <el-date-picker clearable v-model="form.deliveryMonth" type="month" @change="handleMonthChange" value-format="YYYY-MM" placeholder="请选择交割月份">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="代码" prop="code">
          <el-input v-model="form.code" placeholder="请输入代码" />
        </el-form-item>
        <el-form-item label="合约上市日" prop="listingDate">
          <el-date-picker clearable v-model="form.listingDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择合约上市日"> </el-date-picker>
        </el-form-item>
        <el-form-item label="上市基准价" prop="referencePrice">
          <el-input v-model="form.referencePrice" placeholder="请输入上市基准价" />
        </el-form-item>
        <el-form-item label="交易乘数" prop="tradingMultiplier">
          <el-input v-model="form.tradingMultiplier" placeholder="请输入交易乘数" />
        </el-form-item>
        <el-form-item label="涨跌副限制" prop="priceLimit">
          <el-input v-model="form.priceLimit" type="number" placeholder="请输入涨跌副限制">
            <template #suffix>%</template>
          </el-input>
        </el-form-item>
        <el-form-item label="保证金比例" prop="marginRatio">
          <el-input v-model="form.marginRatio" type="number" placeholder="请输入保证金比例">
            <template #suffix>%</template>
          </el-input>
        </el-form-item>
        <el-form-item label="最后交易日" prop="lastTradingDay">
          <el-date-picker clearable v-model="form.lastTradingDay" type="date" value-format="YYYY-MM-DD" placeholder="请选择最后交易日"> </el-date-picker>
        </el-form-item>
        <el-form-item label="最后交割日" prop="deliveryDate">
          <el-date-picker clearable v-model="form.deliveryDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择最后交割日"> </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" style="width: 792px" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template v-if="title !== '查看期货基本合约'" #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 查询记录对话框 -->
    <el-dialog :title="titleSyn" v-model="openSyn" width="500px" append-to-body>
      <el-form ref="CreditQueryRecordAnalysisRef" :model="formSyn" :rules="dailyRules" label-width="100px">
        <el-form-item label="开始日期">
          <el-date-picker clearable v-model="formSyn.start_date" type="date" value-format="YYYY-MM-DD" placeholder="请选择开始日期"> </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker clearable v-model="formSyn.end_date" type="date" value-format="YYYY-MM-DD" placeholder="请选择结束日期"> </el-date-picker>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" icon="Search" @click="handleSynFuture">同步</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="FutureBaseInfor">
import { listFutureBaseInfor, getFutureBaseInfor, delFutureBaseInfor, addFutureBaseInfor, updateFutureBaseInfor } from '@/api/invest/futureBaseInfor'
import { listFutureStandardInfor, getFutureStandardInfor } from '@/api/invest/futureStandardInfor'
import { synFuturesDailyHistory } from '@/api/invest/futuresDailyHistory'

// eslint-disable-next-line no-unused-vars
import { require } from '@/utils/require'
const { proxy } = getCurrentInstance()

const futureBaseInforList = ref([])

const futureStandardInforList = ref([])

const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const standardInforId = ref(null)
const title = ref('')

const openSyn = ref(false)
const titleSyn = ref('')

const operateList = ref([
  { id: 'view', icon: 'View', title: '查看', hasPermi: ['invest:futureBaseInfor:query'] },
  { id: 'edit', icon: 'Edit', title: '修改', hasPermi: ['invest:futureBaseInfor:edit'] },
  { id: 'copy', icon: 'Link', title: '复制', hasPermi: ['health:futureBaseInfor:edit'] },
  { id: 'syn', icon: 'Refresh', title: '同步历史行情', hasPermi: ['invest:stockBaseInfor:edit'] },
  { id: 'delete', icon: 'Delete', title: '删除', hasPermi: ['invest:futureBaseInfor:remove'] }
])
const data = reactive({
  form: {},
  formSyn: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    code: null,
    standardId: null
  },
  queryStandardParams: {
    pageNum: 1,
    pageSize: 100
  },
  rules: {
    name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
    code: [{ required: true, message: '代码不能为空', trigger: 'blur' }],
    standardId: [{ required: true, message: '标准合约不能为空', trigger: 'blur' }],
    listingDate: [{ required: true, message: '合约上市日不能为空', trigger: 'blur' }],
    referencePrice: [{ required: true, message: '上市基准价不能为空', trigger: 'blur' }],
    tradingMultiplier: [{ required: true, message: '交易乘数不能为空', trigger: 'blur' }],
    priceLimit: [{ required: true, message: '涨跌副限制不能为空', trigger: 'blur' }],
    deliveryMonth: [{ required: true, message: '交割月份不能为空', trigger: 'blur' }],
    marginRatio: [{ required: true, message: '保证金比例不能为空', trigger: 'blur' }],
    lastTradingDay: [{ required: true, message: '最后交易日不能为空', trigger: 'blur' }],
    deliveryDate: [{ required: true, message: '最后交割日不能为空', trigger: 'blur' }]
  }
})

const handleOperate = (operate, row) => {
  switch (operate) {
    case 'view':
      handleView(row)
      break
    case 'edit':
      handleUpdate(row)
      break
    case 'delete':
      handleDelete(row)
      break
    case 'copy':
      handleCopy(row)
      break
    case 'syn':
      handleSyn(row)
      break
    default:
      break
  }
}

const { queryParams, queryStandardParams, form, formSyn, rules } = toRefs(data)

const handleStandardChange = (standardId) => {
  standardInforId.value = standardId
  getFutureStandardInfor(standardId).then((response) => {
    form.value.name = response.data.name
    form.value.code = response.data.code
  })
}

const handleMonthChange = (month) => {
  if (standardInforId.value != null) {
    getFutureStandardInfor(standardInforId.value).then((response) => {
      const monthArray = month.split('-')
      const year = monthArray[0].substring(monthArray[0].length - 2)
      form.value.name = response.data.name + year + monthArray[1]
      form.value.code = response.data.code + year + monthArray[1]
    })
  } else {
    proxy.$modal.msgError('请选择标准合约')
  }
}

/** 查询期货品种标准合约列表 */
function getStandardList() {
  loading.value = true
  listFutureStandardInfor(queryStandardParams.value).then((response) => {
    futureStandardInforList.value = response.rows
  })
}

/** 查询期货基本合约列表 */
function getList() {
  loading.value = true
  listFutureBaseInfor(queryParams.value).then((response) => {
    futureBaseInforList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    code: null,
    standardId: null,
    referencePrice: null,
    tradingMultiplier: null,
    priceLimit: null,
    deliveryMonth: null,
    marginRatio: null,
    lastTradingDay: null,
    deliveryDate: null,
    listingDate: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    remark: null
  }
  proxy.resetForm('futureBaseInforRef')
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

// 分页
const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getList()
}

//每页显示条数改变
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  getList()
}
// 序号翻页递增
const indexMethod = (index) => {
  const nowPage = queryParams.value.pageNum //当前第几页，根据组件取值即可
  const nowLimit = queryParams.value.pageSize //当前每页显示几条，根据组件取值即可
  return index + 1 + (nowPage - 1) * nowLimit // 这里可以理解成一个公式
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 查看
const handleView = (row) => {
  title.value = '查看期货基本合约'
  form.value = row
  open.value = true
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加期货基本合约'
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getFutureBaseInfor(_id).then((response) => {
    standardInforId.value = response.data.standardId
    form.value = response.data
    open.value = true
    title.value = '修改期货基本合约'
  })
}
/** 复制按钮操作 */
function handleCopy(row) {
  reset()
  const _id = row.id || ids.value
  getFutureBaseInfor(_id).then((response) => {
    standardInforId.value = response.data.standardId
    form.value = response.data
    form.value.id = null
    open.value = true
    title.value = '复制期货基本合约'
  })
}

/** 同步按钮操作 */
function handleSyn(row) {
  formSyn.value.ts_code = row.tsCode
  formSyn.value.ts_id = row.id
  openSyn.value = true
  titleSyn.value = '同步-' + row.name + '-' + row.code + '-日行情历史数据'
}
/** 查询记录统计按钮操作 */
function handleSynFuture() {
  if (formSyn.value.start_date == undefined) {
    proxy.$modal.msgError('开始日期必须填写')
    return
  }
  if (formSyn.value.end_date == undefined) {
    proxy.$modal.msgError('结束日期必须填写')
    return
  }
  synFuturesDailyHistory(formSyn.value).then((response) => {
    proxy.$modal.msgSuccess('同步成功')
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs.futureBaseInforRef.validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateFutureBaseInfor(form.value).then((response) => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addFutureBaseInfor(form.value).then((response) => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal
    .confirm('是否确认删除选中的数据项？')
    .then(function () {
      return delFutureBaseInfor(_ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'invest/futureBaseInfor/export',
    {
      ...queryParams.value
    },
    `futureBaseInfor_${new Date().getTime()}.xlsx`
  )
}

getList()
getStandardList()
</script>
