<template>
  <div>
    <!-- <div class="search"> -->
    <ButtonNav style="padding: 0;" :menus="['邯郸', '瑞昌']" :button-mode="true" @change="currentMenu = $event">
    </ButtonNav>
    <!-- </div> -->
    <div class="containerTop">
      <el-form :model="listQuery" :inline="true" ref="dataForm" class="blueTip">
        <el-form-item label="时间维度" prop="date">
          <el-select size="small" clearable v-model="listQuery.type" placeholder="请选择">
            <el-option v-for="item in timeList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-show="listQuery.type === 0 || listQuery.type === ''" label="时间范围" prop="reportTime">
          <el-date-picker size="small" clearable v-model="listQuery.reportTime" type="daterange" range-separator="至"
            start-placeholder="开始日期" value-format="yyyy-MM-dd HH:mm:ss" @change="changeDayTime" end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item v-show="listQuery.type === 1" label="时间范围" prop="reportTime">
          <el-date-picker size="small" clearable v-model="start" type="week" format="yyyy 第 WW 周" placeholder="选择周"
            style="width: 180px" @change="onValueChange">
          </el-date-picker>
          至
          <el-date-picker size="small" clearable v-model="end" type="week" format="yyyy 第 WW 周" placeholder="选择周"
            style="width: 180px" @change="onValueChange">
          </el-date-picker>
          <!-- <span v-if="start && end" style="margin-left: 10px">
            {{ date1 }} 至 {{ date2 }}，共 {{ weekNum }} 周
          </span> -->
        </el-form-item>
        <el-form-item v-show="listQuery.type === 2" label="时间值" prop="reportTime">
          <el-date-picker size="small" v-model="listQuery.reportTime" type="monthrange"
            value-format="yyyy-MM-DD HH:mm:ss" range-separator="至" start-placeholder="开始月份" end-placeholder="结束月份"
            @change="changeTime">
          </el-date-picker>
        </el-form-item>
        <el-form-item v-show="listQuery.type === 3" label="时间值" prop="reportTime">
          <el-date-picker size="small" clearable v-model="listQuery.reportTime[0]" value-format="yyyy" type="year"
            placeholder="开始时间">
          </el-date-picker>
          ~
          <el-date-picker size="small" clearable v-model="listQuery.reportTime[1]" value-format="yyyy" type="year"
            placeholder="结束时间" @change="getYear">
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="玻璃类型" prop="type">
          <el-select v-model="listQuery.type" placeholder="请选择玻璃类型">
            <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="玻璃类型" prop="type">
          <el-select v-model="listQuery.type" placeholder="请选择玻璃类型">
            <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" size="small" @click="getDataList">查询</el-button>
          <el-divider direction="vertical"></el-divider>
          <!-- <el-button type="primary" size="small" plain @click="handleImport">导入</el-button> -->
          <el-button type="primary" size="small" plain @click="handleExport">导出</el-button>
          <!-- <el-button type="success" size="small" plain @click="addFactory">新增</el-button> -->
        </el-form-item>
      </el-form>
      <!-- <div class="smallTitle">产量转化效率</div> -->

      <!-- <bmSearchBar @getSearch="getSearch" @handleExport="handleExport" /> -->
      <bm-line-bar :chartHeight="chartHeight" :legendList="legendList" :chartMsg="chartMsg" :chartId="chartId"
        :chartNum="chartNum" />
      <base-table :table-props="tableProps" :page="listQuery.current" :limit="listQuery.size" :table-data="tableData"
        :max-height="tableH" />
    </div>
    <!-- <div class="containerBottom">

    </div> -->
  </div>
</template>

