<template>
  <div class="app-container">
    <div v-show="viewState == 1">
      <button-bar ref="btnbar" view-title="采购订单列表" :btndisabled="btndisabled" @btnhandle="btnHandle" />
      <div class="main-content" style="margin-top: 10px;">

        <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" align="center" />
          <el-table-column fixed width="80" label="操作" align="center">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="showEditDrawer(scope.row)">查看</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="purchaseState" label="状态" align="center" width="80">
            <template slot-scope="scope">
              <span>{{ scope.row.purchaseState==0?'未审核':'通过' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="code" label="订单编号" align="center" width="150" />
          <el-table-column prop="supplierCode" label="供应商编码" align="center" width="110" />
          <el-table-column prop="supplierOnlyCode" label="统一编码" align="center" width="100" />
          <el-table-column prop="supplierName" label="供应商名称" header-align="center" align="left" />
          <el-table-column prop="createTime" label="录入时间" align="center" width="160" />
          <el-table-column prop="arrivalDate" label="到货日期" align="center" width="120" />
        </el-table>
      </div>
    </div>
    <el-drawer :visible.sync="drawerUploadXlsx" size="85%" :with-header="false" :before-close="drawerUploadXlsxClose">
      <upload-xlsx ref="draweruploadxlsx" @doback="drawerUploadXlsxClose" @reloadlist="loadList" />
    </el-drawer>
  </div>
</template>

<script>
  import ButtonBar from '@/components/ButtonBar'
  import UploadXlsx from './PrUploadXlsx'
  import req from '@/api/supervise/purchaserequisition'
  import reqPro from '@/api/supervise/purchaserequisitionpro'
  export default {
    name: 'PurchaserequisitionUploadxlsx',
    components: {
      ButtonBar,
      UploadXlsx
    },
    data() {
      return {
        btndisabled: false,
        viewState: 1, // 1、列表 2、添加 3、修改 4、查看
        isSearchShow: false,
        searchxianshitit: '显示查询条件',
        btnList: [{
          type: 'primary',
          size: 'small',
          icon: 'upload',
          btnKey: 'toUploadXlsx',
          btnLabel: '上传采购订单'
        }],
        drawerUploadXlsx: false,
        tableLoading: false,
        dataList: [],
        queryParams: {
          current: 1,
          size: 10,
          total: 0,
          params: {
            codeUnified: '',
            name: '',
            contacts: '',
            bankAccountNumber: '',
            legalRepresentative: '',
            businessLicenseNo: ''
          }
        },
        collOrderInfoActiveNames: '1',
        candownload: true,
        submitdisabled: false,
        viewTitle: '',
        tableKey: 0,
        index: 0,
        updateAction: '/api/customer/v1/purchaserequisition/uploadXlsxFile',
        fileList: [],
        totalQuantity: '', // 合计数量
        amountInTotal: '', // 合计金额
        formobj: {
          sid: '',
          code: '', // 单号
          buyerName: '', // 采购人姓名
          buyerCode: '', // 采购人编码
          purchaseDate: '', // 采购日期
          arrivalDate: '', // 到货日期
          purchasingOrgName: '', // 采购组织名称
          purchasingOrgCode: '', // 采购组织编码
          purchasingDeptCode: '', // 采购部门名称
          purchasingDeptName: '', // 采购部门编码
          supplierName: '', // 供应商名称
          supplierCode: '', // 供应商编码
          logisticsCompanyName: '', // 物流公司名称
          logisticsCompanyCode: '', // 物流公司编码
          expiryDate: '', // 单据到效期
          warehousePosition: '', // 仓位
          warehousePositionCode: '', // 仓位code
          newCode: '', // 新订单编号
          oldCode: '', // 旧订单编号
          completionStatus: '', // 完成状态
          completionStatusKey: '', // 完成状态key
          pros: [] // 采购商品明细列表
        },
        prolist: [],
        supplierCheckState: 0,
        supplierCheckMsg: '等待检测',
        supplierChecklist: [],
        proCheckState: 0,
        proCheckMsg: '等待检测',
        proChecklist: [],
        rules: {}
      }
    },
    mounted() {
      this.$refs['btnbar'].setButtonList(this.btnList)
    },
    created() {
      this.loadList()
    },
    methods: {
      loadList() {
        req.listOfCheck().then(res => {
          console.log('2222', res)
          this.dataList = res.data
        })
      },
      handleSelectionChange(row) {
        console.log('zzz', row)
      },
      showEditDrawer(row) {
        this.drawerUploadXlsx = true
        this.$refs['draweruploadxlsx'].showEdit(row)
      },
      // 搜索条件效果
      clicksearchShow() {
        this.isSearchShow = !this.isSearchShow
        if (this.isSearchShow) {
          this.searchxianshitit = '隐藏查询条件'
        } else {
          this.searchxianshitit = '显示查询条件'
        }
      },
      btnHandle(btnKey) {
        switch (btnKey) {
          case 'toUploadXlsx':
            this.toUploadXlsx()
            break
          case 'filing':
            this.filing()
            break
          case 'doDel':
            this.doDel()
            break
          default:
            break
        }
      },
      toUploadXlsx() {
        this.drawerUploadXlsx = true
      },
      drawerUploadXlsxClose() {
        console.log('DDDD')
        this.drawerUploadXlsx = false
      },
      handleReturn() {
        this.formobj = {
          sid: '',
          code: '', // 单号
          buyerName: '', // 采购人姓名
          buyerCode: '', // 采购人编码
          purchaseDate: '', // 采购日期
          arrivalDate: '', // 到货日期
          purchasingOrgName: '', // 采购组织名称
          purchasingOrgCode: '', // 采购组织编码
          purchasingDeptCode: '', // 采购部门名称
          purchasingDeptName: '', // 采购部门编码
          supplierName: '', // 供应商名称
          supplierCode: '', // 供应商编码
          logisticsCompanyName: '', // 物流公司名称
          logisticsCompanyCode: '', // 物流公司编码
          expiryDate: '', // 单据到效期
          warehousePosition: '', // 仓位
          warehousePositionCode: '', // 仓位code
          newCode: '', // 新订单编号
          oldCode: '', // 旧订单编号
          completionStatus: '', // 完成状态
          completionStatusKey: '', // 完成状态key
          pros: [] // 采购商品明细列表
        }
        this.totalQuantity = ''
        this.amountInTotal = ''
        this.$refs['form_obj'].resetFields()
        this.$store.dispatch('tagsView/delView', this.$route)
        this.$router.go(-1)
        // this.$emit('doback')
      },
      handleProgress(event, file, fileList) {
        // this.progressFlag = true; // 显示进度条
        // this.loadProgress = parseInt(event.percent); // 动态获取文件上传进度
        // if (this.loadProgress >= 100) {
        //     this.loadProgress = 100
        //     setTimeout( () => {this.progressFlag = false}, 1000) // 一秒后关闭进度条
        // }
        // const _this = this
        // this.fullscreenloading = this.$loading({
        //   lock: true,
        //   text: '文件正在上传',
        //   spinner: 'el-icon-loading',
        //   background: 'rgba(0, 0, 0, 0.7)'
        // })
        // console.log('111', event.percent)
        // if (event.percent >= 100) {
        //   _this.fullscreenloading.text = '上传完成，正在导入数据库'
        // }
      },
      // handleSuccess(resp, file, fileList) {
      //   // if (this.fullscreenloading) this.fullscreenloading.close()
      //   // this.fullscreenloading = null
      //   console.log('222', resp)
      //   // const rdata = resp.data
      //   // const _this = this
      //   // _this.fullscreenloading.text = '数据导入完成，进行汇总'
      //   // _this.uploadResultMesssage = '共导入数据：' + rdata.allNum + ' 条；符合监管条件的数据：' + rdata.validNum + ' 条；用时：' + rdata.durations + ' 毫秒。'

      //   // kchz()
      //   //   .then(res => {
      //   //     if (this.fullscreenloading) this.fullscreenloading.close()
      //   //     this.fullscreenloading = null
      //   //     console.log('333', res)
      //   //     _this.hzFilePath = res.data
      //   //   })
      //   //   .catch(e => {
      //   //     if (this.fullscreenloading) this.fullscreenloading.close()
      //   //     this.fullscreenloading = null
      //   //   })
      //   // // kchzyc()
      //   // //   .then(res => {
      //   // //     if (this.fullscreenloading) this.fullscreenloading.close()
      //   // //     this.fullscreenloading = null
      //   // //     console.log('444', res)
      //   // //     _this.ychzFilePath = res.data
      //   // //   })
      //   // //   .catch(e => {
      //   // //     if (this.fullscreenloading) this.fullscreenloading.close()
      //   // //     this.fullscreenloading = null
      //   // //   })
      // },
      showAdd() {
        this.$nextTick(() => {
          this.$refs['form_obj'].clearValidate()
        })
        this.viewTitle = '【审核编号】'
      },
      showEdit(row) {
        this.$nextTick(() => {
          this.$refs['form_obj'].clearValidate()
        })
        this.viewTitle = '【审核编号】'
        req
          .fetchBySid(row.sid)
          .then(resp => {
            if (resp.success) {
              this.formobj = resp.data
              if (this.formobj.pros.length > 0) {
                this.totalQuantity = this.formobj.pros.length
                var aa = 0
                for (var i = 0; i < this.formobj.pros.length; i++) {
                  if (this.formobj.pros[i].totalPrice !== '') {
                    aa = parseFloat(aa) + parseFloat(this.formobj.pros[i].totalPrice)
                  }
                }
                this.amountInTotal = aa
              }
            } else {
              // 根据resp.code进行异常情况处理
            }
          })
          .catch(e => {
            this.formobj = row
          })
      },
      downCheckExcel() {
        window.location.href = process.env.VUE_APP_BASE_API + '/v1/productnum/products?code=' + this.formobj.code
      },
      handleDownload() {
        window.location.href = process.env.VUE_APP_BASE_API + '/v1/purchaserequisition/yb'
      },
      handleSuccess(resp, file, fileList) {
        this.fileList = []
        if (resp.success) {
          this.$message({
            showClose: true,
            type: 'success',
            message: '导入成功'
          })
          this.formobj = resp.data
          this.loadProList()
          this.checkPro()
          this.checkSupplier()
        } else {
          this.$message({
            showClose: true,
            type: 'error',
            message: resp.msg
          })
        }
      },
      loadProList() {
        if (this.formobj.sid) {
          reqPro.listByMainSid(this.formobj.sid).then(resp => {
            this.prolist = resp.data
            this.totalQuantity = this.prolist.length
            var aa = 0
            for (var i = 0; i < this.prolist.length; i++) {
              if (this.prolist[i].totalPrice !== '') {
                aa = parseFloat(aa) + parseFloat(this.prolist[i].totalPrice)
              }
            }
            this.amountInTotal = aa
          })
        }
      },
      checkPro() {
        if (this.formobj.sid) {
          this.proCheckMsg = '正在对订单的商品信息进行检测...'
          reqPro.checkByMainSid(this.formobj.sid).then(resp => {
            this.proChecklist = resp.data
            if (this.proChecklist.length > 0) {
              this.proCheckState = 1
            } else {
              this.proCheckState = 2
              if (this.formobj.purchaseState === '0' && this.supplierCheckState === 2) {
                this.updatePurchaseStateSucess()
              }
            }
            this.loadProList()
          })
        }
      },
      checkSupplier() {
        if (this.formobj.sid) {
          this.supplierCheckMsg = '正在检测供应商信息...'
          req.checkSupplier(this.formobj.sid).then(resp => {
            this.supplierChecklist = resp.data
            if (this.supplierChecklist.length > 0) {
              this.supplierCheckState = 1
            } else {
              this.supplierCheckState = 2
              if (this.formobj.purchaseState === '0' && this.proCheckState === 2) {
                this.updatePurchaseStateSucess()
              }
            }
          })
        }
      },
      updatePurchaseStateSucess() {
        req.updatePurchaseStateSucess(this.formobj.sid).then(resp => {
          this.formobj.purchaseState = '1'
        })
      },
      dataDelete(index) {
        const tip = '请确认是否删除所选记录?'
        this.$confirm(tip, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.formobj.pros.splice(index, 1)
        })
      },
      saveOrUpdate() {
        this.$refs['form_obj'].validate(valid => {
          if (valid) {
            this.submitdisabled = true
            req
              .saveOrUpdate(this.formobj)
              .then(resp => {
                this.submitdisabled = false
                if (resp.success) {
                  this.$message({
                    showClose: true,
                    type: 'success',
                    message: resp.msg
                  })
                  this.handleReturn()
                } else {
                  // 根据resp.code进行异常情况处理
                }
              })
              .catch(() => {
                this.submitdisabled = false
              })
          } else {
            return false
          }
        })
      }
    }
  }
</script>

<style scoped>
  .title {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }
</style>
