<template>
  <div>
    <!-- 采购随货单上传 -->
    <p-card title="采购随货单上传">
      <span slot="extra">
        <!-- <p-button type="primary" style="margin-right: 10px" @click="showmodel()">添加</p-button> -->
        <a-space>
          <a-button type="primary" @click="upload">上传</a-button>
          <a-button type="primary" @click="del">删除</a-button>
          <a-button type="primary" @click="bizDown">下载</a-button>
        </a-space>
      </span>
      <p-grid-form :span="8" :label-col="{ span: 8 }" :items="config.items" @submit="hanlderSubmit" />
      <p-table
        ref="table"
        row-key="rowId"
        bordered
        :columns="config.columns"
        :remoteUrl="config.remoteUrl"
        :remoteParams="remoteParams"
        :rowSelectType="false"
        :data-source="data"
        @clickRow="clickRow"
      >
      </p-table>
    </p-card>

    <p-card title="采购随货单上传明细" style="margin-top:10px">
      <p-table
        ref="tableDetail"
        row-key="rcvLineId"
        bordered
        :autoLoad="false"
        :columns="config.detail.columns"
        :remoteUrl="config.detail.remoteUrl"
        :remoteParams="DetailremoteParams"
        :rowSelectType="2"
        :doneBefore="doneBefore"
        @selectChange="selectChange"
        :data-source="data"
      >
        <template slot="operation" slot-scope="text, record">
          <a v-if="record.picFileurl" @click="showmodel(text)">查看</a>
          <span v-else>未上传</span>
        </template>
      </p-table>
    </p-card>
    <p-modal
      :title="lookats ? $lang('查看图片') : $lang('上传图片')"
      :visible="isUpload"
      :width="lookats ? 580 : 900"
      :confirm-loading="confirmLoading"
      @cancel="isUpload = false"
    >
      <p-grid-form ref="imgForm" :span="8" :label-col="{ span: 8 }" :items="config.detail.items" />
      <imgsUpload
        ref="imgsUpload"
        v-model="isUpload"
        :isView="lookats"
        :uploadIdlist="uploadIdlist"
        @completed="item => handleUploadImgs(item, text, record)"
      ></imgsUpload>

      <template slot="footer">
        <!-- <a @click="showmodel(text)">查看</a> -->
        <a-space>
          <a-button v-if="!lookats" type="primary" @click="save">上传</a-button>
          <a-button>退出</a-button>
        </a-space>
      </template>
      <!-- footer -->
    </p-modal>
  </div>
</template>

<script>
import config from './config.js'

import { add, deletes, update, bizFileDown } from './api'
import { diffOption } from '@/views/kzyWMS/utils/index.js'
import ImgsUpload from '@/views/kzyWMS/components/ImgsUpload/noModelindex.vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import storage from 'store'

