<template>
  <div class="app-container">
    <div v-show="viewState == 1">
      <!--标题按钮部分开始-->
      <div class="tab-header webtop">
        <!--标题-->
        <div>{{ viewTitle }}</div>
        <!--start 添加修改按钮-->
        <div>
          <el-button type="primary" size="small" @click="doExport">导出</el-button>
          <el-button type="primary" size="small" @click="download">下载</el-button>
          <el-button type="danger" size="small" @click="openRevoke()">撤回</el-button>
        </div>
      </div>
      <!--标题按钮部分结束-->
      <!--Start 新增修改部分-->
      <div class="">
        <div class="titwu"><span>{{ formobj.withApply }}专项返利预提申请</span></div>
        <el-form ref="form_obj" :model="formobj" :rules="rules" class="formaddcopy02">
          <el-row class="rowStyle">
            <el-col :span="24" class="colOneStyle">
              <div style="text-align: right;font-weight: bold">金额单位：元</div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="16">
              <div class="span-sty">申请编号</div>
              <el-form-item><span class="addinputInfo">{{ formobj.billNo }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">申请日期</div>
              <el-form-item><span class="addinputInfo">{{ formobj.createTime }}</span></el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <div class="span-sty">分公司</div>
              <el-form-item><span class="addinputInfo">{{ formobj.createOrgName }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">申请部门</div>
              <el-form-item><span class="addinputInfo">{{ formobj.deptName }}</span></el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="span-sty">申请人</div>
              <el-form-item><span class="addinputInfo">{{ formobj.createByName }}</span></el-form-item>
            </el-col>
          </el-row>
          <el-table :key="tableKey" :data="formobj.scmSpecialRebateWiths" :index="index" border style="width: 100%" show-summary :summary-method="getSummaries">
            <el-table-column fixed width="80px" label="序号" type="index" :index="index + 1" align="center"/>
            <el-table-column prop="purchaseSystemName" label="采购系统" align="center" min-width="120" />
            <el-table-column prop="brandName" label="品牌" align="center" min-width="100" />
            <el-table-column prop="rebateTypeValue" label="返利类型" align="center" min-width="120" />
            <el-table-column prop="withRebate" label="预提返利" align="center" min-width="120" />
            <el-table-column prop="expectItureCost" label="其中支出费用" align="center" min-width="130" />
            <el-table-column prop="expectTreatCost" label="其中待支付费用" align="center" min-width="150" />
            <el-table-column prop="expectSuppCost" label="其中抵顶费用" align="center" min-width="130" />
            <el-table-column label="明细" align="center" width="100">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="handleLook(scope.row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-row>
            <el-col :span="24">
              <div class="span-sty">备注</div>
              <el-form-item><span class="addinputInfo">{{ formobj.remarks }}</span></el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <!--End 添加修改部分-->
    <zhuanxiangfanliyutiInfo v-show="viewState == 2" ref="divInfo" @doback="resetState"/>
  </div>
</template>

<script>
import req from '@/api/specialrebate/specialrebatewithholding'
import zhuanxiangfanliyutiInfo from './relation/zhuanxiangfanliyutiInfo'
import { getStorage } from '@/utils/auth'

export default {
  name: 'ZhuanXiangFanLiYuTiYiBanInfo',
  components: {
    zhuanxiangfanliyutiInfo
  },
  data() {
    return {
      viewTitle: '',
      index: 0,
      tableKey: 0,
      viewState: 1,
      // 表单数据
      formobj: {
        sid: '',
        createTime: '',
        withApply: '',
        deptName: '',
        deptSid: '',
        createOrgName: '',
        createOrgSid: '',
        useOrgName: '',
        useOrgSid: '',
        remarks: '',
        withRebateTotal: '',
        createByName: '',
        createBySid: '',
        instanceId: '', // 流程实例ID
        taskId: '', // 任务ID
        orgPath: '',
        scmSpecialRebateWiths: []
      },
      rules: {},
      // 环节所需参数
      linkByParameter: {
        businessSid: '',
        comment: '',
        instanceId: '',
        taskId: '',
        orgSidPath: '',
        taskDefKey: '',
        userSid: ''
      }
    }
  },
  created() {
    console.log('url:' + window.location.href)
    var one = window.location.href.indexOf('&data') + 6
    const data = window.location.href.substr(one) // url解码unescape()已从web中移除,尽量不使用
    const obj = JSON.parse(decodeURIComponent(data))
    console.log('iframe页面获取的obj:', obj)
    // 点击（同意、终止、驳回、驳回）操作时所需的参数
    this.linkByParameter.businessSid = obj.businessSid
    this.linkByParameter.instanceId = obj.instanceId
    this.linkByParameter.taskId = obj.taskId
    this.linkByParameter.taskDefKey = obj.taskDefKey
    this.linkByParameter.orgSidPath = window.sessionStorage.getItem('orgSidPath')
    this.linkByParameter.userSid = window.sessionStorage.getItem('userSid')
    // 加载表单数据
    this.showInfo(obj.businessSid)
  },
  mounted() {
    window.parent.postMessage({
      cmd: 'returnHeight',
      params: {
        // 告诉父级页面，子页面的弹框高度。
        code: 2,
        data: 400 + 'px'
      }
    }, '*')
  },
  methods: {
    showInfo(sid) {
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.viewTitle = '专项返利预提申请详情'
      console.log('编辑回显', sid)
      req.fetchBySid(sid).then((resp) => {
        if (resp.success) {
          this.formobj = resp.data
        }
      }).catch((e) => {
        this.formobj = {}
      })
    },
    handleLook(row) {
      this.viewState = 2
      this.$refs['divInfo'].showInfo(row)
    },
    resetState() {
      this.viewState = 1
    },
    // 合计
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (column.property === 'withRebate') {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] += ''
        } else if (column.property === 'expectItureCost') {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] += ''
        } else if (column.property === 'expectTreatCost') {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] += ''
        } else if (column.property === 'expectSuppCost') {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] += ''
        }
      })
      return sums
    },
    doExport() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      req.downloadExcel({ sid: this.formobj.sid }).then((resp) => {
        loading.close()
        const blob = new Blob([resp], {
          type: 'application/vnd.ms-excel'
        })
        const fileName = '专项返利预提明细' + '.xls'
        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href)
        document.body.removeChild(elink)
      }).catch(() => {
        loading.close()
      })
    },
    download() {
      req.createPdf({ specialWithSid: this.formobj.sid, userName: window.sessionStorage.getItem('name') }).then((resp) => {
        if (resp.success && resp.data !== '') {
          var xhr = new XMLHttpRequest()
          xhr.open('GET', process.env.VUE_APP_BASE_API + '/base/file/download?filePath=' + resp.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()
        }
      })
    },
    /** 确认撤回任务 */
    openRevoke() {
      this.$confirm('是否确认执行撤回操作', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleRevoke()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消撤回'
        })
      })
    },
    /** 撤回任务 */
    handleRevoke() {
      req.revokeProcess(this.linkByParameter).then((response) => {
        if (response.success) {
          this.$notify({
            title: '提示',
            message: '执行成功',
            type: 'success',
            duration: 2000
          })
          this.nodeDialogVisible = false
          // 子页面向父级页面传递值
          window.parent.postMessage({
            cmd: 'returnHeight',
            params: {
              // 操作成功，告诉父级页面关闭弹框
              code: 1
            }
          }, '*')
        }
      })
    }
  }
}
</script>
<style scoped>
.titwu {
  font-size: 28px;
  text-align: center;
  padding: 30px 0 20px 0;
}
.rowStyle {
  border-left: 0px;
}
.colOneStyle {
  border-right: 0px !important;
}
.span-sty {
  width: 130px !important;
}
.addinputInfo {
  margin-left: 120px !important;
}
</style>

