<template>
  <div style="display: flex; flex-direction: column">
    <el-button size="small" style="margin-left: auto; margin-right: 15px" type="primary" icon="el-icon-bottom-right" @click="onSubmit">登记</el-button>
    <el-form :model="inputQuery" :rules="formRules" ref="dataForm" label-width="150px" style="padding-top: 40px">
      <el-card style="margin-top: -30px">
        <el-row>
          <el-col :span="20">
            <el-form-item prop="code" label="请扫入发票二维码:">
              <el-input
                id="inputer"
                @focus="getInputFocus($event)"
                @keypress.enter.native="enterKey($event)"
                ref="inputRef"
                style="ime-mode: disabled"
                type="password"
                v-model="inputQuery.code"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="机器编码:" prop="machineNo">
              <el-input
                v-model="inputQuery.machineNo"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="发票代码:" prop="invoiceCode">
              <el-input
                v-model="inputQuery.invoiceCode"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="发票编码:" prop="invoiceEncode">
              <el-input
                v-model="inputQuery.invoiceEncode"
                :disabled="this.list.length>0"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="发票价格:" prop="price">
              <el-input
                v-model="inputQuery.price"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="开票日期:" prop="invoiceDate">
              <el-date-picker
                v-model="inputQuery.invoiceDate"
                type="datetime"
                placeholder="请选择日期"
                clearable
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="备注:" prop="remark">
              <el-input
                v-model="inputQuery.remark"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="文件:">
              <el-upload
                :disabled="formData.auditStatus == 1"
                class="upload-demo"
                ref="upload"
                :action="this.uploadUrl"
                :on-preview="uploadHandlePreview"
                :on-remove="uploadHandleRemove"
                :limit="1"
                :headers="headers"
                :on-exceed="uploadHandleExceed"
                accept=".jpg,.png,.pdf,.doc"
                :on-change="uploadOnchange"
                :on-success="uploadHandleSuccess"
                :on-error="uploadHandleError"
                :file-list="fileList"
                :data="{ type: 'image2' }"
                :auto-upload="true"
              >
                <el-button
                  slot="trigger"
                  size="small"
                  type="primary"
                  :disabled="formData.auditStatus == 1"
                >
                  {{ choiceFile }}
                </el-button>
                <div>只能上传 jpg,png,pdf,doc 文件，且不超过 10 MB</div>
              </el-upload>
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item
              label="文件预览:"
              v-if="this.inputQuery.licenseUrl != null"
            >
              <el-button
                type="success"
                size="mini"
                icon="search"
                v-if="this.inputQuery.licenseUrl != null"
                style="text-align: right"
                @click="showImgViewer"
              >
                文件预览
              </el-button>
            </el-form-item>
            <el-image-viewer
              v-if="imgViewerVisible"
              style="z-index: 9999"
              :on-close="closeImgViewer"
              :url-list="imgList"
            />
          </el-col>
        </el-row>
      </el-card>
    </el-form>

    <el-tabs type="border-card" style="margin: 15px">
      <!--单据业务详情-->
      <el-button-group style="display: flex">
        <el-button type="primary" size="small" @click.native.stop="selectOrderFunction()"
                   style="margin: 0px 0px 10px auto; height: 35px" :loading="loading"
        >选择单据
        </el-button>
      </el-button-group>
      <el-table v-loading="loading"  @current-change="handleSelectionChange" :data="list" style="width: 100%" highlight-current-row border>
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column label="单据号" prop="billNo" show-overflow-tooltip width="180"></el-table-column>
        <el-table-column label="单据类型" prop="billTypeName" width="150"></el-table-column>
        <el-table-column label="送货单位" prop="fromName" width="220" v-if="showSup"></el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="150" show-overflow-tooltipsortable="custom"
                         :sort-orders="['ascending', 'descending']"
        ></el-table-column>
        <el-table-column label="审核时间" prop="auditTime" width="150" show-overflow-tooltip sortable="custom"
                         :sort-orders="['ascending', 'descending']"
        ></el-table-column>
        <el-table-column label="采购部门" prop="deptName" width="120" v-if="enableDept"></el-table-column>
        <el-table-column label="收货仓库" prop="invName" width="120"></el-table-column>
        <el-table-column label="来源单号" prop="corpOrderId" show-overflow-tooltip width="180"></el-table-column>
        <el-table-column label="总金额" prop="allAmount" width="120"></el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template slot-scope="scope">
            <el-button type="text"   size="small" @click.native.stop="delectSub(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="filterQuery.page"
        :limit.sync="filterQuery.limit"
        @pagination="getCodeDetailLists"
      />
    </el-tabs>


    <!--单据业务详情-->
    <el-tabs type="border-card" style="margin: 15px">
      <!--单据业务详情-->
      <el-tab-pane>
        <span slot="label">单据 {{ currentRow.billNo }}-单据详情</span>
        <el-table :data="codeDetailList" style="width: 100%" border row-key="id" highlight-current-row>
          <el-table-column label="序号" type="index"></el-table-column>
          <el-table-column label="发票编码" prop="invoiceCodes" width="150" show-overflow-tooltip></el-table-column>
          <el-table-column label="物资名称" prop="coName" width="150" show-overflow-tooltip></el-table-column>
          <el-table-column label="规格型号" width="150" prop="spec"></el-table-column>
          <el-table-column label="批次号" width="100" prop="batchNo"></el-table-column>
          <el-table-column label="数量" prop="count" width="100"></el-table-column>
          <el-table-column label="价格" prop="price" width="100"></el-table-column>
          <el-table-column label="金额" prop="amount" width="100"></el-table-column>
          <el-table-column label="生产日期" prop="productDate" width="100"></el-table-column>
          <el-table-column label="失效日期" prop="expireDate" width="100"></el-table-column>
          <el-table-column width="100" label="计量单位" prop="measname"></el-table-column>
          <el-table-column label="生产企业" prop="manufacturer" width="160" show-overflow-tooltip></el-table-column>
          <el-table-column label="注册/备案号" width="160" prop="certCode" show-overflow-tooltip></el-table-column>
          <el-table-column label="扫码数量" prop="reCount" width="100"></el-table-column>
        </el-table>
        <pagination
          v-show="codeTotal>0"
          :total="codeTotal"
          :page.sync="codeQuery.page"
          :limit.sync="codeQuery.limit"
          @pagination="getCodeDetailList"
        />
      </el-tab-pane>
    </el-tabs>

    <el-image-viewer
      v-if="imgViewerVisible"
      style="z-index: 9999"
      :on-close="closeImgViewer"
      :url-list="imgList"
    />


    <el-dialog
      title="选入单据"
      :visible.sync="invoiceSelectRegByOrderVisible"
      width="80%"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      v-if="invoiceSelectRegByOrderVisible"
    >
      <invoiceSelectRegByOrder
        :closeDialog="closeAcceptDialog"
        :inputQuery="inputQuery"
      ></invoiceSelectRegByOrder>
    </el-dialog>


  </div>
