<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="handleCopy(scope.row)"
              >
                <el-button
                  slot="reference"
                  v-permisaction="['admin:lineOrderTemplateLogs:copy']"
                  size="mini"
                  type="text"
                  icon="el-icon-document-copy"
                >复制
                </el-button>
              </el-popconfirm>
              <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="1300px" :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="api用户类型" prop="api_id_type">
                <el-radio-group v-model="inForm.api_id_type" @change="apiIdTypeChange">
                  <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 v-if="inForm.api_id_type === 1" 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="inForm.api_id_type === 2" label="api用户组" prop="api_user_group_id">
                <el-select
                  v-model="inForm.api_user_group_id"
                  size="small"
                  clearable
                  filterable
                  @change="apiUserGroupChange"
                >
                  <el-option
                    v-for="(op, index) in apiUserGroupList"
                    :key="'op_user_group' + index"
                    :label="op.label"
                    :value="op.id"
                    :disabled="op.disabled"
                  />
                </el-select>
              </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="策略类型">
                <el-radio-group v-model="inForm.strategy_template_type" @input="changeStrategyTemplateType">
                  <el-radio
                    v-for="(item, index) in strategyTemplateTypeOptions"
                    :key="'strategyTemplateType' + index"
                    :label="item.value"
                    :disabled="item.value === 1"
                  >{{ item.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item v-if="inForm.strategy_template_type === 1" label="策略模板">
                <el-select
                  v-model="inForm.strategy_template_id"
                  style="width: 100%;"
                  placeholder="请选择策略"
                  clearable
                  filterable
                  :remote-method="queryStrategyTemplate"
                  :loading="searchLoding"
                  remote
                  size="small"
                >
                  <el-option
                    v-for="dict in strategyTemplateOptions"
                    :key="'strategyTemplateId' + dict.id"
                    :label="dict.name"
                    :value="dict.id"
                  />
                  <div class="page">
                    <pagination
                      v-show="strategyTemplatePagition.total > 0"
                      :background="false"
                      :total="strategyTemplatePagition.total"
                      layout="prev, pager, next"
                      :page.sync="strategyTemplatePagition.pageIndex"
                      :limit.sync="strategyTemplatePagition.pageSize"
                      @pagination="queryStrategyTemplate"
                    />
                  </div>
                </el-select>
              </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="14">
                  <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 JSON.stringify(aicoins) !== '{}' ? 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>
                      <template #append>
                        <span v-if="inForm.price_pattern !== 'percentage'">{{ comPrice }}</span>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="5">
                  <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="inForm.price_pattern === 'mixture' ? '止盈价格' : '止盈百分比'" prop="profit">
                <el-input v-model="inForm.profit" :placeholder="inForm.price_pattern === 'mixture' ? '止盈价格' : '止盈百分比'">
                  <template v-if="inForm.price_pattern === 'mixture'" slot="append">{{ comTakePrice }}</template>
                </el-input>
              </el-form-item>
              <el-form-item :label="inForm.price_pattern === 'mixture' ? '止损价格' : '止损价百分比'" prop="stop_loss">
                <el-input
                  v-model="inForm.stop_loss"
                  min="0"
                  type="number"
                  :placeholder="inForm.price_pattern === 'mixture' ? '止损价格' : '止损价百分比'"
                />
              </el-form-item>
              <el-form-item label="止盈数量百分比" prop="profit_num_ratio">
                <el-input v-model="inForm.profit_num_ratio" placeholder="止盈数量百分比" />
              </el-form-item>
              <el-form-item label="第二止盈价百分比" prop="profit_tp_tp_price_ratio">
                <el-input v-model="inForm.profit_tp_tp_price_ratio" placeholder="第二止盈价百分比" />
              </el-form-item>
              <el-form-item label="第二止损价百分比" prop="profit_tp_sl_price_ratio">
                <el-input v-model="inForm.profit_tp_sl_price_ratio" 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="减仓策略">
                <el-select
                  v-model="inForm.reduce_strategy_id"
                  style="width: 100%;"
                  placeholder="请选择策略"
                  clearable
                  filterable
                  :remote-method="queryReduceStrategy"
                  :loading="searchLoding"
                  remote
                  size="small"
                >
                  <el-option
                    v-for="dict in reduceStrategyPagition.reduceStrategyList"
                    :key="'reduce_stratefy.' + dict.id"
                    :label="dict.name"
                    :value="dict.id"
                  />
                  <div class="page">
                    <pagination
                      v-show="reduceStrategyPagition.total > 0"
                      :background="false"
                      :total="reduceStrategyPagition.total"
                      layout="prev, pager, next"
                      :page.sync="reduceStrategyPagition.pageIndex"
                      :limit.sync="reduceStrategyPagition.pageSize"
                      @pagination="queryReduceStrategy"
                    />
                  </div>
                </el-select>
              </el-form-item>
              <el-form-item :label="inForm.price_pattern === 'mixture' ? '主单亏损价格' : '主单亏损百分比'" prop="reduce_price">
                <el-input
                  v-model="inForm.reduce_price"
                  type="number"
                  :placeholder="inForm.price_pattern === 'mixture' ? '主单亏损价格' : '主单亏损百分比'"
                >
                  <template v-if="inForm.price_pattern === 'mixture'" slot="append">{{ comReducePrice }}</template>
                </el-input>
              </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="主单减仓后止盈价百分比">
                  <template v-if="form.type === 1" #append>{{ re_take_profit_ratio }}</template>
                </el-input>
              </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="2"><el-button type="primary" size="mini" @click="onAddExt(0)">新增加仓</el-button></el-col>
                <el-col :span="2"><el-button type="primary" size="mini" @click="onAddExt(2)">新增减仓</el-button></el-col>
                <el-col v-if="form.type === 1" :span="2"><el-button
                  type="primary"
                  size="mini"
                  :disabled="inForm.ext && inForm.ext.length === 0"
                  @click="onCalculate"
                >计算</el-button></el-col>
              </el-row>
              <el-form ref="extForm" :model="inForm" label-position="top" :rules="inRules" class="ext-form">
                <div v-for="(item, index) in inForm.ext" :key="index" class="exts">
                  <el-row v-if="item.addType === 1" :gutter="20" style="margin-bottom: 20px;">
                    <el-col :span="5">
                      <div style="margin-bottom: 8px;">{{ item.addType === 1 ? '加仓类型' : '减仓类型' }}</div>
                      <el-radio-group v-model="item.orderType" 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;">{{ item.addType === 1 ? '加仓方式' : '减仓方式' }}</div>
                      <el-radio-group v-model="item.addPositionType" size="mini">
                        <el-radio :label="1">百分比</el-radio>
                        <el-radio :label="2" :disabled="item.addType === 2">实际金额</el-radio>
                      </el-radio-group>
                    </el-col>

                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="3">
                      <!-- {{ item.addType === 1 ? '加仓下跌百分比' : '减仓下跌百分比' }} -->
                      <el-form-item
                        :prop="'ext.' + index + '.priceRatio'"
                        :rules="inRules.priceRatio"
                        class="ext-form-item"
                        :label="item.addType === 1 ? '加仓下跌百分比' : '减仓下跌百分比'"
                      >
                        <el-input
                          v-model.number="item.priceRatio"
                          min="0"
                          size="mini"
                          type="number"
                          :placeholder="item.addType === 1 ? '加仓下跌百分比' : '减仓下跌百分比'"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="3">
                      <!-- {{ item.addType === 1 ? '加仓数值' : '减仓百分比' }} -->
                      <el-form-item
                        :prop="'ext.' + index + '.addPositionVal'"
                        :label="item.addType === 1 ? '加仓数值' : '减仓百分比'"
                        :rules="inRules.addPositionVal"
                        class="ext-form-item"
                      >
                        <el-input
                          v-model.number="item.addPositionVal"
                          min="0"
                          size="mini"
                          type="number"
                          :placeholder="item.addType === 1 ? '加仓数值' : '减仓百分比'"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <!-- <span>止盈/止损百分比</span> -->
                      <el-form-item
                        label="止盈/止损百分比"
                        :prop="'ext.' + index + '.takeProfitRatio'"
                        :rules="[{ validator: validateTakeProfitAndStopLoss, trigger: 'blur' }]"
                        class="ext-form-item"
                      >
                        <div>
                          <el-input
                            v-model="item.takeProfitRatio"
                            min="0"
                            style="width:50%;"
                            size="mini"
                            type="number"
                            placeholder="止盈百分比"
                          >
                            <template v-if="form.type === 1" #append>{{ ext[index] ? ext[index].reTakeProfitRatio : 0
                            }}</template>
                          </el-input>
                          —
                          <el-input
                            v-model.number="item.stopLossRatio"
                            style="width:42%;"
                            size="mini"
                            type="number"
                            placeholder="止损百分比"
                          />
                        </div>
                      </el-form-item>
                    </el-col>
                    <!-- <el-col :span="3">止损百分比<el-input v-model.number="item.stopLossRatio" size="mini" type="number" placeholder="止损百分比" /></el-col> -->

                    <template v-if="item.addType === 1">
                      <el-col :span="3">
                        <!-- 止盈数量百分比 -->
                        <el-form-item
                          label="止盈数量(%)"
                          :prop="'ext.' + index + '.takeProfitNumRatio'"
                          :rules="inRules.takeProfitNumRatio"
                          class="ext-form-item"
                        >
                          <el-input
                            v-model.number="item.takeProfitNumRatio"
                            size="mini"
                            type="number"
                            placeholder="止盈数量百分比"
                          />
                        </el-form-item>
                      </el-col>
                      <el-col :span="4">
                        <!-- <span>第二止盈/止损百分比</span> -->
                        <el-form-item
                          label="第二止盈/止损百分比"
                          :prop="'ext.' + index + '.tpTpPriceRatio'"
                          :rules="[{ validator: validateTp, trigger: 'blur' }]"
                          class="ext-form-item"
                        >
                          <div>
                            <el-input
                              v-model.number="item.tpTpPriceRatio"
                              min="0"
                              style="width:42%"
                              size="mini"
                              type="number"
                              placeholder="第二止盈价百分比"
                            />
                            —
                            <el-input
                              v-model.number="item.tpSlPriceRatio"
                              min="0"
                              style="width:42%"
                              size="mini"
                              type="number"
                              placeholder="第二止损价百分比"
                            />
                          </div>
                        </el-form-item>
                      </el-col>
                    </template>
                    <el-col :span="2">
                      <el-form-item
                        label="过期(H)"
                        :prop="'ext.' + index + '.expirateHour'"
                        :rules="inRules.expirateHour"
                        class="ext-form-item"
                      >
                        <el-input v-model.number="item.expirateHour" size="mini" type="number" placeholder="过期时间（小时）" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="3">
                      <div style="margin-bottom: 14px;" /><el-button
                        size="mini"
                        type="danger"
                        @click="onAddExt(1, index)"
                      >删除</el-button>
                    </el-col>
                  </el-row>
                </div>
              </el-form>

              <!-- <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 { calculate, aicoinSymbol, quickAddPreOrder } from '@/api/admin/line-pre-order'
