<template>
  <div class="app-container">
    <!--列表页面-->
    <div v-show="viewState == 1">
      <button-bar view-title="车辆回购管理" ref="btnbar" :btndisabled="btndisabled" @btnhandle="btnHandle"/>
      <!--Start查询列表部分-->
      <div class="main-content">
        <div class="searchcon">
          <el-button size="small" class="searchbtn" @click="clicksearchShow">{{ searchxianshitit }}</el-button>
          <div v-show="isSearchShow" class="search">
            <el-form ref="listQueryform" :inline="true" :model="listQuery" class="tab-header">
              <el-form-item label="分公司">
                <el-input v-model="listQuery.params.useOrgName" placeholder="" clearable/>
              </el-form-item>
              <el-form-item label="申请部门">
                <el-input v-model="listQuery.params.createDept" placeholder="" clearable/>
              </el-form-item>
              <el-form-item label="申请人">
                <el-input v-model="listQuery.params.createByName" placeholder="" clearable/>
              </el-form-item>
              <el-form-item label="申请日期">
                <el-date-picker v-model="listQuery.params.applyStartDate" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type="date" placeholder="选择日期"></el-date-picker>
                <span style="padding: 0 8px">至</span>
                <el-date-picker v-model="listQuery.params.applyEndDate" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type="date" placeholder="选择日期"></el-date-picker>
              </el-form-item>
              <el-form-item label="办结日期">
                <el-date-picker v-model="listQuery.params.closeStartDate" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type="date" placeholder="选择日期"></el-date-picker>
                <span style="padding: 0 8px">至</span>
                <el-date-picker v-model="listQuery.params.closeEndDate" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type="date" placeholder="选择日期"></el-date-picker>
              </el-form-item>
              <el-form-item label="贷款合同编号">
                <el-input v-model="listQuery.params.loanContractNo" placeholder="" clearable/>
              </el-form-item>
              <el-form-item label="车架号">
                <el-input v-model="listQuery.params.vinNo" placeholder="" clearable/>
              </el-form-item>
              <el-form-item label="车牌号">
                <el-input v-model="listQuery.params.vehMark" placeholder="" clearable/>
              </el-form-item>
              <el-form-item label="资方">
                <el-input v-model="listQuery.params.bankName" placeholder="" clearable/>
              </el-form-item>
              <el-form-item label="资方合同编号">
                <el-input v-model="listQuery.params.bankContractNo" placeholder="" clearable/>
              </el-form-item>
              <el-form-item label="客户名称">
                <el-input v-model="listQuery.params.customerName" placeholder="" clearable/>
              </el-form-item>
              <el-form-item label="贷款人">
                <el-input v-model="listQuery.params.loanName" placeholder="" clearable/>
              </el-form-item>
              <el-form-item label="预计结清日期">
                <el-date-picker v-model="listQuery.params.prepareStartDate" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type="date" placeholder="选择日期"></el-date-picker>
                <span style="padding: 0 8px">至</span>
                <el-date-picker v-model="listQuery.params.prepareEndDate" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type="date" placeholder="选择日期"></el-date-picker>
              </el-form-item>
            </el-form>
            <div class="btn" style="text-align: center;">
              <el-button type="primary" icon="el-icon-search" size="small" @click="handleFilter">查询</el-button>
              <el-button type="primary" icon="el-icon-refresh" size="small" @click="handleReset">重置</el-button>
            </div>
          </div>
        </div>
        <!--End查询列表部分-->
        <div class="listtop">
          <div class="tit">垫款结清申请列表</div>
          <pageye v-show="list.length > 0" :total="listQuery.total" :page.sync="listQuery.current" :limit.sync="listQuery.size" class="pagination" @pagination="getList"/>
        </div>
        <!--Start 主页面主要部分 -->
        <div class="">
          <el-table :key="tableKey" v-loading="listLoading" :data="list" :border="true" style="width: 100%;" @selection-change="handleSelectionChange">
            <el-table-column type="selection" align="center" width="50"/>
            <el-table-column label="序号" type="index" width="80" :index="indexMethod" align="center"/>
            <el-table-column label="操作" width="180px" align="center">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="toEdit(scope.row)" :disabled="scope.row.nodeState =='发起申请' ? false : scope.row.nodeState == '待提交' ? false : true">办理</el-button>
                <el-button type="primary" size="mini" :disabled="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="状态" width="150" 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="useOrgName" label="分公司" align="center" width="130" />
            <el-table-column prop="createDept" label="申请部门" align="center" width="130" />
            <el-table-column prop="createByName" label="申请人" align="center" width="100" />
            <el-table-column prop="applyDate" label="申请日期" align="center" width="100" />
            <el-table-column prop="closeDate" label="办结日期" align="center" width="100" />
            <el-table-column prop="loanContractNo" label="贷款合同编号" align="center" width="160" />
            <el-table-column prop="vinNo" label="车架号" align="center" width="120" />
            <el-table-column prop="vehMark" label="车牌号" align="center" width="120" />
            <el-table-column prop="bankName" label="资方" align="center" width="100" />
            <el-table-column prop="bankContractNo" label="资方合同编号" align="center" width="160" />
            <el-table-column prop="customerName" label="客户名称" align="center" width="100" />
            <el-table-column prop="loanName" label="贷款人" align="center" min-width="100" />
            <el-table-column prop="prepareDate" label="预计结清日期" align="center" width="140" />
            <el-table-column prop="amount" label="回购金额" align="center" width="120" />
          </el-table>
        </div>
        <!--End 主页面主要部分-->
        <div class="pages">
          <div class="tit"/>
          <!-- 翻页 -->
          <pagination v-show="list.length > 0" :total="listQuery.total" :page.sync="listQuery.current" :limit.sync="listQuery.size" class="pagination" @pagination="getList"/>
        </div>
        <!--End查询列表部分-->
      </div>
    </div>
    <!--新增及修改 -->
    <buybackAdd v-show="viewState == 2 || viewState == 3" ref="divAdd" @doback="resetState" @reloadlist="getList"/>
    <!--详情-->
    <buybackInfo v-show="viewState == 4" ref="divInfo" @doback="resetState" />
    <!--新增结清申请 -->
    <settleAdd v-show="viewState == 5" ref="divSettle" @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>
    <!-- 选择车辆 -->
    <el-dialog title="未结清车辆列表" :visible.sync="carVisible" width="80%">
      <div>
        <el-form ref="multipleTable" :inline="true" :model="carList" class="vinNoForm" label-width="100px">
          <el-form-item label="客户名称">
            <el-input v-model="carList.params.customer" clearable style="width: 150px;" placeholder=""/>
          </el-form-item>
          <el-form-item label="贷款人">
            <el-input v-model="carList.params.borrowerName" clearable style="width: 150px;" placeholder=""/>
          </el-form-item>
          <el-form-item label="车牌号">
            <el-input v-model="carList.params.vehMark" clearable style="width: 150px;" placeholder=""/>
          </el-form-item>
          <el-form-item label="车架号">
            <el-input v-model="carList.params.vinNo" clearable style="width: 150px;" placeholder=""/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="selectCar">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table :key="carKey" v-loading="carLoading" :data="listByCar" border fit highlight-current-row style="width: 100%;">
        <el-table-column :index="carindexMethod" align="center" label="序号" type="index" width="80"/>
        <el-table-column label="操作" align="center" width="80">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="chooseCar(scope.row)">选择</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="loanContractNo" label="贷款合同编号" align="center" width="160" />
        <el-table-column prop="vinNo" label="车架号" align="center" />
        <el-table-column prop="vehMark" label="车牌号" align="center" />
        <el-table-column prop="bankName" label="资方" align="center" />
        <el-table-column prop="bankContractNo" label="资方合同编号" align="center" width="160" />
        <el-table-column prop="customer" label="客户" align="center" />
        <el-table-column prop="borrowName" label="贷款人" align="center" />
      </el-table>
      <div class="pages">
        <div class="tit"/>
        <!-- 翻页 -->
        <pagination v-show="listByCar.length > 0" :limit.sync="carList.size" :page.sync="carList.current" :total="carList.total" class="pagination" @pagination="getCarList"/>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/pagination'
