
<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card">
        <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
          <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 label="用户" prop="userId"><el-select
            v-model="queryParams.userId"
            placeholder="请选择"
            clearable
            size="small"
          >
            <el-option
              v-for="dict in userIdOptions"
              :key="dict.key"
              :label="dict.value"
              :value="dict.key"
            />
          </el-select>
          </el-form-item> -->
          <el-form-item label="模板类型" prop="type">
            <el-select
              v-model="queryParams.type"
              placeholder="请选择模板类型"
              clearable
              size="small"
            >
              <el-option
                v-for="dict in types"
                :key="dict.v"
                :label="dict.l"
                :value="dict.v"
              />
            </el-select>
          </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
                                v-permisaction="['admin:lineOrderTemplateLogs:add']"
                                type="primary"
                                icon="el-icon-plus"
                                size="mini"
                                @click="handleAdd"
                        >新增
                        </el-button>
                    </el-col> -->
          <el-col :span="1.5">
            <el-button
              v-permisaction="['admin:lineOrderTemplateLogs:edit']"
              type="success"
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
            >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-permisaction="['admin:lineOrderTemplateLogs:remove']"
              type="danger"
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
            >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              :disabled="multiple"
              @click="handleOrders"
            >一键下单
            </el-button>
          </el-col>
        </el-row>

        <el-table ref="table" v-loading="loading" :data="lineOrderTemplateLogsList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            label="id"
            align="center"
            prop="id"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="模板名称"
            align="center"
            prop="name"
            :show-overflow-tooltip="true"
          />
          <!-- <el-table-column label="用户id" align="center" prop="userId" :formatter="userIdFormat" width="100">
            <template slot-scope="scope">
              {{ userIdFormat(scope.row) }}
            </template>
          </el-table-column> -->
          <el-table-column
            label="模板类型"
            align="center"
            prop="type"
            :show-overflow-tooltip="true"
          >
            <template #default="{row}">{{ ['单独添加','批量添加'][row.type-1] }}</template>
          </el-table-column><el-table-column
            label="开关"
            align="center"
            prop="switch"
            :show-overflow-tooltip="true"
          >
            <template #default="{row}">
              <div @click="onSwitch(row)">
                <el-switch
                  :value="row.switch"
                  active-value="1"
                  inactive-value="0"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-popconfirm
                class="delete-popconfirm"
                title="确认要修改吗?"
                confirm-button-text="修改"
                @confirm="handleUpdate(scope.row)"
              >
                <el-button
                  slot="reference"
                  v-permisaction="['admin:lineOrderTemplateLogs:edit']"
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                >修改
                </el-button>
              </el-popconfirm>
              <el-popconfirm
                class="delete-popconfirm"
                title="确认要删除吗?"
                confirm-button-text="删除"
                @confirm="handleDelete(scope.row)"
              >
                <el-button
                  slot="reference"
                  v-permisaction="['admin:lineOrderTemplateLogs:remove']"
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                >删除
                </el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

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

        <!-- 添加或修改对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="1200px" :close-on-click-modal="false">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="模板名称" prop="name">
              <el-input
                v-model="form.name"
                placeholder="模板名称"
              />
            </el-form-item>
            <el-form ref="inForm" :model="inForm" :rules="inRules" label-width="180px" style="height: 500px;overflow: hidden auto;">
              <el-form-item label="交易所" prop="exchange_type">
                <el-select
                  v-model="inForm.exchange_type"
                  style="width: 100%;"
                  placeholder="请选择交易所"
                  clearable
                  filterable
                  size="small"
                  @change="onchangeForm"
                >
                  <el-option
                    v-for="dict in exchangeTypes"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="订单类型" prop="symbol_type">
                <el-radio-group v-model="inForm.symbol_type" @change="onChangeSymbolType">
                  <el-radio :label="1">现货</el-radio>
                  <el-radio :label="2">合约</el-radio>
                </el-radio-group>
              </el-form-item>
              <!-- <el-form-item label="对冲类型" prop="cover_type">
                <el-radio-group v-model="inForm.cover_type">
                  <el-radio :label="1" :disabled="inForm.order_type==2">现货对合约</el-radio>
                  <el-radio :label="2" :disabled="inForm.order_type==1">合约对合约</el-radio>
                  <el-radio :label="3" :disabled="inForm.order_type==1">合约对现货</el-radio>
                </el-radio-group>
              </el-form-item> -->
              <el-form-item label="api用户" prop="api_id">
                <el-row>
                  <el-col :span="21">
                    <el-select
                      v-model="inForm.api_id"
                      multiple
                      style="width: 100%;"
                      placeholder="请选择api用户"
                      clearable
                      filterable
                      size="small"
                    >
                      <el-option
                        v-for="dict in lineUsers"
                        :key="dict.id"
                        :label="dict.apiName"
                        :value="String(dict.id)"
                      />
                    </el-select>
                  </el-col>
                  <el-col :span="3">
                    <el-button size="mini" type="primary" style="margin-left: 10px;" @click="onSelectAll">全选</el-button>
                  </el-col>
                </el-row>
              </el-form-item>
              <el-form-item v-if="form.type===2" label="交易对组" prop="symbol_group_id">
                <el-select
                  v-if="form.type===2"
                  v-model="inForm.symbol_group_id"
                  style="width: 100%;"
                  placeholder="请选择交易对组"
                  clearable
                  filterable
                  size="small"
                >
                  <el-option
                    v-for="dict in comSymbols"
                    :key="dict.id"
                    :label="dict.groupName"
                    :value="dict.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item v-else label="交易对" prop="symbol">
                <el-select
                  v-model="inForm.symbol"
                  style="width: 100%;"
                  placeholder="请选择交易对"
                  clearable
                  filterable
                  remote
                  :remote-method="getSymbol"
                  :loading="searchLoding"
                  size="small"
                  @change="onchangeSymbol"
                >
                  <el-option
                    v-for="dict in comSymbols"
                    :key="dict.id || dict.symbol"
                    :label="dict.symbol"
                    :value="dict.symbol"
                  />
                  <div class="page">
                    <pagination
                      v-show="symbol.total>0"
                      :background="false"
                      :total="symbol.total"
                      layout="prev, pager, next"
                      :page.sync="symbol.pageIndex"
                      :limit.sync="symbol.pageSize"
                      @pagination="getSymbol"
                    />
                  </div>
                </el-select>
              </el-form-item>
              <el-form-item label="购买方向" prop="site">
                <el-radio-group v-model="inForm.site">
                  <el-radio label="BUY">买（多）</el-radio>
                  <el-radio label="SELL" :disabled="inForm.order_type==1">卖（空）</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="购买金额（U）" prop="buy_price">
                <el-input
                  v-model="inForm.buy_price"
                  placeholder="购买金额（U）"
                />
              </el-form-item>
              <el-form-item label="价格模式" prop="price_pattern">
                <el-radio-group v-model="inForm.price_pattern" @change="onchangePattern">
                  <el-radio label="percentage">百分比</el-radio>
                  <el-radio label="mixture" :disabled="form.type===2">主单实价委托百分比</el-radio>
                  <el-radio label="aicoin" :disabled="form.type===2">aiCoin买入点</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item v-if="inForm.price_pattern === 'percentage'" label="下单百分比" prop="price">
                <el-input
                  v-model="inForm.price"
                  placeholder="下单百分比"
                />
              </el-form-item>
              <el-row v-else type="flex">
                <el-col :span="12">
                  <el-form-item label="下单价(实际价格)" prop="price">
                    <el-input
                      v-model="inForm.price"
                      placeholder="下单价(实际价格)"
                    >
                      <template #prepend>
                        <el-select v-if="inForm.price_pattern === 'aicoin'" v-model="aicoinPrice" placeholder="请选择" style="width: 150px;" @change="onchangeAicoin">
                          <el-option v-for="o in options" :key="o.label" :label="o.label" :value="aicoins[o.value]">
                            <span style="float: left">{{ o.label }}</span>
                            <span style="float: right">{{ aicoins[o.value] || 0 }}</span>
                          </el-option>
                        </el-select>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item label="计算百分比">
                    <el-inputNumber v-model="percenter" controls-position="right" :min="0" style="width: 100px;" />
                  </el-form-item>
                </el-col>
                <el-col :span="5">
                  <el-button type="primary" style="margin-left: 50px;" @click="onCalc">计算</el-button>
                </el-col>
              </el-row>
              <!-- <el-form-item label="止盈百分比" prop="profit">
                <el-input
                  v-model="inForm.profit"
                  placeholder="止盈百分比"
                />
              </el-form-item>
              <el-form-item label="亏损百分比" prop="stop_price">
                <el-input
                  v-model="inForm.stop_price"
                  placeholder="亏损百分比"
                />
              </el-form-item>
              <el-form-item label="对冲百分比" prop="cover_rate">
                <el-input
                  v-model="inForm.cover_rate"
                  placeholder="对冲百分比"
                />
              </el-form-item>
              <el-form-item label="加仓后盈利比例" prop="profit_rate">
                <el-input
                  v-model="inForm.profit_rate"
                  placeholder="加仓后盈利比例"
                />
              </el-form-item>
              <el-form-item label="对冲平仓最大次数" prop="hedge_close_count">
                <el-input
                  v-model.number="inForm.hedge_close_count"
                  type="number"
                  placeholder="对冲平仓最大次数"
                />
              </el-form-item>
              <el-form-item label="随机累加百分比" prop="hedge_trigger_percent">
                <el-row :gutter="20">
                  <el-col :span="11"><el-input v-model.number="inForm.hedge_trigger_percent" type="number" placeholder="最小值"><template #append>最小值</template></el-input></el-col>
                  <el-col :span="11"><el-input v-model.number="inForm.hedge_trigger_percent_max" type="number" placeholder="最大值"><template #append>最大值</template></el-input></el-col>
                </el-row>
              </el-form-item> -->
              <el-form-item label="主单类型" prop="main_order_type">
                <el-radio-group v-model="inForm.main_order_type">
                  <el-radio label="LIMIT">限价</el-radio>
                  <el-radio label="MARKET">市价</el-radio>
                </el-radio-group>
              </el-form-item>
              <!-- <el-form-item label="对冲单下单类型" prop="hedge_order_type">
                <el-radio-group v-model="inForm.hedge_order_type">
                  <el-radio label="LIMIT">限价</el-radio>
                  <el-radio label="MARKET">市价</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="加仓主单类型" prop="add_position_main_type">
                <el-radio-group v-model="inForm.add_position_main_type">
                  <el-radio label="LIMIT">限价</el-radio>
                  <el-radio label="MARKET">市价</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="加仓对冲单类型" prop="add_position_hedge_type">
                <el-radio-group v-model="inForm.add_position_hedge_type">
                  <el-radio label="LIMIT">限价</el-radio>
                  <el-radio label="MARKET">市价</el-radio>
                </el-radio-group>
              </el-form-item> -->
              <el-form-item label="对标价类型" prop="price_type">
                <el-radio-group v-model="inForm.price_type">
                  <el-radio label="new">最新价</el-radio>
                  <el-radio label="mixture" :disabled="form.type===2">标记价</el-radio>
                  <el-radio label="aicoin" :disabled="form.type===2">aicoin</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="订单过期时间" prop="profit_rate">
                <el-input
                  v-model.number="inForm.expire_hour"
                  class="hour"
                  type="number"
                  placeholder="订单过期时间"
                >
                  <template slot="append">小时</template>
                </el-input>
              </el-form-item>
              <el-form-item v-if="form.type===2" label="批量下单次数" prop="order_num">
                <el-input
                  v-model.number="inForm.order_num"
                  min="1"
                  type="number"
                  placeholder="批量下单次数"
                />
              </el-form-item>
              <el-form-item v-if="form.type===2" label="执行类型" prop="script">
                <el-radio-group v-model="inForm.script">
                  <el-radio label="1"><span>脚本执行</span></el-radio>
                  <el-radio label="0">直接执行</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="主单减仓价格百分比" prop="reduce_price">
                <el-input v-model.number="inForm.reduce_price" type="number" placeholder="主单减仓价格百分比" />
              </el-form-item>
              <el-form-item label="主单减仓数量百分比" prop="reduce_num">
                <el-input v-model.number="inForm.reduce_num" type="number" placeholder="主单减仓数量百分比" />
              </el-form-item>
              <el-form-item label="主单减仓后止盈价百分比" prop="reduce_take_profit">
                <el-input v-model.number="inForm.reduce_take_profit" type="number" placeholder="主单减仓后止盈价百分比" />
              </el-form-item>
              <el-form-item label="主单减仓后止损价百分比" prop="reduce_stop_price">
                <el-input v-model.number="inForm.reduce_stop_price" type="number" placeholder="主单减仓后止损价百分比" />
              </el-form-item>
              <el-row>
                <el-col :span="4"><el-form-item label="主单加仓配置" /></el-col>
                <el-col :span="20"><el-button type="primary" size="mini" @click="onAddExt(0)">新增</el-button></el-col>
              </el-row>
              <div v-for="(item,index) in inForm.ext" :key="index" class="exts">
                <el-row :gutter="20">
                  <el-col :span="5">
                    <div style="margin-bottom: 8px;">加仓类型</div>
                    <el-radio-group v-model="item.addPositionOrderType" size="mini">
                      <el-radio label="LIMIT">限价</el-radio>
                      <el-radio label="MARKET">市价</el-radio>
                    </el-radio-group>
                  </el-col>
                  <el-col :span="5">
                    <div style="margin-bottom: 8px;">加仓方式</div>
                    <el-radio-group v-model="item.addPositionType" size="mini">
                      <el-radio :label="1">百分比</el-radio>
                      <el-radio :label="0">实际金额</el-radio>
                    </el-radio-group>
                  </el-col>
                  <el-col :span="5">加仓数值<el-input v-model.number="item.addPositionVal" size="mini" type="number" placeholder="加仓数值" /></el-col>
                  <el-col :span="5">加仓价格百分比<el-input v-model.number="item.addPositionPriceRatio" size="mini" type="number" placeholder="加仓价格百分比" /></el-col>
                  <el-col :span="4">加仓后止盈百分比<el-input v-model.number="item.takeProfitRatio" size="mini" type="number" placeholder="止盈百分比" /></el-col>
                </el-row>
                <el-row :gutter="20" style="margin-top: 10px;">
                  <el-col :span="5">减仓价格百分比<el-input v-model.number="item.reducePriceRatio" size="mini" type="number" placeholder="减仓价格百分比" /></el-col>
                  <el-col :span="5">减仓数量百分比<el-input v-model.number="item.reduceNumRatio" size="mini" type="number" placeholder="减仓数量百分比" /></el-col>
                  <el-col :span="5">减仓后止盈百分比<el-input v-model.number="item.reduceTakeProfitRatio" size="mini" type="number" placeholder="减仓后止盈百分比" /></el-col>
                  <el-col :span="5">减仓后止损百分比<el-input v-model.number="item.reduceStopLossRatio" size="mini" type="number" placeholder="减仓后止损百分比" /></el-col>
                  <el-col :span="4"><div style="margin-bottom: 14px;" /><el-button size="mini" type="danger" @click="onAddExt(1,index)">删除</el-button></el-col>
                </el-row>
              </div>
              <!-- <el-form-item label="是否保存模板" prop="save_template">
                <el-radio-group v-model="inForm.save_template">
                  <el-radio label="0">否</el-radio>
                  <el-radio label="1">保存并下单</el-radio>
                  <el-radio label="2">仅保存模板</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="模板名称" prop="template_name">
                <el-input
                  v-model="inForm.template_name"
                  placeholder="模板名称"
                />
              </el-form-item> -->

            </el-form>
            <el-form-item label="开关" prop="switch">
              <el-radio-group v-model="form.switch">
                <el-radio label="0">关</el-radio>
                <el-radio label="1">开</el-radio>
              </el-radio-group>
            </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-card>
    </template>
  </BasicLayout>
