<template>
  <div
    :class="[
      'chart-position-analysis-page',
      isPcShow ? 'chart-position-analysis-page-pc' : '',
    ]"
    v-loading="pageLoading"
    element-loading-text="加载中"
  >
    <div class="chart-wrap-box">
      <div class="wrap-top">
        <div>
          <el-radio-group
            v-model="tabKey"
            @change="chartItemInfo = chartListState[tabKey]"
            v-show="chartListState.BuyList.List"
          >
            <el-radio-button
              :label="tab.key"
              v-for="tab in tabKeys"
              :key="tab.key"
              >{{ tab.label }}</el-radio-button
            >
          </el-radio-group>
        </div>
        <div>
            <el-date-picker
                v-model="selectDate"
                type="date"
                :placeholder="$t('ToolBox.PositionAnalysis.select_date_placeholder')"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOption"
                @change="$emit('handleOpt','date')"
                style="margin-right: 10px"
            />
            <el-button type="primary" plain @click="$emit('handleOpt','beforeDate')">{{$t('ToolBox.PositionAnalysis.see_before_day')}}</el-button>
            <el-button type="primary" plain @click="$emit('handleOpt','nextDate')" :disabled="disabledNextBtn">{{$t('ToolBox.PositionAnalysis.see_next_day')}}</el-button>
        </div>
      </div>
      <div
        class="chart-wrap"
        v-if="chartItemInfo&&chartItemInfo.List && chartListState.BuyList.List"
      >
        <div class="top-info-box">
          <span>{{$route.query.classify_type}}</span>
          <span>{{ chartItemInfo.name }}</span>
          <span
            ><span style="color: #999; margin-right: 2px">{{$t('ToolBox.PositionAnalysis.count_name')}} </span
            >{{ chartItemInfo.TotalDealValue }}</span
          >
          <span
            ><span style="color: #999; margin-right: 2px">{{$t('ToolBox.PositionAnalysis.compare_yesterday')}} </span
            >{{ chartItemInfo.TotalDealChange }}</span
          >
        </div>
        <chart-box :keyVal="tabKey" :data="chartItemInfo" />
      </div>

      <div class="empty-wrap" v-else>
        <tableNoData :text="$t('ToolBox.PositionAnalysis.no_data')" />
      </div>
    </div>

  </div>
</template>

