<template>
  <div class="testdiv">
    <div class="divborder newSearchDiv" style="margin: 0px">
      <!-- 产线层级 -->
      <div class="filter">
        <label>{{ $t(1132) }}：</label>
        <Cascader
          :data="levelData"
          :value="curLevel"
          trigger="click"
          change-on-select
          class="searchSelect"
          @on-change="cascaderChange"
        ></Cascader>
      </div>
      <!-- 产品名称 -->
      <div class="filter">
        <label>{{ $t(100088) }}：</label>
        <Select v-model="productId" class="searchSelect" clearable>
          <Option v-for="(v, i) in productList" :key="i" :value="v.id">{{
            v.name
          }}</Option>
        </Select>
      </div>
      <!-- 时间范围 -->
      <div class="filter">
        <label>{{ $t(900908) }}：</label>
        <DatePicker
          type="daterange"
          :value="dateRange"
          class="searchInput middleWidth"
          @on-change="dateRangeChange"
        ></DatePicker>
      </div>
      <!-- 快捷日期 -->
      <div class="filter">
        <label>{{ $t(900910) }}</label>
        <Select
          v-model="quickDate"
          clearable
          @on-change="quickDateChange"
          class="searchSelect"
        >
          <Option :value="1" id="今天">{{ $t(900911) }}</Option>
          <Option :value="2" id="昨天">{{ $t(900390) }}</Option>
          <Option :value="3" id="本周">{{ $t(900912) }}</Option>
          <Option :value="4" id="上周">{{ $t(900913) }}</Option>
          <Option :value="5" id="本月">{{ $t(900914) }}</Option>
          <Option :value="6" id="上月">{{ $t(900915) }}</Option>
          <Option :value="7" id="本年">{{ $t(900916) }}</Option>
          <Option :value="8" id="上年">{{ $t(900917) }}</Option>
        </Select>
      </div>
      <!-- 按钮组 -->
      <div class="searchBtn">
        <Button
          type="primary"
          class="twoWord"
          icon="ios-search-outline"
          @click="search()"
          >{{ $t(1001) }}</Button
        >
        <Button
          type="primary"
          class="fourWord"
          icon="ios-close-circle-outline"
          @click="clear()"
          >{{ $t(1039) }}</Button
        >
      </div>
    </div>
    <div class="divborder newTableDiv">
      <!-- 可视化图表区域 -->
      <div class="analysis">
        <div class="circle circle_div">
          <p>计划生产数量</p>
          <p>{{ summary[0] }}件</p>
        </div>
        <div class="circle circle_div">
          <p>实际完工数量</p>
          <p>{{ summary[1] }}件</p>
        </div>
        <div class="circle circle_div">
          <p>计划工单数量</p>
          <p>{{ summary[2] }}件</p>
        </div>
        <div class="circle" id="chart_1"></div>
        <div class="circle" id="chart_2"></div>
        <div class="circle" id="chart_3"></div>
      </div>
      <!-- 主体表格 -->
      <Table
        class="echartsTable"
        :data="tableData"
        :columns="tableColumns"
      ></Table>
      <!-- 分页器 -->
      <div class="pageDiv">
        <div class="pageDirection">
          <Page
            :total="total"
            :current="page"
            @on-change="changePage"
            show-elevator
            show-sizer
            show-total
            @on-page-size-change="handlePageSize"
            :page-size-opts="[10, 20, 30, 40, 100]"
          ></Page>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import echarts from "echarts";
import moment from "moment";

