<template>
  <div v-loading.body.fullscreen="fullscreenLoading" element-loading-background="rgba(255, 255, 255, 0)">
    <div class="header">
      <div class="left flex">
        <backIcon1></backIcon1>
        <div class="info-box">
          <div class="title">
            {{ symbolInfo.title }}
          </div>
          <div class="flex">
            <div class="tag" v-if="activeMarket && activeMarket.id">{{ $t('product.l93') }}</div>
            <div class="tag" v-else-if="tradeState">{{ tradeStateText[tradeState] }}</div>
            <div v-if="symbolInfo.symbol">
              {{ $handleDigits(symbolInfo.ask, symbolInfo.digits) }}{{ symbolInfo.spread > 0 ? '+' : symbolInfo.spread == 0 ? " " : ''  }}{{ $handleDigits(symbolInfo.spread, symbolInfo.digits) }}{{ symbolInfo.spread > 0 ? '+' : symbolInfo.spread == 0 ? " " : ''  }}{{ symbolInfo.percentage }}%
            </div>
          </div>
        </div>
      </div>
      <div class="icon-box flex">
        <likeIcon :symbol="symbol"></likeIcon>
        <shareIcon1></shareIcon1>
      </div>
    </div>
    <noticeView v-if="activeMarket && activeMarket.id && activeNoticeShow" :market="symbolInfo.market" :activeMarket="activeMarket" @close="activeNoticeShow = false" />
    <div class="container" v-if="symbolInfo.symbol">
      <img class="meau" @click="tabOperatePop = true" src="/img/product/meau.png" alt="极度证券">
      <van-tabs line-width="12px" line-height="2px" :ellipsis="false" v-model="activeName" animated>
        <!-- 报价 -->
        <van-tab name="1" :title="$t('product.l23')">
          <quotation :symbolOpen="symbolOpen" :activeMarket="activeMarket" :timeDiff="timeDiff" :tradeState="tradeState" :companyInfo="companyInfo" :symbol="symbol" :symbolInfo="symbolInfo" />
        </van-tab>
        <!-- 期权 -->
        <van-tab name="6" :title="$t('home.l5')">
          <optionView :loading="loading" :optionInfo="optionInfo" :symbolInfo="symbolInfo" :optionFeeInfo="optionFeeInfo"/>
        </van-tab>
        <template v-if="tabShow">
          <van-tab :name="item.name" :title="tabName[item.title]" v-for="item in tabList" :key="item.name">
            <component :activeMarket="activeMarket" :symbolCopy='symbolCopy' :tradeState="tradeState" :is="item.components" :companyInfo="companyInfo" :symbol="symbol" :symbolInfo="symbolInfo"></component>
          </van-tab>
          <!-- <van-tab name="5" title="公告">
            <noticeList :symbolInfo="symbolInfo"/>
          </van-tab> -->
        </template>
      </van-tabs>
    </div>
    <div class="fixed" v-if="activeName == '1' && symbolInfo.symbol && !(countDown > 0) && countDownLoading">
      <template v-if="symbolCopy.enable == 1">
        <div class="btn ltn" @click="toExchange(`/exchange/${symbol}/buy`)">
          <!-- 买入/做多 -->
          {{ (language == 'zh-CN' || language == 'zh-TW') ? `${$t('exchange.l50')}/${$t('product.l77')}` : $t('exchange.l50') }}
        </div>
        <div class="btn rtn" @click="toExchange(`/exchange/${symbol}/sell`)">
          <!-- 卖出/做空 -->
          {{ (language == 'zh-CN' || language == 'zh-TW') ? `${$t('exchange.l51')}/${$t('product.l78')}` : $t('exchange.l51') }}
        </div>
      </template>
      <template v-else-if="optionInfo.visible_list && optionInfo.visible_list.indexOf(1) !== -1">
        <div class="btn ltn" @click="activeName = '6'">
          <!-- 看涨期权 -->
          {{ $t('product.l90') }}
        </div>
        <div class="btn rtn" @click="activeName = '6'">
          <!-- 看跌期权 -->
          {{ $t('product.l91') }}
        </div>
      </template>
      <template v-else>
        <div class="btn dis">
          <!-- 该标的暂不支持交易 -->
          {{ $t('product.l92') }}
        </div>
      </template>
    </div>
    <div v-if="countDown > 0 && countDownLoading" class="count-down flex" @click="countDownPop = true">
      <div>
        <!-- 距离开盘还有 -->
        {{ $t('product.l103') }}
      </div>
      <div class="right flex">
        <van-count-down :time="countDown" @change="countChange" @finish="countDownFinish">
          <template #default="timeData">
            <span class="block">{{ getCountDownHours(timeData) }}</span>
              <!-- 小时 -->
            <span class="colon">{{ $t('product.l104') }}</span>
            <span class="block">{{ timeData.minutes < 10 ? ('0' + timeData.minutes) : timeData.minutes }}</span>
              <!-- 分钟 -->
            <span class="colon">{{ $t('product.l106') }}</span>
          </template>
        </van-count-down>
        <i class="el-icon-caret-top"></i>
      </div>
    </div>
    <van-popup overlay-class="overlay1" @open="countDownOpen" @close="countDownClose" v-model="countDownPop" round position="bottom">
      <countDownBox :countDownDiff="countDownDiff" @cancel="countDownPop = false" :symbolInfo="symbolInfo" :countDown="countDown1" v-if="countDownPop" />
    </van-popup>
    <van-popup v-model="tabOperatePop" round position="bottom">
      <tabOperate :tabName="tabName" :list="tabList" :allTablist="allTablist" :activeName="activeName" @cancel="tabOperatePop = false" @back="tabBack" v-if="tabOperatePop"/>
    </van-popup>
    <van-popup v-model="serviceTipsPop" round position="bottom">
      <serviceTips :symbol="symbol" @cancel="serviceTipsPop = false" v-if="serviceTipsPop"/>
    </van-popup>
  </div>
