<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="请选择日期"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOption"
            @change="getInfo"
            style="margin-right: 10px"
          />
          <el-button type="primary" @click="handleDateChange('before')"
            >查看前一天</el-button
          >
          <el-button type="primary" @click="handleDateChange('next')"
            >查看后一天</el-button
          >
        </div>
      </div>
      <div
        class="chart-wrap"
        v-if="chartItemInfo && chartListState.BuyList.List"
      >
        <div class="top-info-box">
          <span>{{ chartItemInfo.name }}</span>
          <span
            ><span style="color: #999; margin-right: 2px">总计 </span
            >{{ chartItemInfo.TotalDealValue }}</span
          >
          <span
            ><span style="color: #999; margin-right: 2px">较昨日 </span
            >{{ chartItemInfo.TotalDealChange }}</span
          >
        </div>
        <chart-box :keyVal="tabKey" :data="chartItemInfo" />
      </div>
    </div>

    <div class="empty-wrap" v-if="!chartListState.BuyList.List">
      <tableNoData text="该日期无数据" />
    </div>
  </div>
</template>

<script>
import {
  apiPositionAnalysisInfo,
  apiPositionAnalysisList,
} from "@/api/modules/positionAnalysis";
import chartBox from "./chartBox.vue";
export default {
  components: { chartBox },
  computed: {
    pickerOption() {
      let that = this;
      let obj = {
        // 周六日禁用
        disabledDate(t) {
          if ([5, 6].includes(that.$moment(t).weekday())) {
            return true;
          } else {
            return false;
          }
        },
      };
      return obj;
    },
  },
  watch: {
    "$route.query": {
      handler(nval) {
        this.selectDate = "";
        this.getInfo();
      },
    },
  },
  data() {
    return {
      isPcShow: true,

      isRefresh: false,

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

      allClassifyTypeList: [],

      pageLoading: false,
      chartListState: {
        BuyList: {
          name: "多单",
          labelName: "持多单量",
        },
        SoldList: {
          name: "空单",
          labelName: "持空单量",
        },
        CleanBuyList: {
          name: "净多单",
          labelName: "净多单量",
        },
        CleanSoldList: {
          name: "净空单",
          labelName: "净空单量",
        },
      },

      tabKeys: [
        { label: "多单", key: "BuyList" },
        { label: "空单", key: "SoldList" },
        { label: "净多单", key: "CleanBuyList" },
        { label: "净空单", key: "CleanSoldList" },
      ],
      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;
      });
      // console.log(indexNum);
      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
          ];
      }
      // console.log(obj);

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

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

      this.getInfo();
    },

    async getInfo() {
      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];
        if (res.Data.DataTime) {
          this.selectDate = this.$moment(res.Data.DataTime).format(
            "YYYY-MM-DD"
          );
        }

        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));
}
.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;
}

// @media (min-width: 600px){
.chart-position-analysis-page-pc {
  padding: 0;
  .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>