<script>
import bmSearchBar from "./components/bmSearchBar.vue";
import BmLineBar from "./components/bmLineBar.vue";
import ButtonNav from '@/components/ButtonNav'
import moment from 'moment'
const tableProps = [
  {
    prop: "factory",
    label: "玻璃类型",
    // filter: (val) => factoryList[val],
    minWidth: 200,
    showOverflowtooltip: true,
  },
  {
    prop: "name",
    label: "科目",
    minWidth: 120,
    showOverflowtooltip: true,
  },
  {
    prop: "unit",
    label: "单位",
    minWidth: 80,
    showOverflowtooltip: true,
  },
  {
    prop: "time1",
    label: "时间1",
    minWidth: 150,
    showOverflowtooltip: true,
  },
  {
    prop: "time2",
    label: "时间2",
    minWidth: 150,
    showOverflowtooltip: true,
  },
  {
    prop: "mubiao",
    label: "目标值",
    minWidth: 150,
    showOverflowtooltip: true,
  },
];
export default {
  name: "ChipYieldBM",
  data() {
    return {
      tableProps,
      start: undefined,
      end: undefined,
      listQuery: {
        // size: 10,
        // current: 1,
        factory: null,
        // total: 0,
        type: 2,
        startDate: undefined,
        endDate: undefined,
        reportTime: []
      },
      timeList: [
        {
          value: 0,
          label: '日'
        },
        {
          value: 1,
          label: '周'
        },
        {
          value: 2,
          label: '月'
        },
        {
          value: 3,
          label: '年'
        }
      ],
      tableData: [
        { factory: "工厂1" },
        { factory: "工厂1" },
        { factory: "工厂1" },
        { factory: "工厂1" },
        { factory: "工厂1" },
        { factory: "工厂1" },
        { factory: "工厂1" },
        { factory: "工厂1" },
        { factory: "工厂1" },
        { factory: "工厂1" },
        { factory: "工厂1" },
        { factory: "工厂1" },
        { factory: "工厂1" },
        { factory: "工厂1" },
        { factory: "工厂1" },
        { factory: "工厂1" },
        { factory: "工厂1" },
        { factory: "工厂1" },
        { factory: "工厂1" },
        { factory: "工厂1" },
        { factory: "工厂1" },
        { factory: "工厂1" },
        { factory: "工厂1" },
        { factory: "工厂1" },
        { factory: "工厂1" },
        { factory: "工厂1" },
        { factory: "工厂1" },
      ],
      chartHeight: this.tableHeight(137) / 2 - 111,
      tableH: this.tableHeight(137) / 2 - 70,
      legendList: [
        { id: 1, name: "2024年4月目标值", type: 2, color: "#FFCE6A" },
        { id: 2, name: "2023年4月", type: 1, color: "#8EF0AB" },
        { id: 3, name: "2024年4月", type: 1, color: "#288AFF" },
      ],
      chartMsg: {
        color: ["#FFCE6A", "#8EF0AB", "#288AFF"],
        xData: ["成都", "邯郸", "瑞昌"],
        yName: "单位/%",
        series: [
          {
            name: "2024年4月目标值",
            data: [
              { name: "%", value: 85 },
              { name: "%", value: 85 },
              { name: "%", value: 85 },
            ],
            type: "line",
            symbol: "circle",
            symbolSize: 6,
            label: {
              show: true,
              color: "#FFAE17",
              formatter: function (params) {
                return params.value.toFixed(2) + "%";
              },
            },
          },
          {
            name: "2023年4月",
            data: [
              { name: "%", value: 57.5 },
              { name: "%", value: 21.66 },
              { name: "%", value: 18.4 },
            ],
            type: "bar",
            barWidth: 20,
            label: {
              show: true,
              position: [-18, -16],
              color: "#68C483",
              formatter: function (params) {
                return params.value.toFixed(2) + "%";
              },
            },
          },
          {
            name: "2024年4月",
            data: [
              { name: "%", value: 23.33 },
              { name: "%", value: 7.02 },
              { name: "%", value: 80.2 },
            ],
            type: "bar",
            barWidth: 20,
            label: {
              show: true,
              position: [0, -16],
              color: "#288AFF",
              formatter: function (params) {
                return params.value.toFixed(2) + "%";
              },
            },
          },
        ],
      },
      chartId: "chipYieldBMChart",
      chartNum: 1,
    };
  },
  components: {
    bmSearchBar,
    BmLineBar,
    ButtonNav
  },
  computed: {
    weekNum() {
      return Math.round((this.end - this.start) / (24 * 60 * 60 * 1000 * 7)) + 1
    },
    isOpen() {
      return this.$store.getters.sidebar.opened;
    },
  },
  watch: {
    // 监听左侧菜单栏是否展开
    isOpen(val) {
      if (this.$route.name === "ChipYieldBM") {
        this.chartNum++;
      }
    },
  },
  created() {
    this.tableH = this.tableHeight(137) / 2 - 70;
    this.chartHeight = this.tableHeight(137) / 2 - 111;
    window.addEventListener("resize", this._setTableHeight);
  },
  destroyed() {
    window.removeEventListener("resize", this._setTableHeight);
  },
  activated() {
    // 图重新加载，为了防止窗口变化后尺寸图显示不佳，数据不更新
    if (this.$route.name === "ChipYieldBM") {
      this.chartNum++;
    }
  },
  mounted() {
    // this.getOverView()
    const currentMonth = new Date()
    this.listQuery.reportTime = [moment(currentMonth).format('yyyy-MM-DD HH:mm:ss'), moment(currentMonth).format('yyyy-MM-DD HH:mm:ss')]
    this.changeTime()
    this.getDataList()
  },
  methods: {
    getYear(e) {
      if (this.end && Number(this.end) - Number(this.start) > 10) {
        this.$message({
          message: '年份起止时间不能超过十年',
          type: 'warning'
        });
        this.start = undefined
        this.end = undefined
        // console.log();
      } else {
        if (Number(this.end) < Number(this.start)) {
          this.$message({
            message: '结束年份不能小于开始年份',
            type: 'warning'
          });
          this.start = undefined
          this.end = undefined
        } else {
          this.listQuery.startDate = Number(this.start)
          this.listQuery.endDate = Number(this.end)
        }
      }
      if (!this.start && !this.end) {
        this.listQuery.startDate = undefined
        this.listQuery.endDate = undefined
      }
      // console.log(e);
    },
    changeTime() {
      if (this.listQuery.reportTime) {
        console.log(this.listQuery.reportTime)
        let start = new Date(this.listQuery.reportTime[0])
        let end = new Date(this.listQuery.reportTime[1])
        // const years = Number(this.listQuery.reportTime[1].slice(0, 4)) - Number(this.listQuery.reportTime[0].slice(0, 4))
        // const months = Number(this.listQuery.reportTime[1].slice(4)) - Number(this.listQuery.reportTime[0].slice(4))
        // console.log(years);
        if ((end - start) > 31104000000) {
          this.$message({
            message: '时间范围不能超过24个月',
            type: 'warning'
          });
          this.listQuery.reportTime = [];
        } else {
          this.listQuery.startDate = this.listQuery.reportTime[0]
          this.listQuery.endDate = this.listQuery.reportTime[1]
        }
      } else {
        this.listQuery.startDate = undefined
        this.listQuery.endDate = undefined
      }
    },
    onValueChange(picker, k) { // 选中近k周后触发的操作
      if (this.start && this.end) {
        this.date1 = moment(this.start.getTime() - 24 * 60 * 60 * 1000).format('YYYY-MM-DD HH:mm:ss')
        this.date2 = moment(this.end.getTime() + 5 * 24 * 60 * 60 * 1000).format('YYYY-MM-DD HH:mm:ss')
        const numDays = (new Date(this.date2).getTime() - new Date(this.date1).getTime()) / (24 * 3600 * 1000);
        if (numDays > 168) {
          console.log(numDays)
          this.$message({
            message: '周范围不能超过24周',
            type: 'warning'
          });
        } else {
          this.listQuery.startDate = this.date1
          this.listQuery.endDate = this.date2
          // this.listQuery.startDate = Number(moment(this.start.getTime()).format('YYYYWW'))
          // this.listQuery.endDate = Number(moment(this.end.getTime()).format('YYYYWW'))
        }
      }
      if (!this.start && !this.end) {
        this.listQuery.startDate = undefined
        this.listQuery.endDate = undefined
      }
    },
    changeDayTime() {
      if (this.listQuery.reportTime) {
        const numDays = Number(this.listQuery.reportTime[1]) - Number(this.listQuery.reportTime[0])
        if (numDays > 30) {
          this.$message({
            message: '时间范围不能超过30天',
            type: 'warning'
          });
          this.listQuery.reportTime = [];
        } else {
          this.listQuery.startDate = this.listQuery.reportTime[0]
          this.listQuery.endDate = this.listQuery.reportTime[1]
        }
      } else {
        this.listQuery.startDate = undefined
        this.listQuery.endDate = undefined
      }
    },
    getOverView() {
      // getOverView().then(res => {
      //   this.data = res.data
      //   console.log('aa', res.data)
      // })
    },
    otherMethods(val) {
      this.detailOrUpdateVisible = true;
      // this.addOrEditTitle = "详情";
      this.$nextTick(() => {
        // this.$refs.detailOrUpdate.init(val.data.id);
      });
    },
    async getDataList() {
      console.log(this.listQuery);
      if (this.listQuery.type == 3) {
        this.listQuery.startDate = this.listQuery.reportTime[0] + '-01-01 00:00:00'
        this.listQuery.endDate = this.listQuery.reportTime[1] + '-12-31 23:59:59'
      }
      this.listQuery.factory = this.currentMenu === '邯郸' ? 1 : 2
      const res = await getComprehensiveDataPage(this.listQuery)
      this.tableData = res.data.list
      this.listQuery.total = res.data.total
      if (this.listQuery.total > 0) {
        this.tableData.forEach(item => {
          item.startTime = item.startDate ? item.startDate[0] + '-' + item.startDate[1] + '-' + item.startDate[2] : '--'
          item.endTime = item.endDate ? item.endDate[0] + '-' + item.endDate[1] + '-' + item.endDate[2] : '--'
        })
      }
    },
    _setTableHeight() {
      this.tableH = this.tableHeight(137) / 2 - 70;
      this.chartHeight = this.tableHeight(137) / 2 - 111;
      if (this.$route.name === "ChipYieldBM") {
        this.chartNum++;
      }
    },
    getSearch(val) {
      console.log(val);
      console.log("=========================");
    },
    handleExport() {
      console.log("导出");
    },
  },
};
</script>

<style lang="scss" scoped>
.search {
  // height: calc((100px));
  background-color: #fff;
  border-radius: 8px;
  padding: 16px 16px 0 16px;
  margin-bottom: 8px;
}

.containerTop {
  height: calc((100vh - 170px));
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
}

.blueTip::before {
  display: inline-block;
  content: '';
  width: 4px;
  height: 18px;
  background: #0B58FF;
  border-radius: 1px;
  margin-right: 8PX;
  margin-top: 8px;
}

.containerTop {
  margin-top: 8px;

  .smallTitle {
    font-size: 16px;
    color: #000;
    margin-bottom: 15px;
  }

  .smallTitle::before {
    display: inline-block;
    width: 4px;
    height: 16px;
    background: #0b58ff;
    content: "";
    margin-right: 8px;
    vertical-align: -3px;
  }
}
</style>
