<template>
  <div class="app-container">
    <div v-show="viewState == 1">
      <button-bar ref="btnbar" view-title="厂家采购管理" :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" label-width="100px">
              <el-form-item :model="queryParams" label="申请日期">
                <el-date-picker value-format="yyyy-MM-dd" v-model="queryParams.params.applicationDateStart" clearable style="width: 160px;" type="date" placeholder="开始日期"/>
                <div class="line">至</div>
                <el-date-picker value-format="yyyy-MM-dd" v-model="queryParams.params.applicationDateEnd" clearable style="width: 160px;" type="date" placeholder="结束日期"/>
              </el-form-item>
              <el-form-item label="采购类型">
                <el-select v-model="queryParams.params.applyTypeKey" placeholder="请选择" clearable filterable>
                  <el-option v-for="item in applyType_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="采购原因">
                <el-select v-model="queryParams.params.schedulingTypeKey" placeholder="请选择" clearable filterable>
                  <el-option v-for="item in schedulingType_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey"></el-option>
                </el-select>
              </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>
        <div class="">
          <el-table v-loading="tableLoading" :data="dataList" border style="width: 100%;" @selection-change="handleSelectionChange">
            <el-table-column fixed width="50" type="selection" align="center"/>
            <el-table-column fixed width="60" label="序号" type="index" :index="indexMethod" align="center"/>
            <el-table-column fixed width="150" label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="primary" size="small" :disabled="scope.row.nodeState =='发起申请' ? false : scope.row.nodeState == '待提交' ? false : true" @click="handleEdit(scope.row)">办理</el-button>
                <el-button type="primary" size="small" @click="toInfo(scope.row)">查看</el-button>
              </template>
            </el-table-column>
            <el-table-column label="状态" width="150px" 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 width="150" prop="applyType" label="采购类型" align="center"/>
            <el-table-column width="150" prop="schedulingType" label="采购原因" align="center"/>
            <el-table-column width="200" prop="applicationCode" label="申请编号" align="center"/>
            <el-table-column width="150" prop="applicationDate" label="申请日期" align="center"/>
            <el-table-column width="150" prop="createOrgName" label="分公司" align="center"/>
            <el-table-column width="150" prop="createByName" label="申请人" align="center"/>
            <el-table-column width="150" prop="applyForDeposit" label="申请订金" align="center"/>
            <el-table-column prop="remarks" fit label="备注" align="left" header-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/busvehicleapply'
import ButtonBar from '@/components/ButtonBar'
import Pagination from '@/components/pagination'
import pageye from '@/components/pagination/pageye'
import divAdd from './cheliangpaichanAdd'
import divInfo from './cheliangpaichanInfo'
import { getStorage } from '@/utils/auth'

