<template>
  <div>
    <div class="divborder newSearchDiv">
      <div>1、选择需要分析的数据信息</div>
      <div class="filter">
        <label>{{$t('1132')}}：</label>
        <Cascader
          class="searchInput"
          :data="datalevel"
          :value="leveldata"
          trigger="click"
          change-on-select
          @on-change="handlelevelchange"
          @on-visible-change="getProducts"
        ></Cascader>
      </div>
      <div class="filter">
        <label>{{$t('100307')}}：</label>
        <Select class="searchSelect" v-model="productid" label-in-value @on-change="inititems">
          <Option
            v-for="item in products"
            :value="item.code"
            :key="item.id"
          >{{ item.name + "【" + item.code +"】" }}</Option>
        </Select>
      </div>
      <div class="filter">
        <label>{{$t('5500250')}}：</label>
        <Select
          class="searchSelect"
          v-model="itemid"
          label-in-value
          clearable
          @on-change="getItems"
        >
          <Option v-for="item in items" :value="item.id" :key="item.id">{{ item.item }}</Option>
        </Select>
      </div>
      <div class="filter">
        <label>{{$t('1046')}}：</label>
        <DatePicker
          id="日期"
          type="datetimerange"
          v-model="daterange"
          confirm
          placeholder="请选择"
          format="yyyy-MM-dd HH:mm:ss"
          class="searchInput MaxWidth"
          @on-change="selectdate"
        ></DatePicker>
      </div>
      <div class="searchBtn">
        <Button class="twoWord" type="primary" icon="ios-search" @click="search()">{{$t('600568')}}</Button>
      </div>
    </div>
    <div class="divborder newSearchDiv otherSelect">
      <div>2、相关检验数据展示选择</div>
      <div style="display:inline-block;">
        <Table
          v-for="(item,index) in TableDatas"
          :key="index"
          highlight-row
          :data="item.data"
          :columns="item.title"
          @on-selection-change="selectionChange"
          class="tablechild"
          :max-height="200"
          :ref="'checkTable'+index"
        ></Table>
      </div>
      <div class="searchBtn">
        <Button
          v-show="showBtn"
          class="fourWord"
          type="primary"
          icon="ios-pulse-outline"
          @click="startSearch()"
        >开始分析</Button>
      </div>
    </div>

    <div class="divborder newSearchDiv otherSelect">
      <div>3、数据清洗规则</div>
      <div>
        <p>规则1：排除此工位之后的数据</p>
        <p>规则2：排除没有SN的数据</p>
        <p>规则3：排除没有有效值的数据</p>
        <p>规则4：排除值不变的数据</p>
        <p>规则5：排除变量的值不正确的数据</p>
      </div>
    </div>

    <div class="divborder newSearchDiv otherSelect">
      <Tabs :value="tabvalue" @on-click="checkTabs">
        <TabPane label="数据展示" name="1" class="newTableDiv">
          <div>4、有效数据呈现</div>
          <!-- <div class="searchBtn">
            <Button
              v-show="showBtn"
              class="fourWord"
              type="primary"
              icon="md-download"
              @click="download()"
            >{{$t('1007')}}</Button>
          </div> -->
          <div>
            <Table
              highlight-row
              :data="tableData1"
              :columns="tableColumns1"
              :show-header="true"
              class="tableClass"
              border
            ></Table>
            <div class="pageDiv">
              <div class="pageDirection">
                <Page
                  :total="total"
                  :current="page"
                  :page-size="pagesize"
                  @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>
        </TabPane>
        <TabPane label="可视化显示" name="2">
          <div class="top_echart" id="topechart"></div>
          <div class="top_echart">
            <div class="mid_echart" id="m_l"></div>
            <div class="mid_echart" id="m_m"></div>
            <div class="mid_echart" id="m_r"></div>
          </div>
          <div>
            <List header="详细信息" border size="large">
              <ListItem>
                <div v-html="errorHtml">

                </div>
              </ListItem>
            </List>
          </div>
        </TabPane>
        <TabPane label="二次拟合分析" name="3">
          <div>1、相关检验数据展示</div>
          <!-- <div>
            <div class="filter">
              <label>去除工位：</label>
              <Select class="searchSelect" v-model="removeStation" label-in-value clearable>
                <Option v-for="(item,index) in stationlists" :value="item.section" :key="index">{{ item.title }}</Option>
              </Select>
            </div>
            <div class="filter">
              <label>去除值：</label>
              <Select
                class="searchSelect minWidth"
                v-model="removeSymbol"
                label-in-value
                style="margin-right:10px;"
              >
                <Option :value="1">>=</Option>
                <Option :value="2"><</Option>
              </Select>
              <InputNumber class="searchInput" :min="0" v-model="removeNum" />
            </div>
            <div class="searchBtn">
              <Button
                v-show="showBtn"
                class="fourWord"
                type="primary"
                icon="md-close-circle"
                @click="removeItem()"
              >去除</Button>
            </div>
          </div> -->
          <div>
            <Table
              @on-selection-change="handleSelectRow"
              highlight-row
              :data="tableData2"
              :columns="tableColumns2"
              class="tableClass"
              :max-height="400"
            ></Table>
            <div class="searchBtn" style="margin-top:10px;">
              <Button
                v-show="showBtn"
                class="fourWord"
                type="primary"
                icon="ios-pulse-outline"
                @click="lastAnalysis"
              >二次分析</Button>
            </div>
          </div>
        </TabPane>
      </Tabs>
    </div>
  </div>
