<template>
  <u-loading-page v-if="load" :loading="load"></u-loading-page>
  <view class="market_index" v-else>
    <view class="market_head" :class="{ market_head1: isUnfold }">
      <view class="market_head_top">
        <view class="closed_price" @tap="collection">
          <view class="closed_price_top">
            <view
              class="closed_price_text colorGreen"
              :class="{ colorRed: data.riseLossesCurrentDay > 0 }"
              >{{ data.closingPrice }}</view
            >
            <u-icon v-if="!isCollection" name="star" size="20"></u-icon>
            <u-icon v-else name="star-fill" size="20" color="#EC7C00"></u-icon>
          </view>
          <view
            class="closed_price_bottom colorGreen"
            :class="{ colorRed: data.riseLossesCurrentDay > 0 }"
            >{{ data.cha.toFixed(2) }} [{{
              data.riseLossesCurrentDay.toFixed(2)
            }}%]</view
          >
        </view>
        <view class="closed_opening">
          <view style="margin-top: 4rpx">
            <text class="head_text">开</text>
            <text class="head_num">{{ data.openingPrice }}</text>
          </view>
          <view style="margin-top: 20rpx">
            <text class="head_text">收</text>
            <text class="head_num">{{ data.closingPrice }}</text>
          </view>
        </view>
        <view class="quantity_quota" @tap="isUnfold = !isUnfold">
          <view style="margin-top: 4rpx">
            <text class="head_text">量</text>
            <text class="head_num">{{ data.volume }}</text>
          </view>
          <view style="margin-top: 20rpx">
            <text class="head_text">额</text>
            <text class="head_num">{{ data.turnover }}</text>
          </view>
        </view>
        <view @tap="isUnfold = !isUnfold">
          <image
            src="../../../static/zhan.png"
            v-if="!isUnfold"
            style="width: 32rpx; height: 32rpx"
            mode="scaleToFill"
          />
          <image
            v-else
            src="../../../static/show.png"
            style="width: 32rpx; height: 32rpx"
            mode="scaleToFill"
          />
        </view>
      </view>
    </view>
    <view class="line"> </view>
    <view style="height: 1100rpx; padding: 0 20rpx; width: 710rpx">
      <l-echart ref="chart"></l-echart>
    </view>
    <view class="line_1"> </view>
    <view class="footer">
      <view>基本信息</view>
      <view class="footer_list">
        <view class="footer_list_left">首发上市日期</view>
        <view>{{ data.initialListingDate }}</view>
      </view>
      <view class="footer_list">
        <view class="footer_list_left">可交易日数</view>
        <view>{{ data.numberDaysAvailable }}</view>
      </view>
      <view class="footer_list">
        <view class="footer_list_left">机构持仓合计</view>
        <view>{{ data.totalInstitutionalPositions }}</view>
      </view>
      <view class="footer_list">
        <view class="footer_list_left">所属东财行业指数2级</view>
        <view>汽车</view>
      </view>
      <view class="footer_list">
        <view class="footer_list_left">所属东财行业指数3级</view>
        <view>{{ data.dongCaiIndustryIndexLevel3 }}</view>
      </view>
      <view class="footer_list">
        <view class="footer_list_left">所属东财行业指数代码</view>
        <view>802030.EI</view>
      </view>
    </view>
    <u-popup :show="isUnfold" mode="top">
      <view class="market_head" :class="{ market_head1: isUnfold }">
        <view class="market_head_top">
          <view class="closed_price" @tap="collection">
            <view class="closed_price_top">
              <view
                class="closed_price_text colorGreen"
                :class="{ colorRed: data.riseLossesCurrentDay > 0 }"
                >{{ data.closingPrice }}</view
              >
              <u-icon v-if="!isCollection" name="star" size="20"></u-icon>
              <u-icon
                v-else
                name="star-fill"
                size="20"
                color="#EC7C00"
              ></u-icon>
            </view>
            <view
              class="closed_price_bottom colorGreen"
              :class="{ colorRed: data.riseLossesCurrentDay > 0 }"
            >
              {{ data.cha.toFixed(2) }} [{{
                data.riseLossesCurrentDay.toFixed(2)
              }}%]
            </view>
          </view>
          <view class="closed_opening">
            <view style="margin-top: 4rpx">
              <text class="head_text">开</text>
              <text class="head_num">{{ data.openingPrice }}</text>
            </view>
            <view style="margin-top: 20rpx">
              <text class="head_text">收</text>
              <text class="head_num">{{ data.closingPrice }}</text>
            </view>
          </view>
          <view class="quantity_quota" @tap="isUnfold = !isUnfold">
            <view style="margin-top: 4rpx">
              <text class="head_text">量</text>
              <text class="head_num">{{ data.volume }}</text>
            </view>
            <view style="margin-top: 20rpx">
              <text class="head_text">额</text>
              <text class="head_num">{{ data.turnover }}</text>
            </view>
          </view>
          <view @tap="isUnfold = !isUnfold">
            <image
              src="../../../static/zhan.png"
              v-if="!isUnfold"
              style="width: 32rpx; height: 32rpx"
              mode="scaleToFill"
            />
            <image
              v-else
              src="../../../static/show.png"
              style="width: 32rpx; height: 32rpx"
              mode="scaleToFill"
            />
          </view>
        </view>
        <view class="market_head_bottom">
          <view class="head_bottom_list">
            <view class="security_code">
              <view class="bottom_list_text"> 证券代码 </view>
              <view class="bottom_list_num">{{ data.securityCode }}</view>
            </view>
            <view class="trade_date">
              <view class="bottom_list_text"> 交易日 </view>
              <view class="bottom_list_num">{{ data.businessDate }}</view>
            </view>
            <view class="opening_high">
              <view class="bottom_list_text"> 最高 </view>
              <view class="bottom_list_num">{{ data.highestPrice }}</view>
            </view>
            <view class="opening_less">
              <view class="bottom_list_text"> 最低 </view>
              <view class="bottom_list_num">{{ data.lowestPrice }}</view>
            </view>
          </view>
          <view class="head_bottom_list">
            <view class="security_code">
              <view class="bottom_list_text"> 涨跌幅 </view>
              <view class="bottom_list_num"
                >{{ data.riseLossesCurrentDay.toFixed(2) }}%</view
              >
            </view>
            <view class="trade_date">
              <view class="bottom_list_text"> 10日涨跌幅 </view>
              <view class="bottom_list_num"
                >{{ data.rangeRiseLosses10.toFixed(2) }}%</view
              >
            </view>
            <view class="opening_high">
              <view class="bottom_list_text"> 20日涨跌幅 </view>
              <view class="bottom_list_num"
                >{{ data.rangeRiseLosses20.toFixed(2) }}%</view
              >
            </view>
            <view class="opening_less">
              <view class="bottom_list_text"> 60日涨跌幅 </view>
              <view class="bottom_list_num"
                >{{ data.rangeRiseLosses60.toFixed(2) }}%</view
              >
            </view>
          </view>
          <view class="head_bottom_list">
            <view class="security_code">
              <view class="bottom_list_text"> 流通 </view>
              <view class="bottom_list_num">{{ data.freeCapitalization }}</view>
            </view>
            <view class="trade_date">
              <view class="bottom_list_text"> 20日区间平均成交量 </view>
              <view class="bottom_list_num">{{ data.averageVolumeDay20 }}</view>
            </view>
          </view>
        </view>
      </view>
    </u-popup>
    <!-- 个股所属板块 -->
    <!-- <u-picker
      :show="showPrivateBelong"
      :columns="columnsBelong"
      cancelColor="#EC7C00"
      confirmColor="#EC7C00"
      @cancel="cancelPrivateBelong"
      @confirm="confirmPrivateBelong"
    ></u-picker> -->
  </view>