export default {
  name: 'cheliangpaichan',
  components: {
    ButtonBar,
    Pagination,
    pageye,
    divAdd,
    divInfo
  },
  data() {
    return {
      url: '',
      dialogHeight: '80%',
      centerDialogVisible: false,
      btndisabled: false,
      viewState: 1, // 1、列表 2、添加 3、修改 4、查看
      isSearchShow: false, // 显示隐藏
      tableLoading: false,
      // 列表数据
      dataList: [],
      btnList: [
        {
          type: 'primary',
          size: 'small',
          icon: 'plus',
          btnKey: 'toAdd',
          btnLabel: '新增'
        },
        {
          type: 'danger',
          size: 'small',
          icon: 'del',
          btnKey: 'doDel',
          btnLabel: '删除'
        },
        {
          type: 'danger',
          size: 'small',
          icon: '',
          btnKey: 'doCancellation',
          btnLabel: '作废'
        },
        {
          type: 'info',
          size: 'small',
          icon: 'cross',
          btnKey: 'doClose',
          btnLabel: '关闭'
        }
      ],
      // sid数组
      sids: [], // 用于导出的时候保存已选择SID
      nodeState_list: [],
      schedulingType_list: [],
      applyType_list: [],
      queryParams: {
        current: 1,
        size: 10,
        total: 0,
        params: {
          applicationDateStart: '',
          applicationDateEnd: '',
          applyTypeKey: '',
          schedulingTypeKey: '',
          userSid: ''
        }
      },
      row: {}
    }
  },
  created() {
    this.init()
    this.loadList()
  },
  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)))
    },
    init() {
      req.pullDown({ type: 'schedulingType' }).then((res) => {
        if (res.success) {
          this.schedulingType_list = res.data
          console.log('下拉框请求111', res.data)
        }
      })
      req.pullDown({ type: 'applyType' }).then((res) => {
        if (res.success) {
          this.applyType_list = res.data
          console.log('下拉框请求111', res.data)
        }
      })
    },
    btnHandle(btnKey) {
      console.log('XXXXXXXXXXXXXXX' + btnKey)
      switch (btnKey) {
        case 'toAdd':
          this.toAdd()
          break
        case 'doDel':
          this.doDel()
          break
        case 'doCancellation':
          this.doCancellation()
          break
        case 'doClose':
          this.doClose()
          break
        default:
          break
      }
    },
    // 获取数据sid
    handleSelectionChange(row) {
      const aa = []
      const bb = []
      row.forEach(element => {
        aa.push(element.sid)
        bb.push(element.nodeState)
      })
      this.sids = aa
      this.nodeState_list = bb
      console.log('获取sids数组', this.sids)
    },
    toAdd(row) {
      this.viewState = 2
      this.$refs['divadd'].showAdd()
    },
    toInfo(row) {
      this.viewState = 4
      console.log('这是打开详情接口', row)
      const sid = row.sid
      this.$refs['divinfo'].showInfo(sid, row)
    },
    handleEdit(row){
      this.viewState = 3
      this.$refs['divadd'].showEdit(row.sid, row)
    },
    // 查询
    dosearch() {
      this.queryParams.current = 1
      this.loadList()
    },
    // 重置
    resetQuery() {
      this.queryParams = {
        current: 1,
          size: 10,
          total: 0,
          params: {
          applicationDateStart: '',
            applicationDateEnd: '',
            applyTypeKey: '',
            schedulingTypeKey: '',
            userSid: ''
        }
      }
      this.dosearch()
    },
    // 加载分页列表
    loadList() {
      this.tableLoading = true
      this.queryParams.params.userSid = window.sessionStorage.getItem('userSid')
      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(row) {
      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)'
        })
        const _this = this
        req.delBySids(this.sids).then(resp => {
          loading.close()
          if (resp.success) {
            _this.$message({ type: 'success', message: resp.msg, showClose: true })
            _this.loadList()
          }
        }).catch(e => {
          loading.close()
        })
      }).catch(() => {})
    },
    doCancellation() {
      if (this.sids.length === 0) {
        this.$message({ showClose: true, type: 'error', message: '请选择至少一条记录进行作废操作' })
        return
      }
      if (this.nodeState_list.length > 0) {
        for (var i = 0; i < this.nodeState_list.length; i++) {
          if (this.nodeState_list[i] !== '已办结') {
            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)'
        })
        const _this = this
        req.abandonApply(this.sids).then(resp => {
          loading.close()
          if (resp.success) {
            _this.$message({ type: 'success', message: resp.msg, showClose: true })
            _this.loadList()
          }
        }).catch(e => {
          loading.close()
        })
      }).catch(() => {})
    },
    // 子组件关闭（返回）
    resetState() {
      this.viewState = 1
      this.loadList()
    },
    doClose() {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.go(-1)
    }
  }
}
</script>

<style scoped>
.line {
  display: inline-block;
  margin: 0px 15px;
}
/*表格列设置fixed后固定列出现下边框的设置*/
/deep/ .el-table__fixed {
  height: 100% !important;
}
/*表格列设置fixed后固定列出现下边框的设置*/
/deep/ .el-table__fixed-right {
  height: 100% !important;
}
</style>
