
<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card">
        <el-form ref="queryForm" :model="queryParams" inline>
          <el-form-item label="api用户" prop="apiId">
            <el-select
              v-model="queryParams.apiId"
              placeholder="请选择api用户"
              clearable
              size="small"
            >
              <el-option
                v-for="dict in lineUsersAll"
                :key="dict.id"
                :label="dict.apiName"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="交易对" prop="symbol"><el-input
            v-model="queryParams.symbol"
            placeholder="请输入交易对"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
          </el-form-item>
          <el-form-item label="计价货币" prop="quoteSymbol"><el-input
            v-model="queryParams.quoteSymbol"
            placeholder="请输入计价货币"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
          </el-form-item>
          <!-- <el-form-item label="对标价类型" prop="signPriceType"><el-select
            v-model="queryParams.signPriceType"
            placeholder="请选择对标价类型"
            clearable
            size="small"
          >
            <el-option
              v-for="dict in priceTypes"
              :key="dict.k"
              :label="dict.l"
              :value="dict.v"
            />
          </el-select>
          </el-form-item> -->
          <el-form-item label="购买方向" prop="site"><el-select
            v-model="queryParams.site"
            placeholder="请选择购买方向"
            clearable
            size="small"
          >
            <el-option
              v-for="dict in buyer"
              :key="dict.k"
              :label="dict.l"
              :value="dict.v"
            />
          </el-select>
          </el-form-item>
          <el-form-item label="订单号" prop="orderSn"><el-input
            v-model="queryParams.orderSn"
            placeholder="请输入订单号"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
          </el-form-item>
          <el-form-item label="订单类型" prop="orderType"><el-select
            v-model="queryParams.orderType"
            placeholder="请选择订单类型"
            clearable
            size="small"
          >
            <el-option
              v-for="dict in [{l:'现货',v:1},{l:'合约',v:2}]"
              :key="dict.k"
              :label="dict.l"
              :value="dict.v"
            />
          </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status"><el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            size="small"
          >
            <el-option
              v-for="dict in statuss"
              :key="dict.k"
              :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:linePreOrder:add']"
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd('')"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              size="mini"
              @click="handleAdd('批量添加')"
            >批量添加
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              size="mini"
              @click="onPosition"
            >平仓
            </el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button
              type="primary"
              size="mini"
              @click="onStore"
            >加仓
            </el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button
              type="warning"
              size="mini"
              @click="onMode('设置杠杆')"
            >设置杠杆
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              size="mini"
              @click="onMode('设置保证金模式')"
            >设置保证金模式
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              size="mini"
              @click="onCancel"
            >取消委托
            </el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button
              v-permisaction="['admin:linePreOrder: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:linePreOrder: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="danger"
              icon="el-icon-delete"
              size="mini"
              :disabled="linePreOrderList.length===0"
              @click="handleDeleteAll"
            >一键清除数据
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              :disabled="linePreOrderList.length===0"
              @click="handleTrigger"
            >清除待触发交易对
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-permisaction="['admin:linePreOrder:remove']"
              type="danger"
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
            >批量删除
            </el-button>
          </el-col>
        </el-row>

        <el-table
          ref="table"
          v-loading="loading"
          :data="linePreOrderList"
          row-key="id"
          lazy
          :load="onLoadChild"
          :tree-props="{children: 'children', hasChildren: 'hasChildren', checkStrictly: true }"
          height="560"
          @selection-change="handleSelectionChange"
          @expand-change="onExpand"
        >
          <el-table-column type="selection" width="55" align="center" :selectable="(row)=>row.pid===0" />
          <el-table-column
            label="交易对"
            align="left"
            prop="symbol"
            width="150"
            :show-overflow-tooltip="true"
            fixed="left"
          >
            <template #default="{row}">
              <span v-if="row.pid===0">（{{ row.child_num }}）</span>
              <span v-else-if="row.child_num">（{{ row.child_num }}）</span>
              <span>{{ row.symbol }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="api用户名"
            align="center"
            prop="api_name"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="对标价"
            align="center"
            prop="signPrice"
            min-width="120"
            :show-overflow-tooltip="true"
          /><el-table-column
            label="对标价类型"
            align="center"
            prop="signPriceType"
            width="100"
            :show-overflow-tooltip="true"
          >
            <template #default="{ row }">
              {{ {new:'最新价',mixture:'标记价',aicoin:'aicoin'}[row.signPriceType] }}
            </template>
          </el-table-column>
          <el-table-column
            label="下单百分比"
            align="center"
            prop="rate"
            min-width="100"
            :show-overflow-tooltip="true"
          /><el-table-column
            label="触发价格"
            align="center"
            prop="price"
            min-width="120"
            :show-overflow-tooltip="true"
          /><el-table-column
            label="购买数量"
            align="center"
            prop="num"
            min-width="120"
            :show-overflow-tooltip="true"
          /><el-table-column
            label="购买金额"
            align="center"
            prop="buyPrice"
            min-width="120"
            :show-overflow-tooltip="true"
          /><el-table-column
            label="购买方向"
            align="center"
            prop="site"
            :show-overflow-tooltip="true"
          >
            <template #default="{row}">
              <el-tag size="mini" :type="row.site==='BUY'?'success':'danger'">{{ {BUY:'买(多)',SELL:'卖(空)'}[row.site] }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="订单类型"
            align="center"
            prop="orderType"
            :show-overflow-tooltip="true"
          >
            <template #default="{row}">
              {{ orderTypes[row.orderType] ? orderTypes[row.orderType].l : '' }}
              <!-- {{ orderTypes[row.orderType-1] ? orderTypes[row.orderType-1].l : '' }} -->
            </template>
          </el-table-column>
          <el-table-column
            label="交易对类型"
            align="center"
            prop="symbolType"
            min-width="90"
            :show-overflow-tooltip="true"
          >
            <template #default="{row}">
              {{ ['现货','合约'][row.symbolType-1] }}
            </template>
          </el-table-column>
          <!-- <el-table-column
            label="补仓百分比"
            align="center"
            prop="coverRate"
            width="100"
            :show-overflow-tooltip="true"
          /> -->
          <el-table-column
            label="状态"
            align="center"
            prop="status"
            width="100"
            :show-overflow-tooltip="true"
          >
            <template #default="{row}">
              <span :style="comStatusStyle(row)">{{ status[row.status] ? status[row.status].l : '' }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="订单描述"
            align="center"
            prop="desc"
            :show-overflow-tooltip="true"
          />
          <!-- <el-table-column
            label="对冲状态"
            align="center"
            prop="status"
            width="100"
            :show-overflow-tooltip="true"
          >
            <template #default="{row}">
              <el-tag v-if="row.pid===0" size="mini" :type="row.hedgeStatus===1?'success':'danger'">
                {{ ['未对冲','已对冲'][row.hedgeStatus] }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="加仓状态"
            align="center"
            prop="status"
            width="100"
            :show-overflow-tooltip="true"
          >
            <template #default="{row}">
              <el-tag v-if="row.pid===0" size="mini" :type="row.addPositionStatus===1?'success':'danger'">
                {{ ['未加仓','已加仓'][row.addPositionStatus] }}
              </el-tag>
            </template>
          </el-table-column> -->
          <el-table-column
            label="计价货币"
            align="center"
            prop="quoteSymbol"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="交易所"
            align="center"
            prop="exchangeType"
            :show-overflow-tooltip="true"
          >
            <template #default="{row}">
              {{ exchangeTypeFormat(row) }}
            </template>
          </el-table-column>
          <!-- <el-table-column
            label="预估方向"
            align="center"
            prop="direction"
            :show-overflow-tooltip="true"
          /> -->
          <el-table-column
            label="订单号"
            align="center"
            prop="orderSn"
            width="200"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="过期时间"
            align="center"
            prop="expireTime"
            width="150"
            :show-overflow-tooltip="true"
          >
            <template #default="{row}">{{ parseTime(row.expireTime) }}</template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            prop="createdAt"
            width="150"
            :show-overflow-tooltip="true"
          >
            <template #default="{row}">{{ parseTime(row.createdAt) }}</template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150" fixed="right">
            <template v-if="scope.row.pid===0" slot-scope="scope">
              <!-- <el-popconfirm
                class="delete-popconfirm"
                title="确认要修改吗?"
                confirm-button-text="修改"
                @confirm="handleUpdate(scope.row)"
              >
                <el-button
                  slot="reference"
                  v-permisaction="['admin:linePreOrder:edit']"
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                >修改
                </el-button>
              </el-popconfirm> -->
              <el-popconfirm
                class="delete-popconfirm"
                title="确认要取消委托吗?"
                confirm-button-text="确定"
                @confirm="handleCancel(scope.row)"
              >
                <el-button
                  slot="reference"
                  size="mini"
                  type="text"
                  :disabled="scope.row.status!=5"
                >取消委托
                </el-button>
              </el-popconfirm>
              <el-popconfirm
                class="delete-popconfirm"
                title="确认要删除吗?"
                confirm-button-text="删除"
                @confirm="handleDelete(scope.row)"
              >
                <el-button
                  slot="reference"
                  v-permisaction="['admin:linePreOrder:remove']"
                  size="mini"
                  type="text"
                  style="color: #ff6d6d;"
                  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="180px" style="height: 600px;overflow: hidden auto;">
            <el-form-item label="交易所" prop="exchange_type">
              <el-select
                v-model="form.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="form.symbol_type">
                <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="form.cover_type">
                <el-radio :label="0">无对冲</el-radio>
                <el-radio :label="1" :disabled="form.symbol_type==2">现货对合约</el-radio>
                <el-radio :label="2" :disabled="form.symbol_type==1">合约对合约</el-radio>
                <el-radio :label="3" :disabled="form.symbol_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="form.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="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 label="交易对组id" prop="groupId">
              <el-input
                v-model="form.groupId"
                placeholder="交易对组id"
              />
            </el-form-item> -->
            <el-form-item v-if="title==='批量添加'" label="交易对组" prop="symbol_group_id">
              <el-select
                v-if="title==='批量添加'"
                v-model="form.symbol_group_id"
                style="width: 100%;"
                placeholder="请选择交易对组"
                clearable
                size="small"
                filterable
              >
                <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="form.symbol"
                style="width: 100%;"
                placeholder="请选择交易对"
                clearable
                filterable
                :remote-method="getSymbol"
                :loading="searchLoding"
                remote
                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="form.site">
                <el-radio label="BUY">买（多）</el-radio>
                <el-radio label="SELL" :disabled="form.order_type==1">卖（空）</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="购买金额（U）" prop="buy_price">
              <el-input
                v-model="form.buy_price"
                placeholder="购买金额（U）"
              />
            </el-form-item>
            <el-form-item label="价格模式" prop="price_pattern">
              <el-radio-group v-model="form.price_pattern">
                <el-radio label="percentage">百分比</el-radio>
                <el-radio label="mixture" :disabled="title==='批量添加'">主单实价委托百分比</el-radio>
                <el-radio label="aicoin" :disabled="title==='批量添加'">aiCoin买入点</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="form.price_pattern === 'percentage'" label="下单百分比" prop="price">
              <el-input
                v-model="form.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="form.price"
                    placeholder="下单价(实际价格)"
                  >
                    <template #prepend>
                      <el-select v-if="form.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="form.profit"
                placeholder="止盈百分比"
              />
            </el-form-item>
            <!-- <el-form-item label="亏损百分比" prop="stop_price">
              <el-input
                v-model="form.stop_price"
                placeholder="亏损百分比"
              />
            </el-form-item> -->
            <!-- <template v-if="form.cover_type!=0">
              <el-form-item label="对冲单购买类型" prop="hedge_buy_type">
                <el-radio-group v-model="form.hedge_buy_type">
                  <el-radio :label="1">百分比</el-radio>
                  <el-radio :label="2">实际金额</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="对冲总购买金额" prop="HedgeBuyTotal">
                <el-input
                  v-model.number="form.HedgeBuyTotal"
                  type="number"
                  placeholder="对冲总购买金额"
                />
              </el-form-item>
              <el-form-item label="对冲止盈百分比" prop="HedgeTakeProfit">
                <el-input
                  v-model.number="form.HedgeTakeProfit"
                  type="number"
                  placeholder="对冲止盈百分比"
                />
              </el-form-item>
              <el-form-item label="对冲止损百分比" prop="HedgeStopLoss">
                <el-input
                  v-model.number="form.HedgeStopLoss"
                  type="number"
                  placeholder="对冲止损百分比
"
                />
              </el-form-item>
            </template> -->
            <!-- <el-form-item label="对冲百分比" prop="cover_rate">
              <el-input
                v-model="form.cover_rate"
                placeholder="对冲百分比"
              />
            </el-form-item>
            <el-form-item label="加仓后盈利比例" prop="profit_rate">
              <el-input
                v-model="form.profit_rate"
                placeholder="加仓后盈利比例"
              />
            </el-form-item>
            <el-form-item label="对冲平仓最大次数" prop="hedge_close_count">
              <el-input
                v-model.number="form.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="form.hedge_trigger_percent" type="number" placeholder="最小值"><template #append>最小值</template></el-input></el-col>
                <el-col :span="11"><el-input v-model.number="form.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="form.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="form.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="form.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="form.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="form.price_type">
                <el-radio label="new">最新价</el-radio>
                <el-radio label="mixture" :disabled="title==='批量添加'">标记价</el-radio>
                <el-radio label="aicoin" :disabled="title==='批量添加'">aicoin</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="订单过期时间" prop="profit_rate">
              <el-input
                v-model.number="form.expire_hour"
                class="hour"
                type="number"
                placeholder="订单过期时间"
              >
                <template slot="append">小时</template>
              </el-input>
            </el-form-item>
            <el-form-item v-if="title==='批量添加'" label="批量下单次数" prop="order_num">
              <el-input
                v-model.number="form.order_num"
                min="1"
                type="number"
                placeholder="批量下单次数"
              />
            </el-form-item>
            <el-form-item v-if="title==='批量添加'" label="执行类型" prop="script">
              <el-radio-group v-model="form.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="form.reduce_price" type="number" placeholder="主单减仓价格百分比" />
            </el-form-item>
            <el-form-item label="主单减仓数量百分比" prop="reduce_num">
              <el-input v-model.number="form.reduce_num" type="number" placeholder="主单减仓数量百分比" />
            </el-form-item>
            <el-form-item label="主单减仓后止盈价百分比" prop="reduce_take_profit">
              <el-input v-model.number="form.reduce_take_profit" type="number" placeholder="主单减仓后止盈价百分比" />
            </el-form-item>
            <el-form-item label="主单减仓后止损价百分比" prop="reduce_stop_price">
              <el-input v-model.number="form.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 form.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="form.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="form.template_name"
                placeholder="模板名称"
              />
            </el-form-item>

          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
        <!-- 设置杠杆  保证金模式 -->
        <el-dialog :title="mode.modeTitle" :visible.sync="mode.modeOpen" width="700px" :close-on-click-modal="false">
          <el-form ref="formMode" :model="modeForm" :rules="modeRules" label-width="100px">
            <el-form-item label="交易所" prop="exchangeType">
              <el-select
                v-model="modeForm.exchangeType"
                style="width: 100%;"
                placeholder="请选择交易所"
                clearable
                filterable
                size="small"
                @change="onchangeMode"
              >
                <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="api用户" prop="api_user_ids">
              <el-row>
                <el-col :span="21">
                  <el-select
                    v-model="modeForm.api_user_ids"
                    multiple
                    style="width: 100%;"
                    placeholder="请选择api用户"
                    clearable
                    filterable
                    size="small"
                  >
                    <el-option
                      v-for="dict in lineUsers"
                      :key="dict.id"
                      :label="dict.apiName"
                      :value="dict.id"
                    />
                  </el-select>
                </el-col>
                <el-col :span="3">
                  <el-button size="mini" type="primary" style="margin-left: 10px;" @click="onAll">全选</el-button>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="交易对" prop="symbol">
              <el-select
                v-model="modeForm.symbol"
                style="width: 100%;"
                placeholder="请选择交易对"
                clearable
                multiple
                filterable
                :remote-method="(e)=>getSymbol(e,2,modeForm.exchangeType)"
                :loading="searchLoding"
                remote
                size="small"
              >
                <el-option
                  v-for="dict in symbol.symbolList"
                  :key="dict.id"
                  :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($event,2,modeForm.exchangeType)"
                  />
                </div>
              </el-select>
            </el-form-item>
            <el-form-item label="交易对组" prop="group_id">
              <el-select
                v-model="modeForm.group_id"
                style="width: 100%;"
                placeholder="请选择交易对组"
                clearable
                filterable
                size="small"
              >
                <el-option
                  v-for="dict in symbolGroups"
                  :key="dict.id"
                  :label="dict.groupName"
                  :value="dict.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item v-if="mode.modeTitle==='设置杠杆'" label="杠杆倍数" prop="leverage">
              <el-inputNumber
                v-model.number="modeForm.leverage"
                :min="1"
                :max="125"
                step-strictly
                placeholder="杠杆倍数"
              />
            </el-form-item>
            <el-form-item v-else label="保证金模式" prop="margin_type">
              <el-radio-group v-model="modeForm.margin_type">
                <el-radio label="CROSSED">全仓</el-radio>
                <el-radio label="ISOLATED"> 逐仓</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="全部交易对" prop="is_all">
              <el-radio-group v-model="modeForm.is_all" :disabled="!!modeForm.group_id || !!(modeForm.symbol && modeForm.symbol.length)">
                <el-radio :label="0">否</el-radio>
                <el-radio :label="1"> 是</el-radio>
              </el-radio-group>
              <span v-if="modeForm.is_all===1" style="color: red;margin-left: 20px;">耗时比较久，请耐心等待</span>
            </el-form-item>
          </el-form>
          <div style="color: red;"><i class="el-icon-warning-outline" style="margin-right: 4px;" />请保证该操作下的交易对无仓位，否则会直接失败</div>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" :loading="btnLoading" @click="modeConfirm">确 定</el-button>
            <el-button @click="modeCancel">取 消</el-button>
          </div>
        </el-dialog>
        <!-- 加仓  -->
        <el-dialog title="加仓" :visible.sync="storeOpen" width="700px" :close-on-click-modal="false">
          <el-form ref="formStore" :model="storeForm" :rules="storeRules" label-width="120px">
            <el-form-item label="交易所" prop="exchangeType">
              <el-select
                v-model="storeForm.exchangeType"
                style="width: 100%;"
                placeholder="请选择交易所"
                clearable
                filterable
                size="small"
              >
                <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="api用户" prop="api_id">
              <el-select
                v-model="storeForm.api_id"
                style="width: 100%;"
                placeholder="请选择api用户"
                clearable
                filterable
                size="small"
              >
                <el-option
                  v-for="dict in lineUsers"
                  :key="dict.id"
                  :label="dict.apiName"
                  :value="dict.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="加仓账户" prop="cover_account">
              <el-radio-group v-model="storeForm.cover_account">
                <el-radio :label="1">加仓主账号</el-radio>
                <el-radio :label="2">加仓副账号</el-radio>
                <el-radio :label="3">都加</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="加仓交易对类型" prop="symbol_type">
              <el-radio-group v-model="storeForm.symbol_type">
                <el-radio :label="1">现货</el-radio>
                <el-radio :label="2">合约</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="加仓交易对" prop="symbols">
              <el-select
                v-model="storeForm.symbols"
                style="width: 100%;"
                placeholder="请选择加仓交易对"
                clearable
                multiple
                filterable
                :remote-method="(e)=>getSymbol(e,storeForm.symbol_type,storeForm.exchangeType)"
                :loading="searchLoding"
                remote
                size="small"
              >
                <el-option
                  v-for="dict in symbol.symbolList"
                  :key="dict.id"
                  :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($event,storeForm.symbol_type,storeForm.exchangeType)"
                  />
                </div>
              </el-select>
            </el-form-item>
            <el-form-item label="加仓主账号类型" prop="cover_account_a_type">
              <el-radio-group v-model="storeForm.cover_account_a_type">
                <el-radio label="MARKET">市价</el-radio>
                <el-radio label="LIMIT">限价</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="storeForm.cover_account_a_type==='LIMIT'" label="加仓主账号限价比例" prop="cover_account_a_rate">
              <el-input
                v-model="storeForm.cover_account_a_rate"
                placeholder="加仓主账号限价比例"
              />
            </el-form-item>
            <el-form-item label="加仓副账号类型" prop="cover_account_b_type">
              <el-radio-group v-model="storeForm.cover_account_b_type">
                <el-radio label="MARKET">市价</el-radio>
                <el-radio label="LIMIT">限价</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="storeForm.cover_account_b_type==='LIMIT'" label="加仓副账号限价比例" prop="cover_account_b_rate">
              <el-input
                v-model="storeForm.cover_account_b_rate"
                placeholder="加仓副账号限价比例"
              />
            </el-form-item>
            <el-form-item label="加仓类型" prop="cover_type">
              <el-radio-group v-model="storeForm.cover_type">
                <el-radio :label="1">百分比</el-radio>
                <el-radio :label="2">金额</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item :label="`加仓数值${storeForm.cover_type===2?'(U)':''}`" prop="value">
              <el-input
                v-model="storeForm.value"
                :placeholder="`加仓数值${storeForm.cover_type===2?'(U)':''}`"
              />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="storeConfirm">确 定</el-button>
            <el-button @click="storeCancel">取 消</el-button>
          </div>
        </el-dialog>
        <!-- 平仓  -->
        <el-dialog title="平仓" :visible.sync="positionOpen" width="700px" :close-on-click-modal="false">
          <el-form ref="formPosition" :model="positionForm" :rules="positionRules" label-width="120px">
            <el-form-item label="交易所" prop="exchange_type">
              <el-select
                v-model="positionForm.exchange_type"
                style="width: 100%;"
                placeholder="请选择交易所"
                clearable
                filterable
                size="small"
                @change="onChangePosition"
              >
                <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="close_type">
              <el-radio-group v-model="positionForm.close_type" @change="onChangePosition">
                <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">
              <el-select
                v-model="positionForm.api_id"
                style="width: 100%;"
                placeholder="请选择api用户"
                clearable
                filterable
                size="small"
              >
                <el-option
                  v-for="dict in lineUsers"
                  :key="dict.id"
                  :label="dict.apiName"
                  :value="dict.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="交易对" prop="symbol">
              <template #label>
                <span>交易对</span>
                <el-popover
                  trigger="hover"
                  content="交易对为空时，代表平仓全部"
                >
                  <template #reference>
                    <i class="el-icon-question" />
                  </template>
                </el-popover>
              </template>
              <el-select
                v-model="positionForm.symbol"
                style="width: 100%;"
                placeholder="请选择交易对"
                clearable
                filterable
                :remote-method="(e)=>getSymbol(e,positionForm.close_type,positionForm.exchange_type)"
                :loading="searchLoding"
                remote
                size="small"
              >
                <el-option
                  v-for="dict in symbol.symbolList"
                  :key="dict.id"
                  :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($event,positionForm.close_type,positionForm.exchange_type)"
                  />
                </div>
              </el-select>
            </el-form-item>
            <el-form-item label="平仓行情百分比" prop="rate">
              <el-input v-model="positionForm.rate" placeholder="平仓行情百分比" />
            </el-form-item>
          </el-form>
          <div style="color: red;"><i class="el-icon-warning-outline" style="margin-right: 4px;" />该功能仅适用于本系统内的下单数据，且交易对为空时代表全部平仓</div>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="positionConfirm">确 定</el-button>
            <el-button @click="positionCancel">取 消</el-button>
          </div>
        </el-dialog>

        <!-- 取消委托 -->
        <el-dialog title="取消委托" :visible.sync="cancelOpen" width="700px" :close-on-click-modal="false">
          <el-form ref="formCancel" :model="cancelForm" label-width="80px">
            <el-form-item label="交易所" prop="exchangeType" :rules="[{required: true,message: '交易所不能为空', trigger: 'blur'}]">
              <el-select
                v-model="cancelForm.exchangeType"
                style="width: 100%;"
                placeholder="请选择交易所"
                clearable
                filterable
                size="small"
                @change="onChangeCancel"
              >
                <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="api用户" prop="api_id" :rules="[{required: true,message: 'api用户不能为空', trigger: 'blur'}]">
              <el-select
                v-model="cancelForm.api_id"
                style="width: 100%;"
                placeholder="请选择api用户"
                clearable
                filterable
                size="small"
              >
                <el-option
                  v-for="dict in lineUsers"
                  :key="dict.id"
                  :label="dict.apiName"
                  :value="Number(dict.id)"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="订单类型" prop="order_type">
              <el-radio-group v-model="cancelForm.order_type">
                <el-radio :label="1">现货</el-radio>
                <el-radio :label="2">合约</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <div style="color: red;"><i class="el-icon-warning-outline" style="margin-right: 4px;" />该功能仅适用于本系统内的下单数据</div>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="handleCancel('formCancel')">确 定</el-button>
            <el-button @click="cancelOpen = false">取 消</el-button>
          </div>
        </el-dialog>
      </el-card>
    </template>
  </BasicLayout>
</template>

<script>
import { listLineSymbol, getSameSymbol } from '@/api/admin/line-symbol'
import { aicoinSymbol, clearUnTriggered, clearAll, closePosition, manuallyCover, orderMarginType, orderLever, batchAddOrder, addOrder, delLinePreOrder, getLinePreOrder, listLinePreOrder, updateLinePreOrder, getChildOrder, cancelOpenOrder } from '@/api/admin/line-pre-order'
import { getMainUser, listLineApiUser } from '@/api/admin/line-api-user'
import { listLineSymbolGroup } from '@/api/admin/line-symbol-group'
export default {
  name: 'LinePreOrder',
  data() {
    return {
      // : new=最新价格;tall=24小时最高;low=24小时最低;mixture=标记价;entrust=委托实价;add=补仓
      priceTypes: [
        { l: '最新价', v: 'new' },
        // { l: '24小时最高', v: 'tall' },
        // { l: '24小时最低', v: 'low' },
        // { l: '委托实价', v: 'entrust' },
        { l: '标记价', v: 'mixture' }
        // { l: '补仓', v: 'add' }
      ],
      // :1=现货;2=合约;3=合约止盈;4=合约止损;5=现货止盈;6=现货止损;7=止损补仓;8=现货加仓；9=现货平仓;10 = 合约止损补仓,11=合约加仓；12=合约平仓
      orderTypes: [
        { v: 0, l: '主单' },
        { v: 1, l: '止盈' },
        { v: 2, l: '止损' },
        { v: 3, l: '平仓' },
        { v: 4, l: '减仓' }
        // { v: 1, l: '现货' },
        // { v: 2, l: '合约' },
        // { v: 3, l: '合约止盈' },
        // { v: 4, l: '合约亏损' },
        // { v: 5, l: '现货止盈' },
        // { v: 6, l: '现货亏损' },
        // { v: 7, l: '现货对冲' },
        // { v: 8, l: '现货加仓' },
        // { v: 9, l: '现货平仓' },
        // { v: 10, l: '合约对冲' },
        // { v: 11, l: '合约加仓' },
        // { v: 12, l: '合约平仓' }
      ],
      buyer: [
        { v: 'BUY', l: '买（多）' },
        { v: 'SELL', l: '卖（空）' }
      ],
      // :0=待触发;1=已触发;2=下单失败;3=已记录;4=已取消;5=委托中;6=已平仓;7=已补单;8=补单失败;9=现货已成交；10=合约已补单;11=合约补单失败;12=合约已成交;13=已开仓
      status: [
        { v: 0, l: '待触发' },
        { v: 1, l: '已触发' },
        { v: 2, l: '下单失败' },
        { v: 3, l: '未知' },
        { v: 4, l: '已取消' },
        { v: 5, l: '委托中' },
        { v: 6, l: '已成交' },
        { v: 7, l: '未知' },
        { v: 8, l: '未知' },
        { v: 9, l: '已平仓' }
        // { v: 0, l: '待触发' },
        // { v: 1, l: '已触发' },
        // { v: 2, l: '下单失败' },
        // { v: 3, l: '已记录' },
        // { v: 4, l: '已取消' },
        // { v: 5, l: '委托中' },
        // { v: 6, l: '已平仓' },
        // { v: 7, l: '已补单' },
        // { v: 8, l: '补单失败' },
        // { v: 9, l: '现货已成交' },
        // { v: 10, l: '合约已补单' },
        // { v: 11, l: '合约补单失败' },
        // { v: 12, l: '合约已成交' },
        // { v: 13, l: '已开仓' }
      ],
      statuss: [
        { v: 0, l: '待触发' },
        { v: 1, l: '已触发' },
        { v: 2, l: '下单失败' },
        { v: 4, l: '已取消' },
        { v: 5, l: '委托中' },
        { v: 6, l: '已成交' },
        { v: 9, 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: [],
      linePreOrderList: [],

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

      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
        apiId: undefined,
        symbol: undefined,
        quoteSymbol: undefined,
        signPriceType: undefined,
        rate: undefined,
        site: undefined,
        orderSn: undefined,
        orderType: undefined,
        idOrder: 'desc',
        addPositionStatus: -1,
        hedgeStatus: -1,
        status: ''
      },
      // 表单参数
      form: {
      },
      // 表单校验
      rules: {
        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' }]
      },
      currentExpandId: undefined,
      cacheRefresh: {},

      symbol: {
        symbolList: [],
        total: 0,
        pageIndex: 1,
        pageSize: 6
      },
      percenter: undefined,
      // 交易对组
      batchOpen: false,
      symbolGroups: [],
      modeForm: {},
      modeRules: {
        exchangeType: [{ required: true, message: '交易所不能为空', trigger: 'blur' }],
        api_user_ids: [{ required: true, message: 'api用户不能为空', trigger: 'blur' }]
      },
      mode: {
        modeTitle: '',
        modeOpen: false
      },
      lineUsersAll: [],
      lineUsers: [],
      lineTotal: 0,
      storeOpen: false,
      storeForm: {},
      storeRules: {
        exchangeType: [{ required: true, message: '交易所不能为空', trigger: 'blur' }],
        api_id: [{ required: true, message: 'api用户不能为空', trigger: 'blur' }],
        symbols: [{ required: true, message: '加仓交易对不能为空', trigger: 'blur' }],
        value: [{ required: true, message: '加仓数值不能为空', trigger: 'blur' }]
      },
      positionOpen: false,
      positionForm: {},
      positionRules: {
        exchangeType: [{ required: true, message: '交易所不能为空', trigger: 'blur' }],
        api_id: [{ required: true, message: 'api用户不能为空', trigger: 'blur' }]
        // symbol: [{ required: true, message: '交易对不能为空', trigger: 'blur' }]
      },
      searchLoding: false,
      // 取消委托
      cancelOpen: false,
      cancelForm: {
        exchangeType: '',
        api_id: undefined,
        order_type: 1,
        symbol: undefined,
        order_sn: undefined
      },
      btnLoading: false,
      exchangeTypes: [],
      aicoins: {},
      aicoinPrice: ''
    }
  },
  computed: {
    comSymbols() {
      return this.title === '批量添加' ? this.symbolGroups : this.symbol.symbolList
    },
    comStatusStyle() {
      return row => {
        const s = this.status[row.status] ? this.status[row.status].l : ''
        if (['已取消', '下单失败'].includes(s)) {
          return { color: '#f56c6c' }
        } else if (['已触发', '已平仓', '委托中'].includes(s)) {
          return { color: '#67c23a' }
        } else if (['现货已成交', '已开仓', '已成交'].includes(s)) {
          return { color: '#e6a23c' }
        } else {
          return {}
        }
      }
    }
  },
  watch: {
    'form.symbol_type'(newValue) {
      if (newValue === 1) {
        this.form.cover_type = 0
      } else {
        this.form.cover_type = 0
      }
      this.form.symbol_group_id = undefined
      this.form.symbol = undefined
      this.getSymbol({})
      this.getSymbolGroup(this.form.symbol_type, this.form.exchange_type)
    },
    // 'form.cover_type'(newValue) {
    //   if (newValue === 3) {
    //     this.form.symbol = undefined
    //     this.getSymbol({})
    //   }
    // },
    'form.price_pattern'(newValue) {
      if (newValue === 'aicoin') {
        this.aicoinPrice = undefined
        this.form.price = undefined
        this.form.price_type = 'aicoin'
        if (this.form.symbol) {
          aicoinSymbol({ symbol: this.form.symbol, symbolType: this.form.symbol_type }).then(res => {
            this.aicoins = res.data
          })
        }
      } else {
        this.form.price_type = newValue === 'percentage' ? 'new' : newValue
        this.form.sign_price_type = newValue
      }
    },
    'storeForm.symbol_type'(newValue) {
      this.storeForm.symbols = undefined
      this.getSymbol({}, newValue)
    },
    'postionForm.close_type'(newValue) {
      this.postionForm.symbol = undefined
      this.getSymbol({}, newValue)
    }
  },
  created() {
    this.getList()
    this.getSymbolGroup()
    // this.getLineApiUserItems()
    // this.getListLineApiUser()
    // 获取交易所字典数据
    this.getDicts('exchange_type').then(response => {
      this.exchangeTypes = response.data
    })
    listLineApiUser({ pageIndex: 1, pageSize: 999, exchangeType: '' }).then(response => { this.lineUsersAll = response?.data?.list || [] })
  },
  methods: {
    onchangeSymbol() {
      if (this.form.price_pattern === 'aicoin') {
        aicoinSymbol({ symbol: this.form.symbol, symbolType: this.form.symbol_type }).then(res => {
          this.aicoinPrice = undefined
          this.form.price = undefined
          this.aicoins = res.data
        })
      }
    },
    onchangeAicoin() {
      this.form.price = this.aicoinPrice
    },
    onAddExt(type, index) {
      if (type === 0) {
        this.form.ext.push({
          reducePriceRatio: undefined,
          reduceNumRatio: undefined,
          reduceTakeProfitRatio: undefined,
          reduceStopLossRatio: undefined,

          takeProfitRatio: undefined,
          addPositionPriceRatio: undefined,
          addPositionOrderType: 'LIMIT',
          addPositionType: 1,
          addPositionVal: undefined
        })
        return false
      }
      this.form.ext.splice(index, 1)
    },
    exchangeTypeFormat(row) {
      return this.selectDictLabel(this.exchangeTypes || [], row.exchangeType)
    },
    onChangePosition() {
      // this.getLineApiUserItems(this.positionForm.exchange_type)
      this.getListLineApiUser(this.positionForm.exchange_type)
      this.$set(this.positionForm, 'symbol', undefined)
      this.getSymbol({}, this.positionForm.close_type, this.positionForm.exchange_type)
    },
    onChangeCancel() {
      this.cancelForm.api_id = undefined
      // this.getLineApiUserItems(this.cancelForm.exchangeType)
      this.getListLineApiUser(this.cancelForm.exchangeType)
    },
    onchangeMode() {
      this.getListLineApiUser(this.modeForm.exchangeType)
      this.getSymbol({}, 2, this.modeForm.exchangeType)
      this.getSymbolGroup(2, this.modeForm.exchangeType)
    },
    onchangeForm() {
      this.getListLineApiUser(this.form.exchange_type)
      this.getSymbol({}, this.form.symbol_type, this.form.exchange_type)
      this.getSymbolGroup(this.form.symbol_type, this.form.exchange_type)
    },
    onSelectAll() {
      if (this.form.api_id && this.form.api_id.length > 0) {
        this.form.api_id = []
        return false
      }
      this.form.api_id = this.apiIdOptions.map(item => item.key)
    },
    onAll() {
      if (this.modeForm.api_user_ids && this.modeForm.api_user_ids.length > 0) {
        this.modeForm.api_user_ids = []
        return false
      }
      this.modeForm.api_user_ids = this.lineUsers.map(item => item.id)
    },
    // 获取杠杆api用户
    getListLineApiUser(exchangeType) {
      listLineApiUser({ pageIndex: 1, pageSize: 999, exchangeType: exchangeType || this.form.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.title === '添加委托管理' && ([1, 3].includes(this.form.cover_type)) ? getSameSymbol : listLineSymbol
      apiCall({ pageIndex, pageSize: 6, type: type || this.form.symbol_type, symbol, exchangeType: exchangeType || this.form.exchange_type }).then(res => {
        this.symbol.total = res.data.count
        this.symbol.symbolList = res.data.list
      }).finally(() => {
        this.searchLoding = false
      })
    },
    // 获取交易对组
    getSymbolGroup(type = 2, exchangeType) {
      console.log(type, exchangeType, '??')
      listLineSymbolGroup({ pageIndex: 1, pageSize: 999, beginTime: undefined, endTime: undefined, type, exchangeType: exchangeType || this.form.exchange_type }).then(res => {
        this.symbolGroups = res.data.list
      })
    },
    onCalc() {
      if (!this.form.price || !this.percenter) {
        return 0
      }
      let res
      if (this.form.site === 'BUY') {
        res = (1 - (this.percenter / 100)) * Number(this.form.price)
      } else {
        res = (1 + (this.percenter / 100)) * Number(this.form.price)
      }
      const [num, decimal] = String(res).split('.')
      if (decimal) {
        this.form.price = decimal.length > 4 ? `${num}.${decimal.substring(0, 4)}` : res
      } else {
        this.form.price = res
      }
    },
    onExpand(row, expanded) {
      const { symbol, id, mainId } = row
      // 查询后更新数据
      if (Object.keys(row).length > 0) {
        for (const x in this.cacheRefresh) {
          // 当前的刷新
          if (`${symbol}${id}` === x) {
            const curr = this.cacheRefresh[`${symbol}${id}`]
            curr.expandCount++
            // 如果是展开状态，且展开次数大于1，且上一次的状态为折叠，则请求api数据，不需要更新子菜单
            if (expanded && curr.expandCount > 1 && !curr.prevStatus) {
              getChildOrder({ id }).then(res => {
                const r = res.data.map((item) => ({ ...item, hasChildren: item.child_num > 0 }))
                curr.resolve(r)
              }).finally(() => {})
            }
            curr.expandCount = 1
            curr.prevStatus = expanded
          } else {
            if (this.cacheRefresh[x].prevStatus && mainId !== this.cacheRefresh[x].mainId) {
              const flag = this.linePreOrderList.findIndex(item => `${item.symbol}${item.id}` === x)
              if (flag >= 0) {
                this.cacheRefresh[x].expandCount = 0
                this.cacheRefresh[x].prevStatus = false
                this.$refs.table && this.$refs.table.toggleRowExpansion(this.linePreOrderList[flag], false)
              }
            }
          }
        }
      }
    },
    // 获取子数据
    onLoadChild(tree, treeNode, resolve) {
      const { symbol, id } = tree
      this.currentExpandId = id
      this.cacheRefresh[`${symbol}${id}`] = {}
      this.cacheRefresh[`${symbol}${id}`].mainId = id
      this.cacheRefresh[`${symbol}${id}`].resolve = resolve
      this.cacheRefresh[`${symbol}${id}`].expandCount = 0
      getChildOrder({ id }).then(res => {
        const r = res.data.map((item) => ({ ...item, hasChildren: item.child_num > 0 }))
        resolve(r)
      }).finally(() => {})
    },
    /** 查询参数列表 */
    getList() {
      this.loading = true
      listLinePreOrder(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.linePreOrderList = response.data.list.map(item => ({ ...item, hasChildren: true }))
        this.total = response.data.count
        // 查询后更新数据
        for (const x in this.cacheRefresh) {
          const flag = this.linePreOrderList.findIndex(item => `${item.symbol}${item.id}` === x)
          if (flag !== -1 && this.cacheRefresh[x].prevStatus) {
            this.$refs.table && this.$refs.table.toggleRowExpansion(this.linePreOrderList[flag], false)
            this.$refs.table && this.$refs.table.toggleRowExpansion(this.linePreOrderList[flag], true)
          }
        }
        this.loading = false
      })
    },
    onPosition() {
      this.title = ''
      this.resetForm('formPosition')
      this.positionForm = {
        exchange_type: this.exchangeTypes.length ? this.exchangeTypes[0].value : '',
        api_id: undefined,
        symbol: undefined,
        rate: '0',
        close_type: 1
      }
      this.getSymbol({}, 1)
      // this.getLineApiUserItems(this.positionForm.exchange_type)
      this.getListLineApiUser(this.positionForm.exchange_type)
      this.positionOpen = true
    },
    positionCancel() {
      this.positionOpen = false
      this.positionForm = {
        exchange_type: this.exchangeTypes.length ? this.exchangeTypes[0].value : '',
        api_id: undefined,
        symbol: undefined,
        rate: '0',
        close_type: 1
      }
      this.resetForm('formPosition')
    },
    positionConfirm() {
      this.$refs['formPosition'].validate((valid) => {
        if (valid) {
          const { api_id } = this.positionForm
          closePosition({ ...this.positionForm, api_id: Number(api_id) }).then(res => {
            if (res.code === 200) {
              this.msgSuccess(res.msg)
              this.storeOpen = false
            } else {
              this.msgError(res.msg)
            }
          })
        }
      })
    },
    onStore() {
      this.title = ''
      this.storeForm = {
        exchangeType: this.exchangeTypes.length ? this.exchangeTypes[0].value : '',
        api_id: undefined,
        cover_account: 1,
        symbol_type: 1,
        symbols: undefined,
        cover_account_a_type: 'MARKET',
        cover_account_b_type: 'MARKET',
        cover_account_a_rate: undefined,
        cover_account_b_rate: undefined,
        cover_type: 1,
        value: undefined
      }
      this.resetForm('formStore')
      this.getSymbol({}, 1)
      this.storeOpen = true
    },
    storeCancel() {
      this.storeOpen = false
      this.storeForm = {
        exchangeType: this.exchangeTypes.length ? this.exchangeTypes[0].value : '',
        api_id: undefined,
        cover_account: 1,
        symbol_type: 1,
        symbols: undefined,
        cover_account_a_type: 'MARKET',
        cover_account_b_type: 'MARKET',
        cover_account_a_rate: undefined,
        cover_account_b_rate: undefined,
        cover_type: 1,
        value: undefined
      }
      this.resetForm('formStore')
    },
    storeConfirm() {
      this.$refs['formStore'].validate((valid) => {
        if (valid) {
          const { symbols, api_id } = this.storeForm
          manuallyCover({ ...this.storeForm, api_id: Number(api_id), symbols: symbols.toString() }).then(res => {
            if (res.code === 200) {
              this.msgSuccess(res.msg)
              this.storeOpen = false
            } else {
              this.msgError(res.msg)
            }
          })
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.resetMode()
    },
    onMode(title) {
      this.title = ''
      this.mode.modeTitle = title
      this.resetMode()
      this.getListLineApiUser(this.modeForm.exchangeType)
      this.getSymbol({}, 2, this.modeForm.exchangeType)
      this.getSymbolGroup(2, this.modeForm.exchangeType)
      this.mode.modeOpen = true
    },
    modeCancel() {
      this.mode.modeOpen = false
      this.resetMode()
    },
    // 表单重置
    resetMode() {
      this.modeForm = {
        exchangeType: this.exchangeTypes.length ? this.exchangeTypes[0].value : '',
        api_user_ids: undefined,
        symbol: undefined,
        group_id: undefined,
        is_all: 0
      }
      if (this.mode.modeTitle === '设置杠杆') {
        this.$set(this.modeForm, 'leverage', 1)
      } else {
        this.$set(this.modeForm, 'margin_type', 'CROSSED')
      }
      this.resetForm('formMode')
    },
    modeConfirm() {
      // 交易对 交易对组 二选一
      const { symbol, group_id, is_all } = this.modeForm
      this.$refs['formMode'].validate(valid => {
        if (valid) {
          // 否的话
          if (is_all === 0) {
            if ((!symbol || symbol?.length === 0) && !group_id) {
              this.msgError('交易对/交易对组二选一')
              return false
            }
          }
          if (this.mode.modeTitle === '设置杠杆') {
            this.btnLoading = true
            orderLever({ ...this.modeForm, symbol: this.modeForm.symbol?.toString(), api_user_ids: this.modeForm.api_user_ids.toString() }).then(response => {
              if (response.code === 200) {
                this.msgSuccess(response.msg)
                this.mode.modeOpen = false
              } else {
                this.msgError(response.msg)
              }
            }).finally(() => { this.btnLoading = false })
            return false
          }
          this.btnLoading = true
          orderMarginType({ ...this.modeForm, symbol: this.modeForm.symbol.toString(), api_user_ids: this.modeForm.api_user_ids.toString() }).then(response => {
            if (response.code === 200) {
              this.msgSuccess(response.msg)
              this.mode.modeOpen = false
            } else {
              this.msgError(response.msg)
            }
          }).finally(() => { this.btnLoading = false })
        }
      })
    },
    reset() {
      this.percenter = undefined
      this.form = {
        id: undefined,
        api_id: undefined,
        group_id: undefined,
        quote_symbol: undefined,
        sign_price: undefined,
        price_type: 'new',
        rate: undefined,
        price: undefined,
        num: undefined,
        buy_price: undefined,
        site: 'BUY',
        order_sn: undefined,
        order_type: 0,
        cover_rate: undefined,
        desc: undefined,
        status: undefined,
        admin_id: undefined,
        is_auto_scale: undefined,
        close_type: undefined,
        direction: undefined,

        ext: [],
        symbol_type: 1,
        hedge_buy_type: 1,
        HedgeBuyTotal: undefined,
        HedgeTakeProfit: undefined,
        HedgeStopLoss: undefined,
        exchange_type: this.exchangeTypes.length ? this.exchangeTypes[0].value : '',
        scale_type: 2,
        main_order_type: 'LIMIT',
        hedge_order_type: 'LIMIT',
        add_position_main_type: 'LIMIT',
        add_position_hedge_type: 'LIMIT',
        hedge_trigger_percent: undefined,
        hedge_trigger_percent_max: undefined,
        hedge_close_count: 0,
        expire_hour: 4,
        profit_rate: '',
        cover_type: 0,
        price_pattern: 'percentage',
        profit: '',
        stop_price: '',
        save_template: '0',
        template_name: ''
      }
      if (this.title === '批量添加') {
        this.$set(this.form, 'order_num', 1)
        this.$set(this.form, 'script', '1')
        this.$set(this.form, 'symbol_group_id', undefined)
      } else {
        this.$set(this.form, 'symbol', undefined)
      }
      this.resetForm('form')
    },
    getImgList: function() {
      this.form[this.fileIndex] = this.$refs['fileChoose'].resultList[0].fullUrl
    },
    fileClose: function() {
      this.fileOpen = false
    },
    apiIdFormat(row) {
      return this.selectItemsLabel(this.apiIdOptions, row.apiId)
    },
    // 关系
    getLineApiUserItems(exchangeType) {
      this.getItems(getMainUser, { pageSize: 10000, exchangeType: exchangeType || this.form.exchange_type }).then(res => {
        this.apiIdOptions = this.setItems(res || [], 'id', 'apiName')
      })
    },
    // 文件
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageIndex = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd(title) {
      this.title = title || '添加委托管理'
      this.reset()
      this.getListLineApiUser()
      this.open = true
      this.isEdit = false
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.title = '修改委托管理'
      this.reset()
      const id =
                row.id || this.ids
      getLinePreOrder(id).then(response => {
        this.form = response.data
        this.open = true
        this.isEdit = true
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.price) {
            this.form.price = String(this.form.price)
          }

          if (this.form.id !== undefined) {
            updateLinePreOrder(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess(response.msg)
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          } else {
            if (this.title === '批量添加') {
              const params = JSON.parse(JSON.stringify({ ...this.form, symbol_group_id: String(this.form.symbol_group_id), api_id: this.form.api_id.toString() }))
              delete params.symbol
              batchAddOrder(params).then(response => {
                if (response.code === 200) {
                  this.msgSuccess(response.msg)
                  this.open = false
                  this.getList()
                } else {
                  this.msgError(response.msg)
                }
              })
              return false
            }
            addOrder({ ...this.form, api_id: this.form.api_id.toString() }).then(response => {
              if (response.code === 200) {
                this.msgSuccess(response.msg)
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          }
        }
      })
    },
    onCancel() {
      this.cancelOpen = true
      this.$refs.formCancel?.resetFields()
      this.cancelForm.exchangeType = this.exchangeTypes.length ? this.exchangeTypes[0].value : ''
      // 获取用户
      // this.getLineApiUserItems(this.cancelForm.exchangeType)
      this.getListLineApiUser(this.cancelForm.exchangeType)
    },
    handleCancel(row) {
      if (typeof row === 'string') {
        this.$refs[row].validate((valid) => {
          if (valid) {
            cancelOpenOrder(this.cancelForm)
              .then((response) => {
                if (response.code === 200) {
                  this.msgSuccess(response.msg)
                  this.cancelOpen = false
                  this.getList()
                } else {
                  this.msgError(response.msg)
                }
              })
          }
        })
        return false
      }
      const { orderType, orderSn, apiId, symbol } = row
      this.$confirm('是否确认取消委托为"' + symbol + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return cancelOpenOrder({ order_type: Number(orderType), order_sn: orderSn, api_id: apiId, symbol })
      }).then((response) => {
        if (response.code === 200) {
          this.msgSuccess(response.msg)
          this.getList()
        } else {
          this.msgError(response.msg)
        }
      }).catch(function() {})
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      var Ids = (row.id && [row.id]) || this.ids
      this.$confirm(`是否确认删除此（${Ids.length}）数据吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delLinePreOrder({ 'ids': Ids })
      }).then((response) => {
        if (response.code === 200) {
          this.msgSuccess(response.msg)
          this.open = false
          this.getList()
        } else {
          this.msgError(response.msg)
        }
      }).catch(function() {
      })
    },
    handleTrigger() {
      this.$confirm('是否确清除待触发数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return clearUnTriggered()
      }).then((response) => {
        if (response.code === 200) {
          this.msgSuccess(response.msg)
          this.getList()
        } else {
          this.msgError(response.msg)
        }
      }).catch(function() {
      })
    },
    // 一键清除所有
    handleDeleteAll() {
      this.$confirm('是否确认一键清除所有下单数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return clearAll()
      }).then((response) => {
        if (response.code === 200) {
          this.msgSuccess(response.msg)
          this.getList()
        } 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%;
  }
}
::v-deep.el-table{
  .el-table__row--level-0{
    background: #f5f5f5;
  }
}
.exts{
  font-size: 13px;
  margin-bottom: 20px;
  border: 1px solid #ebebeb;
  padding: 10px;
  border-radius: 8px;
}
</style>