</template>
<script>
import quotation from "./quotation/index.vue";
import newsList from "./newsList/index.vue";
import { getPriceList } from '@/api/product'
// import noticeList from "./noticeList/index.vue";
// import finance from "./finance/index.vue";
import backIcon1 from "@/components/backIcon1";
import likeIcon from "@/components/likeIcon";
import shareIcon1 from "@/components/shareIcon1";
import company from "./company/index.vue";
import rules from "./rules/index.vue";
import optionView from "./option/index";
import tabOperate from "./components/tabOperate.vue";
import serviceTips from "./components/serviceTips.vue";
import bus from '@/utils/bus'
import { getProductList } from "@/api/product";
import { getProductCompanyList } from "@/api/market";
import { getOptionProductListGroup } from "@/api/option";
import { getStorage, setStorage } from '@/utils/localStorage'
import { getSystemDatetime } from '@/api/app'
import { getProductTime } from '@/api/exchange'
import { mapGetters } from "vuex";
import noticeView from "@/components/closedMarket/notice.vue";
import countDownBox from "./components/countDownBox.vue";
export default {
  components: {
    backIcon1,
    likeIcon,
    shareIcon1,
    noticeView,
    quotation,
    // finance,
    company,
    rules,
    newsList,
    // noticeList,
    optionView,
    tabOperate,
    countDownBox,
    serviceTips
  },
  inject: ['getproductDataObj'],
  data () {
    return {
      activeName: '1',
      symbol: '',
      loading: false,
      tabShow: true,
      activeNoticeShow: true,
      symbolCopy: {},
      companyInfo: {},
      optionInfo: {
        visible_list: ''
      },
      optionFeeInfo: {},
      tabOperatePop: false,
      tradeState: '',
      tradeStateTimer: null,
      timeDiff: 0,
      countDown: 0,
      countDown1: 0,
      countDownLoading: false,
      countDownDiff: 0,
      countDownPop: false,
      serviceTipsPop: false,
      tabList: [],
      symbolOpen: {},
      allTablist: [
        // {
        //   title: '财务',
        //   name: '2',
        //   components: 'finance'
        // },
        {
          title: '简况',
          name: '3',
          components: 'company'
        },
        {
          title: '新闻',
          name: '4',
          components: 'newsList'
        },
        {
          title: '细则',
          name: '5',
          components: 'rules'
        }
      ]
    }
  },
  computed: {
    ...mapGetters(['marketCN', 'marketHK', 'marketUS', 'marketCFD', 'marketPopCN', 'marketPopHK', 'marketPopUS', 'marketPopCFD']),
    tabName() {
      return {
        '报价': this.$t('product.l23'),
        '财务': this.$t('product.l24'),
        '简况': this.$t('product.l25'),
        '新闻': this.$t('product.l26'),
        '细则': this.$t('product.l27'),
      }
    },
    tradeStateText() {
      return {
        '已休盘': this.$t('product.l93'),
        '盘中': this.$t('product.l94'),
      }
    },
    productDataObj() {
      return this.getproductDataObj()
    },
    symbolInfo() {
      return this.productDataObj[this.symbol] || {}
    },
    activeMarket() {
      return this['market' + this.symbolInfo.market]
    },
  },
  watch: {
    'symbolInfo.market'() {
      this.getProductCompanyList()
      this.getTabList()
      this.getProductTime()
      this.getSystemDatetime()
      this.getPriceList()
      if (!this['market' + this.symbolInfo.market]) {
        this.$store.dispatch('getProductVacationList', this.symbolInfo.market)
      }
    }
  },
  beforeDestroy() {
    (this.tradeStateTimer && clearTimeout(this.tradeStateTimer))
    bus.$off('updateChart', this.updateSymbolOpen)
  },
  created () {
    this.symbol = this.$route.params.symbol
    if (this.$route.params.type) {
      this.activeName = this.$route.params.type
    }
    this.getMargin()
    bus.$emit("alterProductData", {
      getData: [this.symbol],
      subscribeList: [this.symbol],
    });
    bus.$on('updateChart', this.updateSymbolOpen)
    if (this.isLogin) {
      bus.$emit('updateAssets', ['getAccountList'])
      var serviceTipsPop = sessionStorage.getItem('serviceTipsPop')
      if (serviceTipsPop) {
        this.serviceTipsPop = JSON.parse(serviceTipsPop)
        sessionStorage.removeItem('serviceTipsPop')
      }
    }
    this.getOptionProductListGroup()
  },
  methods: {
    getProductCompanyList() {
      if (this.symbolInfo.type != 1) {
        return
      }
      getProductCompanyList({
        symbol: this.symbolInfo.symbol,
        // market: this.symbolInfo.market
      }).then(res => {
        this.companyInfo = res || {}
      }).catch(() => {})
    },
    getOptionProductListGroup() {
      this.fullscreenLoading = true
      getOptionProductListGroup({
        code: this.symbol
      }).then(res => {
        var list = res.list || []
        if (res.fee) {
          this.optionFeeInfo = JSON.parse(res.fee)
        }
        this.optionInfo = list[0] || {}
      }).catch(() => {
      }).finally(() => {
        this.loading = true
        this.fullscreenLoading = false;
      })
    },
    tabBack(list) {
      var list1 = list
      if (this.symbolInfo.type != 1) {
        list1 = []
        list.forEach(item => {
          if (item.name == '5') {
            list1.push(item)
          }
          if (this.symbolInfo.crypto == 1 && item.name == '3') {
            list1.push(item)
          }
        })
      }
      this.tabList = list1
      this.tabOperatePop = false
      this.tabShow = false
      this.$nextTick(() => {
        this.tabShow = true
      })
    },
    getTabList() {
      var tabList = this.allTablist
      var list = getStorage('productShowTab1')
      var list1 = getStorage('productHideTab1')
      if (list) {
        tabList = tabList.filter(item => list.indexOf(item.name) !== -1).sort((a, b) => list.indexOf(a.name) - list.indexOf(b.name))
        var list2 = this.allTablist.filter(item => list.indexOf(item.name) === -1 && list1.indexOf(item.name) === -1)
        tabList = tabList.concat(list2)
      }
      if (this.symbolInfo.type != 1) {
        // tabList = tabList.filter(item => item.name == '5')
        tabList = tabList.filter(item => item.name == '5' || (this.symbolInfo.crypto == 1 && item.name == '3'))
      }
      if (this.language != 'zh-CN' && this.language != 'zh-TW') {
        // tabList = tabList.filter(item => item.name == '5')
        tabList = tabList.filter(item => item.name != '4')
      }
      this.tabList = tabList
      this.tabShow = false
      this.$nextTick(() => {
        this.tabShow = true
      })
    },
    toExchange(url) {
      if (this.isLogin) {
        if (this.userInfo.group == 9999) {
          bus.$emit('abnormalPopSign')
          return
        }
        var trade_protocol = this.userInfo.trade_protocol ? JSON.parse(this.userInfo.trade_protocol) : [];
        var sign = 0
        trade_protocol.forEach(item => {
          if (['user', 'tradeconfirm', 'risk', 'legal'].indexOf(item.code) !== -1 && item.status == 1) {
            sign += 1
          }
        })
        if (sign !== 4) {
          sessionStorage.setItem('exchangeUrl', JSON.stringify(url))
          this.serviceTipsPop = true
          return
        }
      }
      this.$router.push(url)
    },
    getMargin() {
      getProductList({
        symbol: JSON.stringify([this.symbol])
      }).then(res => {
        var list = res.list || []
        this.symbolCopy = list[0] || {}
      }).catch(() => {})
    },
    getSystemDatetime() {
      getSystemDatetime().then(res => {
        this.timeDiff = res.timestamp - new Date().getTime()
        this.getTradeState(res.timestamp)
      }).catch(() => {})
    },
    getTradeState(timestamp) {
      if (this.symbolInfo.timeList) {
        // 获取北京时区的时间字符串
        // 将北京时间字符串转换为日期对象
        var nowTime = new Date(timestamp);
        var offset = nowTime.getTimezoneOffset()/60;
        var beijingDate = new Date(timestamp + ((offset + 8) * 60 * 60 * 1000));
        var year = beijingDate.getFullYear()
        var m = beijingDate.getMonth() + 1
        if (m < 10) {
          m = '0' + m
        }
        var d = beijingDate.getDate()
        if (d < 10) {
          d = '0' + d
        }
        var week = beijingDate.getDay()
        // 获取北京时间的时间戳
        var beijingTimestamp = timestamp;
        var sign = false
        var time = ''
        this.symbolInfo.timeList.forEach(item => {
          if (item.week == week) {
            if (new Date(`${year}-${m}-${d}T${item.start_time}:00+08:00`).getTime() < beijingTimestamp && beijingTimestamp < new Date(`${year}-${m}-${d}T${item.end_time}:00+08:00`).getTime()) {
              sign = true
              time = new Date(`${year}-${m}-${d}T${item.end_time}:00+08:00`).getTime()
            } else {
              if (!time) {
                if (beijingTimestamp < new Date(`${year}-${m}-${d}T${item.start_time}:00+08:00`).getTime()) {
                  time = new Date(`${year}-${m}-${d}T${item.start_time}:00+08:00`).getTime()
                }
              }
            }
          }
        })
        if (sign) {
          this.tradeState = '盘中'
          if (time - beijingTimestamp < 0) {
            return
          }
          this.tradeStateTimer = setTimeout(() => {
            this.tradeState = '已休盘'
            setTimeout(() => {
              bus.$emit("alterProductData", {
                getData: [this.symbol],
                subscribeList: [this.symbol],
              });
              this.getSystemDatetime()
            }, 1000)
          }, time - beijingTimestamp)
        } else {
          this.tradeState = '已休盘'
          if (time - beijingTimestamp < 0) {
            return
          }
          this.tradeStateTimer = setTimeout(() => {
            this.tradeState = '盘中'
            setTimeout(() => {
              this.getPriceList()
              bus.$emit("alterProductData", {
                getData: [this.symbol],
                subscribeList: [this.symbol],
              });
              this.getSystemDatetime()
            }, 1000)
          }, time - beijingTimestamp)
        }
      }
    },
    getProductTime() {
      var data = {
        symbol: this.symbolInfo.market
      }
      if (this.symbolInfo.market == 'CFD') {
        data.symbol = this.symbolInfo.symbol
      }
      getProductTime(data).then(res => {
        this.countDown = (res.time || 0)
        this.countDown1 = (res.time || 0)
        var countDownPop = getStorage('countDown' + this.symbolInfo.market)
        if (this.countDown > 0) {
          this.countDownPop = countDownPop === false ? false : true
        } else {
          setStorage('countDown' + this.symbolInfo.market, true)
        }
        this.countDownDiff = (res.open_time - res.close_time)
      }).catch(() => {}).finally(() => {
        this.countDownLoading = true
      })
    },
    countDownFinish() {
      this.countDown = 0
      this.countDownPop = false
    },
    countChange(currentTime) {
      this.countDown1 = (currentTime.days * 24 * 60 * 60 * 1000) + (currentTime.hours * 60 * 60 * 1000) + (currentTime.minutes * 60 * 1000) + (currentTime.seconds * 1000) + currentTime.milliseconds
    },
    getCountDownHours(timeData) {
      var hours = timeData.days * 24
      hours += timeData.hours
      return hours < 0 ? ('0' + hours) : hours
    },
    countDownClose() {
      setStorage('countDown' + this.symbolInfo.market, false)
    },
    countDownOpen() {
      setStorage('countDown' + this.symbolInfo.market, true)
    },
    getPriceList() {
      var data = {
        symbol: this.symbol,
        type: 1440,
        count: 3,
        endTime: parseInt(new Date().getTime()),
      }
      getPriceList(data).then(res => {
        var list = res || [];
        this.symbolOpen = (list[list.length - 1] || {})
      }).catch(() => {})
    },
    updateSymbolOpen(data) {
      if ((this.symbol == data.symbol)) {
        if (this.symbolOpen.high < data.ask) {
          this.$set(this.symbolOpen, 'high', data.ask)
        }
        if (this.symbolOpen.low > data.ask) {
          this.$set(this.symbolOpen, 'low', data.ask)
        }
      }
    }
  }
}
</script>
<style lang="less" scoped>
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 50px;
  padding: 0 16px;
  position: sticky;
  top: 0;
  z-index: 8;
  background-color: var(--bg-);
  .left {
    flex: 1;
    min-width: 0px;
    column-gap: 14px;
    padding-right: 6px;
  }
  .info-box {
    flex: 1;
    min-width: 0px;
    >.flex {
      column-gap: 6px;
      font-size: 12px;
      color: #FF6301;
    }
  }
  .title {
    font-size: 16px;
    margin-bottom: 6px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .tag {
    color: #888888;
  }
  .icon-box {
    column-gap: 16px;
  }
}
.container {
  position: relative;
  .meau {
    position: absolute;
    right: 20px;
    top: 16px;
    width: 3px;
    z-index: 5;
    cursor: pointer;
  }
}
.fixed {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background-color: #fff;
  padding: 10px 16px;
  border-top: 1px solid #F6F6F6;
  display: flex;
  column-gap: 23px;
  .btn {
    flex: 1;
    border-radius: 4px;
    line-height: 40px;
    text-align: center;
    cursor: pointer;
    color: #fff;
    font-size: 16px;
    &.dis {
      cursor: not-allowed;
      color: #A5A5A5;
      border: 1px solid #E0E0E0;
    }
  }
  .ltn {
    background-color: #F6465D;
  }
  .rtn {
    background-color: #2EBD85;
  }
}
.van-count-down {
  line-height: 1;
  white-space: nowrap;
}
.count-down {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background-color: #fff;
  padding: 20px 18px;
  justify-content: space-between;
  font-size: 14px;
  box-shadow: 0px -4px 15px 0px rgba(0,0,0,0.14);
  .el-icon-caret-top {
    font-size: 17px;
    line-height: 14px;
    color: #7B7B7B;
  }
}
.block {
  color: #058AFF;
}
::v-deep {
  .van-tabs {
    .van-tabs__wrap {
      height: 48px;
      padding-left: 8px;
      padding-right: 28px;
    }
    .van-tab {
      flex: none;
      padding: 0;
      color: #888888;
      font-size: 14px;
      align-items: flex-end;
      padding-bottom: 15px;
      &+.van-tab {
        margin-left: 20px;
      }
      &.van-tab--active {
        color: #000;
        font-size: 16px;
        font-weight: 600;
      }
    }
    .van-tabs__line {
      background-color: #000;
      bottom: 21px;
    }
  }
  .overlay1 {
    background-color: transparent;
    top: 54px;
  }
}
.van-popup.van-popup--round.van-popup--bottom {
  box-shadow: 0px 11px 39px 0px #00000029;
}
</style>