import { getLineApiUserGroupList } from '@/api/admin/line-api-user-group'
import { listLineStrategyTemplate } from '@/api/admin/line-strategy-template'
import { listLineReduceStrategy } from '@/api/admin/line-reduce-strategy'

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: [],
      apiUserGroupList: [],

      // 查询参数
      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: {
        price: [{ required: true, message: '请输入下单百分比不能为空', trigger: 'blur' },
          { validator: this.validatePercentage, trigger: 'blur' }
        ],
        profit: [{ required: true, message: '请输入', trigger: 'blur' },
          { validator: this.validateProfit, trigger: 'blur' }],

        stop_loss: [{ required: true, message: '请输入止损', trigger: 'blur' }, { validator: this.validateStopLoss, trigger: 'blur' }],
        reduce_price: [
          { required: true, message: '主单亏损不能为空', trigger: 'blur' },
          { validator: this.validateReducePrice, trigger: 'blur' }],
        reduce_num: [
          { required: true, message: '主单减仓数量百分比不能为空', trigger: 'blur' },
          { validator: this.validateReduceNum, trigger: 'blur' }],
        reduce_take_profit: [
          { required: true, message: '主单减仓后止盈价百分比不能为空', trigger: 'blur' },
          { validator: this.validateReduceTakeProfit, trigger: 'blur' }],
        reduce_stop_price: [{ required: true, message: '主单减仓后止损价百分比不能为空', trigger: 'blur' }],
        buy_price: [
          { required: true, message: '购买金额不能为空', trigger: 'blur' },
          { validator: this.validateBuyPrice, trigger: 'blur' }
        ],
        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' }],
        profit_num_ratio: [
          { required: true, message: '止盈数量百分比不能为空', trigger: 'blur' },
          { validator: this.validateProfitNumRatio, trigger: 'blur' }
        ],
        profit_tp_tp_price_ratio: [{ validator: this.validateTptpPriceRatio, trigger: 'blur' }],

        priceRatio: [{ required: true, message: '下跌百分比不能为空', trigger: 'blur' }, { validator: this.validateExtPriceRatio, trigger: 'blur' }],
        addPositionVal: [
          { required: true, message: '追加仓位不能为空', trigger: 'blur' },
          { validator: this.validateAddPosition, trigger: 'blur' }],
        takeProfitRatio: [
          { required: true, message: '请输入止盈百分比', trigger: 'blur' },
          { type: 'number', message: '止盈百分比必须为数字', trigger: 'blur' },
          { min: 0, message: '止盈百分比不能小于 0', trigger: 'blur' }
        ],
        stopLossRatio: [
          { required: true, message: '请输入止损百分比', trigger: 'blur' },
          { type: 'number', message: '止损百分比必须为数字', trigger: 'blur' },
          { min: 0, message: '止损百分比不能小于 0', trigger: 'blur' }
        ],
        takeProfitNumRatio: [
          { required: true, message: '止盈数量不能为空', trigger: 'blur' },
          { validator: this.validateExtTakeProfitNumRatio, trigger: 'blur' }
        ],
        tpTpPriceRatio: [{ required: true, message: '第二止盈价格百分比不能为空', trigger: 'blur' }],
        slSlPriceRatio: [{ required: true, message: '第二止损价格百分比不能为空', trigger: 'blur' }],
        expirateHour: [{ required: true, message: '请输入过期时间(H)', trigger: 'blur' }],
        api_id_type: [{ required: true, message: '请选择用户类型', trigger: 'blur' }],
        api_user_group_id: [{ required: true, message: '请选择用户组', trigger: 'blur' }]
      },
      inForm: {},
      searchLoding: false,
      lineUsers: [],
      lineTotal: 0,
      exchangeTypes: [],
      aicoins: {},
      aicoinPrice: undefined,
      ext: [],
      re_take_profit_ratio: 0,
      strategyTemplateOptions: [],
      // 策略分页数据
      strategyTemplatePagition: {
        total: 0,
        pageIndex: 1,
        pageSize: 10
      },
      reduceStrategyPagition: {
        total: 0,
        pageIndex: 1,
        pageSize: 10,
        // 减仓策略信息
        reduceStrategyList: []
      },
      strategyTemplateTypeOptions: [{
        value: 0,
        label: '无'
      }, {
        value: 1,
        label: '波段涨跌幅'
      }]
    }
  },
  computed: {
    comSymbols() {
      return this.form.type === 2 ? this.symbolGroups : this.symbol.symbolList
    },
    comPrice() {
      // (this.form.price-?)/? *100 + '%'
      // 主单委托实际价下  获取交易对行情价
      const { symbol, price, price_pattern } = this.inForm
      if (symbol && price_pattern !== 'percentage') {
        const s = this.comSymbols.find(item => item.symbol === symbol)
        if (s) {
          const res = ((price - s.lastPrice) / s.lastPrice) * 100
          return `${res.toFixed(2)}%`
        }
        return 0
      }
      return 0
    },
    /* 计算止盈百分比 */
    comTakePrice() {
      // console.log('this.form', this.form)
      const { profit, price, price_pattern, site } = this.inForm

      if (price_pattern === 'mixture' && Number(price) > 0 && Number(profit) > 0) {
        let res = 0

        if (site === 'BUY') {
          res = ((Number(profit) - Number(price)) / Number(price)) * 100
        } else {
          res = ((Number(price) - Number(profit)) / Number(price)) * 100
        }

        return `${res.toFixed(2)}%` // 取绝对值并保留两位小数
      }

      return 0
    },
    /* 计算减仓百分比 */
    comReducePrice() {
      const { reduce_price, price, price_pattern, site } = this.inForm

      if (price_pattern === 'mixture' && Number(price) > 0 && Number(reduce_price) > 0) {
        let res = 0
        if (site === 'BUY') {
          res = ((Number(price) - Number(reduce_price)) / Number(price)) * 100
        } else {
          res = ((Number(reduce_price) - Number(price)) / Number(price)) * 100
        }
        return `${res.toFixed(2)}%` // 取绝对值并保留两位小数
      }

      return 0
    }
  },
  created() {
    this.getList()
    this.queryReduceStrategy()
    // this.getLineApiUserItems()
    this.getSymbolGroup()
    // 获取交易所字典数据
    this.getDicts('exchange_type').then(response => {
      this.exchangeTypes = response.data
    })
  },
  methods: {
    /** 主单止损价 */
    validateStopLoss(rule, value, callback) {
      if (value < 0) {
        callback(new Error('止损价不能小于0'))
      } else if (this.form.price_pattern !== 'mixture' && value > 100) {
        callback(new Error('止损价不能大于100'))
      } else {
        callback()
      }
    },
    validatePercentage(rule, value, callback) {
      if (value <= 0 || value === undefined || value === null || value === '') {
        callback(new Error('百分比必须大于0'))
      } else {
        callback()
      }
    },
    validateExtTakeProfitNumRatio(rule, value, callback) {
      if (value === 0 || value === undefined || value === null || value === '') {
        callback(new Error('止盈数量百分比必须大于0'))
      } else {
        callback()
      }
    },
    validateReducePrice(rule, value, callback) {
      if (value === 0 || value === undefined || value === null || value === '') {
        callback(new Error('必须大于0'))
      } else {
        callback()
      }
    },
    validateBuyPrice(rule, value, callback) {
      if (value === 0) {
        callback(new Error('购买金额必须大于0'))
      } else {
        callback()
      }
    },
    validateReduceTakeProfit(rule, value, callback) {
      if (this.inForm.reduce_num > 0 && this.inForm.reduce_num < 100 && this.inForm.reduce_take_profit === 0) {
        callback(new Error('主单减仓后止盈必须大于0'))
      } else if (this.inForm.reduce_num === 100 && this.inForm.reduce_take_profit > 0) {
        callback(new Error('主单减仓全部后无需止盈'))
      } else {
        callback()
      }
    },
    /** 主单减仓数量 */
    validateReduceNum(rule, value, callback) {
      if (value <= 0) {
        callback(new Error('主单减仓数量必须大于0'))
      } else {
        callback()
      }
    },
    /** 主单止盈数量 */
    validateProfitNumRatio(rule, value, callback) {
      if (value <= 0) {
        callback(new Error('止盈数量比例必须大于0'))
      } else {
        callback()
      }
    },
    /** 验证第二止盈止损 */
    validateTptpPriceRatio(rule, value, callback) {
      if (!this.inForm) {
        callback(new Error('表单未初始化'))
        return
      }

      if (this.inForm.profit_num_ratio > 0 && this.inForm.profit_num_ratio < 100 && (!value || value <= 0)) {
        callback(new Error('第二止盈百分比不能为空且必须大于 0'))
      } else if (this.inForm.profit_num_ratio === 100 && value > 0) {
        callback(new Error('第一止盈已经全部止盈了，不需要第二止盈百分比'))
      } else {
        callback()
      }
    },
    validateProfit(rule, value, callback) {
      if (this.inForm.profit === '' || this.inForm.profit === undefined || this.inForm.profit === null) {
        callback(new Error('不能为空'))
      } else if (this.inForm.profit <= 0) {
        callback(new Error('不能小于0'))
      } else {
        callback()
      }
    },
    validateExtPriceRatio(rule, value, callback) {
      const index = rule.fullField.split('.')[1] // 获取索引
      const item = this.inForm.ext[index]
      const message = item.addType === 1 ? '加仓下跌百分比' : '减仓下跌百分比'

      if (item.priceRatio === '') {
        callback(new Error(message + '不能为空'))
      } else if (isNaN(item.priceRatio)) {
        callback(new Error('必须输入数字'))
      } else if (item.priceRatio < 0) {
        callback(new Error('百分比不能小于 0'))
      }

      if (index === 0 && Number(item.priceRatio) <= Number(this.inForm.reduce_price)) {
        callback(new Error('下跌百分比不能小于上一节点'))
      } else if (index > 0 && Number(item.priceRatio) <= Number(this.inForm.ext[index - 1].priceRatio)) {
        callback(new Error('下跌百分比不能小于上一节点'))
      } else {
        callback()
      }
    },
    validateAddPosition(rule, value, callback) {
      const index = rule.fullField.split('.')[1] // 获取索引
      const item = this.inForm.ext[index]
      const message = item.addType === 1 ? '加仓数值' : '减仓百分比'

      if (item.addPositionVal === '') {
        callback(new Error(message + '不能为空'))
      } else if (isNaN(item.addPositionVal)) {
        callback(new Error('必须输入数字'))
      } else if (item.addPositionVal <= 0) {
        callback(new Error(message + '必须大于 0'))
      } else {
        callback() // 校验通过
      }
    },
    // 自定义校验逻辑
    validateTakeProfitAndStopLoss(rule, value, callback) {
      const index = rule.fullField.split('.')[1] // 获取索引
      const item = this.inForm.ext[index]

      if (item.takeProfitRatio === '' || item.stopLossRatio === '') {
        callback(new Error('止盈和止损百分比都不能为空'))
      } else if (isNaN(item.takeProfitRatio) || isNaN(item.stopLossRatio)) {
        callback(new Error('必须输入数字'))
      } else if (item.takeProfitRatio < 0 || item.stopLossRatio < 0) {
        callback(new Error('百分比不能小于 0'))
      } else if (item.addType === 2 && item.addPositionVal < 100 && item.takeProfitRatio === 0) {
        callback(new Error('止盈百分比不能为0'))
      } else {
        callback() // 校验通过
      }
    },
    // 自定义 第二止盈止损校验
    validateTp(rule, value, callback) {
      const index = rule.fullField.split('.')[1] // 获取索引
      const item = this.inForm.ext[index]
      if (item.tpTpPriceRatio === '' || item.tpSlPriceRatio === '') {
        callback(new Error('第二止盈、止损百分比不能为空'))
      } else if (isNaN(item.tpTpPriceRatio) || isNaN(item.tpSlPriceRatio)) {
        callback(new Error('必须输入数字'))
      } else if (item.tpTpPriceRatio < 0 || item.tpSlPriceRatio < 0) {
        callback(new Error('百分比不能小于 0'))
      } else if (item.takeProfitNumRatio < 100 && item.takeProfitNumRatio > 0 && item.tpTpPriceRatio <= 0) {
        callback(new Error('第二止盈百分比必须大于0'))
      } else {
        callback() // 校验通过
      }
    },
    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 = '0')
        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() {
      this.inForm.price = 0
      if (this.inForm.price_pattern === 'aicoin') {
        aicoinSymbol({ symbol: this.inForm.symbol, symbolType: this.inForm.symbol_type }).then(res => {
          this.aicoinPrice = undefined
          this.inForm.price = 0
          this.aicoins = res.data
        }).catch(() => {
          this.aicoinPrice = undefined
          this.inForm.price = 0
          this.aicoins = {}
        })
      }
    },
    onchangeAicoin() {
      this.inForm.price = this.aicoinPrice || 0
    },
    onAddExt(type, index) {
      if (type === 1) {
        this.inForm.ext.splice(index, 1)
        return false
      }

      this.inForm.ext.push({
        // 类型 订单类型 加仓类型 加仓数值 价格百分比 止盈百分比 止损百分比
        addType: type === 0 ? 1 : 2,
        orderType: 'LIMIT',
        addPositionType: 1,
        addPositionVal: 0,
        priceRatio: 0,
        takeProfitRatio: 0,
        stopLossRatio: 0,
        // 止盈数量百分比 止盈后止盈价格百分比 止盈后止损价格百分比
        takeProfitNumRatio: 100,
        tpTpPriceRatio: 0,
        tpSlPriceRatio: 0,
        expirateHour: 0
      })
    },
    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.lineUsers.map(item => item.id + '')
    },
    // 获取杠杆api用户
    getListLineApiUser(exchangeType) {
      listLineApiUser({ pageIndex: 1, pageSize: 999, exchangeType: exchangeType || this.inForm.exchange_type, openStatus: 1 }).then(response => {
        this.lineUsers = response.data.list
        this.lineTotal = response.data.count
      })
    },
    // 获取api用户分组
    getApiUserGroupList(exchangeType) {
      getLineApiUserGroupList({ exchangeType: exchangeType || this.inForm.exchange_type }).then(response => {
        this.apiUserGroupList = response.data
      })
    },
    // 交易对列表
    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)
        }
      })
    },
    /* 切换用户选择 */
    apiIdTypeChange() {
      this.inForm.api_id = undefined
      this.inForm.api_user_group_id = undefined
    },
    /* 用户分组选中 */
    apiUserGroupChange(selection) {
      console.log(selection)
      if (selection) {
        // 过滤出匹配的项
        const matchedGroup = this.apiUserGroupList.find(x => x.id === selection)

        console.log(matchedGroup)
        // 确保 matchedGroup 存在，并且有 value 数组
        if (matchedGroup && matchedGroup.value) {
          this.inForm.api_id = matchedGroup.value // 转字符串
        } else {
          this.inForm.api_id = undefined // 处理未找到的情况
        }
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {

        id: undefined,
        name: undefined,
        userId: undefined,
        params: undefined,
        type: 1,
        switch: '0',
        ext: []
      }
      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')
      })
    },

    changeStrategyTemplateType(val) {
      if (val === 1) {
        this.queryStrategyTemplate()
      } else {
        this.form.strategy_template_id = undefined
      }
    },
    queryStrategyTemplate() {
      this.searchLoding = true

      listLineStrategyTemplate({ pageIndex: this.strategyTemplatePagition.pageIndex, pageSize: this.strategyTemplatePagition.pageSize }).then(res => {
        this.strategyTemplatePagition.total = res.data.count
        this.strategyTemplateOptions = res.data.list
      })
        .finally(() => {
          this.searchLoding = false
        })
    },
    // 查询减仓策略
    queryReduceStrategy() {
      this.searchLoding = true
      listLineReduceStrategy({ pageIndex: this.reduceStrategyPagition.pageIndex, pageSize: this.reduceStrategyPagition.pageSize }).then(res => {
        this.reduceStrategyPagition.reduceStrategyList = res.data.list
        this.reduceStrategyPagition.total = res.data.count
      })
        .finally(() => {
          this.searchLoding = false
        })
    },
    // 文件
    /** 搜索按钮操作 */
    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
    },
    handleCopy(row) {
      this.reset()
      this.ext = []
      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.form.type === 1 && this.onCalculate()
        // 获取交易对用于计算
        this.getSymbol(this.inForm.symbol)
        this.form.id = undefined
        this.open = true
        this.title = '添加委托下单模板'
        this.isEdit = false
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.ext = []
      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(','),
          api_id_type: x.api_id_type ? x.api_id_type : 1,
          api_user_group_id: x.api_user_group_id ? x.api_user_group_id : undefined,
          symbol_group_id: x.symbol_group_id ? Number(x.symbol_group_id) : undefined
        }

        if (this.inForm.price_pattern === 'aicoin') {
          this.inForm.price = null
        }

        this.getApiUserGroupList()
        this.onchangePattern(false)
        this.getListLineApiUser()
        this.form.type === 2 && this.getSymbolGroup(this.inForm.symbol_type)
        this.form.type === 1 && this.onCalculate()
        // 获取交易对用于计算
        this.getSymbol(this.inForm.symbol)
        this.open = true
        this.title = '修改委托下单模板'
        this.isEdit = true
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      Promise.all([
        this.$refs['inForm'].validate(), // 验证第一个表单
        this.$refs['extForm'].validate() // 验证第二个表单
      ])
        .then((formValid) => {
          if (formValid.every(valid => valid)) {
            this.inForm.price = this.inForm.price ? String(this.inForm.price) : ''

            if (this.inForm.api_user_group_id && this.inForm.api_id_type === 2) {
              this.apiUserGroupChange(this.inForm.api_user_group_id)
            }

            const params = JSON.stringify({
              ...this.inForm,
              reduce_price: this.inForm.reduce_price || 0,
              reduce_num: this.inForm.reduce_num || 0,
              reduce_take_profit: this.inForm.reduce_take_profit || 0,
              reduce_stop_price: this.inForm.reduce_stop_price || 0,
              symbol_group_id: String(this.inForm.symbol_group_id),
              profit_num_ratio: this.inForm.profit_num_ratio || 100,
              profit_tp_tp_price_ratio: this.inForm.profit_tp_tp_price_ratio || 0,
              profit_tp_sl_price_ratio: this.inForm.profit_tp_sl_price_ratio || 0,
              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),
              ext: Array.isArray(this.inForm.ext)
                ? this.inForm.ext.map(item => ({
                  ...item,
                  stopLossRatio: item.stopLossRatio || 0,
                  takeProfitNumRatio: item.takeProfitNumRatio || 0,
                  tpTpPriceRatio: item.tpTpPriceRatio || 0,
                  tpSlPriceRatio: item.tpSlPriceRatio || 0,
                  expirateHour: item.expirateHour || 0
                }))
                : []
            })
            if (this.form.id !== undefined) {
              this.$refs['inForm'].validate(valided => {
                if (!valided) return false

                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.form, params }).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) {
          if (response.data !== '') {
            this.$notify({
              title: '部分失败',
              message: response.data,
              type: 'warning'
            })
          } else {
            this.msgSuccess(response.msg)
          }
          this.ids = []
          this.$refs.table?.clearSelection()
        } else {
          this.msgError(response.msg)
        }
      }).catch(function() {
      })
    },
    // 计算需要回本利润
    onCalculate() {
      calculate({ ...this.inForm, api_id: this.inForm.api_id.toString() }).then(res => {
        this.ext = res?.data?.ext || []
        this.re_take_profit_ratio = res?.data?.re_take_profit_ratio || 0
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.hour {
  ::v-deep.el-input__inner {
    line-height: 1;
  }
}

::v-deep.ext-form-item {
  .el-form-item__label {
    padding: 0px !important;
  }
}

.el-form--label-top .el-form-item__label {
  padding: 0px !important;
}

.ext-form .el-form-item__content .el-input-group {
  vertical-align: middle;
}

.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>
