<template>
  <div class="sub-container">
    <!-- <plan-table class_name="class-test" /> -->
    <div class="search-bar">
      <div class="left">
        <div class="search-date item">
          <!-- 建立日期 -->
          <div class="title">建立日期：</div>
          <el-date-picker
            v-model="dateValue"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']"
            value-format="yyyy-MM-dd HH:mm:ss"
            @focus="hiddenToolTip"
          />
        </div>
        <div class="search-protocol item">
          <!-- 协议 -->
          <div class="title">协议：</div>
          <el-select v-model="protocolValue" filterable placeholder="请选择">
            <el-option
              v-for="item in protocolOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </div>
        <div class="search-device-type item">
          <!-- 设备类型 暂时取消-->
          <div class="title">方案名称：</div>

          <el-input
            v-model="searchName"
            placeholder="请输入方案名称"
            clearable
            maxlength="32"
          />

        </div>
      </div>
      <div class="right">
        <div class="reset item">
          <el-button
            icon="el-icon-refresh-left"
            class="light-button"
            @click="searchReset()"
          >重置</el-button>
        </div>
        <div class="search-submit item">
          <el-button
            type="primary"
            icon="el-icon-search"
            class="dark-button"
            @click="planSearch()"
          >查询</el-button>
        </div>
      </div>
    </div>
    <div class="content">
      <div class="content-title">
        <div class="left">
          <div class="clear item">
            <el-button
              :ref="`btn_case_batch_delete`"
              data-controlcode="btn_case_batch_delete"
              :class="{'dark-button':showDel}"
              icon="el-icon-delete"
              :disabled="!showDel"
              @click="multDelete()"
            >批量删除</el-button>
          </div>
        </div>
        <div class="right">
          <div class="creat-plan">
            <el-button
              ref="btn_case_new"
              data-controlcode="btn_case_new"
              icon="el-icon-plus"
              class="light-button"
              @click="routerGoto('/plan/save')"
            >新建方案</el-button>
          </div>
          <div ref="btn_exp_case" data-controlcode="btn_exp_case" class="export-plan">
            <a download="方案列表.xls" target="_blank" :href="`${APP_BASE_API}/test/suite/suite.xls`">
              <el-button
                icon="el-icon-upload"
                class="light-button"
              >列表导出</el-button>
            </a>
          </div>
        </div>
      </div>
      <div class="table-container">
        <el-table :data="tableData" :height="tableHeight" stripe @selection-change="handleSelectionChange">
          <!-- 隐藏 列 这里不用显示，但是在编辑的时候需要获取此数据 -->
          <el-table-column v-if="false" prop="planId" label="序号" />
          <!-- 隐藏 列 -->
          <el-table-column
            type="selection"
          />
          <el-table-column prop="planName" label="方案名称" />
          <el-table-column prop="deviceType" label="检测协议" />
          <el-table-column prop="checkModel" label="测点模型">
            <template slot-scope="scope">
              <el-link type="primary" @click="toSee(scope.row)">查看</el-link>
            </template>
          </el-table-column>
          <el-table-column prop="creatDate" label="创建日期" />
          <el-table-column fixed="right" label="操作" width="160">
            <template slot-scope="scope">
              <!--
                按状态显示
                未运行
                  编辑
                  删除
                已运行
                  详情
                  导出
                -->
              <!-- planId > 0 时显示 -->
              <span
                v-if="scope.row.planId > 0"
                :ref="`btn_case_edit_${scope.$index}`"
                data-controlcode="btn_case_edit"
                class="table-act"
                type="text"
                icon="el-icon-edit"
                size="small"
                style="cursor: pointer;"
                @click="editClick(scope.row)"
              ><i class="el-icon-edit" /> 编辑</span>
              <span
                v-if="scope.row.planId > 0"
                :ref="`btn_case_delete_${scope.$index}`"
                data-controlcode="btn_case_delete"
                class="table-act"
                type="text"
                icon="el-icon-delete"
                size="small"
                style="cursor: pointer;"
                @click="delClick(scope.row, scope.$index)"
              ><i class="el-icon-delete" /> 删除</span>
              <!-- planId = 0 时显示 -->
              <div v-if="scope.row.planId == 0">加载中...</div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <div class="page-bar">
        <pagination
          background
          layout="pager"
          :limit="pageLimit"
          :total="paginationTotalElements"
          :current-page.sync="paginationNumber"
          :page="paginationNumber"
          @pagination="planSearch"
        />
      </div>

      <!-- 查看模型点弹出框 -->
      <el-dialog title="模型点表" :visible.sync="showCheckModel">
        <el-table :data="checkModelData" :height="modaltableHeight" stripe>
          <el-table-column property="id" label="序号" />
          <el-table-column property="name" label="测点名称" />
          <el-table-column property="groupingName" label="设备名称" />
          <el-table-column property="range" label="测点类型" />
          <el-table-column property="offset" label="点号" />
        </el-table>
        <!-- 分页 -->
        <div class="page-bar">
          <pagination
            background
            layout="pager"
            :limit="dialogPageLimit"
            :total="dialogPaginationTotalElements"
            :current-page.sync="dialogPaginationNumber"
            :page="dialogPaginationNumber"
            @pagination="getdialogPoint"
          />
        </div></el-dialog>
      <!-- 底部按钮 -->
      <!-- <div class="bottom-button">
        <div class="cancel-plan">
          <el-button class="light-button">取消</el-button>
        </div>
        <div class="save-plan">
          <el-button class="dark-button">保存</el-button>
        </div>
      </div> -->
    </div>
  </div>