</template>

<script>
  import * as echarts from '@/uni_modules/lime-echart/static/echarts.min'
  export default {
    data() {
      return {
        isCollection: false,
        isUnfold: false,
        data: {},
        load: true,
        id: '',
      }
    },
    onLoad(options) {
      uni.setNavigationBarTitle({
        title: options.name,
      })
      this.id = options.id

      // this.rending(options.id)
    },
    mounted() {
      this.$nextTick(() => {
        //  执行echarts方法
        this.rending()
      })
    },
    methods: {
      rending(id) {
        this.$api
          .post('/stock/getByCode', {
            businessDate: '',
            securityCode: this.id,
          })
          .then(r => {
            if (r) {
              this.data = r
              this.data.cha = this.data.closingPrice - this.data.openingPrice
              this.load = false
              this.$api
                .post('/stock/kLine', {
                  securityCode: this.data.securityCode,
                  securityType: '',
                })
                .then(r => {
                  if (r) {
                    // this.data = r
                    console.log(r)
                    this.$refs.chart.init(echarts, chart => {
                      let upColor = '#ec0000'
                      let downColor = '#00da3c'
                      // 数据意义：开盘(open)，收盘(close)，最低(lowest)，最高(highest)
                      let data = splitData(r)
                      function splitData(rawData) {
                        let categoryData = []
                        let values = []
                        let volumes = []
                        for (let i = 0; i < rawData.length; i++) {
                          categoryData.push(rawData[i].splice(0, 1)[0])
                          values.push(rawData[i])
                          volumes.push([
                            i,
                            rawData[i][4],
                            rawData[i][0] > rawData[i][1] ? 1 : -1,
                          ])
                        }
                        return {
                          categoryData: categoryData,
                          values: values,
                          volumes: volumes,
                        }
                      }

                      function calculateMA(dayCount) {
                        let result = []
                        for (
                          let i = 0, len = data.values.length;
                          i < len;
                          i++
                        ) {
                          if (i < dayCount) {
                            result.push('-')
                            continue
                          }
                          let sum = 0
                          for (let j = 0; j < dayCount; j++) {
                            sum += data.values[i - j][1]
                          }
                          result.push(sum / dayCount)
                        }
                        return result
                      }

                      let option = {
                        animation: false,
                        legend: {
                          top: 10,
                          left: 'center',
                          data: ['日K', 'MA5', 'MA10', 'MA20', 'MA30'],
                        },
                        tooltip: {
                          trigger: 'axis',
                          axisPointer: {
                            type: 'cross',
                          },
                          formatter: function (param) {
                            // let param1 = param[1];
                            if (param[0].data.length < 6) {
                              param = param[1]
                              console.log(param)
                              return [
                                '日期: ' + param.axisValue + '\n',
                                '开盘: ' + param.data[1] + '\n',
                                '关盘: ' + param.data[2] + '\n',
                                '最低: ' + param.data[3] + '\n',
                                '最高: ' + param.data[4] + '\n',
                                '成交额: ' + param.data[5] + '\n',
                              ].join('')
                            } else {
                              param = param[0]
                              console.log(param)
                              return [
                                '日期: ' + param.axisValue + '\n',
                                '开盘: ' + param.data[1] + '\n',
                                '关盘: ' + param.data[2] + '\n',
                                '最低: ' + param.data[3] + '\n',
                                '最高: ' + param.data[4] + '\n',
                                '成交额: ' + param.data[5] + '\n',
                              ].join('')
                            }
                          },
                          borderWidth: 1,
                          borderColor: '#ccc',
                          padding: 10,
                          textStyle: {
                            color: '#000',
                          },
                          position: function (pos, params, el, elRect, size) {
                            const obj = {
                              top: 10,
                            }
                            obj[
                              ['left', 'right'][
                                +(pos[0] < size.viewSize[0] / 2)
                              ]
                            ] = 30
                            return obj
                          },
                          // extraCssText: 'width: 170px'
                        },
                        axisPointer: {
                          link: [
                            {
                              xAxisIndex: 'all',
                            },
                          ],
                          label: {
                            backgroundColor: '#777',
                          },
                        },
                        toolbox: {
                          feature: {
                            dataZoom: {
                              yAxisIndex: false,
                            },
                            brush: {
                              type: ['lineX', 'clear'],
                            },
                          },
                        },
                        brush: {
                          xAxisIndex: 'all',
                          brushLink: 'all',
                          outOfBrush: {
                            colorAlpha: 0.1,
                          },
                        },
                        visualMap: {
                          show: false,
                          seriesIndex: 5,
                          dimension: 2,
                          pieces: [
                            {
                              value: 1,
                              color: upColor,
                            },
                            {
                              value: -1,
                              color: downColor,
                            },
                          ],
                        },
                        grid: [
                          {
                            left: '10%',
                            right: '8%',
                            height: '50%',
                          },
                          {
                            left: '10%',
                            right: '8%',
                            top: '63%',
                            height: '16%',
                          },
                        ],
                        xAxis: [
                          {
                            type: 'category',
                            data: data.categoryData,
                            boundaryGap: false,
                            axisLine: { onZero: false },
                            splitLine: { show: false },
                            min: 'dataMin',
                            max: 'dataMax',
                            axisPointer: {
                              z: 100,
                            },
                          },
                          {
                            type: 'category',
                            gridIndex: 1,
                            data: data.categoryData,
                            boundaryGap: false,
                            axisLine: { onZero: false },
                            axisTick: { show: false },
                            splitLine: { show: false },
                            axisLabel: { show: false },
                            min: 'dataMin',
                            max: 'dataMax',
                          },
                        ],
                        yAxis: [
                          {
                            scale: true,
                            splitArea: {
                              show: true,
                            },
                          },
                          {
                            scale: true,
                            gridIndex: 1,
                            splitNumber: 2,
                            axisLabel: { show: false },
                            axisLine: { show: false },
                            axisTick: { show: false },
                            splitLine: { show: false },
                          },
                        ],
                        dataZoom: [
                          {
                            type: 'inside',
                            xAxisIndex: [0, 1],
                            start: 0,
                            end: 100,
                          },
                          {
                            show: true,
                            xAxisIndex: [0, 1],
                            type: 'slider',
                            top: '85%',
                            start: 0,
                            end: 100,
                          },
                        ],
                        series: [
                          {
                            name: '日K',
                            type: 'candlestick',
                            data: data.values,
                            itemStyle: {
                              color: downColor,
                              color0: upColor,
                              borderColor: undefined,
                              borderColor0: undefined,
                            },
                            tooltip: {
                              formatter: function (param) {
                                console.log(param)
                                param = param[0]
                                return [
                                  'Date: ' +
                                    param.name +
                                    '<hr size=1 style="margin: 3px 0">',
                                  '开盘: ' + param.data[0] + '<br/>',
                                  'Close: ' + param.data[1] + '<br/>',
                                  'Lowest: ' + param.data[2] + '<br/>',
                                  'Highest: ' + param.data[3] + '<br/>',
                                ].join('')
                              },
                            },
                          },
                          {
                            name: 'MA5',
                            type: 'line',
                            data: calculateMA(5, data),
                            smooth: true,
                            lineStyle: {
                              opacity: 0.5,
                            },
                          },
                          {
                            name: 'MA10',
                            type: 'line',
                            data: calculateMA(10, data),
                            smooth: true,
                            lineStyle: {
                              opacity: 0.5,
                            },
                          },
                          {
                            name: 'MA20',
                            type: 'line',
                            data: calculateMA(20, data),
                            smooth: true,
                            lineStyle: {
                              opacity: 0.5,
                            },
                          },
                          {
                            name: 'MA30',
                            type: 'line',
                            data: calculateMA(30, data),
                            smooth: true,
                            lineStyle: {
                              opacity: 0.5,
                            },
                          },
                          {
                            name: 'Volume',
                            type: 'bar',
                            xAxisIndex: 1,
                            yAxisIndex: 1,
                            itemStyle: {
                              // normal: {
                              //   color: function (param) {
                              //     return downColor;
                              //   },
                              // },
                            },
                            data: data.volumes,
                          },
                        ],
                      }
                      chart.setOption(option)
                    })
                  }
                })
                .catch(fall => {
                  console.log(fall)
                })
              this.queryCollection()
              // this.data = r
              // this.privateList = r.list
              // console.log(this.privateList)
              console.log(r)
            }
          })
          .catch(fall => {
            console.log(fall)
          })
      },
      // 查询是否收藏
      queryCollection() {
        this.$api
          .post('/collect/queryIsCollect', {
            securityCode: this.id,
          })
          .then(r => {
            if (r) {
              r == 1 ? (this.isCollection = true) : (this.isCollection = false)
            }
          })
          .catch(fall => {
            console.log(fall)
          })
      },
      // 选择导航
      selectNav(name) {
        this.showLoad = true
        this.navList.forEach((item, index) => {
          if (item.name == name) {
            item.is = true
            setTimeout(() => {
              this.showLoad = false
            }, 1000)
          } else {
            item.is = false
          }
        })
      },
      // 是否收藏
      collection() {
        if (this.isCollection) {
          this.$api
            .post('/collect/del', {
              securityCode: this.data.securityCode,
              securityType: this.data.securityType,
            })
            .then(r => {
              // if (r.code == 200) {
              uni.$u.toast('已取消收藏')
              this.isCollection = false
              // }
            })
            .catch(fall => {
              uni.$u.toast('已取消收藏')
              this.isCollection = false
              console.log(fall)
            })
        } else {
          this.$api
            .post('/collect/add', {
              securityCode: this.data.securityCode,
              securityType: this.data.securityType,
            })
            .then(r => {
              // if (r.code == 200) {
              uni.$u.toast('收藏成功')
              this.isCollection = true
              // }
            })
            .catch(fall => {
              uni.$u.toast('收藏成功')
              this.isCollection = true
              console.log(fall)
            })
        }
      },
      initEcharts() {},
    },
  }
