<template>
  <div v-loading.body.fullscreen="fullscreenLoading" element-loading-background="rgba(255, 255, 255, 0)">
    <div class="header">
      <backIcon class="back"></backIcon>
      <div>
        <div class="name flex">
          <div class="title" v-if="language == 'zh-CN'">
            {{ symbolInfo.title }}
          </div>
          <div class="title" v-else-if="language == 'zh-TW'">
            {{ symbolInfo.name_cht || symbolInfo.title }}
          </div>
          <div class="title" v-else>
            {{ symbolInfo.name_en || (symbolInfo.market == 'CFD' ? symbolInfo.symbol : symbolInfo.title) }}
          </div>
          <div class="tag" v-if="activeMarket && activeMarket.id">{{ $t('product.l93') }}</div>
          <div class="tag" v-else-if="tradeState">{{ tradeStateText[tradeState] }}</div>
        </div>
        <div class="number flex" v-if="symbolInfo.symbol"><div>{{ $handleDigits(symbolInfo.ask, symbolInfo.digits) }}</div><div>{{ symbolInfo.spread > 0 ? '+' : ''  }}{{ $handleDigits(symbolInfo.spread, symbolInfo.digits) }}</div><div>{{ symbolInfo.percentage > 0 ? '+' : ''  }}{{ symbolInfo.percentage }}%</div></div>
      </div>
      <div class="icon-box">
        <likeIcon :symbol="symbol"></likeIcon>
        <shareIcon></shareIcon>
      </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/icon/meau.png" alt="">
      <van-tabs class="vtabs" :ellipsis="false" v-model="activeName" animated>
        <!-- 报价 -->
        <van-tab name="1" :title="$t('product.l23')">
          <quotation :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" :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="fiexd" v-if="activeName == '1' && symbolInfo.symbol">
      <template v-if="symbolInfo.enable == 1">
        <div class="btn ltn" @click="$router.push(`/exchange/${symbol}/buy`)">
          <!-- 买入/做多 -->
          {{ (language == 'zh-CN' || language == 'zh-TW') ? `${$t('exchange.l50')}/${$t('product.l77')}` : $t('exchange.l50') }}
        </div>
        <div class="btn rtn" @click="$router.push(`/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>
    <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>
  </div>
