<template>
  <div style="padding: 0 20px">

    <div ref="lxHeader">
      <lx-header icon="md-apps" text="库存管理" style="margin-bottom: 10px; border: 0px; margin-top: 15px">
        <slot>
          <div style="display: flex;justify-content: flex-start;flex-wrap: wrap;">
            <Input v-model="select.keyword" style="width: 200px;margin-right: 10px;" placeholder="关键字搜索" />
            <Button type="primary" @click="getindex">查询</Button>
            <Button type="primary" style="margin-left: 10px;"
              @click="toprint">打印</Button>
           <Button type="primary" style="margin-left: 10px;"
              @click="exportExcel(new Date().getTime().toString())">导出</Button>


          </div>
        </slot>
      </lx-header>
    </div>

    <xy-table :list="list" :total="total" @selection-change="selectionChange" @pageSizeChange="e => select.pageSize = e" @pageIndexChange="pageChange"
      :table-item="table" :auths='[]'>
      <template v-slot:btns>
        <div></div>
       <!-- <el-table-column fixed="right" label="操作" width="260" header-align="center">
          <template slot-scope="scope">
            <Button type="primary" size="small" @click="editorRuku(scope.row.id,'editor')">编辑</Button>
            <Button type="primary" size="small" @click="editorActivity(scope.row.id,'editor')">编辑</Button>
             <Button style="margin-left: 10px;" type="primary" size="small" @click="checkActivity(scope.row.id)">审核</Button>
            <Button type="primary" size="small" style="margin-left: 10px;" @click="editorActivity(scope.row.id,'copy')">复制新增</Button>
            <Poptip transfer confirm title="确认要删除吗？" @on-ok="deleteRuku(scope.row)">
              <Button type="primary" style="margin-left: 10px;" size="small" ghost>删除</Button>
            </Poptip>
          </template>
        </el-table-column> -->
      </template>

    </xy-table>
    <!-- <addRuku ref="addRuku" @refresh="getindex"></addRuku> -->
    <div class="code" v-if="showcode" @click="closeCode">
      <div id="qrCode" ref="qrCodeDiv"></div>
    </div>



    <imports :table-name="customForm.tableName" :form-info="form" ref="imports" @refresh="getindex"></imports>

  </div>
</template>