</template>

<script>
import { listLineSymbol, getSameSymbol } from '@/api/admin/line-symbol'
import { addLineOrderTemplateLogs, delLineOrderTemplateLogs, getLineOrderTemplateLogs, listLineOrderTemplateLogs, updateLineOrderTemplateLogs } from '@/api/admin/line-order-template-logs'
import { listLineSymbolGroup } from '@/api/admin/line-symbol-group'
import { getMainUser, listLineApiUser } from '@/api/admin/line-api-user'
import { aicoinSymbol, quickAddPreOrder } from '@/api/admin/line-pre-order'
export default {
  name: 'LineOrderTemplateLogs',
  components: {
  },
  data() {
    return {
      types: [
        { v: 1, l: '单独添加' },
        { v: 2, l: '批量添加' }
      ],
      options: [
        { label: '买入点1', value: 'buyPoint1' },
        { label: '买入点2', value: 'buyPoint2' },
        { label: '买入点3', value: 'buyPoint3' },
        { label: '卖出点1', value: 'sellPoint1' },
        { label: '卖出点2', value: 'sellPoint2' },
        { label: '卖出点3', value: 'sellPoint3' }
      ],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      isEdit: false,
      // 类型数据字典
      typeOptions: [],
      lineOrderTemplateLogsList: [],

      // 关系表类型
      userIdOptions: [],

      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
        name: undefined,
        userId: undefined,
        type: undefined,
        idOrder: 'desc'
      },
      // 表单参数
      form: {
      },
      // 表单校验
      rules: {
        name: [{ required: true, message: '模板名称不能为空', trigger: 'blur' }],
        userId: [{ required: true, message: '用户id不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '模板类型:1=单独添加;2=批量添加不能为空', trigger: 'blur' }]
      },
      symbol: {
        symbolList: [],
        total: 0,
        pageIndex: 1,
        pageSize: 6
      },
      percenter: undefined,
      symbolGroups: [],
      inRules: {
        exchange_type: [{ required: true, message: '交易所不能为空', trigger: 'blur' }],
        api_id: [{ required: true, message: 'api用户不能为空', trigger: 'blur' }],
        symbol: [{ required: true, message: '交易对不能为空', trigger: 'blur' }],
        symbol_group_id: [{ required: true, message: '交易对组不能为空', trigger: 'blur' }],
        quote_symbol: [{ required: true, message: '计较货币不能为空', trigger: 'blur' }],
        order_sn: [{ required: true, message: '订单号不能为空', trigger: 'blur' }]
      },
      inForm: {},
      searchLoding: false,
      lineUsers: [],
      lineTotal: 0,
      exchangeTypes: [],
      aicoins: {},
      aicoinPrice: undefined
    }
  },
  computed: {
    comSymbols() {
      return this.form.type === 2 ? this.symbolGroups : this.symbol.symbolList
    }
  },
  created() {
    this.getList()
    // this.getLineApiUserItems()
    this.getSymbolGroup()
    // 获取交易所字典数据
    this.getDicts('exchange_type').then(response => {
      this.exchangeTypes = response.data
    })
  },
  methods: {
    onChangeSymbolType() {
      if (this.inForm.symbol_type === 1) {
        this.inForm.cover_type = 0
      } else {
        this.inForm.cover_type = 0
      }
      this.inForm.symbol_group_id = undefined
      this.inForm.symbol = undefined
      this.getSymbol({})
      this.getSymbolGroup(this.inForm.symbol_type, this.inForm.exchange_type)
    },
    onchangePattern(init = true) {
      if (this.inForm.price_pattern === 'aicoin') {
        init && (this.inForm.price = '')
        init && (this.inForm.price_type = 'aicoin')
        this.aicoinPrice = undefined
        if (this.inForm.symbol) {
          aicoinSymbol({ symbol: this.inForm.symbol, symbolType: this.inForm.symbol_type }).then(res => {
            this.aicoins = res.data
          })
        }
      } else {
        this.inForm.price_type = this.inForm.price_pattern === 'percentage' ? 'new' : this.inForm.price_pattern
        // this.inForm.sign_price_type = newValue
      }
    },
    onchangeSymbol() {
      if (this.inForm.price_pattern === 'aicoin') {
        aicoinSymbol({ symbol: this.inForm.symbol, symbolType: this.inForm.symbol_type }).then(res => {
          this.aicoinPrice = undefined
          this.inForm.price = undefined
          this.aicoins = res.data
        })
      }
    },
    onchangeAicoin() {
      this.inForm.price = this.aicoinPrice
    },
    onAddExt(type, index) {
      if (type === 0) {
        this.inForm.ext.push({
          reducePriceRatio: undefined,
          reduceNumRatio: undefined,
          reduceTakeProfitRatio: undefined,
          reduceStopLossRatio: undefined,

          takeProfitRatio: undefined,
          addPositionPriceRatio: undefined,
          addPositionOrderType: 'LIMIT',
          addPositionType: 1,
          addPositionVal: undefined
        })
        return false
      }
      this.inForm.ext.splice(index, 1)
    },
    onchangeForm() {
      this.getListLineApiUser(this.inForm.exchange_type)
      this.getSymbol({}, this.inForm.symbol_type, this.inForm.exchange_type)
      this.getSymbolGroup(this.inForm.symbol_type, this.inForm.exchange_type)
    },
    onSelectAll() {
      if (this.inForm.api_id && this.inForm.api_id.length > 0) {
        this.inForm.api_id = []
        return false
      }
      this.inForm.api_id = this.userIdOptions.map(item => item.key)
    },
    // 获取杠杆api用户
    getListLineApiUser(exchangeType) {
      listLineApiUser({ pageIndex: 1, pageSize: 999, exchangeType: exchangeType || this.inForm.exchange_type }).then(response => {
        this.lineUsers = response.data.list
        this.lineTotal = response.data.count
      })
    },
    // 交易对列表
    getSymbol(e, type, exchangeType) {
      this.searchLoding = true
      const { pageIndex } = this.symbol
      const symbol = typeof e === 'object' ? '' : e
      const apiCall = this.form.type === 1 && ([1, 3].includes(this.inForm.cover_type)) ? getSameSymbol : listLineSymbol
      apiCall({ pageIndex, pageSize: 6, type: type || this.inForm.symbol_type, symbol, exchangeType: exchangeType || this.inForm.exchange_type }).then(res => {
        this.symbol.total = res.data.count
        this.symbol.symbolList = res.data.list
      }).finally(() => {
        this.searchLoding = false
      })
    },
    // 获取交易对组
    getSymbolGroup(type = 2, exchangeType) {
      listLineSymbolGroup({ pageIndex: 1, pageSize: 999, beginTime: undefined, endTime: undefined, type, exchangeType: exchangeType || this.inForm.exchange_type }).then(res => {
        this.symbolGroups = res.data.list
      })
    },
    onCalc() {
      if (!this.inForm.price || !this.percenter) {
        return 0
      }
      let res
      if (this.inForm.site === 'BUY') {
        res = (1 - (this.percenter / 100)) * Number(this.inForm.price)
      } else {
        res = (1 + (this.percenter / 100)) * Number(this.inForm.price)
      }
      const [num, decimal] = String(res).split('.')
      console.log(num, decimal, '?')
      if (decimal) {
        this.inForm.price = decimal.length > 4 ? `${num}.${decimal.substring(0, 4)}` : res
      } else {
        this.inForm.price = res
      }
    },
    /** 查询参数列表 */
    getList() {
      this.loading = true
      listLineOrderTemplateLogs(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.lineOrderTemplateLogsList = response.data.list
        this.total = response.data.count
        this.loading = false
      }
      )
    },
    onSwitch(row) {
      const s = row.switch === '1' ? '0' : '1'
      updateLineOrderTemplateLogs({ ...row, switch: s }).then(response => {
        if (response.code === 200) {
          this.msgSuccess(response.msg)
          this.getList()
        } else {
          this.msgError(response.msg)
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {

        id: undefined,
        name: undefined,
        userId: undefined,
        params: undefined,
        type: 1,
        switch: '0'
      }
      this.resetForm('form')
    },
    getImgList: function() {
      this.form[this.fileIndex] = this.$refs['fileChoose'].resultList[0].fullUrl
    },
    fileClose: function() {
      this.fileOpen = false
    },
    userIdFormat(row) {
      return this.selectItemsLabel(this.userIdOptions, row.userId)
    },
    // 关系
    getLineApiUserItems() {
      this.getItems(getMainUser, undefined).then(res => {
        this.userIdOptions = this.setItems(res, 'id', 'apiName')
      })
    },
    // 文件
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageIndex = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加委托下单模板'
      this.isEdit = false
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id =
                row.id || this.ids
      getLineOrderTemplateLogs(id).then(response => {
        this.form = response.data
        const x = JSON.parse(response.data.params)
        this.inForm = { ...x, api_id: x.api_id.split(','), symbol_group_id: x.symbol_group_id ? Number(x.symbol_group_id) : undefined }
        // this.getSymbol(undefined, x.symbol_type, x.exchange_type)
        this.onchangePattern(false)
        this.getListLineApiUser()
        this.form.type === 2 && this.getSymbolGroup(this.inForm.symbol_type)
        this.open = true
        this.title = '修改委托下单模板'
        this.isEdit = true
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.inForm.price = this.inForm.price ? String(this.inForm.price) : ''
          if (this.form.id !== undefined) {
            this.$refs['inForm'].validate(valided => {
              if (!valided) return false
              const params = JSON.stringify({
                ...this.inForm,
                symbol_group_id: String(this.inForm.symbol_group_id),
                api_id: this.inForm.api_id.toString(),
                hedge_trigger_percent: Number(this.inForm.hedge_trigger_percent),
                hedge_trigger_percent_max: Number(this.inForm.hedge_trigger_percent_max)
              })
              updateLineOrderTemplateLogs({ ...this.form, params }).then(response => {
                if (response.code === 200) {
                  this.msgSuccess(response.msg)
                  this.open = false
                  this.getList()
                } else {
                  this.msgError(response.msg)
                }
              })
            })
          } else {
            addLineOrderTemplateLogs({ ...this.inForm, symbol_group_id: String(this.inForm.symbol_group_id), api_id: this.inForm.api_id.toString() }).then(response => {
              if (response.code === 200) {
                this.msgSuccess(response.msg)
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      var Ids = (row.id && [row.id]) || this.ids

      this.$confirm('是否确认删除id为"' + Ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delLineOrderTemplateLogs({ 'ids': Ids })
      }).then((response) => {
        if (response.code === 200) {
          this.msgSuccess(response.msg)
          this.open = false
          this.getList()
        } else {
          this.msgError(response.msg)
        }
      }).catch(function() {
      })
    },
    handleOrders() {
      const Ids = this.ids
      this.$confirm('是否确认一键下单id为"' + Ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return quickAddPreOrder({ ids: Ids.toString() })
      }).then((response) => {
        if (response.code === 200) {
          this.ids = []
          this.$refs.table?.clearSelection()
          this.msgSuccess(response.msg)
        } else {
          this.msgError(response.msg)
        }
      }).catch(function() {
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.hour{
  ::v-deep.el-input__inner{
    line-height: 1;
  }
}
.page{
  .pagination-container{
    padding: 0 !important;
    margin-top: 0;
    margin-bottom: 0;
    text-align: center;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  ::v-deep.el-pagination{
    width: 100%;
  }
}
.exts{
  font-size: 13px;
  margin-bottom: 20px;
  border: 1px solid #ebebeb;
  padding: 10px;
  border-radius: 8px;
}
</style>
