<template>
  <!-- 现货仓单 现货明细 挂牌 -->
  <Drawer class="delistingBottom650" title="挂牌" placement="right" :visible="visible" @cancel="cancel">
    <div class="mtp-modal">
      <div class="mtp-modal__header">
        <div class="block">
          <span class="block-tag">{{ selectedRow.deliverygoodsname }}</span>
          <span class="block-tag">{{ selectedRow.wrtypename }}</span>
          <span class="block-tag">{{ selectedRow.warehousename }}</span>
        </div>
      </div>
      <div class="mtp-modal__container form-row">
        <a-form ref="formRef" :model="formState" :rules="rules">
          <a-form-item label="交易市场" name="marketid">
            <a-select class="inlineFormSelect" v-model:value="formState.marketid" @change="handleMarket" placeholder="请选择交易市场">
              <!-- <a-select-option :value="1">一口价</a-select-option>
                  <a-select-option :value="2">浮动价</a-select-option>
                  <a-select-option :value="3">贸易圈</a-select-option>-->
              <a-select-option v-for="item in spotMarkets" :key="item.marketid" :value="item.marketid">{{ item.marketname }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item ref="FixedPrice" label="挂牌价格" name="FixedPrice" :autoLink="false" v-if="!isFloat()">
            <div class="block">
              <div class="block-content">
                <a-input-number class="block-content__input dialogInput" :min="0" v-model:value="formState.FixedPrice" @blur="() => $refs.FixedPrice.onFieldBlur()" />
              </div>
              <div class="block-after" v-if="isBlocs()">
                <a-checkbox class="commonCheckbox" v-model:checked="priceCheck">可议价</a-checkbox>
              </div>
            </div>
          </a-form-item>
          <a-form-item label="行情商品" name="goodsid" v-if="isFloat()" style="width:100%">
            <!-- <a-select class="inlineFormSelect"
                          style="width: 135px"
                          placeholder="请择交易所">
                </a-select>-->
            <a-select class="inlineFormSelect" @change="handleGoodsGroups" style="width: 180px" v-model:value="formState.goodsgroupid" placeholder="请选择商品">
              <a-select-option v-for="item in goodsGroup" :value="item.goodsgroupid" :key="item.goodsgroupid">{{ item.goodsgroupname }}</a-select-option>
            </a-select>
            <a-select class="inlineFormSelect" style="width: 180px;margin-left: 5px" @change="handleGoodsChange" v-model:value="formState.goodsid" placeholder="请选择合约">
              <a-select-option v-for="item in goodsList" :value="item.goodsid" :key="item.goodsid">{{ item.goodsname }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item ref="OrderQty" label="挂牌数量" name="OrderQty" :autoLink="false">
            <div class="block">
              <div class="block-content">
                <a-input-number class="block-content__input dialogInput" :min="0" :max="selectedRow.enableqty" v-model:value="formState.OrderQty" @blur="() => $refs.OrderQty.onFieldBlur()" />
                <span class="block-content__suffix">{{ selectedRow.enumdicname }}</span>
              </div>
              <div class="block-after">
                <a-checkbox class="block-content__checkbox commonCheckbox" v-if="isBlocs()" v-model:checked="numCheck">整单</a-checkbox>
              </div>
            </div>
            <div class="block" v-if="Number.isInteger(formState.OrderQty)">
              <a-slider class="block-slider" :min="0" :max="selectedRow.enableqty" :marks="{ 0: '0', [selectedRow.enableqty]: selectedRow.enableqty + selectedRow.enumdicname }" v-model:value="formState.OrderQty" @afterChange="() => $refs.OrderQty.onFieldBlur()" />
            </div>
          </a-form-item>
          <a-form-item ref="DelistMinQty" label="起摘数量" name="DelistMinQty" :autoLink="false" v-if="!numCheck">
            <div class="block">
              <div class="block-content">
                <a-input-number class="block-content__input commonInput" :min="0" v-model:value="formState.DelistMinQty" @blur="() => $refs.DelistMinQty.onFieldBlur()" />
                <span class="block-content__suffix">{{ selectedRow.enumdicname }}</span>
              </div>
            </div>
            <div class="block">
              <div class="block-tip">最小单位：{{ selectedRow.minivalue }}{{ selectedRow.enumdicname }}</div>
            </div>
          </a-form-item>
          <template v-if="isBlocs()">
            <a-form-item ref="margin" label="履约保证金" name="margin" :autoLink="false">
              <div class="block">
                <div class="block-content">
                  <a-input-number class="block-content__input commonInput" v-model:value="formState.margin" :min="0" @blur="() => $refs.margin.onFieldBlur()" />
                  <span class="block-content__suffix">%</span>
                </div>
              </div>
            </a-form-item>
            <a-form-item label="挂牌有效期" name="vidaliteTime">
              <a-date-picker class="block-content__picker commonDatePicker" v-model:value="formState.vidaliteTime" :allowClear="false" />
            </a-form-item>
          </template>
          <a-form-item label="履约模板" required>
            <div class="block">
              <div class="block-content">
                <span :class="['clickBox', formState.permanceTempName ? 'white' : '']" @click="handlePermance">{{ formState.permanceTempName ? formState.permanceTempName : '选择履约模板' }}</span>
                <svg class="block-content__suffix icon svg-icon" aria-hidden="true" @click="handlePermance">
                  <use xlink:href="#icon-moban" />
                </svg>
              </div>
            </div>
          </a-form-item>
          <a-form-item label="指定用户" v-if="isAgreemt()" required>
            <div class="block">
              <div class="block-content">
                <div class="block-content">
                  <span :class="['clickBox', getFriendLength() ? 'white' : '']" @click="showUser = true">{{ getFriendLength() ? `已选${getFriendLength()}人` : '选择用户' }}</span>
                  <svg class="block-content__suffix icon svg-icon" aria-hidden="true" @click="showUser = true">
                    <use xlink:href="#icon-pengyou1" />
                  </svg>
                </div>
              </div>
            </div>
          </a-form-item>
          <a-form-item label="指定朋友" v-if="isBlocs()">
            <div class="block">
              <div class="block-content">
                <span :class="['clickBox', getFriendLength() ? 'white' : '']" @click="openFriend">{{ getFriendLength() ? `已选${getFriendLength()}人` : '选择朋友' }}</span>
                <svg class="block-content__suffix icon svg-icon" aria-hidden="true" @click="openFriend">
                  <use xlink:href="#icon-pengyou1" />
                </svg>
              </div>
              <div class="block-after">
                <a-checkbox class="commonCheckbox" v-model:checked="friendCheck" @change="limiteFriends">不限</a-checkbox>
              </div>
            </div>
          </a-form-item>
          <a-form-item ref="PriceMove" label="基差" name="PriceMove" :autoLink="false" v-if="isFloat()">
            <div class="block">
              <div class="block-content">
                <a-input-number class="block-content__input commonInput" v-model:value="formState.PriceMove" @blur="() => $refs.PriceMove.onFieldBlur()" />
              </div>
            </div>
          </a-form-item>
          <a-form-item label="估算价" style="width:100%" v-if="isFloat()">
            <span class="white ml8">{{ getPrice() }}</span>
          </a-form-item>
          <a-form-item label="估算金额" style="width:100%" v-if="isFloat()">
            <span class="white ml8">{{ getWrMoney() }}</span>
          </a-form-item>
          <a-form-item label="挂牌金额" style="width:100%" v-else>
            <span class="white ml8">{{ getWrMoney() }}</span>
          </a-form-item>
          <a-form-item label="履约保证金" style="width:100%" v-if="isBlocs()">
            <span class="white ml8">{{ getMargin() }}</span>
          </a-form-item>
          <a-form-item label="履约保证金" style="width:100%" v-else-if="getWrMargin()">
            <span class="white ml8">{{ getWrMargin() }}</span>
          </a-form-item>
          <a-form-item label="可用资金" style="width:100%">
            <span class="white ml8">{{ getCanUseMoney(handleSelectedAccount()) }}</span>
          </a-form-item>
        </a-form>
      </div>
      <div class="mtp-modal__footer">
        <a-button :loading="loading" :disabled="loading" @click="submit">卖出</a-button>
        <a-button :loading="loading" :disabled="loading" @click="cancel(false)">取消</a-button>
      </div>
    </div>
  </Drawer>
  <!-- 选择朋友 -->
  <Friend v-if="showFriend" :friends="formState.friends" :position="'bottom'" @cancel="chooseFriend" @update="chooseFriend" />
  <!-- 选择用户 -->
  <SearchUser v-model:visible="showUser" v-model:selectedValue="formState.friends" :position="'bottom'" />
  <!-- 选择履约模板 -->
  <Permance v-if="showPermance" :position="'bottom'" :marketid="formState.marketid" @cancel="choosePermance" @update="choosePermance" />
</template>

<script lang="ts">
import Drawer from '@/common/components/drawer/index.vue';
import { BuyOrSell } from '@/common/constants/enumCommon';
import { ModalEnum } from '@/common/constants/modalNameEnum';
import { requestResultLoadingAndInfo } from '@/common/methods/request/resultInfo';
import { validateAction } from '@/common/setup/form';
import { _closeModal } from '@/common/setup/modal/modal';
import { useBlocksAccount, useBlocksFriends, useBlocksMoney, useBlocksNumber, useBlocksPermaceTemp, useBlocksPrice } from '@/common/setup/warehouse_receipt_trade/listing';
import { getCanUseMoney, getInTaAccount, getUserId } from '@/services/bus/account';
import { getQuoteDayInfoByCodeFindPrice } from '@/services/bus/goods';
import { getMarketRunByTradeMode } from '@/services/bus/market';
import { WrHoldLB } from '@/services/go/wrtrade/interface';
import { hdWROrder } from '@/services/proto/warehousetrade';
import { WRGoodsInfo } from '@/services/proto/warehousetrade/interface';
import { addSubscribeQuotation, removeSubscribeQuotation } from '@/services/socket/quota';
import Bus from '@/utils/eventBus/index';
import { message } from 'ant-design-vue';
import moment from 'moment';
import { v4 } from 'uuid';
import { defineComponent, defineAsyncComponent, onBeforeUnmount, PropType, ref, } from 'vue';
import { ListingForm } from './interface';
import { handleForm, handleGoods, handleNumAndPrice, queryMarketSection } from './setup';

export default defineComponent({
  name: ModalEnum.spot_warrant_spot_details_listed,
  components: {
    Drawer,
    Friend: defineAsyncComponent(() => import('@/common/components/friends/index.vue')), // 选择朋友
    Permance: defineAsyncComponent(() => import('@/common/components/permanceTemp/choosePermancePlanTmp.vue')), // 选择履约模板
    SearchUser: defineAsyncComponent(() => import('@/common/components/searchUser/index.vue')), // 选择用户
  },
  emits: ['cancel', 'update'],
  props: {
    selectedRow: {
      type: Object as PropType<WrHoldLB>,
      default: {},
    },
  },
  setup(props, context) {
    const loading = ref<boolean>(false);
    const showUser = ref(false);
    const { visible, cancel } = _closeModal(context);
    const { rules, formState, formRef } = handleForm(props.selectedRow);

    // 选择朋友
    const { friendCheck, showFriend, chooseFriend, openFriend, getFriendLength, limiteFriends } = useBlocksFriends(formState);
    // 履约模板
    const { showPermance, choosePermance, openPermance } = useBlocksPermaceTemp(formState);
    // 价格
    const { priceCheck, increasePrice, decreasePrice } = useBlocksPrice(formState);
    // 摘牌数量
    const { numCheck, increaseNumber, decreaseNumber } = useBlocksNumber(formState);

    const { goodsGroup, goodsList, groupsChange, findGoodsCode } = handleGoods();

    // 获取仓单贸易市场
    const { spotMarkets, handleMarket } = queryMarketSection(false)

    // 点选履约模板
    function handlePermance() {
      // 必须先选择市场再选择对应的履约模板
      if (!formState.marketid) {
        message.info('请先选择市场')
        return
      }

      openPermance()
    }

    // 切换商品组
    function handleGoodsGroups(value: number) {
      groupsChange(value);
      formState.goodsid = undefined;
      // formRef.value.validate();
    }
    const uuid = v4();
    const goodsCode = ref<string>('');
    // 切换商品
    function handleGoodsChange(id: number) {
      //行情订阅
      removeSubscribeQuotation(uuid);
      goodsCode.value = goodsList.value.find((e) => e.goodsid === id)?.goodscode as string;
      const arr = [{ exchangeCode: 250, goodsCode: goodsCode.value, subState: 0 }];
      addSubscribeQuotation(uuid, arr);
      formRef.value.validate();
    }
    // 估算价
    function getPrice() {
      let result = '--';
      if (goodsCode.value && typeof formState.PriceMove === 'number') {
        const goodsPrice = getQuoteDayInfoByCodeFindPrice(goodsCode.value);
        if (goodsPrice && goodsPrice !== '--') {
          // 有实时行情价格
          result = ((goodsPrice as number) + formState.PriceMove).toFixed(2);
        }
      }

      return result;
    }
    onBeforeUnmount(() => {
      removeSubscribeQuotation(uuid);
    });
    const { getWrMoney, getWrMargin, isFloat, isFixed, isBlocs, isAgreemt } = handleNumAndPrice();
    function submit() {
      // 市场信息
      if (!formState.marketid) {
        message.info("请选择市场")
        return
      }
      // const marketInfo = getMarketRunByTradeMode(17);
      const market = spotMarkets.value.find(item => item.marketid === formState.marketid)
      if (!market) {
        message.info("市场信息异常，请稍后重试")
        return
      }

      // 履约模板
      if (!formState.permanceTempName) {
        message.info('请选择履约模板')
        return
      }

      const marketInfo = getMarketRunByTradeMode(market!.trademode)
      if (marketInfo) {
        validateAction<ListingForm>(formRef, formState).then((res) => {
          const wrGoodsInfo: WRGoodsInfo = {
            GoodsID: res.goodsid as number, // uint32 配置商品ID
            GoodsCode: findGoodsCode(res.goodsid as number) as string, // string 配置商品代码
            PriceFactor: 1, // double 商品价格系数
            PriceMove: 0, // double 商品升贴水值
            WeightRatio: 1, // double 商品重量系数
          };

          // 仓单贸易挂牌  （仓单贸易 = HasWr = 1）
          const param = {
            OrderSrc: 1, // 1=客户端
            AccountID: getInTaAccount(), // 默认内部资金账号第一个
            ClientSerialNo: v4(), // 客户端流水号
            // OperateSrc: 2,
            ClientType: 4,
            MarketID: formState.marketid,
            LadingBillId: props.selectedRow.ladingbillid.toString(), // 提单id(wrholdlb的LadingBillId字段),卖的时候填写 uint64
            // LadingBillId: 'uint642081626946446000001', // 提单id(wrholdlb的LadingBillId字段),卖的时候填写 uint64
            TradeDate: moment(marketInfo.tradedate).format('YYYYMMDD'), // 交易日 string
            // SubNum: '0', // 提单子单号
            SubNum: props.selectedRow.subnum,
            // WRFactorTypeId: '2121626946446000001', // 仓单要素ID(wrholdlb的WRFactorTypeId字段),卖的时候填写 uint64
            WRFactorTypeId: props.selectedRow.wrfactortypeid, // 仓单要素ID(wrholdlb的WRFactorTypeId字段),卖的时候填写 uint64
            IsSpecified: res.isSpecified, // 是否指定对手 0：不指定 1：指定 uint32
            MatchAccIDs: res.friends, // 仓单贸易对手资金账号ID集合(指定对手时填写) uint32
            OrderQty: res.OrderQty, // 委托数量(可挂部分数据量) ======
            DeliveryGoodsID: props.selectedRow.deliverygoodsid, // 交割商品商品ID
            WRPriceType: res.WRPriceType, // 价格方式 1：固定价 2：浮动价
            FixedPrice: res.FixedPrice, // 固定价格
            PriceFactor: 1, // 价格系数(浮动价时填写)
            PriceMove: res.PriceMove, // 升贴水(浮动价时填写)
            TimevalidType: 4, // 时间有效类型 1：当日有效 2：本周有效 3：指定时间有效 4：一直有效
            // ValidTime: isBlocs() ? moment(res.vidaliteTime).format('YYYY-MM-DD HH:mm:ss') : '', // 有效期限
            ClientOrderTime: moment().format('YYYY-MM-DD HH:mm:ss'),
            FirstRatio: 0, // 首付比例
            PerformanceTemplateID: res.permaceTempId, // 履约计划模板ID
            UserID: getUserId(),
            OperatorID: getUserId(), // 操作员账号ID
            BuyOrSell: BuyOrSell.sell, // 买卖方向 0买1卖
            PriceDisplayMode: 1, // 浮动价显示方式 1：合并显示 2：分开显示
            CanBargain: priceCheck.value ? 1 : 0, // 挂牌是否可议价0:不可1:可-摘牌是否议价
            Attachment1: '', // 附件1
            Attachment2: '', // 附件2
            Remark: '', // 备注
            ApplyID: 0, // 申请ID
            CanPart: numCheck.value ? 0 : 1, // 是否允许部份摘牌0:不允许;1:允许
            WRTradeGoods: [wrGoodsInfo],
            wrstandardid: props.selectedRow.wrstandardid,
            HasWr: 1,
            DeliveryMonth: '',
            MarginFlag: 0,
            DelistMinQty: res.DelistMinQty, // 起摘数量
          };

          if (isAgreemt()) {
            if (!formState.friends.length) {
              message.error('请选择用户');
              return;
            }
          }

          if (isBlocs()) {
            // 贸易圈 是后加的， 处理贸易圈
            // if (!formState.permanceTempName) {
            //     message.error('请选择履约模板');
            //     return;
            // }
            if (!friendCheck.value) {
              if (formState.friends.length === 0) {
                message.error('请选择朋友');
                return;
              }
            }
            const obj = {
              TimevalidType: 3, // 时间有效类型 1：当日有效 2：本周有效 3：指定时间有效 4：一直有效
              MarginFlag: 1, // 挂牌是否指定保证金 0:否 1:是
              MarginAlgorithm: 1, // 指定保证金方式 1:比率 2:固定
              ValidTime: moment(res.vidaliteTime).format('YYYY-MM-DD HH:mm:ss'), // 有效期限
              MarginValue: +(formState.margin / 100).toFixed(2), // 指定保证金设置值
              AllFriendsFlag: friendCheck.value ? 1 : 0, //是否全好友可见 0：否 1:是
            };
            Object.assign(param, obj);
          }

          requestResultLoadingAndInfo(hdWROrder, param, loading, ['挂牌成功', '挂牌失败:']).then(() => {
            Bus.$emit('spotTrade', true);
            cancel(true);
          });
        });
      } else {
        message.error('市场信息未获取到，请联系管理员！');
      }
    }

    return {
      submit,
      visible,
      cancel,
      loading,
      rules,
      formState,
      formRef,
      goodsGroup,
      goodsList,
      handleGoodsGroups,
      handleGoodsChange,
      getWrMoney,
      getWrMargin,
      isFloat,
      isFixed,
      isBlocs,
      isAgreemt,
      getCanUseMoney,
      priceCheck,
      increasePrice,
      decreasePrice,
      ...useBlocksAccount(formState),
      ...useBlocksMoney(formState),
      showUser,
      showPermance,
      choosePermance,
      openPermance,
      numCheck,
      increaseNumber,
      decreaseNumber,
      friendCheck,
      showFriend,
      chooseFriend,
      openFriend,
      getFriendLength,
      limiteFriends,
      getPrice,
      spotMarkets,
      handleMarket,
      handlePermance,
    };
  },
});
</script>