<template>
  <div class="custom-container">
    <el-row :gutter="8" style="height: calc(100vh - 150px)">
      <el-col :span="4">
        <aside class="custom-container__common left-side-container">
          <!-- <section class="left-side-container__title">
            <span v-if="logoUrl" class="logo">
              <img :src="logoUrl" alt="side container logo">
            </span>
            <span class="text-content">
              {{ factoryName }}
            </span>
          </section> -->

          <section class="title-area">
            <span class="title-icon">
              <svg
                width="100%"
                height="100%"
                viewBox="0 0 24 24"
                version="1.1"
                xmlns="http://www.w3.org/2000/svg"
                xmlns:xlink="http://www.w3.org/1999/xlink"
              >
                <title>工厂</title>
                <g id="系统管理" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
                  <g id="质量追溯_设备参数追溯" transform="translate(-376.000000, -152.000000)" fill-rule="nonzero">
                    <g id="工厂" transform="translate(376.000000, 152.000000)">
                      <rect id="矩形" fill="#000000" opacity="0" x="0" y="0" width="24" height="24" />
                      <path
                        id="形状"
                        d="M12.25,6.75 L12.25,10.25 L20.75,10.25 L20.75,21.25 L3.25000001,21.25 L3.25000001,6.75 L12.25,6.75 L12.25,6.75 Z M10.75,8.25 L4.75000001,8.25 L4.75000001,19.75 L19.25,19.75 L19.25,11.75 L10.75,11.75 L10.75,8.25 Z M17.5,16.5 L17.5,18 L16,18 L16,16.5 L17.5,16.5 Z M14,16.5 L14,18 L12.5,18 L12.5,16.5 L14,16.5 Z M17.5,13.5 L17.5,15 L16,15 L16,13.5 L17.5,13.5 Z M14,13.5 L14,15 L12.5,15 L12.5,13.5 L14,13.5 Z M8.99999999,10.256 L8.99999999,11.756 L6.49999999,11.756 L6.49999999,10.256 L8.99999999,10.256 Z M9.4755,2.82499999 C10.4715,2.63649998 11.0695,2.739 12.1845,3.291 L12.581,3.49000001 L12.7945,3.58999999 C13.2545,3.79899998 13.532,3.85899998 13.887,3.82849999 L13.9855,3.81850001 L14.1545,3.79249999 L14.2455,3.77650001 C14.8380746,3.66404309 15.3698683,3.34077505 15.7425,2.8665 L15.8205,2.763 L17.0405,3.636 L16.9485,3.76000001 C16.3504031,4.53742507 15.4872916,5.06774928 14.5235,5.25 C13.5275,5.43799999 12.9285,5.3355 11.814,4.7835 L11.4175,4.58500001 C10.781,4.27450001 10.4765,4.20100001 10.024,4.25599999 L9.9315,4.26850001 L9.7545,4.299 C9.16166181,4.41148918 8.62956287,4.73472685 8.25649999,5.20900001 L8.17849999,5.31199999 L6.95899999,4.43800001 L7.0515,4.31449999 C7.64947141,3.53774907 8.51191259,3.00768671 9.47500001,2.82499999 L9.4755,2.82499999 Z"
                        fill="#0B58FF"
                      />
                    </g>
                  </g>
                </g>
              </svg>
            </span>
            <span class="title-content">合肥新能源工厂</span>
          </section>

          <!-- 导航栏 -->
          <!-- <section class="left-side-container__content">
            <el-tree
              class="custom-tree"
              :icon-class="'el-icon-document-copy'"
              :data="treeData"
              :props="defaultProps"
              @node-click="handleNodeClick"
            />
          </section> -->

          <section class="routes-area" v-if="showList">
            <el-menu @select="handleSelect">
              <!-- 此处假设了只有一个根节点 -->
              <template v-for="(menuItem, index) in treeData">
                <TestMenuItem :level="1" :key="index" :menuItem="menuItem" />
              </template>
            </el-menu>
          </section>
        </aside>
      </el-col>

      <el-col :span="20">
        <div class="custom-container__common right-side-container">
          <head-form :form-config="headFormConfig" @headBtnClick="btnClick" />

          <base-table
            :page="listQuery.current"
            :limit="listQuery.size"
            :table-config="tableProps && tableProps.length ? tableProps : [{ label: '', prop: '' }]"
            :table-data="dataList"
            :is-loading="listLoading"
          >
            <!-- <method-btn slot="handleBtn" :width="trueWidth" :method-list="tableBtn" @clickBtn="handleClick" /> -->
          </base-table>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