<script>
  import {
    index,
    destroy
  } from "@/api/system/baseForm.js"
  // import addRuku from "./component/addRuku.vue"
  import QRCode from 'qrcodejs2';
  import {
    Message
  } from 'element-ui'
  import imports from "@/views/component/imports.vue"
  import { index as fieldIndex } from "@/api/system/customFormField";
  import { getparameter } from "@/api/system/dictionary";
  import * as XLSX from "xlsx";
  import { saveAs } from "file-saver";
  import Cookies from 'js-cookie'
  export default {
    components: {
      imports
    },
    data() {
      return {
        select: {
          pageSize: 10,
          pageIndex: 1,
          keyword: "",
          is_export:0
        },
        showcode:false,
      customForm: {
        customFormId: "",
        tableName: ""
      },
      form:[],
        total: 0,
        list: [],
        table: [
          {
            type:'selection'
          },{
          label:'序号',
          type:'index',
          fixed:'left',
          width:80,
        },
        {
          label: "物资编码",
          width: 180,
          prop: 'wuzibianma',
          align: 'center'
        },
        {
          label: "资产名称",
          prop: 'zichanmingcheng',
          align: 'center'
        },
          {
            label: "物资类型",
            width: 120,
            prop: 'wuzileixing',
            align: 'center'
          },
          {
            label: "计量单位",
            width: 120,
            prop: 'jiliangdanwei',
            align: 'center'

          },
          {
            label: "入库数量",
            width: 120,
            prop: 'rukushuliang'
          },
          {
            label: "在库数量",
            width: 120,
            prop: 'zaikushuliang'
          },
          {
            label: "入库批次",
            width: 120,
            prop: 'rukupici'
          },
          {
            label: "所在仓库",
            width: 180,
            prop: 'suozaicangku'
          },
          {
            label: "所在货架",
            width: 180,
            prop: 'suozaihuojia'
          },
          // {
          //   label: "二维码",
          //   width: 180,
          //   prop: 'erweima',
          //   customFn: (row) => {
          //     return (<Button type='primary' size='small'
          //       on=
          //         {
          //           {
          //             ["click"]: (e) => (this.showCode(e, row))
          //           }
          //         }
          //     >生成二维码</Button>)
          //     }
          // },
        ],
        printObj:[],
        printArr:[]
      }
    },
    methods: {
      selectionChange(e){
        console.log(e)
        let _arrs = []
        if(e.length>0){
          for(var m of e){
            _arrs.push(m.id)
          }
          console.log(_arrs)
          // this.printObj = e
          this.printArr = _arrs.join(",")
        }


      },
      toprint(){
        if(this.printArr.length<1){
          Message({
            type: 'warning',
            message: '请先选择'
          })
          return
        }
        // let _obj = JSON.parse(JSON.stringify(this.printObj))
        // let _objs = []
        // for(var m of this.printObj){
        //   _objs.push({
        //     'wuzibianma':encodeURI(encodeURI(m['wuzibianma'])),
        //     'zichanmingcheng':encodeURI(encodeURI(m['zichanmingcheng'])),
        //     'wuzileixing':encodeURI(encodeURI(m['wuzileixing']))
        //   })
        // }
        // Cookies.remove('objs')
        // Cookies.set('objs',JSON.stringify(_objs))
        window.open('/admin/print.html?ids='+this.printArr,'_blank')
      },
      async exportExcel(sheetName) {
        const res = await index(Object.assign(this.select,{ page: 1,page_size: 9999,table_name: 'inventorys'}))
        if(res.data){
          let headers = this.form.map(i => {
            return {
              key: i.field,
              title: i.name
            }
          })
          const data = res.data.map(row => headers.map(header => row[header.key]));
          data.unshift(headers.map(header => header.title));
          const wb = XLSX.utils.book_new();
          const ws = XLSX.utils.aoa_to_sheet(data);
          XLSX.utils.book_append_sheet(wb, ws, sheetName);
          const wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' });
          saveAs(new Blob([wbout], { type: 'application/octet-stream' }), `${sheetName}.xlsx`);
        }
      },
      showCode(e,row){
        console.log(e,row)
        this.showcode = true
        this.$nextTick(function(){
          new QRCode(this.$refs.qrCodeDiv, {
            text: row.wuzibianma+'-'+row.id,
            width: 200,
            height: 200,
            colorDark: "#333333", //二维码颜色
            colorLight: "#ffffff", //二维码背景色
            correctLevel: QRCode.CorrectLevel.L//容错率，L/M/H
          })
        })


      },
      closeCode(){
        this.$refs.qrCodeDiv.innerHTML = ""
        this.showcode = false
      },
      async getindex() {
        const res = await index({
          page_size: this.select.pageSize,
          page: this.select.pageIndex,
          table_name: 'inventorys',
          // is_export:this.select.is_export,
          filter:[{"key":"zichanmingcheng","op":"like","value":this.select.keyword}],
        })
        this.list = res.data
        this.total = res.total
      },

      pageChange(e) {
        this.select.pageIndex = e
      },
      editorRuku(id,type){
        this.$refs['addRuku'].id = id
        this.$refs['addRuku'].isShow = true
        this.$refs['addRuku'].type = type
      },
      deleteRuku(row) {
        console.log(row.id)
        // return
        destroy({
          id: row.id,
          table_name:this.customForm.tableName
        }).then(res => {
          Message({
            type: 'success',
            message: '删除成功'
          })
          this.getindex()
        })
      },
      async getField() {
        if(this.$route.meta.params?.custom_form) {
          let decode = decodeURIComponent(this.$route.meta.params?.custom_form)
          try {
            let custom_form = JSON.parse(decode)
            this.customForm.customFormId = custom_form.custom_form_id
            this.customForm.tableName = custom_form.table_name
            console.log("123",this.customForm)
            // this.select.table_name = custom_form.table_name
          }catch (err) {
            console.warn(err)
          }
        }
        const res = await fieldIndex({
          page: 1,
          page_size: 999,
          custom_form_id: this.customForm.customFormId,
          sort_name: 'sort',
          sort_type: 'asc',
        })
        if(res.data && res.data instanceof Array) {
          res.data.forEach(i => {
            if (i.field) {
              if (
                (i.edit_input === "checkbox" || i.edit_input === "radio" || i.edit_input === "select") &&
                i.parameter_id
              ) {
                getparameter({ id: i.parameter_id }).then((res) => {
                  i._paramters = res.detail ?? [];
                });
              }
              if (
                (i.edit_input === "checkbox" || i.edit_input === "radio" || i.edit_input === "select") &&
                i.link_table_name
              ) {
                index({
                  page: 1,
                  page_size: 999,
                  table_name: i.link_table_name,
                }).then((res) => {
                  i._paramters = res.data ?? [];
                });
              }
            }
          })
        }
        this.form = res.data
      },
    },
    mounted() {
      this.getField()
      this.getindex()
    }

  }
</script>

<style scoped lang="scss">
  .code{
    position: absolute;
    left:0;
    top:0;
    background: rgba(0, 0, 0, 0.5);
    width:100%;
    height:100%;
    z-index:9999
  }
  #qrCode{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
  }

</style>
