<template>
  <div class="testdiv">
    <div class="divborder newSearchDiv">
      <div>
        <div class="filter">
          <label>{{ $t("1132") }}：</label>
          <Cascader
            :data="datalevel"
            :value="leveldata"
            :render-format="format"
            trigger="click"
            @on-change="levelchange"
            change-on-select
            class="searchSelect"
            :disabled="more == 1"
          ></Cascader>
        </div>
        <div class="filter">
          <label>{{ $t("1129") }}：</label>
          <Select
            v-model="type1"
            class="searchSelect"
            @on-change="xTypechange"
            style="margin-right: 10px"
          >
            <Option :value="1" :label="$t(`500065`)"></Option>
            <Option :value="2" :label="$t(`1132`)"></Option>
          </Select>
          <Select
            v-model="x_id"
            clearable
            class="searchSelect"
            v-show="showStr"
          >
            <Option v-for="(v, i) in xTypeList" :value="v.value" :key="i">{{
              v.label
            }}</Option>
          </Select>
        </div>
        <div class="filter">
          <label>{{ $t("500088") }}：</label>
          <Select
            v-model="statistical_indicators"
            @on-change="indexchange"
            label-in-value
            clearable
            class="searchSelect"
          >
            <Option :value="1" :label="$t(`9900005`)"></Option>
            <Option :value="2">D-time</Option>
            <Option :value="3">MTBF</Option>
          </Select>
        </div>
        <div class="filter">
          <label>{{ $t("90000030") }}：</label>
          <Select
            v-model="andonType"
            multiple
            :max-tag-count="1"
            label-in-value
            clearable
            class="searchSelect nowropStyle"
          >
            <Option v-for="(v, i) in andonList" :value="v.id" :key="i">{{
              v.name
            }}</Option>
          </Select>
        </div>
        <!-- 次级搜索条件 隐藏 -->
        <div v-show="!morecondition">
          <div>
            <div class="filter" v-show="false">
              <label>{{ $t("100074") }}：</label>
              <Cascader
                :data="datamt"
                :value="mtdata"
                trigger="click"
                @on-change="mtchange"
                class="searchSelect"
              ></Cascader>
            </div>
            <div class="filter" v-show="false">
              <label>{{ $t("900572") }}：</label>
              <Select
                v-model="Trouble_code1"
                label-in-value
                :disabled="mtdata.length > 1 ? false : true"
                class="searchSelect"
                @on-change="Trouble_change"
              >
                <Option :value="1" :label="$t(`200022`)"></Option>
                <Option :value="2" :label="$t(`1590018`)"></Option>
                <Option :value="3" :label="$t(`1950472`)"></Option>
              </Select>
              <Select
                v-model="Trouble_code2"
                label-in-value
                :disabled="mtdata.length <= 1 || Trouble_code1 <= 0"
                class="searchSelect"
              >
                <Option
                  v-for="(v, i) in Trouble_codelist"
                  :value="v.id"
                  :key="i"
                  >{{ v.title }}</Option
                >
              </Select>
            </div>
            <div class="filter">
              <label>{{ $t("5000009") }}：</label>
              <Select
                v-model="sections"
                @on-change="moreSelect"
                label-in-value
                clearable
                class="searchSelect"
                multiple
                :disabled="more == 2"
                style="width: 240px"
                :max-tag-count="2"
              >
                <Option
                  v-for="(item, index) in sectionList"
                  :key="index"
                  :value="item.id"
                  >{{ item.name }}</Option
                >
              </Select>
            </div>
            <div class="filter">
              <label>{{ $t("900908") }}：</label>
              <DatePicker
                type="datetimerange"
                :clearable="false"
                v-model="index_time"
                class="searchInput MaxWidth"
              ></DatePicker>
            </div>
          </div>
        </div>
        <!-- 次级搜索条件  结束 -->
        <div class="searchBtn">
          <Button
            type="primary"
            class="twoWord intervalRight"
            icon="ios-search"
            @click="search()"
            >{{ $t("1001") }}</Button
          >
          <Button
            type="primary"
            class="fourWord"
            icon="md-download"
            @click="downpdf()"
            >{{ $t("900741") }}</Button
          >
        </div>
        <!-- 更多条件 按钮 -->
        <MoreConbtn
          @getCon="morecondition = !morecondition"
          :morecondition="morecondition"
        ></MoreConbtn>
      </div>
    </div>
    <div class="divborder newEchartStyle">
      <div v-show="showresult" id="demo">
        <div style="float: right">
          <label v-text="$t('8000050')">目标基准线</label>:
          <Input
            type="number"
            :min="0"
            v-model="line_value"
            @keyup.enter.native="search()"
            style="margin-right: 30px; width: 160px"
          ></Input>
        </div>
        <div style="clear: both"></div>
        <div>
          <div id="main" class="echartsId"></div>
        </div>
        <div style="padding: 0 80px">
          <div style="display: inline-block; margin-right: 80px">
            {{ $t("1035") }}{{ time }}
          </div>
          <div style="display: inline-block">
            {{ $t("1031") }}:{{ linetext }}
          </div>
          <Table
            class="echartsTable"
            highlight-row
            :data="tableData1"
            :columns="tableColumns1"
            :max-height="300"
          ></Table>
        </div>
      </div>
      <!-- MTBF -->
      <div v-show="mtbfshow">
        <div style="float: right">
          <label>目标基准线</label>:
          <Input
            type="number"
            :min="0"
            v-model="line_value1"
            @keyup.enter.native="search()"
            style="margin-right: 30px; width: 160px"
          ></Input>
        </div>
        <div style="clear: both"></div>
        <!-- <Input type="number" :min="1" v-model="line_value1" @keyup.enter.native="search()"></Input> -->
        <div id="mtbf" class="echartsId"></div>
        <div style="display: inline-block; margin-right: 80px">
          {{ $t("1035") }}{{ time }}
        </div>
        <div style="display: inline-block">{{ $t("1031") }}:{{ linetext }}</div>
        <Table
          class="echartsTable"
          highlight-row
          :data="tableData2"
          :columns="tableColumns2"
          :max-height="300"
        ></Table>
      </div>
    </div>
  </div>