</template>

<script>
import {
  filterListInvoice,
  getBizDetailList,
  deleteById,
  insertInvoice,
  uploadInvoice,
  updateOrder,
  filterBizOrderList,
  updateorderBiz, parseInvoice, deleteInvoiceByOrderFk,checkInvoiceCode
} from '@/api/inout/orderDetailBiz'
import AcceptOrder from '@/views/inout/DialogReviewOrder'
import DialogInvoice from '@/views/inout/DialogInvoice'
import InvoiceRegister from '@/views/inout/InvoiceRegister'
import { previewImage, previewFile } from '@/api/purchase/supCompany'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
import store from '@/store'
import invoiceSelectRegByOrder from '@/views/inout/InvoiceSelectRegByOrder'
import { filterInvoiceList } from '@/api/inout/order'
import { isBlank } from '@/utils/strUtil'

const formJson = {
  site_id: '',
  site_name: '',
  describe: '',
  ads: []
}

export default {
  name: 'checkInvoice',
  props: {
    closeDialog: {
      type: Function,
      required: true
    },
    curInvoice: {
      type: Object,
      required: true
    },
  },
  data() {
    return {
      invoiceSelectRegByOrderVisible: false,
      idList: [],
      invoiceRow: [],
      statusCode: null,
      choiceFile: '选取文件',
      fileList: [],
      headers: {},
      uploadUrl: '',
      inputQuery: {
        ggxh: null,
        cpmctymc: null,
        machineNo: null,
        invoiceCode: null,
        invoiceEncode: null,
        price: null,
        invoiceDate: null,
        remark: null,
        licenseUrl: null
      },
      imgList: [],
      imgViewerVisible: false,
      BASE_URL: process.env.VUE_APP_BASE_API,
      showSearch: true,
      filterQuery: {
        id: '',
        billNo: null,
        mainAction: null,
        action: null,
        page: 1,
        supInoivceSearch: 'supInvoice',
        limit: 10,
        startTime: null,
        endTime: null,
      },

      corpLoading: false,
      fromOptions: [],
      invoiceLoading: false,
      formName: 1,
      formMap: {
        1: '发票登记'
      },
      formRules: {
        // machineNo: [
        //   { required: true, message: "请输入机器编码", trigger: "blur" },
        // ],
        // invoiceCode: [
        //   { required: true, message: "请输入发票代码", trigger: "blur" },
        // ],
        invoiceEncode: [
          { required: true, message: '请输入发票编码', trigger: 'blur' }
        ],
        price: [{ required: true, message: '请输入发票价格', trigger: 'blur' }],
        invoiceDate: [{ required: true, message: '请选择开票日期', trigger: 'blur' }]
      },
      certFileUrl: '',
      Upinvoice: false,
      currentManufacturer: {},
      InvoiceRegisterv: false,
      checkStatus: {
        1: '草稿',
        2: '等待处理',
        3: '等待校验',
        4: '处理异常',
        5: '待核对',
        6: '校验异常',
        7: '已审核',
        8: '审核拒绝',
        9: '正在处理',
        10: '待审核'
      },
      storageList: [],
      invList: [],
      deptList: [],
      list: [],
      total: 0,
      loading: false,
      index: null,
      enableDept: false,
      showSup: false,

      fromTypeMap: {
        1: 'UDIMS平台',
        2: '网页新增',
        3: 'pda即时校验',
        4: 'pda未校验',
        5: 'pc端扫码精灵',
        6: '流转自动补单',
        7: 'UDI管理系统',
        8: '平衡补录单据',
        10: '手动补单',
        11: '仓库盘点',
        12: '采购计划',
        13: '领用单据',
        14: '第三方系统单据'
      },
      deleteData: {
        id: '',
        status: 10
      },
      dialogTableVisible: false,
      formLoading: false,
      dialogVisible: false,
      formData: formJson,
      deleteLoading: false,
      busTypes: [],
      currentRow: {
        billNo: ''
      },
      actDateRange: [],
      auditDateRange: [],
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      bizQuery: {
        productName: null,
        orderIdFk: null,
        page: 1,
        limit: 10
      },
      bizTotal: 0,
      invTotal: 0,
      bizDetailLoading: false,
      bizDetailList: [],
      codeQuery: {
        orderIdFk: null,
        page: 1,
        limit: 10
      },
      codeTotal: 0,
      codeDetailLoading: false,
      codeDetailList: [],
      resultQuery: {
        orderId: null,
        code: null,
        page: 1,
        limit: 10
      },
      resultTotal: 0,
      resultDetailLoading: false,
      resultDetailList: [],
      acceptQuery: null,
      acceptOrderVisible: false,
      subRow: null
    }
  },
  components: { AcceptOrder, DialogInvoice, InvoiceRegister, ElImageViewer, invoiceSelectRegByOrder },
  methods: {
    onSubmit() {
      if (this.list == null || this.list.length==0) {
        this.$message.error('请选择要登记的物资! ')
        return false
      }
      if (this.$isBlank(this.inputQuery.invoiceEncode)) {
        this.$message.error('发票编码不能为空！')
        return
      }
      if (this.$isBlank(this.inputQuery.price)) {
        this.$message.error('发票价格不能为空！')
        return
      }
      if (this.$isBlank(this.inputQuery.invoiceDate)) {
        this.$message.error('日期不能为空！')
        return
      }
      let mount = 0
      for (var i = 0; i < this.list.length; i++) {
        mount += this.list[i].allAmount
      }
      if (mount != this.inputQuery.price) {
        this.$confirm('价格不匹配，是否确定提交?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.postInvoice()
          })
          .catch(() => {
          })
        return
      } else {
        this.postInvoice()
      }

    },

    postInvoice() {
      uploadInvoice(this.inputQuery)
        .then((response) => {
          if (response.code === 20000) {
            this.statusCode = response.code
            this.closeDialog()
          } else {
            this.$message.error(response.message)
          }
        })
        .catch((response) => {
          this.$message.error(response.message)
        })

      // 加状态
      updateorderBiz(this.inputQuery.list).then((res) => {
        this.closeDialog()
      })
    },

    getInputFocus(event) {
      event.currentTarget.select()
    },

    enterKey() {
      let param = {
        code: this.inputQuery.code
      }
      parseInvoice(param)
        .then((res) => {
          if (res.code == 20000) {
            this.inputQuery = res.data
          }
        })
    },

    uploadHandleError() {
    },
    uploadHandleSuccess(response, file, fileList) {
      if (response.code === 20000) {
        this.inputQuery.licenseUrl = response.data.name
        // this.onSubmit();
      } else {
        this.$message.error('文件上传失败：' + response.message)
      }
    },
    uploadOnchange(file, fileList) {
      let fileName = file.name
      let uid = file.uid
      let pos = fileName.lastIndexOf('.')
      let lastName = fileName.substring(pos, fileName.length)
      if (
        lastName.toLowerCase() !== '.jpg' &&
        lastName.toLowerCase() !== '.png' &&
        lastName.toLowerCase() !== '.doc' &&
        lastName.toLowerCase() !== '.pdf'
      ) {
        this.$message.error('上传文件只能是 jpg,png,doc,pdf 格式')
        for (let i = 0; i < fileList.length; i++) {
          //从list删除
          if (fileList[i].uid === uid) {
            fileList.splice(i, 1)
          }
        }
        return
      }
      // 限制上传文件的大小
      const isLt = file.size / 1024 / 1024 / 30 <= 1
      if (!isLt) {
        this.$message.error('上传文件大小不能超过 30MB')
        for (let i = 0; i < fileList.length; i++) {
          if (fileList[i].uid === uid) {
            fileList.splice(i, 1)
          }
        }
      }
      return isLt
    },
    uploadHandleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      )
    },
    uploadHandlePreview(file) {
      console.log(file)
      console.log(this.fileList)
    },
    uploadHandleRemove(file, fileList) {
      this.inputQuery.licenseUrl = null
      console.log(file, fileList)
    },
    getOrderDetail() {
      this.codeQuery.page = 1
      this.getCodeDetailLists()
      this.codeDetailList=[]
      this.currentRow={
        billNo: ''
      }
      //this.getResultDetailList();
    },

    getCodeDetailLists() {
      this.filterQuery.invoiceEncode = this.inputQuery.invoiceEncode
      this.filterQuery.vueType = 'supInvoice'
      this.codeDetailLoading = true
      filterInvoiceList(this.filterQuery)
        .then((response) => {
          this.loading = false
          if (response.code === 20000) {
            this.list = response.data.list || []
            this.total = response.data.total || 0
          } else {
            this.$message.error(response.message)
          }
        })
        .catch((error) => {
          this.$message.error(error.message)
          this.loading = false
          this.list = []
          this.total = 0
        })
    },

    BizDetailInv(row) {
      this.bizQuery.page = 1
      this.getBizDetailList(row)
    },
    handleSelectionUdiChange(val) {
      this.invoiceRow = val
      //  this.$emit("upData",this.invoiceRow);
    },
    getBizDetailList(row) {
      this.bizQuery.orderIdFk = this.input.billNo
      if (row != null) {
        this.bizQuery.batchNo = row.batchNo
        this.bizQuery.relId = row.bindRlFk
      }
      filterListInvoice(this.bizQuery)
        .then((res) => {
          this.bizDetailLoading = false
          if (res.code === 20000) {
            this.bizDetailList = res.data.list || []
            this.invTotal = res.data.total || 0
          } else {
            this.$message.error(res.message)
            this.bizDetailList = []
            this.invTotal = 0
          }
        })
        .catch((error) => {
          this.bizDetailLoading = false
          this.$message.error(error.message)
          this.bizDetailList = []
          this.invTotal = 0
        })
    },

    determineBtn() {
      var data = {
        billNo: this.input.billNo,
        checkStatus: 1
      }
      updateOrder(data)
        .then((res) => {
          this.closeDialog()
        })
        .catch((error) => {
        })
    },
    showImgViewer(row) {
      this.certFileUrl =
        this.BASE_URL +
        '/udiwms/image/register/file/getImage?type=image2&name=' + this.inputQuery.licenseUrl
      this.imgList = []
      this.imgList.push(this.certFileUrl)
      let index = this.inputQuery.licenseUrl.lastIndexOf('.')
      if (index === -1) {
        this.$message.error('文件名异常!')
        return false
      }
      if (this.inputQuery.licenseUrl.substr(index + 1) === 'pdf') {
        let pdf = 'application/pdf'
        let binaryData = []
        previewFile(this.certFileUrl).then(res => {
          binaryData.push(res)
          let URL = window.URL.createObjectURL(new Blob(binaryData, { type: pdf }))
          window.open(URL)
        })
        // window.open(this.imgList[0])
        return false
      }
      this.imgViewerVisible = true
      const m = (e) => {
        e.preventDefault()
      }
      document.body.style.overflow = 'hidden'
      document.addEventListener('touchmove', m, false) // 禁止页面滑动
    },

    closeImgViewer() {
      this.imgViewerVisible = false
      const m = (e) => {
        e.preventDefault()
      }
      document.body.style.overflow = 'auto'
      document.removeEventListener('touchmove', m, true)
    },
    /**         -------------------------------------------------后续加的js-------------------------------------------------------------           */
    /**    * 选入单据页面    */
    selectOrderFunction() {
      if (this.$isBlank(this.inputQuery.invoiceEncode)) {
        this.$message.error('发票编码不能为空！')
        return
      }
      if(this.list.length==0){
        //查询发票编码有没有重复
        checkInvoiceCode({invoiceEncode:this.inputQuery.invoiceEncode})
            .then((response) => {
              if (response.code === 20000) {
                this.invoiceSelectRegByOrderVisible = true
              } else {
                this.$message.error(response.message)
              }
            })
            .catch((response) => {
              this.$message.error(response.message)
            })
      }else{
        this.invoiceSelectRegByOrderVisible = true
      }
    },
    closeAcceptDialog(){
      this.invoiceSelectRegByOrderVisible = false
       this.getCodeDetailLists()
    },
    delectSub(row){
      deleteInvoiceByOrderFk({billNo:row.billNo,invoiceEncode:this.inputQuery.invoiceEncode})
        .then((response) => {
          if (response.code === 20000) {
            this.getOrderDetail();
          } else {
            this.$message.error(response.message)
          }
        })
        .catch((response) => {
          this.$message.error(response.message)
        })

    },
    handleSelectionChange(val) {
      this.currentRow.billNo = val.billNo
      this.getOrderDetails()
    },
    getOrderDetails() {
      this.codeQuery.page = 1
      this.getCodeDetailList()
    },
    getCodeDetailList() {
      if (isBlank(this.currentRow.billNo)) {
        this.$message.error('请先选择需要查询的单据！')
        return
      }
      this.codeQuery.orderIdFk = this.currentRow.billNo
      this.codeDetailLoading = true
      this.codeDetailList = []
      filterBizOrderList(this.codeQuery).then((res) => {
        this.codeDetailLoading = false
        if (res.code === 20000) {
          this.codeDetailList = res.data.list || []
          this.codeTotal = res.data.total || 0
        } else {
          this.$message.error(res.message)
          this.codeDetailList = []
          this.codeTotal = 0
        }
      }).catch((error) => {
        this.codeDetailLoading = true
        this.$message.error(error.message)
        this.codeDetailList = []
        this.codeTotal = 0
      })
    },

  },
  created() {
    this.uploadUrl = this.BASE_URL + '/udiwms/upload/register/file'
    this.headers = {
      ADMINID: store.getters.adminId,
      ADMINTOKEN: store.getters.token
    }
    if(this.curInvoice.id!=null){
      this.inputQuery=this.curInvoice
       this.getOrderDetail();
    }
  }
}
</script>

<style type="text/scss" lang="scss"></style>