// 获取树形数据结构:
import { getEquipmentTree, getWorkOrders, equipParams } from '@/api/quality-manage/retrospect'
import BaseTable from '@/components/BaseTable'
// import Pagination from '@/components/Pagination'
import HeadForm from '@/components/basicData/HeadForm'
import testData from './parameter.test.data.js'
import moment from 'moment'
import writeXlsxFile from 'write-excel-file'
import TestMenuItem from './parameter/components/TestMenuItem.vue'

export default {
  name: 'EquipmentRetrospectParameter',
  components: { BaseTable, HeadForm, TestMenuItem },
  data() {
    return {
      showList: false,
      menuListTrue: [],
      factoryName: 'xxx工厂',
      logoUrl: require('../../../../assets/img/cnbm.png'),
      treeData: null,
      defaultProps: { label: 'label', children: 'children' },
      tableProps: [],
      trueWidth: 200,
      dataList: [],
      productLineList: [],
      total: 0,
      listLoading: false,
      addOrUpdateVisible: false,
      listQuery: {
        current: 1,
        size: 20
      },
      selectedEquipmentId: null,
      headFormConfig: [
        {
          // 输入过滤
          // label: i18n.t('module.packingManage.PackingList.orderNo'),
          // placeholder: this.$t('module.packingManage.PackingList.orderNo'),
          type: 'select',
          label: '工单',
          placeholder: '工单',
          filterable: true,
          param: 'workOrderId',
          selectOptions: []
        },
        {
          type: 'datePicker',
          label: '时间段',
          dateType: 'daterange',
          // valueFormat: 'yyyy-MM-dd hh:mm:ss', // 解决时间早一天问题
          rangeSeparator: '-',
          // startPlaceholder: '开始日期',
          // endPlaceholder: '结束日期',
          startPlaceholder: this.$t('module.orderManage.order.StartTime'),
          endPlaceholder: this.$t('module.orderManage.order.EndTime'),
          param: 'timeSlot'
        },
        {
          type: 'button',
          btnName: 'btn.search',
          name: 'search',
          color: 'primary'
        },
        {
          type: 'button',
          btnName: 'btn.export',
          name: 'export',
          color: 'success'
        }
      ],
      headFormValue: {},
      testData
    }
  },
  created() {
    this.showList = false

    this.init()

    this.fetchList('eq-tree').then(res => {
      if (res.data) {
        const eqTree = res.data[0] // 只会返回一条工厂数据
        this.factoryName = eqTree.name
        this.treeData = this.preHandleList(eqTree)
        this.showList = true
      }
    })

    this.fetchList('work-order').then(res => {
      if (res.data.records) {
        this.headFormConfig[0].selectOptions = res.data.records.map(item => ({ id: item.id, name: item.name }))
      }
    })
  },

  methods: {
    preHandleList(list) {
      let result = []

      list.pdlList.forEach(item => {
        const treeItem = {}
        treeItem.name = item.name
        // 整理产线
        if (item.wsList.length) {
          treeItem.children = []
          item.wsList.forEach(workSection => {
            const wsItem = {}
            wsItem.name = workSection.name
            // 整理设备
            if (workSection.eqList.length) {
              wsItem.children = []
              workSection.eqList.forEach(eq => {
                const eqItem = {}
                eqItem.name = eq.eqName
                eqItem.id = eq.eqId
                wsItem.children.push(eqItem)
              })
            }
            treeItem.children.push(wsItem)
          })
        }

        // 产线
        result.push(treeItem)
      })

      return result
    },
    init() {
      this.productLineList.splice(0)
      this.headFormConfig[0].selectOptions.splice(0)
      this.factoryName = ''
      // 设置静态props
      this.resetTableProps()
    },
    fetchList(type) {
      switch (type) {
        case 'eq-tree':
          return getEquipmentTree()
        case 'work-order':
          return getWorkOrders()
        case 'eq-params': {
          return equipParams({
            ...this.listQuery,
            startTime: this.headFormValue.timeSlot ? this.headFormValue.timeSlot[0] : '',
            endTime: this.headFormValue.timeSlot ? this.headFormValue.timeSlot[1] : '',
            equipmentId: this.selectedEquipmentId,
            workOrderId: this.headFormValue.workOrderId ? this.headFormValue.workOrderId : null
          })
        }
      }
    },
    //
    btnClick(val) {
      this.headFormValue = val
      if (this.headFormValue.btnName === 'search') {
        this.getList('eq-params')
      } else if (this.headFormValue.btnName === 'export') {
        this.exportExcel()
      }
    },
    resetTableProps() {
      this.tableProps.splice(0)
      this.tableProps = [
        {
          prop: 'equipmentName',
          // label: i18n.t('module.packingManage.PackingList.shelfId'),
          label: '设备名称',
          fixed: true
        }
      ]
    },
    getList() {
      // 清除数据
      this.dataList.splice(0)
      // 清除原先的prop并设置静态props
      this.resetTableProps()
      // this.fetchList('eq-params').then(res => {})
      setTimeout(() => {
        // 创建动态列名
        this.createDynamicProps(this.testData)
        // 创建扁平化数据
        this.flattenRes(JSON.parse(JSON.stringify(this.testData)))
        // 加载数据
      }, 3000)
    },
    // dynamic props
    createDynamicProps(res) {
      const names = res.data.nameData
      if (names) {
        // 如果数据结构正确
        names
          .filter(item => item.parentId === '0')
          .map(item => item.name)
          .forEach(name => {
            this.tableProps.push({ label: name, prop: name })
          })

        return
      }
      console.log('createDynamicProps(): 数据结构不正确')
    },
    // 数据扁平化
    flattenRes(res) {
      // 注: parentId+tree+id+name 看情况叠加,一般是不会出现重复的prop,有可能多个设备有不同的参数，到时候可能就要求并集
      const dataList = res.data.data
      if (dataList && dataList.length > 0) {
        // 如果数据结构正确
        dataList.forEach(obj => {
          obj.data.forEach(item => {
            obj[item.dynamicName] =
              item.dynamicName === 'time' ? moment(item.dynamicValue).format('YYYY-MM-DD HH:mm:ss') : item.dynamicValue
          })
          // 原地删除data数组
          delete obj.data
        })

        this.dataList = dataList
      }
    },
    async exportExcel() {
      const data = []
      if (this.dataList.length > 0) {
        const HEADER_ROW = this.tableProps.map(item => ({ value: item.label }))
        // table prop 里的 prop 是不全的，要补充
        HEADER_ROW.unshift({ value: 'plc' })
        HEADER_ROW.unshift({ value: '序号' })
        data.push(HEADER_ROW)

        this.dataList.forEach(obj => {
          const DATA_ROW = []
          for (const key in obj) {
            DATA_ROW.push({ value: obj[key] })
          }
          data.push(DATA_ROW)
        })

        await writeXlsxFile(data, {
          fileName: 'equipment_parameters_list.xlsx'
        })
      } else {
        this.$message({
          message: this.$t('module.basicData.visual.hints.searchFirst'),
          type: 'error',
          duration: 1500
        })
      }
    },
    handleNodeClick(data) {
      if (data.id) {
        this.selectedEquipmentId = data.id
      }
    },
    handleSelect(index, indexPath) {
      const [id, name] = index.split('$--$')
      this.selectedEquipmentId = id
    }
  }
}
</script>

