<template>
  <!-- 挂牌求购 -->
  <Drawer :title="!isBuy() ? '摘牌买入' : '摘牌卖出'" :placement="'right'" :visible="visible" :width="1052" @cancel="cancel" class="post-buying-container">
    <a-row>
      <a-col :span="12">
        <div class="post_buying_chart">
          <div class="buying_chart__nav">
            <div class="content--left">{{ parantSelectedRow.goodscode }}</div>
            <div class="content--right">{{ parantSelectedRow.goodsname }}</div>
          </div>
          <div class="chart-tips__last">
            <div :class="['content--left', handleQuotePriceColor_out(parantSelectedRow.refgoodscode, 'last')]">{{ getQuoteValue_out(parantSelectedRow.refgoodscode, 'last') }}</div>
            <div class="content--right">
              <span :class="handleQuotePriceColor_out(parantSelectedRow.refgoodscode, 'last')">{{ quoteChange_out(parantSelectedRow.refgoodscode) }}</span>
              <span :class="handleQuotePriceColor_out(parantSelectedRow.refgoodscode, 'last')">{{ quoteAmplitude_out(parantSelectedRow.refgoodscode) }}</span>
            </div>
          </div>
          <a-row>
            <a-col :span="4" :offset="2">最高价</a-col>
            <a-col :span="6">
              <span :class="handleQuotePriceColor_out(parantSelectedRow.refgoodscode, 'highest')">{{ getQuoteValue_out(parantSelectedRow.refgoodscode, 'highest') }}</span>
            </a-col>
            <a-col :span="4" :offset="2">开盘价</a-col>
            <a-col :span="6">
              <span :class="handleQuotePriceColor_out(parantSelectedRow.refgoodscode, 'opened')">{{ getQuoteValue_out(parantSelectedRow.refgoodscode, 'opened') }}</span>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="4" :offset="2">最低价</a-col>
            <a-col :span="6">
              <span :class="handleQuotePriceColor_out(parantSelectedRow.refgoodscode, 'lowest')">{{ getQuoteValue_out(parantSelectedRow.refgoodscode, 'lowest') }}</span>
            </a-col>
            <a-col :span="4" :offset="2">昨结价</a-col>
            <a-col :span="6">{{ getQuoteValue_out(parantSelectedRow.refgoodscode, 'presettle') }}</a-col>
          </a-row>
          <div class="chart-content">
            <Chart :selectedRow="getQuoteDayInfoByCode(parantSelectedRow.refgoodscode)" :showExchange="false" />
          </div>
        </div>
      </a-col>
      <a-col :span="12">
        <div class="post_buying">
          <a-form class="inlineForm dialogForm" ref="formRef" :model="formState" :rules="rules">
            <div class="formBar">
              <a-row :gutter="24">
                <a-col :span="24">
                  <a-form-item label="贸易账户" name="accountid">
                    <a-select class="inlineFormSelect" style="width: 260px" v-model:value="formState.accountid" placeholder="请选择">
                      <a-select-option v-for="item in accountList" :value="item.accountid" :key="item.accountid">{{ item.accountid }}</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-form-item label="挂牌方">
                    <span class="white">{{ selectedRow.username }}</span>
                  </a-form-item>
                </a-col>
                <a-col :span="24" v-if="!isFloat()">
                  <a-form-item label="价格类型">
                    <span class="white">固定价</span>
                  </a-form-item>
                </a-col>
                <a-col :span="24" v-if="isFloat()">
                  <a-form-item label="挂牌估算价">
                    <span class="white">{{ getRatio() }}</span>
                  </a-form-item>
                </a-col>
                <a-col :span="24" v-if="isFloat()">
                  <a-form-item label="卖出价格" name="priceType">
                    <a-radio-group class="commonRadioGroup" v-model:value="formState.priceType">
                      <a-radio :value="1">市价</a-radio>
                      <a-radio :value="2">限价</a-radio>
                    </a-radio-group>
                  </a-form-item>
                </a-col>
                <a-col :span="24" v-if="isFloat() && isLimit()">
                  <a-form-item label="摘牌价格" name="price" class="inputIconBox">
                    <a-input-number class="commonInput" style="width: 260px" :min="0" v-model:value="formState.price" />
                    <MinusOutlined @click="decreasePrice('price')" />
                    <PlusOutlined @click="increasePrice('price')" />
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-form-item label="挂牌数量">
                    <span class="white">{{ selectedRow.orderqty }}</span>
                  </a-form-item>
                </a-col>
                <a-col :span="24" v-if="!useUserType()">
                  <a-form-item label="摘牌数量">
                    <span class="white">{{ formState.num }}</span>
                  </a-form-item>
                </a-col>
                <a-col :span="24" v-if="useUserType()">
                  <a-form-item label="摘牌数量" name="num" class="inputIconBox">
                    <a-input-number class="commonInput" style="width: 260px" :min="0" :max="selectedRow.orderqty" v-model:value="formState.num" />
                    <MinusOutlined @click="decreaseNumber('num')" />
                    <PlusOutlined @click="increaseNumber('num')" />
                    <span class="input-enumdicname">{{ selectedRow.enumdicname }}</span>
                  </a-form-item>
                </a-col>
                <a-col :span="24" v-if="useUserType()" class="mt-10">
                  <a-form-item>
                    <a-slider :min="0" v-model:value="formState.num" :max="selectedRow.orderqty" class="formSlider" />
                    <div class="unit">
                      <span>0</span>
                      <span>{{ selectedRow.orderqty }}{{ selectedRow.enumdicname }}</span>
                    </div>
                  </a-form-item>
                </a-col>
                <a-col :span="24" class="relative mt20" v-if="!isFloat()">
                  <a-form-item :label="'摘牌金额'">
                    <span class="white ml8">{{ getMoney() }}</span>
                  </a-form-item>
                </a-col>
                <a-col :span="24" class="relative mt20" v-if="isFloat()">
                  <a-form-item :label="'估算金额'">
                    <span class="white ml8">{{ getMoney() }}</span>
                  </a-form-item>
                </a-col>
                <a-col :span="24" v-if="getMargin()">
                  <a-form-item :label="'履约保证金'">
                    <span class="white ml8">{{ getMargin() }}</span>
                  </a-form-item>
                </a-col>
                <a-col :span="24">
                  <a-form-item label="可用资金">
                    <span class="white ml8">{{ canUseMoney() }}</span>
                  </a-form-item>
                </a-col>
              </a-row>
            </div>
            <a-row :gutter="24">
              <a-col :span="24" class="fixedBtns">
                <a-form-item class="btnCenter">
                  <a-button class="listedBtn" @click="submit">{{ !isBuy() ? '买入' : '卖出' }}</a-button>
                  <a-button class="ml10 cancelBtn" @click="cancel">取消</a-button>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </a-col>
    </a-row>
  </Drawer>
