<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-date-picker v-model="queryParams.params.applicationStartDate" class="filter-item" type="date"
                                format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="请选择"/>
                <label>至</label>
                <el-date-picker v-model="queryParams.params.applicationEndDate" class="filter-item" type="date"
                                format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="请选择"/>
              </el-form-item>
              <el-form-item label="车型:">
                <el-input v-model="queryParams.params.modelName" 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="listcon">
          <el-table v-loading="tableLoading" :data="dataList" border style="width: 100%"
                    @selection-change="handleSelectionChange">
            <el-table-column width="50px" type="selection" align="center"/>
            <el-table-column width="80px" label="序号" type="index" :index="indexMethod" align="center"/>
            <el-table-column width="150px" label="操作" align="center">
              <template slot-scope="scope">
                <el-button v-if="scope.row.nodeState=='待提交'||(scope.row.nodeState!='待提交'&&scope.row.nodeState=='外采申请')"
                           type="primary" size="mini" @click="edit(scope.row)">办理
                </el-button>
                <el-button v-else type="info" size="mini">办理</el-button>
                <el-button type="primary" size="mini" @click="toInfo(scope.row)">查看</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="nodeState" width="100px;" label="状态" 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 prop="applicationCode" width="200px;" label="申请编号" align="center"/>
            <el-table-column prop="applicationDate" width="110px;" label="申请日期" align="center"/>
            <el-table-column prop="modelName" label="车型" align="center"/>
            <el-table-column prop="num" width="100px;" label="台数" align="center"/>
            <el-table-column prop="purchasePrice" width="90px;" label="采购价格" align="center"/>
            <el-table-column prop="guidedPrice" width="120px;" label="销售指导价" align="center"/>
          </el-table>
        </div>
        <!-- End 项目列表 -->
        <div class="pages">
          <div class="tit"/>
          <!--  翻页  -->
          <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" />
    <!--<div-info v-show="viewState == 5" 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 req from '@/api/baseoutsourcingapplication/baseoutsourcingapplication'
import ButtonBar from '@/components/ButtonBar'
import Pagination from '@/components/pagination'
import pageye from '@/components/pagination/pageye'
import divAdd from './baseoutsourcingapplicationAdd'
import divInfo from './baseoutsourcingapplicationInfo'
import { getStorage } from '@/utils/auth'

