<template>
  <div class="page-box" v-loading="Loading.appMainLoading">
    <tablePagination
      :currenButtonData="currenButtonData"
      :tableData="tableData"
      :tableLoading="Loading.tableLoading"
      :tableColumns="tableColumns"
      @rowDrop="rowDrop"
      :totalCount="totalCount"
      :multipleSelection="multipleSelection"
      :MaxResultCount="PageListParams.MaxResultCount"
      @topbutton="topbutton"
      @inlineDialog="inlineDialog"
      @sortChange="sortChange"
      @alertoldSkipCount="alertoldSkipCount"
      @alterResultCount="alterResultCount"
      @handleSelectionChange="handleSelectionChange"
      @buttonOperationClick="buttonOperationClick"
      :currentPageProps="oldSkipCount"
      :quicklySearchOption="quicklySearchOption"
      @quicklySearchClick="quicklySearchClick"
      @quicklySearchClear="quicklySearchClear"
      :primarySearchOption="primarySearchOption"
      @overallSearchFormClick="overallSearchFormClick"
      :httpOverallSearchData="httpOverallSearchData"
    >
    </tablePagination>
    <!-- 新增与编辑 -->
    <newAndEdiDialog
      :loading="Loading.newAndEdiLoading"
      :active="active"
      :pageStatus="pageStatus"
      :formReveal="formReveal"
      :formTitle="formTitle"
      :displayDialog="editDialog"
      :FormData="formReveal ? CreateFormData : editFormData"
      :Form="formReveal ? CreateForm : editForm"
      :Options="editOptions"
      :Handle="editHandle"
      :Rules="formReveal ? editRules.cerateRule : editRules.editRule"
      @push="push"
      @FormSubmit="FormSubmit"
      @close="FormClose"
      @goBack="goBack"
    ></newAndEdiDialog>
    <!-- 搜索按钮——窗体组件 -->
    <searchPage
      ref="searchTable"
      :tableLoading="Loading.autoTableLoading"
      :advancedFilter="advancedFilter()"
      :filterPageListParams="filterPageListParams"
      :formTitle="searchTitle"
      :displayDialog="displayDialog.AddNewDialog"
      :searchTableData="searchData"
      :searchTableColumns="searchColumns"
      :searchTotalCount="searchTotalCount"
      :supplierItemPage="searchPageListParams"
      @handleSelectionChange="prepareFormData"
      @SizeChange="searchAlterResultCount($event, searchPageListParams)"
      @CurrentChange="searchAlertoldSkipCount($event, searchPageListParams)"
      @tableButtonClick="searchSubmit(arguments)"
    ></searchPage>
    <!--抽屉-->
    <curren-Drawer
      :title="tableColumns"
      :DrawerLoading="Loading.DrawerLoading"
      :drawer="displayDialog.detailsDialog"
      :dropdownData="dropdownData"
      :propsData="propsData"
      :tabsDesTions="tabsDesTions"
      :tableLoading="tableLoading"
      :column="1"
      direction="vertical"
      @drawerShut="(val) => (displayDialog.detailsDialog = val)"
      @drawerbutton="drawerbutton"
      @handleCommand="drawerHandle"
      @close-value="closeValue"
    ></curren-Drawer>
  </div>
</template>
<script>
import { postCreate ,postUpdate , fileStorageCreate, fileStorage } from '@/api/wms-api'
import { tableMixins } from "@/mixins/TableMixins"
import { LoadingMixins } from "@/mixins/LoadingMixins"
import { drawerMixins } from "@/mixins/drawerMixins"
import { TableHeaderMixins } from "@/mixins/TableHeaderMixins"
import { newAndEdiDialogMixins } from "@/mixins/newAndEdiDialogMixins"
import { mixins } from "@/mixins/mixins"
import { filterSelectMixins } from '@/mixins/filter-Select'