</template>

<script lang="ts">
import { Des } from '@/common/components/commonDes';
import Drawer from '@/common/components/drawer/index.vue';
import { BuyOrSell, TradeMode } from '@/common/constants/enumCommon';
import { ModalEnum } from '@/common/constants/modalNameEnum';
import { requestResultLoadingAndInfo } from '@/common/methods/request/resultInfo';
import { useTaAccount } from '@/common/setup/account';
import { validateAction } from '@/common/setup/form';
import { _closeModal } from '@/common/setup/modal/modal';
import { getQuoteValue_out, handleQuotePriceColor_out, handleSubcriteOnDemandQuote, quoteAmplitude_out, quoteAmplituOfVibration, quoteChange_out } from '@/common/setup/table/tableQuote';
import { useTodayMargin } from '@/hooks/margin';
import { getSelectedAccountId } from '@/services/bus/account';
import { getGoodsAgreeunitByGoodsId, getQuoteDayInfoByCode, getQuoteDayInfoByCodeFindPrice } from '@/services/bus/goods';
import { geLoginID_number } from '@/services/bus/login';
import { getMarketByTradeMode, getMarketIdsByTradeMode } from '@/services/bus/market';
import { QueryQuoteGoodsListRsp, QueryTjmdTodayAccountMarginReq, QueryTjmdTradeOrderDetailRsp } from '@/services/go/Tjmd/interface';
import { diaoQiOrder } from '@/services/socket/order';
import { OrderReq } from '@/services/socket/order/interface';
import Bus from '@/utils/eventBus/index';
import Chart from '@/views/market/market-spot/goods-chart/index.vue';
import { MinusOutlined, PlusOutlined } from '@ant-design/icons-vue';
import Long from 'long';
import moment from 'moment';
import { v4 as uuidv4 } from 'uuid';
import { defineComponent, PropType, ref } from 'vue';
import { RefGoodsList } from '../../interface';
import { useUserType } from '../setup';
import { FormParam } from './interface';
import { handleForm, useBlocksNumber, useBlocksPrice } from './setup';