</template>
<script>
import quotation from "./quotation/index.vue";
import newsList from "./newsList/index.vue";
// import noticeList from "./noticeList/index.vue";
// import finance from "./finance/index.vue";
import company from "./company/index.vue";
import rules from "./rules/index.vue";
import optionView from "./option/index";
import tabOperate from "./components/tabOperate.vue";
import bus from '@/utils/bus'
import { getCompanyInfo } from "@/api/market";
import { getOptionProductListGroup } from "@/api/option";
import { getStorage } from '@/utils/localStorage'
import { getSystemDatetime } from '@/api/app'
import { mapGetters } from "vuex";
import noticeView from "@/components/closedMarket/notice.vue";
export default {
  components: {
    noticeView,
    quotation,
    // finance,
    company,
    rules,
    newsList,
    // noticeList,
    optionView,
    tabOperate
  },
  inject: ['getproductDataObj'],
  data () {
    return {
      activeName: '1',
      symbol: '',
      loading: false,
      tabShow: true,
      activeNoticeShow: true,
      companyInfo: {},
      optionInfo: {
        visible_list: ''
      },
      optionFeeInfo: {},
      tabOperatePop: false,
      tradeState: '',
      tradeStateTimer: null,
      timeDiff: 0,
      tabList: [],
      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.getCompanyInfo()
      this.getTabList()
      this.getSystemDatetime()
      if (!this['market' + this.symbolInfo.market]) {
        this.$store.dispatch('getProductVacationList', this.symbolInfo.market)
      }
    }
  },
  beforeDestroy() {
    (this.tradeStateTimer && clearTimeout(this.tradeStateTimer))
  },
  created () {
    this.symbol = this.$route.params.symbol
    if (this.$route.params.type) {
      this.activeName = this.$route.params.type
    }
    if (this.updateSymbolList.indexOf(this.symbol) == -1) {
      bus.$emit('updateSubscribe', [this.symbol], true)
    }
    if (this.isLogin) {
      bus.$emit('updateAssets', ['getAccountList'])
    }
    this.getOptionProductListGroup()
  },
  methods: {
    getCompanyInfo() {
      if (this.symbolInfo.type != 1) {
        return
      }
      getCompanyInfo({
        symbol: this.symbolInfo.symbol,
        market: this.symbolInfo.market
      }).then(res => {
        this.companyInfo = res || {}
      }).catch(() => {})
    },
    getOptionProductListGroup() {
      this.fullscreenLoading = true
      getOptionProductListGroup({
        code: this.symbol
      }).then(res => {
        let 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) {
      let list1 = list
      if (this.symbolInfo.type != 1) {
        list1 = []
        list.forEach(item => {
          if (item.name == '5') {
            list1.push(item)
          }
        })
      }
      this.tabList = list1
      this.tabOperatePop = false
      this.tabShow = false
      this.$nextTick(() => {
        this.tabShow = true
      })
    },
    getTabList() {
      let tabList = this.allTablist
      let list = getStorage('productShowTab1')
      let 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))
        let 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')
      }
      this.tabList = tabList
      this.tabShow = false
      this.$nextTick(() => {
        this.tabShow = true
      })
    },
    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;
        let sign = false
        let 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 = '已休盘'
          }, time - beijingTimestamp)
        } else {
          this.tradeState = '已休盘'
          if (time - beijingTimestamp < 0) {
            return
          }
          this.tradeStateTimer = setTimeout(() => {
            this.tradeState = '盘中'
            bus.$emit('updateSubscribe', [this.symbol], true)
          }, time - beijingTimestamp)
        }
      }
    }
  }
}
</script>
<style lang="less" scoped>
.header {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 54px;
  padding-left: 9px;
  padding-right: 14px;
  position: sticky;
  top: 0;
  z-index: 8;
  background-color: var(--bg-);
  .back {
    position: absolute;
    left: 9px;
    top: 50%;
    transform: translateY(-50%);
  }
  .name {
    justify-content: center;
    font-size: 18px;
    font-weight: 600;
    column-gap: 5px;
    margin-bottom: 2px;
  }
  .title {
    max-width: 190px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .tag {
    color: var(--color-1-);
    font-size: 12px;
    line-height: 17px;
    font-weight: 400;
    padding: 0 4px;
    background-color: #E9EFF7;
    border-radius: 3px;
  }
  .number {
    text-align: center;
    color: var(--color-);
    font-size: 12px;
    line-height: 16px;
    column-gap: 4px;
    justify-content: center;
  }
  .icon-box {
    display: flex;
    column-gap: 8px;
    position: absolute;
    right: 12px;
    top: 50%;
    transform: translateY(-50%);
  }
}
.container {
  position: relative;
  .meau {
    position: absolute;
    right: 18px;
    top: 13px;
    width: 18px;
    z-index: 5;
    cursor: pointer;
  }
}
.fiexd {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background-color: #fff;
  padding: 11px 17px;
  box-shadow: 0px -1px 0px 0px rgba(220,222,230,0.52);
  display: flex;
  column-gap: 11px;
  .btn {
    flex: 1;
    border-radius: 6px;
    line-height: 42px;
    text-align: center;
    cursor: pointer;
    color: #fff;
    font-size: 16px;
    font-weight: 600;
    &.dis {
      cursor: not-allowed;
      color: #A5A5A5;
      border: 1px solid #E0E0E0;
    }
  }
  .ltn {
    background-color: #EA4A45;
  }
  .rtn {
    background-color: #07AC3A;
  }
}
::v-deep {
  .van-tabs {
    .van-tab {
      font-size: 14px;
      color: #999BA1;
      & + .van-tab {
        margin-left: 26px;
      }
      &.van-tab--active {
        font-size: 16px;
        color: #070707;
      }
    }
    .van-tabs__line {
      width: 24px;
    }
    .van-tabs__wrap {
      height: 42px;
    }
  }
}
</style>