<template>
  <div class="app-container">
    <div v-show="viewState === 1">
      <button-bar view-title="采购退库管理" ref="btnbar" :btndisabled="btndisabled" @btnhandle="btnHandle"/>
      <div class="main-content">
        <div class="searchcon">
          <el-button size="small" class="searchbtn" @click="isSearchShow = !isSearchShow">
            {{ isSearchShow ? '隐藏查询条件' : '显示查询条件' }}
          </el-button>
          <div v-show="isSearchShow" class="search">
            <el-form :inline="true" class="tab-header">
              <el-form-item class="formItem" label="申请日期">
                <el-date-picker value-format="yyyy-MM-dd" v-model="queryParams.params.applyDateStart" clearable style="width: 160px;" type="date" placeholder="开始日期"/>
                <span style="padding: 0 8px">至</span>
                <el-date-picker value-format="yyyy-MM-dd" v-model="queryParams.params.applyDateEnd" clearable style="width: 160px;" type="date" placeholder="结束日期"/>
              </el-form-item>
              <el-form-item label="状态">
                <el-input v-model="queryParams.params.nodeState" placeholder="请输入状态" clearable/>
              </el-form-item>
            </el-form>
            <div class="btn" style="text-align: center;">
              <el-button type="primary" icon="el-icon-search" size="small" @click="dosearch">查询</el-button>
              <el-button type="primary" icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
            </div>
          </div>
        </div>
        <!--Start 项目列表头部-->
        <div class="listtop">
          <div class="tit">车辆采购退库列表</div>
          <pageye v-show="dataList.length > 0" :total="queryParams.total" :page.sync="queryParams.current" :limit.sync="queryParams.size" class="pagination" @pagination="loadList"/>
        </div>
        <!--End 项目列表头部-->
        <!--Start 项目列表-->
        <div class="">
          <el-table v-loading="tableLoading" :data="dataList" border style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column width="50" type="selection" align="center"/>
            <el-table-column width="80" label="序号" type="index" :index="indexMethod" align="center"/>
            <el-table-column width="180" label="操作" align="center">
              <template slot-scope="scope">
                <el-button :disabled="scope.row.nodeState =='发起申请' ? false : scope.row.nodeState == '待提交' ? false : true" type="primary" size="mini" @click="tohandle(scope.row)">办理</el-button>
                <el-button type="primary" size="mini" v-if="scope.row.nodeState =='已办结'" @click="toDownload(scope.row)">下载</el-button>
                <el-button type="primary" size="mini" @click="toInfo(scope.row)">查看</el-button>
              </template>
            </el-table-column>
            <el-table-column label="状态" header-align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.nodeState=='待提交'" type="primary" size="mini">待提交</span>
                <span v-else @click="flowRecord(scope.row)" class="bluezi">{{ scope.row.nodeState }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="applicationCode" label="申请编号" align="center"/>
            <el-table-column prop="orgName" label="分公司" align="center"/>
            <el-table-column prop="applicationName" label="申请人" align="center"/>
            <el-table-column prop="createTime" label="申请日期" align="center"/>
            <el-table-column prop="reason" label="退库原因" align="center"/>
            <el-table-column prop="num" label="台数" align="center"/>
          </el-table>
        </div>
        <!--End 项目列表-->
        <div class="pages">
          <!-- 翻页 -->
          <pagination v-show="dataList.length > 0" :total="queryParams.total" :page.sync="queryParams.current" :limit.sync="queryParams.size" class="pagination" @pagination="loadList"/>
        </div>
      </div>
    </div>
    <!--End 查询和其列表部分-->
    <!--新增修改部分组件-->
    <div-add v-show="viewState == 2 || viewState == 3" ref="divadd" @doback="resetState" @reloadlist="loadList"/>
    <!--详情部分组件-->
    <div-info v-show="viewState == 4" ref="divinfo" @doback="resetState"/>
    <el-dialog title="" :visible.sync="centerDialogVisible" width="78%" height="1%" :before-close="closeIt" center>
      <iframe frameborder="0" id="iframe" style="width:100%;" scrolling="no" :src="this.centerDialogVisible === true ? url :''"></iframe>
    </el-dialog>
  </div>
</template>

<script>
import req from '@/api/supplychain/purchasereturntowarehouse'
import ButtonBar from '@/components/ButtonBar'
import Pagination from '@/components/pagination'
import pageye from '@/components/pagination/pageye'
import divAdd from './caigoutuikuAdd'
import divInfo from './caigoutuikuInfo'
import { getStorage } from '@/utils/auth'
import { selectHaveMessage } from '@/api/cheliang/dictcommons'
import {createPdf} from "@/api/supplychain/tiaozhangshenqing";

export default {
  name: 'caigoutuiku',
  components: {
    ButtonBar,
    Pagination,
    pageye,
    divAdd,
    divInfo
  },
  data() {
    return {
      url: '',
      dialogHeight: '80%',
      centerDialogVisible: false,
      btndisabled: false,
      btnList: [
        {
          type: 'primary',
          size: 'small',
          icon: 'plus',
          btnKey: 'toAdd',
          btnLabel: '新增'
        },
        {
          type: 'danger',
          size: 'small',
          icon: 'del',
          btnKey: 'doDel',
          btnLabel: '删除'
        },
        {
          type: 'info',
          size: 'small',
          icon: 'cross',
          btnKey: 'doClose',
          btnLabel: '关闭'
        }
      ],
      viewState: 1, // 1、列表 2、添加 3、修改 4、查看
      isSearchShow: false, // 显示隐藏
      tableLoading: false,
      // 列表数据
      dataList: [],
      // sid数组
      sids: [], // 用于导出的时候保存已选择SID
      sides: '', // 一条数据的sid
      queryParams: {
        current: 1,
        size: 10,
        total: 0,
        params: {
          applyDateStart: '',
          applyDateEnd: '',
          vehicleName: '', // 车型
          userSid: '',
          orgPath: ''
        }
      },
      row: {},
      multipleSelection: []
    }
  },
  mounted() {
    // 在外部vue的window上添加postMessage的监听，而且绑定处理函数handleMessage
    window.addEventListener('message', this.handleMessage)
    this.$refs['btnbar'].setButtonList(this.btnList)
  },
  created() {
    this.loadList()
  },
  methods: {
    async handleMessage(event) {
      var code = ''
      if (event.data.params !== null && event.data.params !== undefined) {
        code = event.data.params.code
      }
      if (code === 1) {
        this.init()
        this.centerDialogVisible = false
      } else if (code === 2) {
        this.dialogHeight = event.data.params.data
        this.setIframeHeight(document.getElementById('iframe'))
      }
    },
    closeIt() {
      this.url = ''
      this.centerDialogVisible = false
    },
    setIframeHeight(iframe) {
      iframe.height = this.dialogHeight
    },
    flowRecord(row) {
      this.centerDialogVisible = true
      var params = {
        deployId: row.procDefId,
        procInsId: row.instanceId,
        token: getStorage()
      }
      this.url = '/#/flow/flowRecordForBusiness?data=' + encodeURI((JSON.stringify(params)))
    },
    btnHandle(btnKey) {
      console.log('XXXXXXXXXXXXXXX' + btnKey)
      switch (btnKey) {
        case 'toAdd':
          this.toAdd()
          break
        case 'doDel':
          this.doDel()
          break
        case 'doClose':
          this.doClose()
          break
        default:
          break
      }
    },
    // 获取数据sid
    handleSelectionChange(row) {
      this.multipleSelection = row
      const aa = []
      row.forEach((element) => {
        aa.push(element.sid)
      })
      this.sids = aa
    },
    toAdd() {
      selectHaveMessage({ menuUrl: this.$route.path, orgPath: window.sessionStorage.getItem('defaultOrgPath') }).then((resp) => {
        if (resp.success) {
          this.viewState = 2
          this.$refs['divadd'].showAdd()
        }
      })
    },
    tohandle(row) {
      this.viewState = 3
      const sid = row.sid
      this.$refs['divadd'].showEdit(sid)
    },
    toDownload(row) {
      req.createPdf({ sid: row.sid, userName: window.sessionStorage.getItem('name') }).then((res) => {
        if (res.success) {
          var xhr = new XMLHttpRequest()
          xhr.open('GET', process.env.VUE_APP_BASE_API + '/base/file/download?filePath=' + res.data + '&outFileName=' + '采购退库申请单', true)
          xhr.setRequestHeader('token', getStorage())
          xhr.responseType = 'blob'
          xhr.onload = function(e) {
            // 如果请求执行成功
            var blob = this.response
            var filename = '采购退库申请单.pdf'
            var a = document.createElement('a')
            // blob.type="application/octet-stream";
            // 创键临时url对象
            var url = URL.createObjectURL(blob)
            a.href = url
            a.download = filename
            a.click()
            // 释放之前创建的URL对象
            window.URL.revokeObjectURL(url)
          }
          // 发送请求
          xhr.send()
        }
      }).catch(() => {})
    },
    toInfo(row) {
      this.viewState = 4
      console.log('这是打开详情接口', row)
      const sid = row.sid
      this.$refs['divinfo'].showInfo(sid, row)
    },
    // 查询
    dosearch() {
      this.queryParams.current = 1
      this.loadList()
    },
    // 重置
    resetQuery() {
      this.queryParams = {
        current: 1,
        size: 10,
        total: 0,
        params: {
          applicationDateStart: '',
          applicationDateEnd: '',
          vehicleName: '', // 车型
          userSid: '',
          orgPath: ''
        }
      }
      this.loadList()
    },
    loadList() {
      this.tableLoading = true
      this.queryParams.params.userSid = window.sessionStorage.getItem('userSid')
      this.queryParams.params.orgPath = window.sessionStorage.getItem('defaultOrgPath')
      req.listPage(this.queryParams).then(resp => {
        console.log('查询列表', resp)
        this.tableLoading = false
        const data = resp.data
        this.queryParams.total = data.total
        this.dataList = data.records
      }).catch(() => {
        this.tableLoading = false
      })
    },
    // 序号
    indexMethod(index) {
      var pagestart = (this.queryParams.current - 1) * this.queryParams.size
      var pageindex = index + 1 + pagestart
      return pageindex
    },
    // 删除
    doDel() {
      if (this.sids.length === 0) {
        this.$message({ showClose: true, type: 'error', message: '请选择至少一条记录进行删除操作' })
        return
      }
      const tip = '请确认是否删除所选 ' + this.multipleSelection.length + ' 条记录?'
      this.$confirm(tip, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        req.delBySids(this.sids).then(resp => {
          if (resp.success) {
            this.$message({ type: 'success', message: resp.msg, showClose: true })
          }
          this.loadList()
        }).catch(e => {
        })
      }).catch(() => {
      })
    },
    // 子组件关闭（返回）
    resetState() {
      this.viewState = 1
    },
    doClose() {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.go(-1)
    }
  }
}
</script>

<style scoped>
</style>
