<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 label="调帐类型">
                <el-select v-model="listQuery.params.accadjTypeKey" placeholder="请选择" clearable class="addinputw">
                  <el-option v-for="item in accadjType_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey"/>
                </el-select>
                <!--  <el-input v-model="listQuery.params.vin" placeholder="请输入车架号" clearable/>-->
              </el-form-item>
              <el-form-item label="调出分公司">
                <el-select v-model="listQuery.params.callOutOrgSid" placeholder="请选择" clearable class="addinputw">
                  <el-option v-for="item in useOrg_list" :key="item.sid" :label="item.name" :value="item.sid"/>
                </el-select>
              </el-form-item>
              <el-form-item label="调入分公司">
                <el-select v-model="listQuery.params.callInOrgSid" placeholder="请选择" clearable class="addinputw">
                  <el-option v-for="item in useOrg_list" :key="item.sid" :label="item.name" :value="item.sid"/>
                </el-select>
              </el-form-item>
              <el-form-item label="申请日期:">
                <el-date-picker v-model="listQuery.params.applyStartDate" class="filter-item" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="请选择"/>
                <label>至</label>
                <el-date-picker v-model="listQuery.params.applyEndDate" class="filter-item" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="请选择"/>
              </el-form-item>
            </el-form>
            <div class="btn" style="text-align: center;">
              <el-button type="primary" icon="el-icon-search" size="small" @click="getList">查询</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="listQuery.total" :page.sync="listQuery.current" :limit.sync="listQuery.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="50px" fixed type="selection" align="center"/>
            <el-table-column width="80px" fixed label="序号" type="index" :index="indexMethod" align="center"/>
            <el-table-column label="操作" fixed align="center" width="180" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" :disabled="scope.row.nodeState == '待提交' ? false: scope.row.nodeState == '调账申请' ? false : true" @click="handleEdit(scope.row)">办理</el-button>
                <el-button type="primary" size="mini" v-if="scope.row.nodeState =='已办结'" @click="toDownload(scope.row)">下载</el-button>
                <el-button size="mini" type="primary" @click="handleCheck(scope.row)">查看</el-button>
              </template>
            </el-table-column>
            <el-table-column width="140px" prop="nodeState" label="状态" align="left" 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)" style="color: #018ad2;cursor: pointer;">{{ scope.row.nodeState }}</span>
              </template>
            </el-table-column>
            <el-table-column width="140px" prop="applyDate" label="申请日期" align="center"/>
            <el-table-column width="120px" prop="accadjTypeValue" label="调账类型" align="center"/>
            <el-table-column prop="callOutOrgName" label="调出分公司" align="center"/>
            <el-table-column prop="callInOrgName" label="调入分公司" align="center"/>
          </el-table>
        </div>
        <!--End 项目列表-->
        <div class="pages">
          <div class="tit"/>
          <!-- 翻页 -->
          <pagination v-show="dataList.length > 0" :total="listQuery.total" :page.sync="listQuery.current" :limit.sync="listQuery.size" class="pagination" @pagination="loadList"/>
        </div>
      </div>
    </div>
    <!--End 查询和其列表部分-->
    <!--新增修改部分组件-->
    <tiaozhangshenqingguanli-add v-show="viewState == 2 || viewState == 3" ref="divadd" @doback="resetState" @reloadlist="getList"/>
    <!-- 详情部分组件 -->
    <tiaozhangshenqingguanli-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%;" :src="this.centerDialogVisible === true ? url :''"></iframe>
    </el-dialog>
  </div>
</template>

<script>
import ButtonBar from '@/components/ButtonBar'
import Pagination from '@/components/pagination'
import pageye from '@/components/pagination/pageye'
import tiaozhangshenqingguanliAdd from '@/views/supplychain/tiaozhangshenqingguanli/tiaozhangshenqingguanliAdd'
import tiaozhangshenqingguanliInfo from '@/views/supplychain/tiaozhangshenqingguanli/tiaozhangshenqingguanliInfo'
import { listPage, delBySids, createPdf } from '@/api/supplychain/tiaozhangshenqing.js'
import { getOrgSidByPath, getListOrg, typeValues, selectHaveMessage } from '@/api/cheliang/dictcommons'
import { getStorage } from '@/utils/auth'