<script>
import {
  apiPositionAnalysisInfo,
  apiPositionAnalysisList,
} from "@/api/modules/positionAnalysis";
import chartBox from "./chartBox.vue";
export default {
  components: { chartBox },
  watch: {
    "$route.query": {
      handler(nval) {
        this.selectDate = "";
        this.getInfo();
      },
    },
  },
  props:{
    disabledNextBtn:Boolean,
    selectDate:String,
    pickerOption:Object
  },
  computed:{
    tabKeys(){
      return [
        { label: this.$t('ToolBox.PositionAnalysis.long_position')/* "多单" */, key: "BuyList" },
        { label: this.$t('ToolBox.PositionAnalysis.short_position')/* "空单" */, key: "SoldList" },
        { label: this.$t('ToolBox.PositionAnalysis.net_long_position')/* "净多单" */, key: "CleanBuyList" },
        { label: this.$t('ToolBox.PositionAnalysis.net_short_position')/* "净空单" */, key: "CleanSoldList" },
      ]
    },
    chartListState(){
      return {
        BuyList: {
          name: this.$t('ToolBox.PositionAnalysis.long_position')/* "多单" */,
          labelName: this.$t('ToolBox.PositionAnalysis.hold_long_position')/* "持多单量" */,
        },
        SoldList: {
          name: this.$t('ToolBox.PositionAnalysis.short_position')/* "空单" */,
          labelName: this.$t('ToolBox.PositionAnalysis.hold_short_position')/* "持空单量" */,
        },
        CleanBuyList: {
          name:this.$t('ToolBox.PositionAnalysis.net_long_position') /* "净多单" */,
          labelName: this.$t('ToolBox.PositionAnalysis.net_long_position_num')/* "净多单量" */,
        },
        CleanSoldList: {
          name: this.$t('ToolBox.PositionAnalysis.net_short_position')/* "净空单" */,
          labelName: this.$t('ToolBox.PositionAnalysis.net_short_position_num')/* "净空单量" */,
        },
      }
    }
  },
  data() {
    return {
      isPcShow: true,

      isRefresh: false,

      minDate: new Date("2000/01/01"),
      latestDate: "", //
      selectDate: "",

      allClassifyTypeList: [],

      pageLoading: false,
      tabKey: "BuyList",
      chartItemInfo: null,
    };
  },

  methods: {
    getAllClassifyType() {
      apiPositionAnalysisList().then((res) => {
        if (res.Ret !== 200) return;
        const arr = res.Data || [];
        // 将数据展开
        arr.forEach((item) => {
          item.Items &&
            item.Items.forEach((itemC1) => {
              itemC1.Items &&
                itemC1.Items.forEach((itemC2) => {
                  this.allClassifyTypeList.push({
                    exchange: item.Exchange,
                    classify_name: itemC1.ClassifyName,
                    classify_type: itemC2.ClassifyType,
                  });
                });
            });
        });
      });
    },

    handleClassifyTypeChange(type) {
      if (!this.allClassifyTypeList.length) return;

      const currentExchange = this.$route.query.exchange;
      const currentClassifyName = this.$route.query.classify_name;
      const currentClassifyType = this.$route.query.classify_type;
      // 找index
      let indexNum = 0;
      this.allClassifyTypeList.forEach((item, index) => {
        if (
          item.exchange === currentExchange &&
          item.classify_name === currentClassifyName &&
          item.classify_type === currentClassifyType
        )
          indexNum = index;
      });
      let obj = {};
      if (type === "before") {
        obj =
          this.allClassifyTypeList[
            indexNum === 0 ? this.allClassifyTypeList.length - 1 : indexNum - 1
          ];
      } else {
        obj =
          this.allClassifyTypeList[
            indexNum === this.allClassifyTypeList.length - 1 ? 0 : indexNum + 1
          ];
      }

      this.$router.replace({
        query: {
          ...this.$route.query,
          exchange: obj.exchange,
          classify_name: obj.classify_name,
          classify_type: obj.classify_type,
        },
      });
    },

    //切换 前一天\后一天 如果遇到周六日则跳过
    handleDateChange(type) {
      let num = 1;
      if (type === "before") {
        if (this.$moment(this.selectDate).isoWeekday() === 1) {
          //向前一天时 当前为周一则 跳到 上周五
          num = 3;
        }
        this.selectDate = this.$moment(this.selectDate)
          .add(-num, "days")
          .format("YYYY-MM-DD");
      } else {
        if (this.$moment(this.selectDate).isoWeekday() === 5) {
          //向前一天时 当前为周五则 跳到 下周一
          num = 3;
        }
        this.selectDate = this.$moment(this.selectDate)
          .add(num, "days")
          .format("YYYY-MM-DD");
      }

      this.getInfo();
    },

    async getInfo() {
      if(!this.$route.query.classify_name||!this.$route.query.classify_type) return
      this.pageLoading = true;
      const res = await apiPositionAnalysisInfo({
        DataTime: this.selectDate || "",
        ClassifyName: this.$route.query.classify_name,
        ClassifyType: this.$route.query.classify_type,
        Exchange: this.$route.query.exchange,
      });
      this.pageLoading = false;
      if (res.Ret === 200) {
        const obj = res.Data || {};
        for (let key in this.chartListState) {
          this.chartListState[key] = {
            ...this.chartListState[key],
            ...obj[key],
          };
        }
        this.chartItemInfo = this.chartListState[this.tabKey];
        this.latestDate = res.Data.LastDataTime;
        if (res.Data.DataTime) {
          this.selectDate = this.$moment(res.Data.DataTime).format(
            "YYYY-MM-DD"
          );
          this.$emit('setInfo',{date: this.selectDate})
        }

        this.$store.commit(
          "SET_TITLE",
          `${this.$route.query.classify_type} ${this.$moment(
            this.selectDate
          ).format("YYYYMMDD")}持仓`
        );
      } else {
        // 清空数据
        for (let key in this.chartListState) {
          this.chartListState[key].List = null;
        }
      }
    },

    getHandles(data) {
      // 监听选择的日期改变
      if (data.opt == "date") {
        this.selectDate = data.val;
        this.getInfo();
      } else if (data.opt === "beforeDate") {
        this.handleDateChange("before");
      } else if (data.opt === "nextDate") {
        this.handleDateChange("next");
      } else if (data.opt === "beforeClassifyType") {
        this.handleClassifyTypeChange("before");
      } else if (data.opt === "nextClassifyType") {
        this.handleClassifyTypeChange("next");
      }
    },
  },

  mounted() {
    this.getAllClassifyType();
    this.getInfo();
  },
};
</script>

<style lang="scss" scoped>
.chart-position-analysis-page {
  padding-bottom: calc(160px + constant(safe-area-inset-bottom));
  padding-bottom: calc(160px + env(safe-area-inset-bottom));
  overflow-x: auto;
}
.chart-wrap-box{
    min-width: 743px;
    height: 100%;
    overflow-y: hidden;
  }
.chart-wrap {
  width: 100%;
  margin-bottom: 60px;
  .top-info-box {
    padding: 0 34px 30px 34px;
    text-align: center;
    span {
      display: inline-block;
      margin-right: 50px;
    }
  }
}
.wrap-top {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.empty-wrap {
  text-align: center;
  padding: 150px 0;
  box-sizing: border-box;
}

// @media (min-width: 600px){
.chart-position-analysis-page-pc {
  padding: 0;
  height: 100%;
  .top-sticky-wrap {
    display: none;
  }
  .bot-fixed-wrap {
    display: none;
  }
  .empty-wrap {
    font-size: 16px;
  }
  .chart-wrap {
    margin-bottom: 60px;
    .top-info-box {
      padding: 0 20px 20px;
      text-align: center;
      font-size: 20px;
      span {
        display: inline-block;
        margin-right: 30px;
      }
    }
  }
}
// }
</style>