</template>

<script>
import { dictOptions } from '@/api/dict'
import { searchPlanData, planCheckPoint } from '@/api/plan'
import { delRecord, getOptions, httpGet } from '@/api/common-action'
import Pagination from '@/components/Pagination'
export default {
  name: 'PlanList',
  components: { Pagination },
  data() {
    return {
      // 提示框默认数据
      dateToolTip: {
        dateToolTipShow: false,
        dateToolTipContent: '加载中'
      },
      // 表格默认数据
      tableData: [
        {
          planId: 0,
          planName: '加载中...',
          deviceType: '加载中...',
          checkModel: '加载中...',
          protocol: '加载中...',
          creatDate: '加载中...'
        }
      ],
      APP_BASE_API: window.STATIC_CONFIG.proxyUrl,
      // 固定表头的表格高度
      tableHeight: 0,
      // 每页显示多少条
      pageLimit: 20,
      dialogPageLimit: 20,
      // 当前第几页
      paginationNumber: 1,
      dialogPaginationNumber: 1,
      // 一共多少条
      paginationTotalElements: 0,
      dialogPaginationTotalElements: 0,
      // 一共多少页
      // paginationTotalPages: 1,
      // 建立日期
      dateValue: [],
      // 协议
      protocolOptions: [],
      // 协议默认值
      protocolValue: '',
      deviceTypeValue: '',
      searchName: '',
      /*
        // 设备类型暂时取消
        deviceOptions: [
        {
          value: 'device-id-1',
          label: '设备型号1'
        },
        {
          value: 'device-id-2',
          label: '设备型号2'
        },
        {
          value: 'device-id-3',
          label: '设备型号3'
        },
        {
          value: 'device-id-4',
          label: '设备型号4'
        }
      ], */
      // 控制模型点弹出框显示
      showCheckModel: false,
      // 模型点表数据
      checkModelData: [],
      // 控制批量删除按钮状态
      showDel: false,
      // 多选框选中数据
      multipleSelection: [],
      // 功能码选项
      checkPointFuctionOptions: [],
      // 值类型列表
      valueTypeOptions: [],
      // 模态框固定表头的表格高度
      modaltableHeight: 0,
      // 当前查看测点模型的id
      showModelId: ''
    }
  },
  watch: {
    multipleSelection(nv, ov) {
      if (nv.length === 0) {
        this.showDel = false
      }
    }
  },
  created() {
    // 动态设置表格高度
    const marginBottom = 300
    this.tableHeight = window.innerHeight - marginBottom
    const modalmarginBottom = 400
    this.modaltableHeight = window.innerHeight - modalmarginBottom
  },
  mounted() {
    this.$nextTick(() => {
      // 网页加载完成后执行
      this.initFunctions()
      // 对表格中的操作列做了权限控制（根据权限可能会移除其中的按钮）后，会导致操作列的行高错位（原因是有固定列），需要再调用一次查询方法重绘一下表格才能恢复正常，原理不明，但确实能解决问题
      this.planSearch()
    })
  },
  methods: {

    // 初始化
    async initFunctions() {
      // 获取功能码选项 131
      let res = await getOptions('/dict/131/options')
      this.checkPointFuctionOptions = res
      // 获取值类型列表
      res = await dictOptions('132')
      this.valueTypeOptions = res
      // console.log('获取值类型列表 this.valueTypeOptions=', this.valueTypeOptions)
      // console.log('获取功能码 this.checkPointFuctionOptions=', this.checkPointFuctionOptions)
      // 初始化协议选项
      // 初始化检测状态选项
      this.protocolOptions = [
        {
          id: null,
          name: '全部'
        }
      ]
      // 设置默认选中值
      this.protocolValue = this.protocolOptions[0].id
      this.protocolOptions.push(
        ...JSON.parse(localStorage.getItem('dictDeviceProductType'))
      )
      // console.log('获取字典选项 this.protocolOptions=', this.protocolOptions)
      // this.initProtocolOptions()
      this.planSearch()
    },
    // 查询
    planSearch(pageObj) {
      // 翻页时pageObj对象才会有值，属性分别为page和limit
      if (pageObj == null) {
        pageObj = {
          page: 0,
          limit: this.pageLimit
        }
        this.paginationNumber = 1
      } else {
        this.pageLimit = pageObj.limit
      }
      const searchParams = {
        // 通信协议 productType
        productType: this.protocolValue,
        // 建立日期 this.dateValue： start end
        start: this.dateValue ? this.dateValue[0] : null,
        end: this.dateValue ? this.dateValue[1] : null,
        name: this.searchName,
        // 未知 enable #TODO: 这里这个 enable 还不知道什么意思 先使用默认值 1
        enable: 1
      }

      // console.log('getDictOptions dictData=', dictData)
      searchPlanData(pageObj, searchParams).then((response) => {
        this.paginationTotalElements = response.totalElements * 1 // *1 强制转换为数字型
        this.paginationNumber = response.number * 1 + 1
        this.getTableData(response)
        this.$nextTick(() => {
          this.common.ApplyElementPurviewByRef(this.$refs)
        })
      })
    },

    // 重置查询
    searchReset() {
      // 建立日期
      this.dateValue = []
      this.protocolValue = ''
      this.deviceTypeValue = ''
      this.searchName = ''
      // 重置后，重载一次表格数据
      this.planSearch()
    },
    // 改变页码
    changePage(pageObj) {
      // console.log('pageObj= ', pageObj)
      this.getPlan(pageObj)
    },
    // 隐藏提示条
    hiddenToolTip() {
      // console.log('hiddenToolTip start')
      this.dateToolTip.dateToolTipShow = false
    },
    // 列表导出
    exportPlan() {
      // console.log('列表导出')
      this.$message({
        message: '列表导出 正在准备后端数据',
        type: 'warning',
        offset: window.screen.height / 3
      })
    },
    // 跳转到新建一样的界面，只不过会有默认数据
    editClick(row) {
      // console.log('editClick=', row)
      this.$router.push({
        path: `/plan/save`,
        query: { planId: row.planId, isChange: true }
      })
    },
    // 多选按钮状态改变 handleSelectionChange
    handleSelectionChange(val) {
      // console.log('val= ', val)
      // 选中行存入临时变量中
      this.multipleSelection = val
      // console.log('handleSelectionChange val', val)
      // 批量删除按钮激活
      this.showDel = true
    },
    // 批量删除
    async multDelete() {
      for (let i = 0; i < this.tableData.length; i++) {
        const item = this.tableData[i]
        // 判断当前行数据是否被选中
        if (this.multipleSelection.includes(item)) {
          // 如果选中，则从 开始删除
          // console.log('this.multipleSelection item=', item)
          // 如果 id > 0 则表示 是已经保存在后端的数据了，需要向后端发送删除请求
          const delUrl = `/test/suite/${item.planId}`
          await delRecord(delUrl).then((response) => {
            // console.log('delRecord rs=', response)
            // 后端成功执行后，前端再删除选中行
            this.tableData.splice(i, 1)
            i-- // 因为 `splice` 方法会修改数组长度，所以需要将 `i` 减去 1，避免漏删下一个元素
          }).catch((err) => {
            console.log('delRecord err rs=', err)
          })
        }
      }
    },
    delClick(row, index) {
      // console.log('delClick row=', row)
      this.$confirm(
        '此操作将永久删除该记录, 是否继续?',
        `删除:${row.planName}`,
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          if (row.planId > 0) {
            // /test/suite/:suite
            delRecord(`/test/suite/${row.planId}`)
              .then((response) => {
                // console.log('delRecord rs=', response)
                // 后端成功执行后，前端再删除选中行
                this.tableData.splice(index, 1)
                // console.log('delClick index=', index)
                // console.log('delClick this.tableData=', this.tableData)
                this.$message({
                  message: `${row.planName} 删除成功`,
                  type: 'success',
                  offset: window.screen.height / 3
                })
                this.planSearch()
              })
              .catch((err) => {
                console.log('delRecord err rs=', err)
              })
          } else {
            // 如果是新增的临时行，直接删除选中行
            this.tableData.splice(index, 1)
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
            offset: window.screen.height / 3
          })
        })
    },
    routerGoto(goto_url) {
      this.$router.push({ path: goto_url })
    },
    // 获取测点表格数据
    async getdialogPoint(pageObj) {
      // 翻页时pageObj对象才会有值，属性分别为page和limit
      if (pageObj == null) {
        pageObj = {
          page: 0,
          limit: this.dialogPageLimit
        }
        this.dialogPaginationNumber = 0
      } else {
        this.dialogPageLimit = pageObj.limit
      }
      const getUrl = `/product/model/${this.showModelId}/paging?page=${pageObj.page}&size=${pageObj.limit}`
      httpGet(getUrl).then((response) => {
        this.checkModelData = response.content.map(item => {
          this.checkPointFuctionOptions.forEach(par => {
            if (item.range === par.id) {
              item.range = par.name
            }
          })
          this.valueTypeOptions.forEach(par => {
            if (item.dataType === par.id) {
              item.dataType = par.name
            }
          })
          return item
        })
        this.dialogPaginationTotalElements = parseInt(response.totalElements)
        this.dialogPaginationNumber = response.number * 1 + 1
      })
    },
    // 查看模型点表
    async toSee(row) {
      // console.log('tosee=', row)
      this.showCheckModel = true
      this.showModelId = row.checkModel
      const res = await planCheckPoint(row.checkModel)
      // console.log('tosee res=', res)
      this.checkModelData = res.content.map(item => {
        this.checkPointFuctionOptions.forEach(par => {
          if (item.range === par.id) {
            item.range = par.name
          }
        })
        this.valueTypeOptions.forEach(par => {
          if (item.dataType === par.id) {
            item.dataType = par.name
          }
        })
        return item
      })
      this.dialogPaginationTotalElements = parseInt(res.totalElements)
    },
    // 获取表格数据-公用
    getTableData(tmpTableData) {
      const productTypeArr = JSON.parse(
        localStorage.getItem('dictDeviceProductType')
      )
      // console.log('productType=', productTypeArr)
      this.tableData = []
      tmpTableData.content.forEach((rs_v) => {
        const newTable = {
          planId: rs_v.id,
          planName: rs_v.name,
          deviceType: rs_v.productType,
          checkModel: rs_v.product,
          protocol: rs_v.protocol,
          creatDate: rs_v.createdDate
        }
        productTypeArr.forEach((item) => {
          if (item.id === newTable.deviceType) {
            newTable.deviceType = item.name
          }
        })
        this.tableData.push(newTable)
      })
    }
  }
}
</script>
<!-- // tool-tip 样式不能写在 scoped 中-->
<style lang="scss">
$tool-tip-bg: #db1414;
// tool-tip 样式必须写在最外面,dom结构它就在最外面
// 如果 vue 中的 placement = "left" 那么  border-top-color 应该是 border-left-color
.warnning-tool-tip.el-tooltip__popper[x-placement^="top"] .popper__arrow {
  border-top-color: $tool-tip-bg;
}
.warnning-tool-tip.el-tooltip__popper[x-placement^="top"] .popper__arrow:after {
  border-top-color: $tool-tip-bg;
}
.warnning-tool-tip {
  background: $tool-tip-bg !important;
}
</style>
<style lang="scss" scoped>
.sub-container {
  // border: 1px #CCC solid;
  padding: 5px 10px;
  background-color: #fff;
  position: relative;
  font-size: 18px;
  color: rgb(112, 112, 112);
  height: 100%;
  overflow: hidden;
  // 搜索栏
  .search-bar {
    display: flex;
    border: 1px #ccc solid;
    padding: 20px 0 14px 20px;
    justify-content: left;
    font-size: 16px;
    .left {
      width: 80%;
      display: flex;
      .item {
        padding-right: 20px;
        display: flex;
        align-items: center;
      }
      .search-date {
        .title {
          padding-right: 5px;
        }
      }
       .search-device-type {
        .title {
          width: 120px;
          padding-right: 5px;
        }
      }
    }
    .right {
      width: 20%;
      display: flex;
      justify-content: right;
      .item {
        padding-right: 20px;
      }
    }
  }
  // 表格内容
  .content {
    border: 1px #ccc solid;
    margin-top: 20px;
    height: 100%;
    padding: 10px;
    .content-title {
      display: flex;
      justify-content: right;
      padding: 10px;

      .left,
      .right {
        width: 50%;
        .creat-plan {
          padding-right: 20px;
        }
      }
      .right{
        display: flex;
        justify-content: right;
      }
    }
    .table-container {
      height: 100%;
      .table-act {
        padding-right: 20px;
      }
    }
  }
  // 底部按钮
  .bottom-button {
    display: flex;
    justify-content: center;
    padding-bottom: 20px;
    .cancel-plan {
      padding-right: 20px;
    }
  }
  // 按钮公用样式
  .dark-button {
    background-color: #00706b;
    border: 1px #00706b solid;
    color: #fff;
  }
  .light-button {
    color: #00706b;
    border: 1px #00706b solid;
  }
}
</style>