import pageye from '@/components/pagination/pageye'
import ButtonBar from '@/components/ButtonBar'
import req from '@/api/buyback/buyback'
import { getStorage } from '@/utils/auth'
import buybackAdd from './buybackAdd'
import buybackInfo from './buybackInfo'
import settleAdd from '../settle/settleAdd'

export default {
  name: 'BuyBack',
  components: {
    Pagination,
    pageye,
    ButtonBar,
    buybackAdd,
    buybackInfo,
    settleAdd
  },
  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: 'primary',
          size: 'small',
          icon: '',
          btnKey: 'toSettle',
          btnLabel: '结清申请'
        },
        {
          type: 'info',
          size: 'small',
          icon: 'cross',
          btnKey: 'doClose',
          btnLabel: '关闭'
        }
      ],
      isSearchShow: false,
      searchxianshitit: '显示查询条件',
      viewState: 1, // 1、列表 2、新增 3、编辑 4、查看
      tableKey: 0,
      list: [],
      sids: [], // 用于导出的时候保存已选择的SIDs
      multipleSelection: [],
      FormLoading: false,
      listLoading: false,
      // 翻页
      listQuery: {
        current: 1,
        size: 5,
        total: 0,
        params: {
          createDept: '',
          applyStartDate: '',
          applyEndDate: '',
          useOrgName: '',
          createByName: '',
          closeStartDate: '',
          closeEndDate: '',
          loanContractNo: '',
          vinNo: '',
          vehMark: '',
          bankName: '',
          bankContractNo: '',
          customerName: '',
          loanName: '',
          prepareStartDate: '',
          prepareEndDate: '',
          orgPath: '',
          menuUrl: '',
          userSid: ''
        }
      },
      carVisible: false,
      carKey: 2,
      carList: {
        current: 1,
        size: 5,
        total: 0,
        params: {
          borrowerName: '',
          customer: '',
          orgPath: '',
          vehMark: '',
          vinNo: '',
          type: '1'
        }
      },
      listByCar: [],
      carLoading: false
    }
  },
  created() {
    // 初始化变量
    this.getList()
  },
  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.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)))
    },
    // 搜索条件效果
    clicksearchShow() {
      this.isSearchShow = !this.isSearchShow
      if (this.isSearchShow) {
        this.searchxianshitit = '隐藏查询条件'
      } else {
        this.searchxianshitit = '显示查询条件'
      }
    },
    btnHandle(btnKey) {
      console.log('XXXXXXXXXXXXXXX    ' + btnKey)
      switch (btnKey) {
        case 'toAdd':
          this.toAdd()
          break
        case 'doDel':
          this.doDel()
          break
        case 'toSettle':
          this.toSettle()
          break
        case 'doClose':
          this.doClose()
          break
        default:
          break
      }
    },
    // 信息条数 获取点击时当前的sid
    handleSelectionChange(row) {
      const aa = []
      this.multipleSelection = row
      row.forEach(element => {
        aa.push(element.sid)
      })
      this.sids = aa
    },
    // 表中序号
    indexMethod(index) {
      var pagestart = (this.listQuery.current - 1) * this.listQuery.size
      var pageindex = index + 1 + pagestart
      return pageindex
    },
    // 查询列表信息
    getList() {
      this.listLoading = true
      this.listQuery.params.userSid = window.sessionStorage.getItem('userSid')
      this.listQuery.params.orgPath = window.sessionStorage.getItem('defaultOrgPath')
      this.listQuery.params.menuUrl = this.$route.path
      req.listPage(this.listQuery).then(response => {
        this.listLoading = false
        if (response.success) {
          this.list = response.data.records
          this.listQuery.total = response.data.total
        } else {
          this.list = []
          this.listQuery.total = 0
        }
      })
    },
    // 查询按钮
    handleFilter() {
      this.listQuery.current = 1
      this.getList()
    },
    // 点击重置
    handleReset() {
      this.listQuery = {
        current: 1,
        size: 5,
        total: 0,
        params: {
          createDept: '',
          applyStartDate: '',
          applyEndDate: '',
          useOrgName: '',
          createByName: '',
          closeStartDate: '',
          closeEndDate: '',
          loanContractNo: '',
          vinNo: '',
          vehMark: '',
          bankName: '',
          bankContractNo: '',
          customerName: '',
          loanName: '',
          prepareStartDate: '',
          prepareEndDate: '',
          orgPath: '',
          menuUrl: '',
          userSid: ''
        }
      }
      this.getList()
    },
    toAdd() {
      this.carVisible = true
      this.carList.params.vinNo = ''
      this.carList.params.vehMark = ''
      this.getCarList()
    },
    toEdit(row) {
      this.viewState = 3
      this.$refs['divAdd'].showEdit(row)
    },
    toInfo(row) {
      this.viewState = 4
      this.$refs['divInfo'].showInfo(row)
    },
    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(() => {})
    },
    toSettle() {
      if (this.sids.length === 1) {
        if (this.multipleSelection[0].riskStateValue === '正常') {
          if (this.multipleSelection[0].nodeState === '已办结') {
            this.viewState = 5
            this.$refs['divSettle'].showInit(this.sids[0])
          } else {
            this.$message({ showClose: true, type: 'error', message: '请选择流程状态为已办结的记录进行操作' })
          }
        } else {
          this.$message({ showClose: true, type: 'error', message: '当前车辆处于' + this.multipleSelection[0].riskStateValue + '状态，只有正常状态的才能发起结清申请！' })
        }
      } else {
        this.$message({ showClose: true, type: 'error', message: '请选择一条记录进行操作' })
      }
    },
    // 删除
    doDel() {
      if (this.sids.length === 0) {
        this.$message({ showClose: true, type: 'error', message: '请选择至少一条记录进行删除操作' })
        return
      }
      const tip = '请确认是否删除所选 ' + this.sids.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)'
        })
        req.deleteBySids(this.sids).then(resp => {
          if (resp.success) {
            this.$message({ type: 'success', message: resp.msg, showClose: true })
          }
          this.getList()
          loading.close()
        }).catch(e => {
          loading.close()
        })
      }).catch(() => {
      })
    },
    // 现车序号
    carindexMethod(index) {
      var pagestart = (this.carList.current - 1) * this.carList.size
      var pageindex = index + 1 + pagestart
      return pageindex
    },
    getCarList() {
      this.carLoading = true
      this.carList.params.orgPath = window.sessionStorage.getItem('defaultOrgPath')
      req.getListPage(this.carList).then(response => {
        this.carLoading = false
        if (response.success) {
          this.listByCar = response.data.records
          this.carList.total = response.data.total
        } else {
          this.listByCar = []
          this.carList.total = 0
        }
      })
    },
    selectCar() {
      this.carList.current = 1
      this.getCarList()
    },
    chooseCar(row) {
      this.carVisible = false
      this.viewState = 2
      this.$refs['divAdd'].showAdd(row)
    },
    // 修改、编辑、详情返回列表页面
    resetState() {
      this.viewState = 1
    },
    doClose() {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.go(-1)
    }
  }
}
</script>
<style scoped>
</style>