export default {
  name: "ItemGuideBook",
  mixins: [
    tableMixins,
    LoadingMixins,
    drawerMixins,
    TableHeaderMixins,
    mixins,
    filterSelectMixins,
    newAndEdiDialogMixins
  ],
  computed: {
    editDialog: {
      get: function () {
        return this.displayDialog.newDialog || this.displayDialog.editDialog;
      },
    },
  },
  data () {
    return {
      URL: 'basedata/item-guide-book',
      tableLoading:false,
      //常用按钮数据
      currenButtonData: [
        this.defaultAddBtn(),//新增
        this.defaultFieldSettingBtn(),//字段设置
        this.defaultFreshBtn(),//刷新
        this.defaultFilterBtn(),//筛选
      ],
      //新增
      CreateFormData: {
        itemCode: null,
        itemName: null,
        itemDesc1: null,
        itemDesc2: null,
        status: 1,
        abcClass: null,
        canMake: true,
        canBuy: true,
        validity: 0,
        validityUnit: 9,
        company: null,
        warehouseCode: null,
        pictureBlobName: null,
        step: null,
        formFile:[],
        remark:null,
      },
      //编辑
      editFormData: {
        itemCode: null,
        itemName: null,
        itemDesc1: null,
        itemDesc2: null,
        status: 1,
        abcClass: null,
        canMake: true,
        canBuy: true,
        validity: 0,
        validityUnit: 9,
        company: null,
        warehouseCode: null,
        pictureBlobName: null,
        step: null,
        formFile:[],
        concurrencyStamp: null,
        remark:null,
      },
      editOptions: {},
      CreateForm: [
        { type: "filterSelect", label: "物料代码", prop: "itemCode", optionsLabel: "name", optionsValue: "code", 
          focus: (type,val) => { return this.getFilterList(type, val, "basedata/Item-Basic")},
          searchButton: (val) => { this.showSerarchPage(val, 'basedata/Item-Basic', 'ItemBasic', '物料选择', this.CreateFormData) }, colSpan: 12 },
        { type: "input", label: "物料名称", prop: "itemName", disabled: true, colSpan: 12 },
        { type: "uploadPictureCard", label: "图片", prop: "formFile", limit: 1, picExt: ".png,.jpg", colSpan: 12 },
        { type: "textarea", label: "步骤", prop: "step", rows: 5, maxlength: 1000, colSpan: 24 },
        { type: "input", label: "备注", prop: "remark", colSpan: 24 },
      ],
      editForm: [
        { type: "input", label: "物料代码", prop: 'itemCode', disabled: true, colSpan: 12 },
        { type: "input", label: "物料名称", prop: "itemName", disabled: true, colSpan: 12 },
        { type: "uploadPictureCard", label: "图片", prop: "formFile", limit: 1, picExt: ".png,.jpg", colSpan: 12 },
        { type: "textarea", label: "步骤", prop: "step", rows: 5, maxlength: 1000, colSpan: 24 },
        { type: "input", label: "备注", prop: "remark", colSpan: 24 },
      ],
      editRules: {
        cerateRule: {
          itemCode: [{ required: true, trigger: "blur", message: "不可为空" }],
          formFile: [{ required: true, trigger: "blur", message: "不可为空" }],
        },
        editRule: {
          itemName: [{ required: true, trigger: "blur", message: "不可为空" }],
        }
      },
    };
  },
  mounted () {
    this.paging();
  },
  methods: {
    //抽屉常用按钮——编辑数据，需要图片回显，在此特殊处理
    drawerbutton(val) {
      if (val == "edit") {
        this.formTitle = this.$route.meta.title + "编辑";
        this.formReveal = false
        this.theEvent = "edit"
        this.Loading.newAndEdiLoading = true
        this.displayDialog.editDialog = true
        const listAssign = (arr1, arr2) => {
          Object.keys(arr1).forEach(item => {
            arr1[item] = arr2[item]
          })
        }
        listAssign(this.editFormData, this.propsData)
        if (this.editFormData.pictureBlobName != '' && this.editFormData.pictureBlobName != null) {
          fileStorage({blobName: this.editFormData.pictureBlobName}).then(res => {
            var byteString = atob(res.bytes)
            var arrayBuffer = new ArrayBuffer(byteString.length) // 创建缓冲数组
            var intArray = new Uint8Array(arrayBuffer) // 创建视图
            for (var i = 0; i < byteString.length; i++) {
              intArray[i] = byteString.charCodeAt(i)
            }
            const blob = new Blob([intArray], { type: '' })
            let file = ''
            this.editFormData.formFile = [{
              name: res.fileName,
              raw: file,
              size: blob.size,
              url: window.URL.createObjectURL(blob)
            }]
            this.Loading.newAndEdiLoading = false
          }).catch(err => {
            this.Loading.newAndEdiLoading = false
            console.log(err)
          })
        }
      }
    },
    // input下拉框 其他赋值处理
    push(val) {
      if (val[1].prop == "itemCode") {
        this.CreateFormData.itemName = val[0].name
        this.CreateFormData.itemDesc1 = val[0].desc1
        this.CreateFormData.itemDesc2 = val[0].desc2
      }
    },
    // 新增提交
    FormSubmit(val) {
      let that = this
      // 文件上传到服务器
      that.Loading.newAndEdiLoading = true;
      let rd = new FileReader(); // 创建文件读取对象
      switch (that.formReveal) {
        case true:
          // 调用
          that.objectURLToBlob(that.CreateFormData.formFile[0].url, function (blob) {
              const file = new window.File([blob], that.CreateFormData.formFile[0].name, {type: blob.type});
              rd.readAsDataURL(file)
              rd.onloadend = function(){
                var arrayBuffer = rd.result
                let params = {
                  fileName: that.CreateFormData.formFile[0].name,
                  bytes: arrayBuffer.substring(arrayBuffer.indexOf(',') + 1, arrayBuffer.length)
                }
                fileStorageCreate(params).then( createRes => {
                  that.CreateFormData.pictureBlobName =  createRes
                  // 创建作业指导书接口
                  postCreate(that.CreateFormData, that.URL).then(res => {
                    that.Loading.newAndEdiLoading = false
                    that.FormResult("success")
                  }).catch(err => {
                    that.Loading.newAndEdiLoading = false
                    that.FormResult("error")
                  })
                }).catch(err => {
                  that.Loading.newAndEdiLoading = false
                  console.log(err)
                })
              }
          })
          break;
        case false:
          // 调用
          that.objectURLToBlob(that.editFormData.formFile[0].url, function (blob) {
              const file = new window.File([blob], that.editFormData.formFile[0].name, {type: blob.type});
              rd.readAsDataURL(file)
              rd.onloadend = function(){
                var arrayBuffer = rd.result
                let params = {
                  fileName: that.editFormData.formFile[0].name,
                  bytes: arrayBuffer.substring(arrayBuffer.indexOf(',') + 1, arrayBuffer.length)
                }
                fileStorageCreate(params).then( createRes => {
                  that.editFormData.pictureBlobName =  createRes
                  postUpdate(that.editFormData, that.propsData.id, that.URL).then(res => {
                    that.propsData = res
                    that.Loading.newAndEdiLoading = false
                    that.FormResult("success")
                  }).catch(err => {
                    that.Loading.newAndEdiLoading = false
                    that.FormResult("error")
                  })
                }).catch(err => {
                  that.Loading.newAndEdiLoading = false
                  console.log(err)
                })
              }
          })
      }
    },
    /**
     * BlobUrl转blob数据  
     * @param {Object} url blob URL
     * @param {Object} callback 回调函数
     */
    objectURLToBlob(url, callback) {  
        const http = new XMLHttpRequest();  
        http.open("GET", url, true);  
        http.responseType = "blob";  
        http.onload = function (e) {  
            if (this.status == 200 || this.status === 0) {  
                callback(this.response);
            }  
        };  
        http.send();
    },
  },
};
</script>
<style lang="scss" scoped>
@import "../../../styles/basicData.scss";
</style>