<template>
  <div class="eleStyle">
    <el-container class="header_sty">
      <el-header class="public_header">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="测试日报" name="first" />
          <el-tab-pane label="准出报告" name="second" />
          <el-tab-pane label="提测报告" name="third" />
        </el-tabs>
      </el-header>

      <el-main class="public_main report-Layout">
        <div class="Layout_space_between distance">
          <div class="Layout_space_between">
            <span style="width: 100px;">{{ title }}</span>
            <el-input v-if="history" v-model="state" size="medium" filterable placeholder="报告名称搜索" style="width:100%;" @change="getList(state)" />
            <el-input v-if="!history" v-model="state" size="medium" filterable placeholder="报告名称搜索" style="width:100%;" @change="gethistoryData(state)" />
          </div>
          <div class="Layout_space_between">
            <el-button v-if="!history" type="primary" size="medium" @click="returnNewest">返回最新</el-button>
            <el-button v-if="history" type="text" @click="gethistoryData">查看老数据</el-button>
            <el-button v-if="history" type="primary" size="medium" @click="getQueryData">新建{{ title }}</el-button>
          </div>
        </div>
        <el-table v-loading="loading" :data="tableData" size="medium" :header-cell-style="{ background: '#F2F3F6', color: '#333' }" border style="width: 100%" :show-overflow-tooltip="true">
          <el-table-column label="报告名称" min-width="280" show-overflow-tooltip>
            <template slot-scope="scope">
              <a v-if="title === '测试日报' || title === '准出报告'" href="javascript:void(0)" style="color:#20a0ff" @click="history ? toReportView(scope.row) : OldDaily(scope.row)">{{ scope.row.reportName }}</a>
              <div v-if="title === '准出报告' && scope.row.passStatus === 1" class="passStatus1">不通过</div>
              <a v-if="title === '提测报告'" href="javascript:void(0)" style="color:#20a0ff" @click="history ? toReportView(scope.row) : OldDaily(scope.row)">{{ history ? scope.row.reportName : scope.row.name }}</a>
              <div v-if="title === '提测报告' && scope.row.returnReason" style="color: red;" class="breakText1">打回报告：{{ scope.row.returnReason }}</div>
            </template>
          </el-table-column>
          <el-table-column label="状态" min-width="150">
            <template slot-scope="scope">{{ scope.row.statusString }}</template>
          </el-table-column>
          <el-table-column label="报告人" min-width="180">
            <template slot-scope="scope">
              <div v-if="history">
                <div v-if="title === '测试日报' || title === '准出报告'">{{ scope.row.reportorObject.name ===null ? '' : scope.row.reportorObject.name }}</div>
                <div v-if="title === '提测报告'">{{ scope.row.reportorObject.name }}</div>
              </div>
              <div v-if="!history">
                <div v-if="title === '测试日报' || title === '准出报告'">{{ scope.row.ownner }}</div>
                <div v-if="title === '提测报告'">{{ scope.row.submitter }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" min-width="280">
            <template slot-scope="scope">{{ scope.row.gmtCreate }}</template>
          </el-table-column>
          <el-table-column v-if="history" label="操作" align="center" fixed="right" min-width="230">
            <template slot-scope="scope">
              <div v-if="title === '测试日报'">
                <span v-if="scope.row.status === 0 ? true : false" class="didi-hover" @click="dailyButtom(3,scope.row)">发送</span>
                <span v-if="scope.row.status === 0 ? true : false" style="margin: 0 30px;" class="didi-hover" @click="dailyButtom(2,scope.row)">编辑</span>
                <span v-if="scope.row.status === 0 ? true : false" class="didi-hover" @click="report_click(4,scope.row )">删除</span>
                <span v-if="scope.row.status === 3 ? true : false" class="didi-hover" @click="dailyButtom(4,scope.row)">复制</span>
              </div>
              <div v-if="title === '准出报告'">
                <div v-if="scope.row.status === 3 ? false : true">
                  <span v-if="scope.row.status === 0 ? true : false" class="didi-hover" @click="clientButtom(3,scope.row)">发送</span>
                  <span v-if="scope.row.status === 0 ? true : false" style="margin: 0 30px;" class="didi-hover" @click="clientButtom(2, scope.row)">编辑</span>
                  <span v-if="scope.row.status === 0 ? true : false" class="didi-hover" @click="report_click(4,scope.row )">删除</span>
                </div>
              </div>
              <div v-if="title === '提测报告'">
                <div v-if="scope.row.status === 1 ? false : true">
                  <span v-if="scope.row.status === 3 ? true : false" class="didi-hover" @click="report_click(1,scope.row)">通过</span>
                  <span v-if="scope.row.status === 3 ? true : false" style="margin-left: 30px;" class="didi-hover" @click="report_click(2,scope.row)">打回</span>
                  <span v-if="scope.row.status === 0 ? true : false" class="didi-hover" @click="report_click(5,scope.row)">发送</span>
                  <span v-if="scope.row.status === 0 ? true : false" style="margin: 0 30px;" class="didi-hover" @click="report_click(6,scope.row)">编辑</span>
                  <span v-if="scope.row.status === 0 ? true : false" class="didi-hover" @click="report_click(4,scope.row )">删除</span>
                  <span v-if="scope.row.status === 2 ? true : false" class="didi-hover" @click="report_click(3,scope.row)">重新提测</span>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
      <el-footer class="public_footer">
        <el-pagination v-if="history" style="margin-top:30px;" align="center" :current-page="curIndex" :page-sizes="[5, 10, 20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        <el-pagination v-if="!history" style="margin-top:30px;" align="center" :current-page="curIndex" :page-sizes="[5, 10, 20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange1" @current-change="handleCurrentChange1" />
      </el-footer>
    </el-container>
    <!-- 日报/准出/提测选择任务 -->
    <el-dialog title="选择任务" :visible.sync="centerDialogVisible" width="30%" center>
      <div class="Layout_space_between">
        <div style="width:100px;">选择任务 :</div>
        <el-select
          v-model="queryData.code"
          filterable
          :remote="true"
          :remote-method="debounceQuery"
          placeholder="请选择任务"
          size="mini"
          style="width:100%;"
        >
          <el-option v-for="item in restaurants" :key="item.id" :label="item.name" :value="item.id">
            <div class="belong-task">
              <div class="task-id">{{ item.taskId }}</div>
              <div class="modules-name">
                <span class="name">{{ item.name }}</span>
                <span v-if="item.moduleInfoName" class="modules">{{ item.moduleInfoName }}</span>
              </div>
            </div>
          </el-option>
        </el-select>
      </div>
      <div class="tips-report">
        <i class="el-icon-warning-outline" /> 创建日报或准出报告，任务的状态必须是【测试中】！<br>
        <i class="el-icon-warning-outline" /> 创建提测报告，任务的状态必须是【开发中】！
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="createPresentation(queryData.code)">创建</el-button>
      </span>
    </el-dialog>

    <el-dialog :title="report_from.titName" :visible.sync="dialog_testData" width="30%" :close-on-click-modal="false">
      <div style="position: absolute; top: 23px; left: 12px;width:4px;height:17px;background:#409EFF;border-radius:1px;" />
      <div align="center">
        <div v-if="title === '提测报告'">是否{{ report_from.statusString }}以下提测?</div>
        <div v-if="title === '测试日报'">是否{{ report_from.statusString }}以下测试日报?</div>
        <div v-if="title === '准出报告'">是否{{ report_from.statusString }}以下准出报告?</div>
        <div style="color: #f79232;">{{ report_from.name }}</div>
      </div>
      <el-input v-show="report_from.statusString === '打回'" v-model="report_from.reason" type="textarea" placeholder="请输入打回原因..." :rows="3" />
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="passOrBackSend()">确 定</el-button>
        <el-button type="danger" size="mini" @click="endDialog">取 消</el-button>
      </span>
    </el-dialog>

    <TestingReport v-if="dialogVisible1" ref="TestReport" @getList="getList" />
    <DailyReport v-if="dialogDaily" ref="DailyReport" @getList="getList" />
    <ReleaseReport v-if="dialogClient" ref="ClientReport" @getList="getList" />

    <el-dialog :title="title" :visible.sync="reportDaily" class="public_task" width="70%" :close-on-click-modal="false">
      <div class="blueStripe" />
      <div v-if="title === '测试日报'" style=" margin-bottom: 2%; height: 600px; overflow:scroll; overflow-x: hidden">
        <testPresenyL v-if="testPresenyL" :message="message" />
      </div>
      <div v-if="title === '准出报告'" style=" margin-bottom: 2%; height: 600px; overflow:scroll; overflow-x: hidden">
        <ResultPageyL v-if="ResultPageyL" :message="message" />
      </div>
      <div v-if="title === '提测报告'" style=" margin-bottom: 2%; height: 600px; overflow:scroll; overflow-x: hidden">
        <acceptTheReport v-if="acceptTheReport" :message="message" />
      </div>
    </el-dialog>
    <checkListStopConfirm
      :visible="checklistStopVisible"
      @confirm="checklistConfirm"
      @cancel="checklistCancel"
    />
  </div>
</template>

<script>
const _ = require('lodash')
import { EncryptId } from '@/utils/crypto-js.js'
import { mapGetters } from 'vuex'
import '@/styles/PublicStyle/index.scss'
import checkListStopConfirm from '@/components/checkListStopConfirm'
import { dailyReportDelete } from '@/api/testPresentetion' // 日报
import { projectTestReportList } from '@/api/ResultPage' // 准出
import { launchTestList } from '@/api/InterfaceReport' // 提测
import { taskListCreate } from '@/api/defectManage'
import TestingReport from '@/views/reportManagement/components/TestingReport' // 提测
import DailyReport from '@/views/reportManagement/components/DailyReport' // 日报
import ReleaseReport from '@/views/reportManagement/components/ReleaseReport' // 准出
import { dailyReportList, dailyReportListV2, reportreleaseList, reportdelivertestList, reportreleaseDelete, reportdelivertestDelete, reportdelivertestUpdate, dailyReportCheckStatus, reportreleaseCheckStatus, reportdelivertestCheckStatus, reportdelivertestGetReportById } from '@/api/reportTemplate'
import testPresenyL from '@/views/reportManagement/daily/components/testPresenyL.vue' // 老日报数据
import ResultPageyL from '@/views/reportManagement/ReleaseReport/components/ResultPageyL.vue' // 老准出报告
import acceptTheReport from '@/views/reportManagement/Testing/components/acceptTheReport.vue' // 老提测报告

export default {
  name: 'TestPresentation',
  components: {
    TestingReport,
    DailyReport,
    ReleaseReport,
    testPresenyL,
    ResultPageyL,
    acceptTheReport,
    checkListStopConfirm
  },
  data() {
    return {
      activeName: 'first',
      title: '测试日报', // 报告title
      history: true, // 新老数据
      userInformation: localStorage.getItem('username'),
      userNames: localStorage.getItem('realname'),
      message: {}, // 老日报数据
      reportDaily: false,
      testPresenyL: false, // 老日报数据
      ResultPageyL: false, // 老准出报告
      acceptTheReport: false, // 老提测报告
      centerDialogVisible: false, // 新建报告选择任务
      dialog_testData: false, // 操作弹窗
      report_data: {}, // 当前点击数据
      userData: { id: '', ename: this.userInformation, name: this.userNames },
      loading: true,
      pageSize: 10,
      curIndex: 1,
      total: 0,
      state: '',
      restaurants: [],
      queryData: {}, // 选择的任务code为id
      report_from: {
        name: '',
        titName: '',
        statusString: ''
      },
      tableData: [],
      restaurants2: [],
      dialogVisible1: false, // 提测弹窗
      dialogDaily: false,
      dialogClient: false,
      indexPage: {
        pageSize: 10,
        curIndex: 1
      },
      goDataReport: -1,
      checklistStopVisible: false, // checklist拦截弹窗是否显示
      firstChecklistTaskId: -1
    }
  },
  computed: {
    ...mapGetters(['bizId'])
  },
  watch: {
    bizId: {
      handler(newV) {
        if (newV === -1) return
        this.getList()
      },
      immediate: true
    }
  },
  created() {
    this.$store.state.data.status = true
  },
  destroyed() {
    this.$store.state.data.status = false
  },
  methods: {
    logHandle(d) {
      window.log({ c: 'report', d })
    },
    handleClick(tab, event) {
      this.curIndex = 1
      this.loading = true
      switch (Number(tab.index)) {
        case 0:
          this.title = '测试日报'
          this.history ? this.getList() : this.gethistoryData()
          break
        case 1:
          this.title = '准出报告'
          this.history ? this.getList() : this.gethistoryData()
          break
        case 2:
          this.title = '提测报告'
          this.history ? this.getList() : this.gethistoryData()
          break
      }
    },

    async getList(e) { // 报告list
      this.loading = true
      this.history = true
      const indexPage = { bizId: this.bizId, pageSize: this.pageSize, curIndex: this.curIndex }
      e ? indexPage.reportName = this.state : ''
      if (this.title === '测试日报') {
        const res = await dailyReportListV2(indexPage)
        if (res.code === 200) {
          this.tableData = res.data
          this.total = res.total
          this.logHandle('get_report_daily')
        }
      }
      if (this.title === '准出报告') {
        const res = await reportreleaseList(indexPage)
        if (res.code === 200) {
          this.tableData = res.data.list || []
          this.total = res.data.total
          this.logHandle('get_report_release')
        }
      }
      if (this.title === '提测报告') {
        const data = { bizId: this.bizId, pageSize: this.pageSize, curIndex: this.curIndex }
        e ? data.reportName = this.state : ''
        const res = await reportdelivertestList(data)
        if (res.code === 200) {
          this.tableData = res.data.list || []
          this.total = res.data.total
          this.logHandle('get_report_deliver')
        }
      }
      this.loading = false
    },

    returnNewest() { // 返回最新
      this.pageSize = 10
      this.curIndex = 1
      this.state = ''
      this.getList()
    },

    async passOrBackSend() { // 提测打回
      this.dialog_testData = false

      if (this.report_from.statusString === '通过' || this.report_from.statusString === '打回') {
        const data = {
          id: this.report_data.id,
          moduleId: this.report_data.moduleId,
          bizId: this.report_data.bizId,
          taskIds: this.report_data.taskIds,
          reportName: this.report_data.reportName,
          returnReason: this.report_from.reason,
          status: this.report_from.statusString === '打回' ? 2 : this.report_from.statusString === '通过' ? 1 : ''
        }
        const res = await reportdelivertestUpdate(data)
        if (res.code === 200) {
          this.getList()
          this.$message({ message: res.msg, type: 'success', offset: 150 })
        }
      } else if (this.report_from.statusString === '删除') {
        switch (this.title) {
          case '测试日报':
            dailyReportDelete(this.userData, this.report_data.id).then(res => {
              if (res.code === 200) {
                this.$message({ type: 'success', message: '删除成功' })
                this.getList()
              }
            })
            break
          case '准出报告':
            reportreleaseDelete(this.userData, this.report_data.id).then(res => {
              if (res.code === 200) {
                this.$message({ type: 'success', message: '删除成功' })
                this.getList()
              }
            })
            break
          case '提测报告':
            reportdelivertestDelete({}, this.report_data.id).then(res => {
              if (res.code === 200) {
                this.$message({ type: 'success', message: '删除成功' })
                this.getList()
              }
            })
            break
        }
      }
    },

    dailyButtom(e, data) { // 测试报告
      this.report_data = data
      this.dialogDaily = true
      this.$nextTick(() => {
        this.$refs.DailyReport.init(e, data)
      })
    },

    clientButtom(e, data) { // 准出报告
      this.report_data = data
      this.dialogClient = true
      this.$nextTick(() => {
        this.$refs.ClientReport.init(e, data)
      })
    },

    async report_click(e, data) { // 提测报告
      this.report_from.name = data.name || data.reportName
      this.report_data = data
      switch (e) {
        case 1:
          this.dialog_testData = true
          this.report_from.titName = '提测确认'
          this.report_from.statusString = '通过'
          break
        case 2:
          this.dialog_testData = true
          this.report_from.titName = '提测确认'
          this.report_from.statusString = '打回'
          break
        case 3:
          reportdelivertestGetReportById(data.id).then(res => {
            if (res.code === 200) {
              const data = res.data
              reportdelivertestCheckStatus(data.taskIds).then(response => {
                if (response.code === 200) {
                  if (response.data) {
                    this.checklistStopVisible = true
                    this.firstChecklistTaskId = response.data
                    this.goDataReport = data
                    return
                  }
                  this.dialogVisible1 = true
                  this.$nextTick(() => {
                    this.$refs.TestReport.init(4, data)
                  })
                }
              })
            }
          })
          break
        case 4:
          this.dialog_testData = true
          this.report_from.titName = '删除确认'
          this.report_from.statusString = '删除'
          break
        case 5:
          this.dialogVisible1 = true
          this.$nextTick(() => {
            this.$refs.TestReport.init(3, data)
          })
          break
        case 6:
          this.dialogVisible1 = true
          this.$nextTick(() => {
            this.$refs.TestReport.init(2, data)
          })
          break
      }
    },
    // 获取任务数据
    async getQueryData() { // 获取任务数据
      this.centerDialogVisible = true
      this.$set(this.queryData, 'code', '')
      this.getTaskList()
    },
    // 远程搜索任务
    async getTaskList(val) {
      const params = {
        bizId: this.bizId
      }
      if (val) { params.name = val }
      const res = await taskListCreate(params)
      if (res.code === 200) {
        this.restaurants = res.data || []
      }
    },
    debounceQuery: _.debounce(function() {
      this.getTaskList(...arguments)
    }, 500),
    async createPresentation(vel) {
      if (vel !== '') {
        if (this.title === '测试日报') {
          const res = await dailyReportCheckStatus([vel])
          if (res.code === 200) {
            this.centerDialogVisible = false
            this.dialogDaily = true
            this.$nextTick(() => {
              this.$refs.DailyReport.init(7, [vel])
            })
          } else {
            this.centerDialogVisible = true
          }
        }
        if (this.title === '准出报告') {
          const res = await reportreleaseCheckStatus([vel])
          if (res.code === 200) {
            this.centerDialogVisible = false
            this.dialogClient = true
            this.$nextTick(() => {
              this.$refs.ClientReport.init(7, [vel])
            })
          } else {
            this.centerDialogVisible = true
          }
        }
        if (this.title === '提测报告') {
          const res = await reportdelivertestCheckStatus([vel])
          if (res.code === 200) {
            this.centerDialogVisible = false
            if (res.data) {
              this.checklistStopVisible = true
              this.firstChecklistTaskId = res.data
              this.goDataReport = vel
              return
            }
            this.dialogVisible1 = true
            this.$nextTick(() => {
              this.$refs.TestReport.init(7, [vel])
            })
          } else {
            this.centerDialogVisible = true
          }
        }
      } else {
        this.$message({ message: '提示，请选择要添加的任务ID', type: 'warning' })
      }
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },

    // 日报/准出/提测
    toReportView(ele) {
      const bizId_id = EncryptId(`${this.bizId}_${ele.id}`)
      switch (this.title) {
        case '测试日报':
          this.$router.push({ name: '日报详情', query: { bizId_id: bizId_id }})
          break
        case '准出报告':
          this.$router.push({ name: '准出详情', query: { bizId_id: bizId_id }})
          break
        case '提测报告':
          this.$router.push({ name: '提测详情', query: { bizId_id: bizId_id }})
          break
      }
    },

    async gethistoryData(e) { // 查看所有老日报列表
      this.loading = true
      this.history = false
      const indexPage = { bizId: this.bizId, pageSize: this.pageSize, curIndex: this.curIndex }
      e ? indexPage.reportName = this.state : ''
      if (this.title === '测试日报') {
        const res = await dailyReportList(indexPage)
        if (res.code === 200) {
          this.tableData = res.data
          this.total = res.total
        }
      }
      if (this.title === '准出报告') {
        const res = await projectTestReportList(indexPage)
        if (res.code === 200) {
          this.tableData = res.data
          this.total = res.total
        }
      }
      if (this.title === '提测报告') {
        const data = { bizId: this.bizId, pageSize: this.pageSize, curIndex: this.curIndex }
        e ? data.name = this.state : ''
        const res = await launchTestList(data)
        if (res.code === 200) {
          this.tableData = res.data
          this.total = res.total
        }
      }
      this.loading = false
    },

    OldDaily(val) {
      this.reportDaily = true
      if (this.title === '测试日报') {
        this.testPresenyL = true
        this.message = val
      }
      if (this.title === '准出报告') {
        this.ResultPageyL = true
        this.message = val
      }
      if (this.title === '提测报告') {
        this.acceptTheReport = true
        this.message = val
      }
    },

    endDialog() { // 结束对话框
      this.dialog_testData = false
      this.$message({ type: 'warning', message: '已取消' })
    },
    handleSizeChange(size) { // 分页
      this.pageSize = size
      this.getList()
    },
    handleCurrentChange(curIndex) { // 分页
      this.curIndex = curIndex
      this.getList()
    },
    handleSizeChange1(size) { // used 分页
      this.pageSize = size
      this.gethistoryData()
    },
    handleCurrentChange1(curIndex) { // used 分页
      this.curIndex = curIndex
      this.gethistoryData()
    },
    checklistConfirm() {
      this.checklistStopVisible = false
      const { bizId = null } = this.$store.state.global || {}
      const bizId_id = EncryptId(`${bizId}_${this.firstChecklistTaskId}`)
      const newTab = this.$router.resolve({ name: '任务详情', query: { bizId_id: bizId_id, page: 6 }})
      window.open(newTab.href, '_blank')
    },
    checklistCancel() {
      this.checklistStopVisible = false
      this.dialogVisible1 = true
      if (this.goDataReport.taskIds) {
        this.$nextTick(() => {
          this.$refs.TestReport.init(4, this.goDataReport)
        })
      } else {
        this.$nextTick(() => {
          this.$refs.TestReport.init(7, [this.goDataReport])
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.breakText1 {
  word-break: break-all;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.eleStyle {
  width: 100%;
  height:100%;
  background:#F2F3F6;
  display: inline-block;
}
.header_sty {
  font-size: 14px;
  background:#ffffff;
  margin: 0 10px 10px;
  border-radius: 4px;
  overflow: hidden;
}
.distance {
  margin-bottom: 20px;
}
.report-Layout {
  min-height: calc(100vh - 164px)
}
.tips-report {
  font-size: 12px;
  color: #E6A23C;
  margin-top: 10px;
}
.belong-task {
  max-width: 500px;
  display: flex;
  .modules-name {
    width: calc(100% - 100px);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .modules {
    color: #999999;
  }
  .task-id {
    color: #999999;
    width: 80px;
    margin-right: 20px;
  }
  .name {
    color: #333333;
    margin-right: 20px;
  }
}
.passStatus1 {
  color:red;
}
</style>
<style lang="stylus">
.el-tabs__nav-wrap::after {
    background-color: #FFF !important;
    }
</style>
