<template>
  <a-spin :spinning="spinning">
    <a-modal
      title="添加机器人"
      :visible="visible"
      ok-text="确认"
      cancel-text="取消"
      @ok="hideModal"
      @cancel="visible = false"
    >
      <a-form-model
        ref="robotCreateForm"
        :model="form"
        :rules="rules"
        :confirmLoading="confirmLoading"
      >
        <a-form-model-item label="机器人名称" prop="Name">
          <a-input v-model="form.Name"></a-input>
        </a-form-model-item>
        <a-form-model-item label="交易所账户Id" prop="StockAccountId">
          <a-select v-model="form.StockAccountId">
            <a-select-option
              v-for="item in accountList"
              :key="item.Id"
              :value="item.Id"
              >{{ item.Name }}({{ item.UseCount }}/10)</a-select-option
            >
          </a-select>
        </a-form-model-item>
        <!-- <a-form-model-item label="策略类型" prop="PolicyType">
          <a-select v-model="form.PolicyType">
            <a-select-option
              v-for="item in RobotPolicyType"
              :key="item.value"
              :value="item.value"
              >{{ item.title }}</a-select-option
            >
          </a-select>
        </a-form-model-item> -->
        <a-form-model-item label="交易对" prop="Symbol">
          <a-select v-model="form.Symbol">
            <a-select-option
              v-for="item in allSymbol"
              :key="item.Symbol"
              :value="item.Symbol"
            >
              {{ item.Symbol }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-tabs v-model="activeName">
      <a-tab-pane tab="动量现货" :key="0">
        <a-button
          style="margin:10px 0"
          type="primary"
          @click="() => (visible = true)"
          >添加机器人</a-button
        >
        <a-table
          :columns="columns"
          :dataSource="data"
          :row-key="(row) => row.Id"
          :pagination="pagination"
        >
          <!-- 运行状态 -->
          <template slot="Status" slot-scope="text, record">
            <a-switch
              :checked="record.Robot.Status == 1"
              @change="onStatusChange(record, $event)"
            />
          </template>

          <!-- 只卖 -->
          <template slot="OnlySale" slot-scope="text, record">
            <a-switch
              :checked="!(record.TradePolicy.IsEnabledBuySignal == 1)"
              @change="onOnlySaleChange(record, $event)"
            />
          </template>

          <!-- 卖出设置 -->
          <template slot="SaleSetting" slot-scope="text, record">
            多单止盈-{{ record.TradePolicy.SaleSignalProfitRatio }}%、
            主动止盈-{{ record.TradePolicy.AutoSaleProfitRatio }}%
          </template>

          <!-- 通用配置 -->
          <template slot="CommonSetting" slot-scope="text, record">
            {{ record.TradePolicy.PositionFund }}、{{
              record.TradePolicy.MinTradePrice
            }}、{{
              getMatchTitle(record.TradePolicy.OrderMode, orderModes)
            }}、{{ getMatchTitle(record.TradePolicy.PolicyMode, strategyType) }}
          </template>

          <!-- 周期指标 -->
          <template slot="IntervalSetting" slot-scope="text, record">
            {{
              getMatchTitle(record.TradePolicy.PeriodicSignal, periodSignal)
            }}、{{ record.TradePolicy.BuySignalStartCount }}、>{{
              record.TradePolicy.FirstFallRatio
            }}%、>{{ record.TradePolicy.IntervalFallRatio }}%
          </template>

          <!-- 操作 -->
          <template slot="Action" slot-scope="text, record">
            <a-button-group>
              <a-button icon="eye" />
              <a-button type="primary" icon="edit" @click="editPage(record)" />
              <a-button type="danger" icon="delete" />
            </a-button-group>
          </template> </a-table
      ></a-tab-pane>
      <a-tab-pane tab="顶底策略" :key="1"></a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>
/* eslint-disable */
import {
  strategyType,
  fallTime,
  periodSignal,
  orderModes,
  RobotPolicyType,
} from "./js/selectoptions";
import { RobotColumns } from "./js/columns";
import { RobotCreateFormRules } from "./js/rules";
export default {
  data() {
    return {
      activeName: 0,
      spinning: false,
      confirmLoading: false,
      visible: false, //添加机器人表单弹窗
      allSymbol: [], //所有机器人交易对
      accountList: [], //所有的交易所账号
      strategyType,
      fallTime,
      periodSignal,
      orderModes,
      RobotPolicyType,
      form: {}, //机器人创建提交表单数据
      data: [],
      rules: RobotCreateFormRules, //创建机器人表单rules
      columns: RobotColumns, //机器人列表Columns
      pagination: { current: 1, pageSize: 10 },
    };
  },
  created() {
    this.getRobotList();
    this.getAllSymbol();
    this.getAccountList();
  },
  methods: {
    //获取所有的交易所账号
    getAccountList() {
      this.$http.get("/Api/StockExchangeAccount/GetList").then((res) => {
        if (res.Code == 200) {
          this.accountList = res.Data;
        }
      });
    },
    //获取所有交易对
    getAllSymbol() {
      this.$http.get("/Api/Symbol/GetList").then((res) => {
        if (res.Code == 200) {
          this.allSymbol = res.Data;
        }
      });
    },

    //获取机器人列表
    getRobotList() {
      this.spinning = true;
      this.$http.get("/Api/Robot/GetMomentumWaveTradeRobotList").then((res) => {
        this.spinning = false;
        if (res.Code == 200) {
          this.data = res.Data;
        }
      });
    },

    getMatchTitle(value, sourceArray) {
      let title = "";
      sourceArray.forEach((element) => {
        if (element.value == value) title = element.title;
      });
      return title;
    },

    //每个机器人的运行状态改变
    onStatusChange(record, isOn) {
      console.log(record, isOn);
      if (isOn) {
        record.Robot.Status = 1;
        this.$http
          .put("/Api/Robot/Start?robotId=" + record.Robot.Id)
          .then((res) => {
            if (res.Code == 200) {
              this.$message.success("已启用");
            } else {
              this.$message.error(res.Message);
            }
          });
      } else {
        record.Robot.Status = 0;
        this.$http
          .put("/Api/Robot/Stop?robotId=" + record.Robot.Id)
          .then((res) => {
            if (res.Code == 200) {
              this.$message.success("已停用");
            } else {
              this.$message.error(res.Message);
            }
          });
      }
    },

    //每个机器人的只卖设置
    onOnlySaleChange(record, isOn) {
      console.log(record, isOn);
      record.TradePolicy.IsEnabledBuySignal = isOn ? 0 : 1;
      this.$forceUpdate();
      this.$http
        .put("/Api/MomentumWavePolicy/EditPurchaseStatus", {
          RobotId: record.Robot.Id,
          OnlySell: isOn,
        })
        .then((res) => {
          if (res.Code == 200) {
            this.$message.success(isOn ? "已开启" : "已关闭");
          } else {
            this.$message.error(res.Message);
          }
        });
    },

    //跳转编辑机器人策略页
    editPage(record) {
      this.$router.push(`/edit/${record.Robot.Id}`);
    },

    //请求创建新的机器人
    createNewRobot() {
      this.confirmLoading = true;
      this.$http
        .post("/Api/Robot/Add", { ...this.form, PolicyType: this.activeName })
        .then((res) => {
          this.confirmLoading = false;
          if (res.Code == 200) {
            this.visible = false;
            this.$message.success("创建成功");
            this.getRobotList();
          } else {
            this.$message.error(res.Message);
          }
        });
    },

    //创建机器人OK
    hideModal() {
      this.$refs.robotCreateForm.validate((valid) => {
        if (valid) {
          this.createNewRobot();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>