</template>
<script>
import axios from "@/libs/api.request";
import echarts from "echarts";
import moment from "moment";
export default {
  data() {
    return {
      tabvalue: "1",
      products: [],
      productid: 0,
      leveldata: [],
      levelname: "",
      datalevel: [],
      sectionid: 0,
      daterange: '',
      itemid: "",
      itemname: "",
      items: [],
      TableDatas: [],
      showBtn: false, // 开始分析 按钮
      tableData1: [],
      tableColumns1: [],
      page: 1,
      pagesize: 10,
      total: 0,
      selection: [], // 选中检验数据
      removeStation: "", // 去除工位
      stationlists: [], // 工位列表
      removeSymbol: 1,
      removeNum: 0,
      tableColumns2: [
        {
          type: "selection",
          width: 80,
        },
        {
          title: "序号",
          key: "index2",
          render: (h, params) => {
            return h("span", params.index + 1);
          },
        },
        // {
        //   title: "工位",
        //   key: "station",
        //   sortable: true,
        // },
        {
          title: "项目",
          key: "item",
        },
        {
          title: "值",
          key: "value",
          sortable: true,
        },
      ],
      itemselection: [], // 二次分析
      itemids:[],
      tableData2: [],
      errorHtml:'',

      myChartOne:'',
      myChartTwo1:'',
      myChartTwo2:'',
      myChartTwo3:'',
      excel:0,
    };
  },
  created() {
    this.initTime();
    this.initlevel();
  },
  mounted(){
    this.baseEcharts();
    window.onresize = () => {
      this.myChartOne.resize();
      this.myChartTwo1.resize();
      this.myChartTwo2.resize();
      this.myChartTwo3.resize();
    };
  },
  methods: {
    baseEcharts(){
      this.topEcharts([],[]); //显著性分析
      this.midLeftEchart1("m_l", "", "red",[]);
      this.midLeftEchart2("m_m", "", "purple",[]);
      this.midLeftEchart3("m_r", "", "green",[]);
    },
    initTime(){
      //时间默认一周
      var time = this.$time.changetime(5).split(' - ')
      this.daterange = [time[0], time[1]];//['2020-07-01 00:00:00','2020-07-31 00:00:00'];
    },
    handlelevelchange(value, selectedData) {
      this.leveldata = value;
      var sectionid = value[value.length - 1];
      this.sectionid = sectionid;
      this.levelname =
        selectedData[value.length - 1] != undefined
          ? selectedData[value.length - 1].label
          : "";
      // this.initproducts(sectionid);
    },
    getProducts(value){
      //关闭弹窗时请求
      if(!value){
        this.itemid = ''
        this.initproducts(this.sectionid);
      }
    },
    initproducts(sectionid) {
      this.products = [{ id: 0, name: "", code: "" }];
      axios
        .request({
          url:
            "/qms/InspectStandard/GetProductsBySectionId?sectionid=" +
            sectionid,
          method: "get",
        })
        .then((res) => {
          this.productid = "";
          this.products = []
          if(res.data.ret===1 && res.data.data.length > 0){
            this.products = res.data.data;
          }
        });
    },
    initlevel() {
      axios
        .request({
          url: "config/ProjectLevelSection/GetSectionTree",
          method: "get",
        })
        .then((res) => {
          const arr = [];
          this.datalevel = res.data.data;
          // arr.push(res.data.data[0].value);
          this.leveldata = arr;
        });
    },
    inititems() {
      if (this.productid===undefined || this.productid===0){
        return;
      }
      this.items = [{ id: 0, item: "" }];
      axios
        .request({
          url:
            "/qms/InspectStandard/GetItemsByProductCode?productCode=" +
            this.productid +
            "&sectionid=" +
            this.sectionid,
          method: "get",
        })
        .then((res) => {
          this.items = [];
          if (
            res.data.ret === 1 &&
            res.data.data != null &&
            res.data.data.length > 0
          ) {
            this.items = res.data.data;
          }
        });
    },
    getItems(e) {
      this.itemname = ''
      if(e!=null && e!=undefined){
        this.itemname = e.label;
      }
      
    },
    selectdate(e) {
      let dtStart = e[0];
      let dtEnd = e[1];
      let last_str = dtEnd.split(" ")[1];
      if (last_str === "00:00:00") {
        dtEnd = moment(dtEnd).format("YYYY-MM-DD") + " 23:59:59";
      }
      this.daterange = [dtStart, dtEnd];
    },
    search() {
      // 选择方法
      // 判断产线层级最后一个层级
      this.getTableLists();
    },
    getTableLists() {
      this.showBtn = true; // 开始分析按钮
      axios
        .request({
          url:
            "/qms/InspectStandard/GetItemsByParent?productCode=" +
            this.productid +
            "&sectionid=" +
            this.sectionid,
          method: "get",
        })
        .then((res) => {
          this.TableDatas = [];
          this.stationlists = [];
          if (
            res.data.ret === 1 &&
            res.data.data != null &&
            res.data.data.length > 0
          ) {
            let info = res.data.data;
            this.stationlists = info;
            info.forEach((item, index) => {
              let arr = {};
              let title = [
                {
                  type: "selection",
                  width: 80,
                },
                {
                  title: item.title,
                  key: "value",
                  width: 200,
                },
              ];
              let a_arr = [];
              if (item.data.length > 0) {
                item.data.forEach((v, k) => {
                  a_arr.push({
                    table_index: index,
                    row_index: k,
                    value: v.value,
                    id: v.id,
                    _checked: false,
                  });
                });
              }
              arr.title = title;
              arr.data = a_arr;
              this.TableDatas.push(arr);
            });
          }
        });
    },
    selectionChange(value) {
      // this.selection = value;
    },
    download(){
      //导出
      this.excel = 1
      this.startAnalysis();
    },
    startSearch(){
      this.page = 1
      this.pagesize = 10
      this.excel = 0

      // 获取选中数据
      this.itemids = [];
      let num = this.TableDatas.length;
      for (var i = 0; i < num; i++) {
        this.$refs["checkTable" + i][0].getSelection().map((item) => {
          this.itemids.push(item.id);
        });
      }

      this.startAnalysis();

      // 获取tab2 的echarts图
      // this.$nextTick(()=>{
          this.getEchartList();
      // })
    },
    startAnalysis() {

      if (this.itemids.length === 0) {
        this.$Message.error("请选择检验数据");
        return false;
      }
      if (this.itemid === "" || this.itemid === 0) {
        this.$Message.error("请选择检测项目");
        return false;
      }

      // 开始分析
      this.tabvalue = "1";
      this.tableColumns1 = [];
      //请求接口，获取数据
      var data = {
        setYstation: this.sectionid,
        setYProductCode: this.productid,
        setYItem: this.itemid,
        setStarttime:
          this.daterange != "" && this.daterange != null && this.daterange[0]!=""
            ? moment(this.daterange[0]).format("YYYY-MM-DD HH:mm:ss")
            : "",
        setEndtime:
          this.daterange != "" && this.daterange != null  && this.daterange[1]!=""
            ? moment(this.daterange[1]).format("YYYY-MM-DD HH:mm:ss")
            : "",
        setXItems: this.itemids,
        page: this.page,
        pagesize: this.pagesize,
        excel:this.excel
      };
      axios
        .request({
          url: "qms/BI/GetRelationAnalysis",
          data,
          method: "post",
        })
        .then((res) => {
          if(this.excel === 1){
            if (res.data.ret === 1) {
                window.location.href =
                    axios.publicPath + '' + res.data.data;
            } else {
                this.$Message.error(this.$t(res.data.msg));
            }
            return false;
          }
          this.total = 0
          this.tableColumns1 = []
          this.tableData1 = []
          if ( res.data.ret === 1) {
              this.total = res.data.total
              // 标题
              let header = res.data.data.heads
              let headerArr = []
              headerArr = [{
                  title: 'SN',
                  key: 'sn',
                  align: 'center',
                  width: 300,
                  fixed: 'left'
              }]
              header.forEach((item, index) => {
                  let hchild = []
                  let harr = {
                      title: item.station,
                      align: 'center',
                  }
                  if (item.items.length > 0) {
                      item.items.forEach((value, key) => {
                          hchild.push({
                              title: value.item,
                              key: item.section + '_' + key,
                              align: 'center',
                              width: 100
                          })
                      })
                  }
                  harr.children = hchild
                  headerArr.push(harr)
              })
              this.tableColumns1 = headerArr
              // 数据列表
              let bodyArr = []
              let bodyer = res.data.data.bodys
              
              for (var i = 0; i < bodyer.length; i++) {
                  var b_obj = {}
                  var b_child = bodyer[i].rowsCols
                  
                  for (var j = 0; j < b_child.length; j++) {
                      if (j === 0) {
                          b_obj.sn = b_child[j].sn
                      }
                      var bb_child = b_child[j].items
                      for (var z = 0; z < bb_child.length; z++) {
                          var b_key = b_child[j].section + '_' + z
                          b_obj[b_key] = bb_child[z].value
                      }
                  }
                  bodyArr.push(b_obj)
              }
              this.tableData1 = bodyArr
              this.total = res.data.total
                
          }else {
                this.$Message.error(this.$t(res.data.msg))
            }
        });
    },
    changePage(value) {
      this.page = value;
      this.startAnalysis();
    },
    handlePageSize(value) {
      this.pagesize = value;
      this.startAnalysis();
    },
    getEchartList() {
      //请求接口，获取数据
      var data = {
        setYstation: this.sectionid,
        setYProductCode: this.productid,
        setYItem: this.itemid,
        setStarttime:
          this.daterange != "" && this.daterange != null && this.daterange[0]!=""
            ? moment(this.daterange[0]).format("YYYY-MM-DD HH:mm:ss")
            : "",
        setEndtime:
          this.daterange != "" && this.daterange != null && this.daterange[1]!=""
            ? moment(this.daterange[1]).format("YYYY-MM-DD HH:mm:ss")
            : "",
        setXItems: this.itemids,
        page: this.page,
        pagesize: this.pagesize,
      };
      axios
        .request({
          url: "qms/BI/GetRelationVisualization",
          data,
          method: "post",
        })
        .then((res) => {
          this.errorHtml = '' //详细信息
          this.tableData2 = [] //二次分析条件
          //显著性条件
          let nameArr = []
          let dataArr = []
          //项目
          let project1 = {
            value:'',
            echart:[]
          }
          let project2 = {
            value:'',
            echart:[]
          }
          let project3 = {
            value:'',
            echart:[]
          }
          if (res.data.ret === 1 && res.data.data != null && res.data.data!=undefined) {
            //1、详细信息
            this.errorHtml = res.data.data.summary
            //二次分析条件
            let topArr = res.data.data.top
            if(this.itemselection.length ===0 ){
              this.itemselection = topArr
            }
            if(topArr!=null&&topArr!=undefined&&topArr.length > 0){
              topArr.forEach((v,k) => {
                this.tableData2.push({
                  itemId:v.itemId,
                  item:v.item,
                  value:v.value,
                  _checked:true
                })
              });
            }
            //2、显著性排行
            let topData = res.data.data.top;
            topData.sort((a,b)=>{
              return a.value - b.value
            })
            if(topData.length > 0){
              topData.forEach((item,index)=>{
                //取前10条
                if(index < 10){
                  nameArr.push(item.item)
                  dataArr.push(item.value)
                }
              })
            }

            // 2、项目
            let echartdata = res.data.data.rankings
            if(echartdata!=null&&echartdata!=undefined){
              if(echartdata[0]!=undefined&&echartdata[0]!=null){
                project1 = echartdata[0];
              }
              if(echartdata[1]!=undefined&&echartdata[1]!=null){
                project2 = echartdata[1];
              }
              if(echartdata[2]!=undefined&&echartdata[2]!=null){
                project3 = echartdata[2];
              }
            }
          }
          //显著性分析
          this.topEcharts(nameArr,dataArr);
          this.midLeftEchart1("m_l",project1.value, "red",project1.echart);
          this.midLeftEchart2("m_m",project2.value, "purple",project2.echart);
          this.midLeftEchart3("m_r",project3.value, "green",project3.echart);
          
      });
    },
    topEcharts(nameArr,dataArr) {
      if (this.myChartOne !== null && this.myChartOne !== '' && this.myChartOne !== undefined) {
          this.myChartOne.dispose();
          this.myChartOne = null
      }
      this.myChartOne = echarts.init(document.getElementById("topechart"));
      var option = {
        title: {
          text: "显著性排行",
          subtext: "",
          textStyle: {
            fontSize: 18,
          },
          subtextStyle: {
            fontSize: 14,
          },
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "5%",
          containLabel: true,
        },
        xAxis: {
          type: "value",
          boundaryGap: [0, 0.01],
        },
        yAxis: {
          type: "category",
          data: nameArr,
        },
        series: [
          {
            name: "",
            type: "bar",
            data: dataArr,
            itemStyle: {
              normal: {
                color: function (params) {
                  // 给出颜色组
                  var colorList = [
                    "#01B13A",
                    "#4CD624",
                    "#A8DF15",
                    "#F2D418",
                    "#FFB539",
                    "#FF9C32",
                    "#FF5E31",
                    "#F05621",
                    "#DF2F1F",
                    "#F06292",
                    "#01CDD1",
                    "#A9DBFF",
                    "#1AA0FF",
                    "#7986CB",
                  ];
                  return colorList[params.dataIndex];
                },
              },
            },
            // 柱状图宽度
            barMaxWidth: "70",
          },
        ],
      };
      this.myChartOne.setOption(option);
      
    },
    midLeftEchart1(id, name, color,dataArr) {
      if (this.myChartTwo1== null && this.myChartTwo1 !== '' && this.myChartTwo1 !== undefined) {
          this.myChartTwo1.dispose()
      }
      this.myChartTwo1 = echarts.init(document.getElementById(id));
      var option = {
        color: [color],
        title: {
          text: name,
          subtext: "",
          textStyle: {
            fontSize: 18,
          },
          subtextStyle: {
            fontSize: 14,
          },
        },
        xAxis: {
          scale: true,
        },
        yAxis: {
          scale: true,
        },
        series: [
          {
            type: "scatter",
            data: dataArr,
          },
        ],
      };
      this.myChartTwo1.setOption(option);
    },
    midLeftEchart2(id, name, color,dataArr) {
      if (this.myChartTwo2== null && this.myChartTwo2 !== '' && this.myChartTwo2 !== undefined) {
          this.myChartTwo2.dispose()
      }
      this.myChartTwo2 = echarts.init(document.getElementById(id));
      var option = {
        color: [color],
        title: {
          text: name,
          subtext: "",
          textStyle: {
            fontSize: 18,
          },
          subtextStyle: {
            fontSize: 14,
          },
        },
        xAxis: {
          scale: true,
        },
        yAxis: {
          scale: true,
        },
        series: [
          {
            type: "scatter",
            data: dataArr,
          },
        ],
      };
      this.myChartTwo2.setOption(option);
    },
    midLeftEchart3(id, name, color,dataArr) {
      if (this.myChartTwo3== null && this.myChartTwo3 !== '' && this.myChartTwo3 !== undefined) {
          this.myChartTwo3.dispose()
      }
      this.myChartTwo3 = echarts.init(document.getElementById(id));
      var option = {
        color: [color],
        title: {
          text: name,
          subtext: "",
          textStyle: {
            fontSize: 18,
          },
          subtextStyle: {
            fontSize: 14,
          },
        },
        xAxis: {
          scale: true,
        },
        yAxis: {
          scale: true,
        },
        series: [
          {
            type: "scatter",
            data: dataArr,
          },
        ],
      };
      this.myChartTwo3.setOption(option);
    },
    // removeItem() {
    //   // 去除
    // },
    handleSelectRow(value) {
      this.itemselection = value;
    },
    checkTabs(name){
      this.tabvalue = name;
    },
    lastAnalysis() {
      // 二次分析
      this.itemids = []
      if(this.itemselection!=null&&this.itemselection!=undefined &&this.itemselection.length > 0){
        this.itemselection.forEach((item,key)=>{
          this.itemids.push(item.itemId);
        })
        this.tabvalue = "2";
        this.getEchartList()
      }
      else
      {
        this.$$Message.error('请选择检验数据');
        return false;
      }
    },
  },
  beforeDestroy(){
    // this.myChartOne.clear();
  },
};
</script>
<style lang="less" scoped>
.tablechild {
  width: 282px;
  width: 282px;
  // display: inline-block;
  margin-right: 10px;
  margin-bottom: 5px;
  float: left;
}
.otherSelect {
  margin-top: 10px;
  min-height: 100px;
}
.top_echart {
  width: 100%;
  height: 400px;
  margin: 10px 0px;
  padding: 5px;
  border: 1px solid #ddd;
  border-radius: 6px;
}
.mid_echart {
  width: 33%;
  height: 400px;
  display: inline-block;
}
.detailinfo {
  width: 33%;
}
</style>