export default {
  name: 'tiaozhangshenqingguanli',
  components: {
    ButtonBar,
    Pagination,
    pageye,
    tiaozhangshenqingguanliAdd,
    tiaozhangshenqingguanliInfo
  },
  data() {
    return {
      url: '',
      dialogHeight: '80%',
      centerDialogVisible: false,
      btndisabled: false,
      viewState: 1, // 1、列表 2、添加 3、修改 4、查看
      isSearchShow: false,
      tableLoading: false,
      dataList: [],
      useOrg_list: [],
      accadjType_list: [],
      listQuery: {
        current: 1,
        size: 10,
        total: 0,
        params: {
          applyStartDate: '',
          applyEndDate: '',
          accadjTypeKey: '',
          callOutOrgSid: '',
          callInOrgSid: '',
          createOrgSid: '',
          userSid: ''
        }
      },
      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: '关闭'
        }
      ],
      multipleSelection: []
    }
  },
  created() {
    this.getPathSid()
    this.getType()
    this.getListOrgAll()
  },
  mounted() {
    // 在外部vue的window上添加postMessage的监听，而且绑定处理函数handleMessage
    window.addEventListener('message', this.handleMessage)
    this.$refs['btnbar'].setButtonList(this.btnList)
  },
  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.procInstId,
        token: getStorage()
      }
      this.url = '/#/flow/flowRecordForBusiness?data=' + encodeURI((JSON.stringify(params)))
    },
    resetState() {
      this.viewState = 1
    },
    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
      }
    },
    toAdd() {
      selectHaveMessage({ menuUrl: this.$route.path, orgPath: window.sessionStorage.getItem('defaultOrgPath') }).then((res) => {
        this.viewState = 2
        this.$refs['divadd'].showAdd()
      })
    },
    doDel() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          showClose: true, type: 'error', message: '请选择至少一条记录进行删除操作'
        })
        return
      }
      const tip = '请确认是否删除所选 ' + this.multipleSelection.length + ' 条记录?'
      this.$confirm(tip, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        // const sids = this.sids.join()
        delBySids(this.sids).then(resp => {
          if (resp.success) {
            loading.close()
            this.$message({ type: 'success', message: resp.msg, showClose: true })
            this.loadList()
          } else {
            loading.close()
          }
        }).catch(e => {
          loading.close()
        })
      }).catch(() => {
      })
    },
    handleEdit(row) {
      this.viewState = 2
      this.$refs['divadd'].showEdit(row)
    },
    toDownload(row) {
      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(() => {})
    },
    handleCheck(row) {
      this.$refs['divinfo'].showInfo(row)
      console.log('详情回显', row)
      this.viewState = 4
    },
    handleSelectionChange(row) {
      this.multipleSelection = row
      const aa = []
      row.forEach((element) => {
        aa.push(element.sid)
      })
      this.sids = aa
      console.log('勾选的数据', this.sids)
    },
    getPathSid() {
      getOrgSidByPath({ orgPath: window.sessionStorage.getItem('defaultOrgPath') }).then((res) => {
        if (res.success) {
          this.listQuery.params.createOrgSid = res.data
          this.getList()
        }
      })
    },
    getList() {
      this.listQuery.current = 1
      this.loadList()
    },
    resetQuery() {
      this.listQuery = {
        current: 1,
        size: 10,
        total: 0,
        params: {
          applyStartDate: '',
          applyEndDate: '',
          accadjTypeKey: '',
          callOutOrgSid: '',
          callInOrgSid: '',
          createOrgSid: '',
          userSid: ''
        }
      }
      this.getPathSid()
    },
    loadList() {
      this.tableLoading = true
      this.listQuery.params.userSid = window.sessionStorage.getItem('userSid')
      listPage(this.listQuery).then((resp) => {
        this.tableLoading = false
        if (resp.success) {
          this.listQuery.total = resp.data.total
          this.dataList = resp.data.records
        } else {
          this.listQuery.total = 0
          this.dataList = []
        }
      }).catch(() => {
        this.tableLoading = false
      })
    },
    getType() {
      typeValues({ type: 'accadjType' }).then((response) => {
        if (response.success) {
          this.accadjType_list = response.data
        }
      })
    },
    getListOrgAll() {
      getListOrg().then((res) => {
        if (res.success) {
          this.useOrg_list = res.data
        }
      })
    },
    // 序号
    indexMethod(index) {
      var pagestart = (this.listQuery.current - 1) * this.listQuery.size
      var pageindex = index + 1 + pagestart
      return pageindex
    },
    doClose() {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.go(-1)
    }
  }
}
</script>

<style scoped>
</style>