export default defineComponent({
  emits: ['cancel', 'update'],
  name: ModalEnum.spot_trade_warehouse_post_buying,
  components: {
    Des,
    Drawer,
    PlusOutlined,
    MinusOutlined,
    Chart,
  },
  props: {
    selectedRow: {
      type: Object as PropType<QueryTjmdTradeOrderDetailRsp>,
      default: {},
    },
    parantSelectedRow: {
      type: Object as PropType<RefGoodsList>,
      default: {},
    },
    refGoods: {
      type: Object as PropType<QueryQuoteGoodsListRsp[]>,
      default: [],
    },
    buyOrSell: {
      type: Number as PropType<BuyOrSell>,
      defualt: BuyOrSell.buy,
    },
  },
  setup(props, context) {
    const marginParam: QueryTjmdTodayAccountMarginReq = {
      accountid: getSelectedAccountId()!.toString(),
      goodsid: props.selectedRow.goodsid,
      marketids: getMarketIdsByTradeMode(TradeMode.DiaoQi),
    };
    // 获取保证金比例
    const { getReckonMarginTypeAndValueByTradeMode } = useTodayMargin(marginParam);
    // 控制弹窗
    const { visible, cancel } = _closeModal(context);
    // 表单
    const { rules, formState, formRef } = handleForm();
    const loading = ref<boolean>(false);
    // 资金账号
    const { canUseMoney, accountList } = useTaAccount<FormParam>(formState);

    const isBuy = () => props.buyOrSell === BuyOrSell.buy;
    const isFloat = () => props.selectedRow.pricemode === 3;
    // 投资者摘牌时可以选择数量，机构摘牌时不能改数量只能整单摘（全部挂牌数量
    if (!useUserType() || !isFloat()) {
      formState.num = props.selectedRow.orderqty;
    }
    // 是否是 限价
    const isLimit = () => formState.priceType === 2;
    const getPrice = () => (isFloat() && isLimit() ? formState.price : props.selectedRow.orderprice);
    // 四舍五入
    const fn = (value: number) => Math.round(value * 100) / 100;
    // 金额
    const getMoney = () => {
      let result = 0;
      const temp = getGoodsAgreeunitByGoodsId(props.selectedRow.goodsid);
      const argeeunit = temp ? temp : 1;
      let priceTemp: number = 0;
      // 限价
      if (isLimit()) {
        priceTemp = formState.price;
      } else {
        // 市价
        if (isFloat()) {
          const price = getQuoteDayInfoByCodeFindPrice(props.parantSelectedRow.refgoodscode);
          if (price && price !== '--') {
            // 浮动价
            priceTemp = +price + props.selectedRow.marketmaxsub;
          }
        } else {
          priceTemp = props.selectedRow.orderprice;
        }
      }
      if (formState.num) {
        // 四舍五入
        result = fn(formState.num * argeeunit * +priceTemp);
      }
      return result ? result : '--';
    };
    // 估算价
    const getRatio = () => {
      let result = '--';
      const price = getQuoteDayInfoByCodeFindPrice(props.parantSelectedRow.refgoodscode);
      if (price && price !== '--') {
        // 四舍五入
        result = fn(+price + props.selectedRow.marketmaxsub).toString();
      }
      return result;
    };
    // 保证金
    const getMargin = () => {
      let result = '--';
      const price = getMoney();
      if (price !== '--') {
        const [marginType, marginValue] = getReckonMarginTypeAndValueByTradeMode(TradeMode.DiaoQi);
        if (marginValue && formState.num) {
          const temp = marginType === 1 ? +price * marginValue : formState.num * marginValue
          // 四舍五入
          result = fn(temp).toString();
        }
      }
      return result;
    };
    // 估算价
    // function getGuseetPrice() {
    //     let result = '--';
    //     const goodsPrice = getQuoteDayInfoByCodeFindPrice(props.selectedRow.refgoodscode);
    //     console.log('goodsPrice', goodsPrice);
    //     if (goodsPrice && goodsPrice !== '--') {
    //         // 有实时行情价格
    //         result = ((goodsPrice as number) + formState.PriceMove).toFixed(2);
    //     }
    //     return result;
    // }
    // const { getMaxNum, getMoney, getMargin, getPrice } = handleNumAndPrice(props.selectedRow);
    function submit() {
      validateAction<FormParam>(formRef, formState).then((res) => {
        const param: OrderReq = {
          ClientSerialNo: uuidv4(), // 客户端流水号
          ClientOrderTime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'), // 客户端委托时间
          ClientType: 4, // 终端类型
          LoginID: geLoginID_number()!, // 登陆账号
          AccountID: res.accountid, // 交易账号
          GoodsID: props.selectedRow.goodsid, // 商品ID
          MarketID: getMarketByTradeMode(TradeMode.DiaoQi)?.marketid, // 市场ID
          ValidType: 1, // 校验类型 当日有效
          OperateType: 1, // 操作类型: 申请
          OrderSrc: 1, // 单据来源: 客户端下单
          RelatedID: Long.fromString(props.selectedRow.orderid), // 操作员账号ID
          OrderPrice: getPrice(), // 委托价格
          OperatorID: Number(geLoginID_number()),
          // MarketMaxSub: number // 市价允许最大偏差(做市)
          OrderQty: formState.num, // 委托数量
          BuyOrSell: isBuy() ? BuyOrSell.sell : BuyOrSell.buy, // 买卖方向  0 买 1 卖
          BuildType: 1, // 下单类型  1 建 2 平
          // CurtQuotePrice: 0, // 保留，计算冻结金额使用
          // SpPrice: 0 ,// 止盈价格
          // SlPrice: 0 , // 止损价格
          PriceMode: res.priceType, // 取价方式
          TimevalidType: 1, // 时间有效类型 单日有效
          TriggerType: 1, // 预埋单触发类型
          // TriggerPrice: number // 预埋单触发价格
          ListingSelectType: 2, // 挂牌点选类型 1：挂牌 2：摘牌 3：先摘后挂
          DelistingType: 2, // 摘牌类型 2:点选成交
          // RelatedID: number // 关联单号
          OptionType: 1, // 期权类型(1:认购(看涨)2:认沽(看跌))
          // Premium: number // 权利金
          // TriggerOperator: number // 触发条件(1:大于等于2:小于等于)
          // ServiceTime: string // 服务端时间
          // CouponTypeID: number // 优惠券类型ID(买方)
          // UsedQty: number // 使用数量
          // ValidTime: string // 指定有效日期
          // ReceiveInfoID: number // 收货地址ID
        };
        // if (isFloat()) {
        //     // 浮动价
        //     param.MarketMaxSub = res.PriceMove; // 基差
        //     param.OrderPrice = +getQuoteDayInfoByCodeFindPrice(goodscode)!;
        // }
        requestResultLoadingAndInfo(diaoQiOrder, param, loading, ['摘牌求购成功', '摘牌求购失败:']).then(() => {
          cancel(true);
          Bus.$emit('spotTrade', true);
        });
      });
    }
    return {
      submit,
      cancel,
      visible,
      accountList,
      rules,
      formState,
      formRef,
      isFloat,
      getMoney,
      getMargin,
      canUseMoney,
      isBuy,
      useUserType,
      isLimit,
      ...useBlocksPrice(),
      ...useBlocksNumber(),
      getRatio,
      handleQuotePriceColor_out, handleSubcriteOnDemandQuote, quoteAmplitude_out, quoteAmplituOfVibration, quoteChange_out, getQuoteValue_out, getQuoteDayInfoByCode
    };
  },
});