export default {
  name: 'baseoutsourcingapplication',
  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: 'success',
          size: 'small',
          icon: 'Import',
          btnKey: 'build',
          btnLabel: '导入'
        },
        {
          type: 'success',
          size: 'small',
          icon: 'export',
          btnKey: 'build',
          btnLabel: '导出'
        },
        {
          type: 'info',
          size: 'small',
          icon: 'cross',
          btnKey: 'doClose',
          btnLabel: '关闭'
        }
      ],
      queryParams: {
        current: 1,
        size: 10,
        total: 0,
        params: {
          staffSid: window.sessionStorage.getItem('staffSid'),
          userSid: window.sessionStorage.getItem('userSid'),
          sids: [], // 用于导出的时候保存已选择SID
          applicationCode: '', // 申请编号
          createByName: '', // 申请人姓名
          applicationDate: '', // 申请日期
          applicationStartDate: '',
          applicationEndDate: '',
          externalMiningTypeKey: '', // 外采类型key
          externalMiningTypeValue: '', // 外采类型value
          purchasingUnitSid: '', // 采购单位sid
          purchasingUnitName: '', // 采购单位名称
          modelSid: '', // 车型sid
          modelName: '', // 车型名称
          configName: '', // 常用配置名称
				purchasePrice: '', // 采购价格
				guidedPrice: '', // 销售指导价
				manufactorSettlementPrice: '', // 厂家合同价
				num: '', // 台数
				deposit: '', // 订金
				expenseName: '', // 费用名称
				totalExpenseAmount: '', // 费用金额合计
				orgSid: '' // 部门sid
				}
			},
			multipleSelection: [],
      row:{}
		}
	},
  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= 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;//iframeWin.document.documentElement.scrollHeight || iframeWin.document.body.scrollHeight;
    },
    flowRecord(row){
      this.centerDialogVisible = true
      var params = {
        deployId: row.procDefId,
        procInsId: row.procInstSid,
        token : getStorage()
      }
      this.url = 'http://120.46.131.15/#/flow/flowRecordForBusiness?data=' + encodeURI((JSON.stringify(params)))
    },
		resetState() {
			this.viewState = 1
		},
		btnHandle(btnKey) {
			switch (btnKey) {
				case 'toAdd':
					this.toAdd()
					break
				case 'toEdit':
					this.toEdit()
					break
				case 'doSubmit':
					this.doSubmit()
					break
				case 'doDel':
					this.doDel()
					break
				case 'doImport':
					this.doImport()
					break
				case 'doExport':
					this.doExport()
					break
        case 'doClose':
          this.doClose()
          break
				default:
					break
			}
		},
		toAdd(row) {
			this.viewState = 2
			this.$refs['divadd'].showAdd()
		},
    toEdit() {
      if (this.sids.length === 0) {
        this.$message({ showClose: true, type: 'error', message: '请选择一条记录进行编辑' })
        return
      }
      if (this.sids.length > 1) {
        this.$message({ showClose: true, type: 'error', message: '只能选择一条记录进行编辑' })
        return
      }
      this.dataList.forEach(row => {
        if(row.sid === this.sids[0] && (row.nodeState == '待提交' || (row.nodeState!='待提交'&&row.nodeState=='外采申请'))){
          this.viewState = 3
          const row = this.sids[0]
          this.$refs['divadd'].showEdit(row)
        }else if(row.sid === this.sids[0]){
          alert('已经发起的审批业务数据不能进行编辑。');
          return false;
        }else{

        }
      })

    },
    edit(row) {
      this.viewState = 3
      this.$refs['divadd'].showEdit(row)
    },
    doSubmit() {
     /* if (this.multipleSelection.length === 0) {
        this.$message({ showClose: true, type: 'error', message: '请选择一条记录进行编辑' })
        return
      }
      if (this.multipleSelection.length > 1) {
        this.$message({ showClose: true, type: 'error', message: '只能选择一条记录进行编辑' })
        return
      }
      const row = this.multipleSelection[0]
      const sids = []
      this.multipleSelection.forEach(row => {
        if(row.nodeState==''||(row.nodeState!=''&&row.nodeState=='外采申请')){
          sids.push(row.sid)
        }else{
          alert('已经发起的审批业务数据不能进行删除。');
          sids = [];
        }
      })
      req
        .doSubmitBySid(row.sid,this.queryParams.params.userSid)
        .then( resp => {
          if(resp.success){
            alert(123);
          }
        });*/
    },
		doDel(row) {
      if (this.sids.length === 0) {
        this.$message({showClose: true, type: 'error', message: '请选择至少一条记录进行删除操作'})
        return
      }
      var b=false;
      this.multipleSelection.forEach(row => {
        if(!(row.nodeState === '待提交')){
         b=true
        }
      })
      if(b){
        this.$message({showClose: true, type: 'error', message: '提交流程审批的记录不能进行删除!'})
        return
      }
      const tip = '请确认是否删除所选 ' + this.sids.length + ' 条记录?'
      this.$confirm(tip, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
         .then(() => {
           const _this = this
           req
             .delBySids(this.sids)
             .then(resp => {
               if (resp.success) {
                 _this.$message({ type: 'success', message: resp.msg, showClose: true })
                 this.queryParams.current = 1
                 _this.loadList()
               } else {
                 // 根据resp.code进行异常情况处理
               }
             })
             .catch(e => {
               loading.close()
             })
         })
         .catch(() => {})
		},
		doImport(row) {
			// 导入的代码
			req
				.importExcel(this.queryParams.params)
				.then(resp => {
					if (resp.success) {
						console.log(resp)
					}
				})
				.catch(() => {})
		},
		doExport(row) {
			// 导出的代码
			const sids = []
			this.multipleSelection.forEach(row => {
				sids.push(row.sid)
			})
			this.queryParams.params.sids = sids
			req
				.exportExcel(this.queryParams.params)
				.then(resp => {
					if (resp.success) {
						var map = resp.data
						const fileName = map.filename // 导出文件名
						// // 对于<a>标签，只有 Firefox 和 Chrome（内核） 支持 download 属性
						// // IE10以上支持blob但是依然不支持download
						const link = document.createElement('a') // 创建a标签
						link.download = fileName // a标签添加属性
						link.style.display = 'none'
						link.href = map.downurl
						document.body.appendChild(link)
						link.click() // 执行下载
						URL.revokeObjectURL(link.href) // 释放url
						document.body.removeChild(link) // 释放标签
					}
				})
				.catch(() => {})
		},
    doClose(){
      this.$store.dispatch('tagsView/delView', this.$route);
      this.$router.go(-1)
    },
		dosearch() {
			this.queryParams.current = 1
			this.loadList()
		},
		resetQuery() {
			this.queryParams.params = {}
			this.queryParams.params.sid = '' // sid
			this.queryParams.params.name = '' // 登录名
			this.dosearch()
		},
		loadList() {
			const _this = this
			this.tableLoading = true
			req
				.listPage(this.queryParams)
				.then(resp => {
					_this.tableLoading = false
					if (resp.success) {
						const data = resp.data
						_this.queryParams.total = data.total
						_this.dataList = data.records
					} else {
						// 根据resp.code进行异常情况处理
					}
				})
				.catch(() => {
					_this.tableLoading = false
				})
		},
		handleSelectionChange(row) {
			this.multipleSelection = row
      const aa = []
      row.forEach((element) => {
        aa.push(element.sid)
      })
      this.sids = aa
		},
		// 序号
		indexMethod(index) {
			var pagestart = (this.queryParams.current - 1) * this.queryParams.size
			var pageindex = index + 1 + pagestart
			return pageindex
		},
		toInfo(row) {
			this.viewState = 4
      this.$refs['divinfo'].showInfo(row)
    }
	}
}
</script>
<style scoped>
</style>