</script>

<style lang="scss" scoped>
  .show_load {
    margin-top: 100rpx;
  }
  .market_head {
    padding: 32rpx 24rpx 0 24rpx;
    height: 100rpx;
    width: 702rpx;
    overflow: hidden;
    .closed_price {
      font-size: 24rpx;
      .closed_price_top {
        display: flex;
        font-size: 40rpx;
      }
    }
    .closed_price_text {
      margin-right: 24rpx;
      font-weight: bold;
    }
    .closed_price_bottom {
      margin-top: 10rpx;
    }
  }
  .market_head1 {
    height: 100%;
  }
  .market_head_top {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .market_head_bottom {
    padding-bottom: 32rpx;
  }
  .head_bottom_list {
    margin-top: 32rpx;
    display: flex;
    align-items: center;
    .security_code {
      width: 158rpx;
      border-right: 2rpx dashed #c8c8c8;
    }
    .trade_date {
      width: 208rpx;
      border-right: 2rpx dashed #c8c8c8;
      margin-left: 20rpx;
    }
    .opening_high {
      border-right: 2rpx dashed #c8c8c8;
      margin-left: 20rpx;
      width: 160rpx;
    }
    .opening_less {
      margin-left: 20rpx;
    }
    .bottom_list_text {
      font-size: 24rpx;
      color: #999999;
    }
    .bottom_list_num {
      margin-top: 8rpx;
      font-size: 28rpx;
    }
  }
  .closed_opening {
    font-size: 28rpx;
  }
  .quantity_quota {
    font-size: 28rpx;
  }
  .head_text {
    color: #999999;
  }
  .head_num {
    margin-left: 16rpx;
  }
  .line {
    height: 2rpx;
    background-color: #f6f6f6;
    margin-top: 32rpx;
  }
  .nav_list {
    padding: 32rpx 24rpx;
    color: #999999;
    .nav_list_text {
      margin-right: 32rpx;
    }
    .nav_list_text1 {
      font-weight: bold;
      color: #333333;
    }
  }
  .line_1 {
    height: 20rpx;
    background-color: #f6f6f6;
  }
  .private_table_head {
    display: flex;
    align-items: center;
    font-size: 24rpx;
    font-weight: bold;
    background-color: #fff9f3;
    padding: 20rpx 24rpx;
    justify-content: space-between;
    .private_table_head_right {
      display: flex;
      align-items: center;
    }
    .private_table_head_left {
      display: flex;
      align-items: center;
      .private_head_name {
        width: 200rpx;
      }
      .private_head_price {
        width: 150rpx;
        text-align: center;
      }
      .private_head_gains {
        width: 150rpx;
        text-align: center;
      }
    }
  }
  .private_table_list {
    padding: 24rpx 24rpx;
    border-bottom: 2rpx solid #f6f6f6;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
    .private_table_list_left {
      display: flex;
      align-items: center;
      .table_list_name {
        width: 200rpx;
      }
      .table_list_code {
        margin-top: 10rpx;
        font-size: 24rpx;
        color: #999999;
      }
      .table_list_price {
        width: 150rpx;
        text-align: center;
      }
      .table_list_gains {
        width: 150rpx;
        text-align: center;
      }
    }
  }
  .private_screening_icon {
    width: 18rpx;
    height: 10rpx;
    margin-left: 24rpx;
  }
  .list_footer {
    padding: 32rpx 0;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    color: #ec7c00;
    .see_more {
      display: flex;
      align-items: center;
      .see_more_icon {
        width: 22rpx;
        height: 22rpx;
        margin-left: 10rpx;
      }
    }
  }
  .footer {
    padding: 32rpx 24rpx;
    font-weight: bold;
    padding-bottom: 100rpx;
    .footer_list {
      padding-top: 32rpx;
      font-size: 28rpx;
      font-weight: 500;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .footer_list_left {
        color: #666666;
      }
    }
  }
  .colorGreen {
    color: #6fbb60;
  }
  .colorRed {
    color: red;
  }
</style>