export default {
  data() {
    return {
      selectedRows: [],
      rowRecord: {},
      isUpload: false,
      lookats: false,
      uploadIdlist: [],
      config: config(this),
      data: [],
      type: true,
      remoteParams: {
        num: 'findSupplierIsTwoVetoList',
        params: {}
      },
      DetailremoteParams: {},
      visible: false,
      confirmLoading: false
    }
  },
  components: {
    ImgsUpload
  },
  mounted() {
    // this.getinfo()
  },
  created() {
    diffOption(this.config.columns).then(res => {
      this.columns = res
    })
  },
  methods: {
    //下载
    bizDown() {
      if (this.selectedRows.length == 0) {
        this.$message.warn('请先选择数据')
        return
      }
      //   this.selectedRows.forEach()

      // 从 localstorage 获取 token
      const token = storage.get(ACCESS_TOKEN)
      this.selectedRows.forEach(item => {
        console.log(item)
        if (item.picFileurl) {
          bizFileDown({
            // directoryId: text.id,
            id: item.picFileurl,
            access_token: token
          }).then(res => {
            let blob = new Blob([res])
            let downloadElement = document.createElement('a')
            let href = window.URL.createObjectURL(blob) //创建下载的链接
            downloadElement.href = href
            downloadElement.download = item.picFileurl + '.jpg' //下载后文件名
            document.body.appendChild(downloadElement)
            downloadElement.click() //点击下载
            document.body.removeChild(downloadElement) //下载完成移除元素
            window.URL.revokeObjectURL(href) //释放掉blob对象
            this.iconLoading = false
          })
        } else {
          this.$message.warn('暂无图片')
        }
      })
    },

    //点击上传
    upload() {
      if (this.selectedRows.length == 0) {
        this.$message.warn('请先选择数据')
        return
      }
      this.lookats = false
      this.isUpload = true
      this.$nextTick(() => {
        this.$refs.imgForm.form.setFieldsValue({ ...this.rowRecord })
      })
    },
    //明细表 selectChange
    selectChange(selectedRowKeys, selectedRows) {
      this.selectedRows = selectedRows
    },
    //点击图片上传
    save() {
      let that = this
      //   console.log(this.uploadIdlist)
      let rowRecord = this.rowRecord
      let a = this.$refs.imgsUpload.getDataList()[0]
      if (!a) return
      a.picFileurl = a.id
      a.picFilename = a.name
      console.log(a)
      this.$refs.imgForm.form.validateFields(async (error, values) => {
        if (!error) {
          let b = that.selectedRows.map(item => {
            return {
              ...item,
              ...rowRecord,
              ...values,
              ...a
            }
          })
          console.log(b)
          try {
            let res = await update(b)
            console.log(res)
            if (res.success) {
              that.$message.success(res.message)
              that.$refs.tableDetail.reload({ params: { rcvHeaderId: that.rowRecord.rcvHeaderId } })
              that.remoteParams = { ...that.remoteParams }
              that.isUpload = false
              // this.remoteParams = { ...this.remoteParams };
            } else {
              this.$exception(res)
            }
          } catch (error) {
            that.$exception(error)
          }
        }
      })
    },
    //点击弹出
    showmodel(data) {
      let that = this
      console.log(data)
      this.uploadIdlist[0] = data.picFileurl
      console.log(this.uploadIdlist)
      this.lookats = true
      this.isUpload = true
      console.log(that.rowRecord)
      this.$nextTick(() => {
        this.$refs.imgForm.form.setFieldsValue({ ...that.rowRecord })
      })
    },
    handleUploadImgs(item, text, record) {
      console.log(item, text, record)
    },
    //主表点击正行
    clickRow(event, activeID, rowRecord) {
      console.log(rowRecord.rcvHeaderId)
      this.rowRecord = rowRecord
      this.$refs.tableDetail.reload({ params: { rcvHeaderId: rowRecord.rcvHeaderId } })
      //   this.DetailremoteParams = { ...this.DetailremoteParams, rcvHeaderId: rowRecord.rcvHeaderId }
    },
    doneBefore(res) {
      res.data.list.forEach(item => {
        item.id = item.areaNo
      })
      console.log(res)
      return res
    },
    hanlderSubmit(e, form) {
      e.preventDefault()
      form.validateFields((error, values) => {
        if (!error) {
          console.log(error, values, 'valuesvaluesvaluesvaluesvalues')
          this.remoteParams = { ...this.remoteParams, params: { ...values } }
        }
      })
    },
    handleOk(e) {
      console.log(this.$refs.model)
      this.$refs.model.form.validateFields(async (err, value) => {
        if (!err) {
          console.log(value)
          this.confirmLoading = true
          if (this.type) {
            let res = await update(value)
            console.log(res)
            if (res.success) {
              this.visible = false
              this.$message.success(res.message)
              this.remoteParams = { ...this.remoteParams }
            } else {
              this.$exception(res)
              this.visible = false
            }
          } else {
            let res = await add(value)
            console.log(res)

            if (res.success) {
              this.$message.success(res.message)
              this.visible = false
              this.remoteParams = { ...this.remoteParams }
            } else {
              this.$exception(res)
              this.visible = false
            }
          }

          this.confirmLoading = false
          //
        }
      })
    },
    handleCancel(e) {
      console.log('Clicked cancel button')
      this.visible = false
    },

    del() {
      if (this.selectedRows.length == 0) {
        this.$message.warn('请先选择数据')
        return
      }
      let that = this
      //   console.log(text)
      this.$confirm({
        title: '确定是否要删除?',
        content: '',
        async onOk() {
          let res = await deletes(that.selectedRows)
          if (res.success) {
            that.$message.success('删除成功')
            that.remoteParams = { ...that.remoteParams }
            that.$refs.tableDetail.reload({ params: { rcvHeaderId: rowRecord.rcvHeaderId } })
          } else {
            that.$exception(res)
          }
        },
        onCancel() {}
      })
    }
  }
}
</script>

<style lang="less" scoped></style>