export default {
  data() {
    return {
      // 数据总量
      total: 0,
      // 页码
      page: 1,
      // 页距
      pagesize: 10,
      // 产线层级级联数据
      levelData: [],
      // 产线层级深度
      levelNums: 0,
      // 搜索条件--产线层级
      curLevel: [],
      // 搜索条件--产品名称
      productId: "",
      // 产品下拉列表
      productList: [],
      // 搜索条件--时间范围
      dateRange: [],
      // 搜索条件--快捷日期
      quickDate: 1,
      // 可视化图表区域的数据
      summary: [0, 0, 0, 0, 0, 0],
      // 主体表格数据
      tableData: [],
      // 表格字段
      tableColumns: [
        {
          title: this.$t(1008),
          render: (h, params) => {
            return h(
              "span",
              params.index + (this.page - 1) * this.pagesize + 1
            );
          },
          width: 88,
          align: "center",
        },
        {
          title: this.$t(900337),
          key: "code",
          align: "center",
        },
        {
          title: this.$t(100088),
          key: "product_name",
          align: "center",
        },
        {
          title: this.$t(900922),
          key: "plan_number",
          align: "center",
        },
        {
          title: this.$t(900923),
          key: "actual_number",
          align: "center",
        },
        {
          title: this.$t(900924),
          align: "center",
          render: (h, params) => {
            let timestamp = params.row.delivery_time;
            let text = moment(timestamp * 1000).format("YYYY-MM-DD");
            return h("div", {
              domProps: {
                innerHTML: text,
              },
            });
          },
        },
        {
          title: this.$t(600588),
          key: "ok_number",
          align: "center",
        },
        {
          title: this.$t(600589),
          key: "nok_number",
          align: "center",
        },
        {
          title: this.$t(500123),
          align: "center",
          render: (h, params) => {
            let rate = params.row.pass_rate;
            let text = `${rate}%`;
            return h("div", {
              domProps: {
                innerHTML: text,
              },
            });
          },
        },
      ],
    };
  },
  mounted() {
    // 初始化表格字段
    this.tableColumns = this.$time.initTableTitle(this.tableColumns);
    // 获取产线层级级联数据
    this.getCascader();
    // 获取产品下拉列表
    this.getProductList();
    // 初始化查询日期
    this.initSearchDate();
    // 初始查询
    this.search();
  },
  methods: {
    // 获取产线层级级联数据
    getCascader() {
      const _this = this;
      _this.axios
        .request({
          url: "/config/ProjectLevelSection/GetSectionTree",
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            let data = result.data;
            _this.levelData = data;
            _this.levelNums = _this.getMaxFloor(data);
            _this.curLevel = [data[0].value];
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        });
    },
    // 根据树形结构数据算出树形结构数据的深度
    getMaxFloor(treeData) {
      let floor = 0;
      let max = 0;
      function each(data, floor) {
        data.forEach((e) => {
          e.floor = floor;
          if (floor > max) {
            max = floor;
          }
          if (e.children.length > 0) {
            each(e.children, floor + 1);
          }
        });
      }
      each(treeData, 1);
      return max;
    },
    // 监听产线层级级联数据变化
    cascaderChange(v) {
      this.curLevel = v;
    },
    // 获取产品下拉列表
    getProductList() {
      const _this = this;
      _this.axios
        .request({
          url: "/cnc/Product/GetProducetname",
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            _this.productList = result.data;
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        });
    },
    // 监听时间范围变化
    dateRangeChange(v) {
      if (!v[0] || !v[1]) {
        this.dateRange = [];
        return false;
      }

      this.dateRange = [v[0], v[1]];
    },
    // 监听快捷日期变化
    quickDateChange() {
      let v = this.$time.changetime(this.quickDate).split(" - ");
      this.dateRange = [v[0], v[1]];
    },
    // 初始化搜索日期条件
    initSearchDate() {
      let date = new Date();
      let start = this.$time.timestampToTime(date.getTime());
      let end = this.$time.timestampToTime(date.getTime());
      this.dateRange = [start, end];
    },
    // 监听页码变化
    changePage(value) {
      this.page = value;
      this.search();
    },
    // 监听页距变化
    handlePageSize(value) {
      this.pagesize = value;
      this.search();
    },
    // 查询
    search() {
      const _this = this;
      let { curLevel, productId, dateRange, page, pagesize } = this;
      let params = {
        sectionid: curLevel[curLevel.length - 1]
          ? curLevel[curLevel.length - 1]
          : 0,
        productid: productId,
        starttime: dateRange[0]
          ? moment(new Date(dateRange[0])).format("YYYY-MM-DD")
          : "",
        endtime: dateRange[1]
          ? moment(new Date(dateRange[1])).format("YYYY-MM-DD")
          : "",
        page,
        pagesize,
      };
      console.log(
        moment(new Date(dateRange[0])).format("YYYY-MM-DD"),
        moment(new Date(dateRange[1])).format("YYYY-MM-DD")
      );
      _this.axios
        .request({
          url: "cnc/PerformanceStatistics/GetPlanSum",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            let data = result.data;
            _this.$set(_this.summary, 0, data.plannumber ? data.plannumber : 0);
            _this.$set(
              _this.summary,
              1,
              data.actualnumber ? data.actualnumber : 0
            );
            _this.$set(_this.summary, 2, data.total ? data.total : 0);

            _this.summary[3] =
              data.productpercent && data.productpercent != "NaN"
                ? data.productpercent
                : 0;
            _this.summary[4] =
              data.planpercent && data.planpercent != "NaN"
                ? data.planpercent
                : 0;
            _this.summary[5] =
              data.qualitypercent && data.qualitypercent != "NaN"
                ? data.qualitypercent
                : 0;
            _this.drawCharts(
              _this.summary[3],
              _this.summary[4],
              _this.summary[5]
            );
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        });
      _this.axios
        .request({
          url: "cnc/PerformanceStatistics/GetPlanExecutionAnalysis",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            _this.total = result.total;
            let data = result.data;
            let tableData = [];
            if (data && Array.isArray(data) && data.length) {
              data.forEach((v) => {
                tableData.push({
                  id: v.id,
                  code: v.code,
                  product_name: v.product_name,
                  plan_number: v.plan_number,
                  actual_number: v.actual_number,
                  delivery_time: v.delivery_time,
                  ok_number: v.ok_number,
                  nok_number: v.nok_number,
                  pass_rate: v.pass_rate,
                });
              });
            }
            _this.tableData = tableData;
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        });
    },
    // 生成可视化图表
    drawCharts(v1, v2, v3) {
      let option1 = {
        color: ["#FF6600"],
        title: {
          text: "产量达成率",
          subtext: v1 + "%",
          x: "center",
          y: "center",
          textStyle: {
            color: "#000",
            fontSize: 18,
          },
          subtextStyle: {
            color: "#000",
            fontSize: 18,
          },
        },
        animation: true,
        tooltip: {
          show: false,
        },
        series: [
          {
            type: "pie",
            radius: ["100%", "75%"],
            avoidLabelOverlap: false,
            hoverAnimation: false,
            clockwise: true,
            startAngle: 270,
            labelLine: {
              normal: {
                show: false,
              },
            },
            label: {
              normal: {
                show: false,
              },
            },
            data: [
              {
                value: v1 > 100 ? 100 : v1,
                name: "",
              },
              {
                value: v1 > 100 ? 0 : 100 - v1,
                name: "other",
                itemStyle: {
                  normal: {
                    color: "#ddd",
                  },
                },
              },
            ],
          },
        ],
      };
      let option2 = {
        color: ["#FF6600"],
        title: {
          text: "计划达成率",
          subtext: v2 + "%",
          x: "center",
          y: "center",
          textStyle: {
            color: "#000",
            fontSize: 18,
          },
          subtextStyle: {
            color: "#000",
            fontSize: 18,
          },
        },
        animation: true,
        tooltip: {
          show: false,
        },
        series: [
          {
            type: "pie",
            radius: ["100%", "75%"],
            avoidLabelOverlap: false,
            hoverAnimation: false,
            clockwise: true,
            startAngle: 270,
            labelLine: {
              normal: {
                show: false,
              },
            },
            label: {
              normal: {
                show: false,
              },
            },
            data: [
              {
                value: v2 > 100 ? 100 : v2,
                name: "",
              },
              {
                value: v2 > 100 ? 0 : 100 - v2,
                name: "other",
                itemStyle: {
                  normal: {
                    color: "#ddd",
                  },
                },
              },
            ],
          },
        ],
      };
      let option3 = {
        color: ["#FF6600"],
        title: {
          text: "质量合格率",
          subtext: v3 + "%",
          x: "center",
          y: "center",
          textStyle: {
            color: "#000",
            fontSize: 18,
          },
          subtextStyle: {
            color: "#000",
            fontSize: 18,
          },
        },
        animation: true,
        tooltip: {
          show: false,
        },
        series: [
          {
            type: "pie",
            radius: ["100%", "75%"],
            avoidLabelOverlap: false,
            hoverAnimation: false,
            clockwise: true,
            startAngle: 270,
            labelLine: {
              normal: {
                show: false,
              },
            },
            label: {
              normal: {
                show: false,
              },
            },
            data: [
              {
                value: v3 > 100 ? 100 : v3,
                name: "",
              },
              {
                value: v3 > 100 ? 0 : 100 - v3,
                name: "other",
                itemStyle: {
                  normal: {
                    color: "#ddd",
                  },
                },
              },
            ],
          },
        ],
      };
      echarts.init(document.getElementById("chart_1")).setOption(option1);
      echarts.init(document.getElementById("chart_2")).setOption(option2);
      echarts.init(document.getElementById("chart_3")).setOption(option3);
    },
    // 清空查询条件
    clear() {
      this.curLevel = [];
      this.productId = "";
      this.quickDate = 1;
      this.quickDateChange();
    },
  },
};
</script>
<style lang="less" scoped>
.analysis {
  display: flex;
  align-items: center;
  justify-content: space-around;
  margin: 14px 0;

  .circle {
    width: 160px;
    height: 160px;
  }

  .circle_div {
    border-radius: 100%;
    background: #ffaa71;

    p:nth-child(1) {
      text-align: center;
      font-size: 18px;
      font-weight: bold;
      padding-top: 55px;
      color: #fff;
    }
    p:nth-child(2) {
      text-align: center;
      font-size: 18px;
      padding-top: 4px;
      color: #0000ff;
    }
  }
}
</style>