</template>
<script>
import moment from "moment";
import echarts from "echarts";
import html2canvas from "html2canvas";
import JsPDF from "jspdf";
export default {
  data() {
    return {
      datalevel: [], // 产线层级数据
      leveldata: [], // 产线层级value
      statistical_indicators: 1, // 统计指标
      type1: 2, // 横坐标1
      type11: 0, // 时间单位横坐标
      type12: 514, // 产线层级横坐标
      showline: true, // 横坐标产线是否显示
      showstation: true, // 横坐工站是否显示
      datamt: [], // 插件所需数据
      mtdata: [], // 选中数据
      andonList: [], // 安灯列表,
      andonType: [], // 安灯类型,
      mtid: 0, //
      x_id: 0,
      type1: 0,
      xTypeList: [],
      showStr: true,
      index_time: "", // 时间范围
      Trouble_code1: "", // 故障代码第一个下拉框
      Trouble_code2: "", // 故障代码第二个下拉框
      Trouble_codelist: [], // 故障代码第二个下拉框列表
      morecondition: false, // 次级搜索条件 默认隐藏
      dataarr: [], // 利用产线层级id获得数组
      showresult: false, // 查询div --隐藏
      indexobj: {}, // 统计指标
      indexth: "", // 动态表头
      time: "", // 表格上方展示时间
      mtbfshow: false, // MTBF模块默认隐藏
      line_value: 0,
      line_value1: 0,
      linetext: "",

      num2: 20, // mtbf时间间隔
      tableData1: [],
      tableColumns1: [],
      tableData2: [], // mtbf数据
      tableColumns2: [
        // mtbf表头
        {
          type: "index2",
          title: this.$t("1008"), // 序号
          key: "xuhao",
          render: (h, params) => {
            return h("span", params.index + 1);
          },
          width: 60,
        },
        {
          title: this.$t("1129"), // 日期
          key: "date",
          align: "center",
        },
        {
          title: "MTBF",
          key: "MTBF",
          align: "center",
        },
      ],
      more: 0,
      sectionList: [],
      sections: [],
    };
  },
  created() {
    this.initlevel(); // 初始化产线层级
    this.initMT(); // 初始化设备类型下拉菜单
    this.iniandonlist();
    this.getSectionSelect();
    this.index_time = [
      moment(new Date().getTime() - 3600 * 1000 * 24 * 14).format(
        "YYYY-MM-DD "
      ) + "00:00:00",
      moment(new Date().getTime() - 3600 * 1000 * 24 * 1).format(
        "YYYY-MM-DD "
      ) + "23:59:59",
    ];
  },
  methods: {
    // 初始化产线层级
    initlevel() {
      this.axios
        .request({
          url: "config/ProjectLevelSection/GetSectionTree",
          method: "get",
        })
        .then((res) => {
          if (res.data.ret === 1) {
            const arr = [];
            this.datalevel = res.data.data;
            this.levelid = res.data.data[0].value;
            arr.push(res.data.data[0].value);
            this.leveldata = arr;
            // this.search()
          } else {
            this.$Message.error(this.$t(res.data.msg));
          }
        });
    },
    initMT() {
      // 初始化设备类型
      this.axios
        .request({
          url: "/config/MachineType/GetMachineTypeTree",
          method: "get",
        })
        .then((res) => {
          this.datamt = res.data.data;
          this.mtdata = [];
        });
    },
    iniandonlist() {
      // 初始化安灯类型
      var params = {
        level: 2,
        type: 1,
      };
      this.axios
        .request({
          url: "/tpm/andon/GetErrorsByLevel",
          params,
          method: "get",
        })
        .then((res) => {
          if (res.data.ret == 1) {
            this.andonList = res.data.data;
          }
        });
    },
    format(labels, selectedData) {
      const index = labels.length - 1;
      this.linetext = labels[index];
      var label = labels.join(" / ");
      return label;
    },
    levelchange(value) {
      // 横坐标变化函数
      this.levelid = value[value.length - 1];
      this.leveldata = value;
      this.getLevels();
      this.more = 2;
      if (value.length == 0) {
        this.more = 0;
      }
    },
    changecondition() {
      // 更多条件是否展示函数
      this.morecondition = !this.morecondition;
    },
    Trouble_change() {
      // 故障代码变化
      var params = {
        typeid: this.mtdata[this.mtdata.length - 1],
        faulttype: this.Trouble_code1,
        page: 1,
        pagesize: 100,
      };
      this.axios
        .request({
          url: "/tpm/FaultType/GetFaultList",
          params,
          method: "get",
        })
        .then((res) => {
          if (res.data.ret == 1) {
            this.Trouble_codelist = res.data.data;
          } else {
            this.$Message.error(this.$t(res.data.msg));
          }
        });
    },
    mtchange(value) {
      this.mtdata = value;
      if (this.mtdata.length < 1) {
        this.Trouble_code1 = "";
        this.Trouble_code2 = "";
      }
    },
    getSectionSelect() {
      let params = {
        reverselevel: 2,
        parentid: 0,
      };
      this.axios
        .request({
          url: "/config/ProjectLevelSection/GetSectionSelect",
          params,
          method: "get",
        })
        .then((res) => {
          // 产线层级
          if (res.data.ret === 1) {
            this.sectionList = res.data.data;
          }
        });
    },
    moreSelect(val) {
      this.more = 1;
      if (val.length == 0) {
        this.more = 0;
      }
    },
    // 横坐标选择
    xTypechange() {
      this.xTypeList = [];
      this.showStr = true;
      if (this.type1 === 1) {
        this.xTypeList = [
          { value: "a", label: this.$t("900864") },
          { value: "b", label: this.$t("1136") },
          { value: "c", label: this.$t("1138") },
        ];
      } else if (this.type1 === 2) {
        this.getLevels();
      } else {
        this.showStr = true;
      }
    },
    getLevels() {
      this.axios
        .request({
          url:
            "/config/ProjectLevelSection/GetLevelidsBySection?sectionId=" +
            this.levelid,
          method: "get",
        })
        .then((res) => {
          // 产线层级
          if (res.data.ret === 1 && this.type1 === 2) {
            this.xTypeList = [];
            if (res.data.data.length !== 0) {
              res.data.data.forEach((item) => {
                this.xTypeList.push({ value: item.id, label: item.title });
              });
              this.x_id = this.xTypeList[0].value;
            } else {
              this.showStr = false;
            }
          }
        });
    },
    search() {
      if (this.index_time[0] === "") {
        this.$Message.error(this.$t("1143"));
        return;
      }
      if (!this.type1 || !this.x_id) {
        this.$Message.error(this.$t("500133"));
        return;
      }
      this.time =
        moment(this.index_time[0]).format("YYYY-MM-DD HH:mm:ss ") +
        moment(this.index_time[1]).format("YYYY-MM-DD HH:mm:ss");

      let sectionId;
      if (this.leveldata.length && this.more == 2) {
        sectionId = this.leveldata[this.leveldata.length - 1];
      }
      if (this.sections.length && this.more == 1) {
        sectionId = this.sections.join(",");
      }
      var data = {
        sectionId: sectionId ? sectionId : 0,
        starttime: moment(this.index_time[0]).format("YYYY-MM-DD HH:mm:ss"),
        endtime: moment(this.index_time[1]).format("YYYY-MM-DD HH:mm:ss"),
        x_id: this.x_id,
        level_id: this.leveldata[this.leveldata.length - 1],
        onetype: this.statistical_indicators,
        offlinestatus: this.Shutdown,
        x_type: this.type1,
        offlinestatus: "",
        machinetype:
          this.mtdata.length < 1 ? "" : this.mtdata[this.mtdata.length - 1],
        fault_type: this.Trouble_code1 ? this.Trouble_code1 : 0,
        fault_id: this.Trouble_code2 ? this.Trouble_code2 : 0,
        target: this.num2,
        expections: this.andonType ? this.andonType : [],
      };

      if (this.statistical_indicators == 1) {
        // 故障率
        this.mtbfshow = false;
        this.showresult = true;
        this.axios
          .request({
            url: "/tpm/Statistics/faultFrequencyAnalysis",
            data,
            method: "post",
          })
          .then((res) => {
            if (res.data.ret == 1) {
              this.tableColumns1 = [
                {
                  title: this.$t("1008"),
                  render: (h, params) => {
                    return h("span", params.index + 1);
                  },
                  width: 60,
                },
                {
                  title: this.$t("1129"), // 产线层级
                  key: "linelevel",
                },
                {
                  title: this.$t("200085"), // 故障设备数量
                  key: "number",
                },
                {
                  title: this.indexth ? this.indexth : "故障率", // 故障率
                  key: "indexchange",
                },
              ];
              if (this.statistical_indicators === 1) {
                // 故障率
                // 统计指标
                this.mockTableData1(res.data.data);
                if (this.type1 == 2) {
                  this.plansAll1(
                    res.data.data.x,
                    0,
                    res.data.data.y2,
                    this.$t("200175")
                  );
                }
                if (this.type1 !== 2) {
                  const obj = this.$time.removezero(res.data.data);
                  this.plans1(obj.arr, 0, obj.arr2, this.$t("200175"));
                }
              }
            } else {
              this.$Message.error(this.$t(res.data.msg));
            }
          });
      } else if (this.statistical_indicators == 2) {
        // 统计指标 D-time
        this.mtbfshow = false;
        this.showresult = true;
        this.axios
          .request({
            url: "/tpm/Statistics/RepairWorkOrderSum",
            data,
            method: "post",
          })
          .then((res) => {
            if (res.data.ret === 1) {
              this.tableColumns1 = [
                {
                  title: this.$t("1008"), // 序号
                  render: (h, params) => {
                    return h("span", params.index + 1);
                  },
                },
                {
                  title: this.$t("1129"), // 设备类型
                  key: "linelevel",
                },
                {
                  title: this.indexth1 ? this.indexth1 : this.$t("900595"), // 故障时间
                  key: "indexchange",
                },
              ];
              var danwei = this.$t("200028");
              var name = this.$t("900595");
              const obj = this.$time.removezero(res.data.data);
              this.chartSet("main", name, obj.arr, danwei, obj.arr1, obj.arr2);
              this.mockTableData2(res.data.data, danwei);
            } else {
              this.$Message.error(this.$t(res.data.msg));
            }
          });
      } else if (this.statistical_indicators == 3) {
        this.mtbfshow = true;
        this.showresult = false;
        this.mtbf();
      } else if (this.statistical_indicators == 4) {
        this.mtbfshow = false;
        this.showresult = true;
        this.axios
          .request({
            url: "/tpm/Statistics/faultFrequencyAnalysis",
            data,
            method: "post",
          })
          .then((res) => {
            if (res.data.ret === 1) {
              this.tableColumns1 = [
                {
                  title: this.$t("1008"), // 序号
                  render: (h, params) => {
                    return h("span", params.index + 1);
                  },
                  width: 60,
                },
                {
                  title: this.$t("1129"), // 产线层级
                  key: "linelevel",
                },
                {
                  title: this.$t("200085"), // 故障设备数量
                  key: "number",
                },
                {
                  title: this.$t("200177"), // 备件费用
                  key: "indexchange",
                },
              ];
              // 统计指标
              this.mockTableData1(res.data.data);
              if (this.type1 === 2) {
                var obj = this.$time.removezero(res.data.data);
                this.plansAll1(obj.arr, 0, obj.arr2, this.$t("200177"));
              }
              if (this.type1 !== 2) {
                var obj = this.$time.removezero(res.data.data);
                this.plans1(obj.arr, 0, obj.arr2, this.$t("200177"));
              }
              // }
            } else {
              this.$Message.error(this.$t(res.data.msg));
            }
          });
      }
    },
    // 渲染列表开始
    mockTableData2(tablelist, danwei) {
      // 统计分析 D-time table
      let data = [];
      var i = 0;
      for (i; i < tablelist.x.length; i++) {
        data.push({
          linelevel: tablelist.x[i],
          indexchange: tablelist.y1[i] + danwei,
        });
      }
      this.tableData1 = data;
    },
    indexchange(value) {
      this.indexth = value ? value.label : this.$t("9900005"); // '故障率'
    },
    // 渲染列表开始
    mockTableData1(tablelist) {
      let data = [];
      var i = 0;
      var datanum = "";
      for (i; i < tablelist.x.length; i++) {
        if (this.type1 === 1) {
          datanum = "" + tablelist.y2[i] + "%";
        } else if (this.type1 === 2) {
          datanum = "" + tablelist.y2[i] + "%";
        } else if (this.type1 === 3) {
          datanum = "" + tablelist.y2[i];
        } else {
          datanum = "" + datanum;
        }
        data.push({
          linelevel: tablelist.x[i],
          number: tablelist.y1[i],
          indexchange: datanum,
        });
      }
      this.tableData1 = data;
    },
    plansAll1(A, B, C, onetype_name) {
      // 故障率
      var y_data = [];
      var y_title = [];
      if (B == 0) {
        y_title = [onetype_name];
        y_data = [
          {
            name: onetype_name,
            type: "bar",
            barMaxWidth: 70,
            data: C,
          },
        ];
      } else {
        y_title = [this.$t("200085"), onetype_name];
        y_data = [
          {
            name: this.$t("200085"),
            type: "bar",
            barMaxWidth: 70,
            data: B,
          },
          {
            name: onetype_name,
            type: "bar",
            barMaxWidth: 70,
            data: C,
          },
        ];
      }

      if (myChart != null && myChart != "" && myChart != undefined) {
        myChart.dispose();
      }
      var myChart = echarts.init(document.getElementById("main"));
      myChart.clear();
      var option = {
        title: {
          textStyle: {
            fontSize: 18,
          },
          subtextStyle: {
            fontSize: 14,
          },
        },
        legend: {
          data: y_title,
          //                data:['执行数','计划数']
        },

        // title: {
        //   text: onetype_name,
        //   subtext: ''
        // },
        tooltip: {
          trigger: "axis",
          formatter: function (params) {
            console.log(params);
            if (B == 0) {
              return (
                params[0].name +
                "<br/>" +
                params[0].seriesName +
                " : " +
                params[0].value +
                "%"
              );
            } else {
              return (
                params[0].name +
                "<br/>" +
                params[0].seriesName +
                " : " +
                params[0].value +
                "<br/>" +
                params[1].seriesName +
                " : " +
                params[1].value +
                "%"
              );
            }
          },
        },
        calculable: true,
        xAxis: [
          {
            name: this.$t("1132"),
            type: "category",
            data: A,
            axisLabel: {
              interval: 0,
              rotate: -30,
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            name: "%",
            // axisLabel: {
            //     interval: 'auto',
            //     formatter: '{value}%'
            // }
          },
        ],
        series: y_data,
      };
      myChart.setOption(option);
    },
    plans1(A, B, C, onetype_name) {
      // 故障率
      var y_data = [];
      var y_title = [];
      if (B == 0) {
        y_title = [onetype_name];
        y_data = [
          {
            name: onetype_name,
            type: "bar",
            barMaxWidth: 70,
            data: C,
            markLine: {
              data: [{ yAxis: this.line_value }],
            },
          },
        ];
      } else {
        y_title = [this.$t("200085"), onetype_name];
        y_data = [
          {
            name: this.$t("200085"),
            type: "bar",
            barMaxWidth: 70,
            data: B,
          },
          {
            name: onetype_name,
            type: "bar",
            barMaxWidth: 70,
            data: C,
          },
        ];
      }

      var myChart = echarts.init(document.getElementById("main"));
      myChart.clear();
      var option = {
        title: {
          textStyle: {
            fontSize: 18,
          },
          subtextStyle: {
            fontSize: 14,
          },
        },
        legend: {
          data: y_title,
          //                data:['执行数','计划数']
        },
        label: {
          show: true, // 开启显示
          // rotate: 70, // 旋转70度
          position: "top", // 在上方显示
        },
        // title: {
        //   text: onetype_name,
        //   subtext: ''
        // },
        tooltip: {
          trigger: "axis",
          formatter: function (params) {
            if (B == 0) {
              return (
                params[0].name +
                "<br/>" +
                params[0].seriesName +
                " : " +
                params[0].value +
                "%"
              );
            } else {
              return (
                params[0].name +
                "<br/>" +
                params[0].seriesName +
                " : " +
                params[0].value +
                "<br/>" +
                params[1].seriesName +
                " : " +
                params[1].value +
                "%"
              );
            }
          },
        },
        calculable: true,
        xAxis: [
          {
            name: this.$t("600532"),
            type: "category",
            data: A,
            axisLabel: {
              interval: 0,
              rotate: -30,
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            name: "%",
          },
        ],
        series: y_data,
      };
      myChart.setOption(option);
    },
    chartSet(ele, name, xName, danwei, barData, lineData) {
      // 统计分析 D-time Echarts
      for (var i = 0; i < lineData.length; i++) {
        lineData[i] = parseInt(lineData[i] * 100);
      }
      var myChart = echarts.init(document.getElementById(ele));
      var option = {
        title: {
          textStyle: {
            fontSize: 18,
          },
          subtextStyle: {
            fontSize: 14,
          },
        },
        // title: {
        //   text: 'D-time',
        //   subtext: ''
        // },
        legend: {
          data: [name + "(" + danwei + ")", this.$t("700143")],
          //                data:['执行数','计划数']
        },
        tooltip: {
          trigger: "axis",
          formatter: function (params) {
            // if (B == 0) {
            //   return params[0].name + '<br/>' + params[0].seriesName + ' : ' + params[0].value + '%'
            // } else {
            return (
              params[0].name +
              "<br/>" +
              params[0].seriesName +
              " : " +
              params[0].value +
              "<br/>" +
              params[1].seriesName +
              " : " +
              params[1].value +
              "%"
            );
            // }
          },
        },
        grid: {
          left: "10%",
          right: "10%",
          top: "10%",
          bottom: "5%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            data: xName,
            axisPointer: {
              type: "shadow",
            },
            axisLabel: {
              interval: 0,
              rotate: -30,
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            name: name, // lang('800205'),
          },
          {
            type: "value",
            name: this.$t("700143"),
            min: 0,
            max: 100,
            splitLine: {
              show: false,
            },
          },
        ],
        series: [
          {
            name: name + "(" + danwei + ")", // lang('900595')+"("+lang('200028')+")",
            type: "bar",
            barMaxWidth: 70,
            data: barData,
            markLine: {
              data: [{ yAxis: this.line_value }],
            },
          },
          {
            name: this.$t("700143"),
            type: "line",
            yAxisIndex: 1,
            data: lineData,
          },
        ],
      };

      myChart.setOption(option);
      window.onresize = function () {
        myChart.resize();
      };
    },
    mtbf() {
      var data = {
        sectionId: this.leveldata[this.leveldata.length - 1],
        starttime: moment(this.index_time[0]).format("YYYY-MM-DD HH:mm:ss"),
        endtime: moment(this.index_time[1]).format("YYYY-MM-DD HH:mm:ss"),
        // machineidarr: res.data.data,
        x_id: this.x_id,
        level_id: this.leveldata[this.leveldata.length - 1],
        onetype: this.statistical_indicators,
        offlinestatus: this.Shutdown,
        x_type: this.type1,
        offlinestatus: "",
        machinetype:
          this.mtdata.length < 1 ? "" : this.mtdata[this.mtdata.length - 1],
        fault_type: this.Trouble_code1 ? this.Trouble_code1 : 0,
        fault_id: this.Trouble_code2 ? this.Trouble_code2 : 0,
        target: this.num2,
        expections: this.andonType ? this.andonType : [],
      };
      this.axios
        .request({
          url: "/tpm/Statistics/repairDataTrendMTBF",
          data,
          method: "post",
        })
        .then((res) => {
          if (res.data.ret === 1) {
            res.data.data.y3 = res.data.data.y2;
            res.data.data.y2 = res.data.data.y1;
            const obj = this.$time.removezero(res.data.data);
            this.echartMTBF(obj.arr, obj.arr1);
            this.mockTableData3(res.data.data.y3);
          } else {
            this.$Message.error(this.$t(res.data.msg));
          }
        });
    },
    echartMTBF(xdata, linedata) {
      var myChart_mtbf;
      if (
        myChart_mtbf != null &&
        myChart_mtbf != "" &&
        myChart_mtbf != undefined
      ) {
        myChart_mtbf.dispose();
      }
      myChart_mtbf = echarts.init(document.getElementById("mtbf"));
      var option = {
        title: {
          textStyle: {
            fontSize: 18,
          },
          subtextStyle: {
            fontSize: 14,
          },
        },
        legend: {
          data: ["MTBF"],
          //                data:['执行数','计划数']
        },
        color: ["#3398DB"],
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
          },
        },
        grid: {
          left: "10%",
          right: "10%",
          top: "10%",
          bottom: "5%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            data: xdata,
            axisTick: {
              alignWithLabel: true,
            },
            axisLabel: {
              interval: 0,
              rotate: -30,
            },
          },
        ],
        yAxis: [
          {
            name: "MTBF" + this.$t(101107),
            type: "value",
            nameTextStyle: {
              fontSize: 16,
            },
          },
        ],
        series: [
          {
            itemStyle: {
              normal: {
                color: "#c23531",
              },
            },
            name: "MTBF",
            type: "bar",
            barMaxWidth: 70,
            barWidth: "60%",
            data: linedata,
            markLine: {
              data: [{ yAxis: this.line_value1 }],
            },
          },
        ],
      };
      myChart_mtbf.setOption(option);
    },
    // 渲染列表2开始
    mockTableData3(tablelist) {
      let data = [];
      tablelist.forEach((item) => {
        if (item) {
          data.push({
            date: item.time,
            station_name: item.location,
            MTBF: item.mtbf,
          });
        }
      });
      this.tableData2 = data;
    },
    downpdf() {
      var target = document.querySelector("#demo");
      html2canvas(target, {
        allowTaint: true,
        dpi: 172,
        background: "#fff",
      }).then(function (canvas) {
        var contentWidth = canvas.width;
        var contentHeight = canvas.height;

        // 一页pdf显示html页面生成的canvas高度;
        var pageHeight = (contentWidth / 592.28) * 841.89;
        // 未生成pdf的html页面高度
        var leftHeight = contentHeight;
        // pdf页面偏移
        var position = 0;
        // html页面生成的canvas在pdf中图片的宽高（a4纸的尺寸[595.28,841.89]）
        var imgWidth = 595.28;
        var imgHeight = (592.28 / contentWidth) * contentHeight;

        var pageData = canvas.toDataURL("image/jpeg", 1.0);
        var pdf = new JsPDF("", "pt", "a4");

        // 有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
        // 当内容未超过pdf一页显示的范围，无需分页
        if (leftHeight < pageHeight) {
          pdf.addImage(pageData, "JPEG", 0, 0, imgWidth, imgHeight);
        } else {
          while (leftHeight > 0) {
            pdf.addImage(pageData, "JPEG", 0, position, imgWidth, imgHeight);
            leftHeight -= pageHeight;
            position -= 841.89;
            // 避免添加空白页
            if (leftHeight > 0) {
              pdf.addPage();
            }
          }
        }
        pdf.save("content.pdf");
      });
    },
    removezero(list1, list2) {
      var temp1 = [];
      var temp2 = [];
      if (list1.length == list2.length) {
        for (let index = 0; index < list1.length; index++) {
          if (list2[index] != 0) {
            temp1.push(list1[index]);
            temp2.push(list2[index]);
          }
        }
      }
      var ret = { list1, list2 };
      return ret;
    },
  },
};
</script>