<style lang="scss" scoped>
.custom-container {
  height: calc(100vh - 134px);
  margin: 0 16px 0;
}

.custom-container__common {
  background-color: #fff;
  padding: 0;
  border-radius: 8px;
}

.left-side-container {
  height: calc(100vh - 147px);
  padding: 0;
  // background: #fafafa;
  display: flex;
  flex-direction: column;

  .left-side-container__title {
    display: flex;
    align-items: center;
    padding: 8px;
    border-bottom: 1px solid rgba(204, 204, 204, 0.479);

    .text-content {
      font-size: 18px;
      font-weight: 700;
    }
  }

  .left-side-container__content {
    flex: 1 1;
    overflow-y: auto;
  }
}

.right-side-container {
  height: calc(100vh - 147px);
  padding: 16px;
}

.logo {
  width: 36px;
  height: 36px;
  margin: 0 12px 0;

  img {
    width: 100%;
    height: 100%;
  }
}

.custom-tree >>> .el-tree-node {
  padding: 0;
  background-color: #fff;
}

.custom-tree >>> .el-tree-node__content {
  height: 48px;
}

.custom-tree >>> .is-current {
  border-left: 4px solid #0b58ff;
}

.custom-tree >>> .is-current .el-tree-node__content {
  background: #fafafa;
}

.title-area {
  height: 72px;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 0 24px;
}

.routes-area {
  flex: 1;
  height: 1px;
  background-color: #fff;
  overflow: hidden;
  overflow-y: auto;
}

.title-icon {
  height: 24px;
  width: 24px;
}
</style>