</script>

<style lang="less">
.post-buying-container {
    top: 101px;
    .ant-drawer-content-wrapper {
        height: 605px;
    }
}
.chart-content {
    height: 400px;
    .chart-content__header,
    .chart-content__main {
        width: 90% !important;
        margin: auto !important;
    }

    .chart-slider {
        display: none;
    }
}
.formBar {
    height: 100%;
    max-height: 100%;
}
.post_buying_chart {
    [theme='light'] & {
        --bgcolor: #fff;
        --tab-border-color: #dae5ec;
        --tab-checked-color: #0866b8;
        --tab-checked-bgcolor: #d4e0ff;
        --slider-border-color: #b2c4dd;
        --slider-bgcolor: #edf2f7;
        --slider-button-color: #b2c4dd;
        --row-border-color: #dae5ec;
        --row-title-color: #acb8c0;
        --row-content-color: #3c454b;
        --tik-title-bgcolor: #ecf2f5;
        --tik-title-color: #7a8a94;
    }
    color: @m-grey67;

    // background-color: var(--bgcolor, #0e0e0f);

    // background: @m-blue37;
    // color: @m-grey67;
    .buying_chart {
        display: flex;

        // background-color: @m-blue36;
        &__nav {
            display: flex;
            justify-content: center;
            align-items: center;

            .content {
                &:first-child:not(:last-child) {
                    margin-right: 16px;
                }

                &--left {
                    font-size: 16px;
                    color: var(--row-content-color, #acb8c0);
                    margin-right: 6px;
                }

                &--right {
                    font-size: 24px;
                    color: #fc9618;
                }
            }
        }
    }
    .chart-tips {
        display: flex;
        flex-direction: column;
        width: 300px;
        height: 100%;

        &__last {
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 16px 0;
            .content {
                &--left {
                    font-size: 24px;
                    margin-right: 16px;
                }

                &--right {
                    display: flex;
                    flex-direction: column;
                    align-items: flex-start;
                }
            }
        }
    }
}
.post_buying {
    width: 100%;
    height: 100%;
    .flex;
    flex-direction: column;
    position: relative;
    overflow: hidden;
    .ant-form {
        height: 100%;
    }
    .condition {
        width: 100%;
        height: 48px;
        margin: 0 16px;
        padding: 10px 0;
        border-bottom: 1px solid @m-black6;
        .inlineflex;
        .conditionBtn {
            align-self: center;
            align-items: center;
            border: 0;
            min-width: 80px;
            height: 28px;
            line-height: 28px;
            background: @m-black7;
            .rounded-corners(3px);
            font-size: 14px;
            color: @m-blue0;
            &:hover {
                background: @m-black7-hover;
                color: @m-blue0-hover;
            }
        }
        .conditionBtn + .conditionBtn {
            margin-left: 10px;
        }
    }
}

.unit {
    margin-left: 70px;
    width: 260px;
    .flex;
    justify-content: space-between;
    font-size: 14px;
    color: @m-grey41;
    height: 14px;
    line-height: 14px;
}
.listedBtn {
    width: 120px;
    height: 30px;
    line-height: 30px;
    background: linear-gradient(0deg, @m-blue2 0%, @m-blue0 100%);
    border-radius: 3px;
    color: @m-white0;
    font-size: 14px;
    text-align: center;
    border: 0;
    &:hover {
        background: linear-gradient(0deg, @m-blue0-hover 0%, @m-blue2-hover 100%);
        color: @m-white0-hover;
    }
}
.cancelBtn:extend(.listedBtn) {
    background: linear-gradient(0deg, @m-grey12 0%, @m-grey13 100%) !important;
    &:hover {
        background: linear-gradient(0deg, @m-grey12-hover 0%, @m-grey13-hover 100%) !important;
        color: @m-white0-hover;
    }
}
.ml10 {
    margin-left: 10px;
}
.ant-form.dialogForm .ant-row.ant-form-item {
    margin-bottom: 14px;
}
.mt20 {
    margin-top: 20px;
}
.mt-10 {
    margin-top: -10px;
}
.ant-input-suffix {
    position: absolute;
    right: -25px;
}
.minusBtn,
.plusBtn {
    width: 15px;
    height: 32px;
    line-height: 32px;
    font-size: 15px;
    color: @m-blue15;
    cursor: pointer;
}
.minusBtn {
    position: absolute;
    top: -6px;
    left: 14px;
    z-index: 1;
}
.plusBtn {
    position: absolute;
    top: -6px;
    right: 14px;
    z-index: 1;
}
.stepper {
    padding-left: 30px;
    padding-right: 30px;
    text-align: center;
    color: @m-yellow1;
    font-size: 16px;
}
.ant-slider.formSlider {
    width: 260px !important;
    margin-left: 70px;
    .ant-slider-rail {
        margin-right: 0;
        padding-right: 0;
        height: 3px !important;
        border-radius: 2px !important;
        background-color: @m-blue14;
    }
    .ant-slider-track {
        height: 3px;
        background-color: @m-blue0;
    }
    .ant-slider-step {
        height: 3px;
    }
    .ant-progress-text {
        display: none;
    }
}
</style>