<template>
  <div>

    <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;">
            <div class="selector-item">
              <span class="selector-item__label">物资编码：</span>
              <Input v-model="select.wzbm" style="width: 120px;margin-right: 10px;" placeholder="物资编码搜索" />
            </div>
            <div class="selector-item">
              <span class="selector-item__label">物资名称：</span>
              <Input v-model="select.keyword" style="width: 120px;margin-right: 10px;" placeholder="物资名称搜索" />
            </div>
            <div class="selector-item">
              <span class="selector-item__label">入库数量：</span>
              <Input v-model="select.rmin" clearable style="width: 60px;margin:0 3px" placeholder="" />
              <span class="selector-item__label">～</span>
              <Input v-model="select.rmax" clearable style="width: 60px;margin:0 3px" placeholder="" />
            </div>
            <div class="selector-item">
              <span class="selector-item__label">在库数量：</span>
              <Input v-model="select.min" clearable style="width: 60px;margin:0 3px" placeholder="" />
              <span class="selector-item__label">～</span>
              <Input v-model="select.max" clearable style="width: 60px;margin:0 3px" placeholder="" />
            </div>

            <Button type="primary" style="margin-left: 10px;" @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
      v-loading="loading"
      :span-method="objectSpanMethod"
      :list="list"
      :total="total"
      :table-item="table"
      :auths="[]"
      @selection-change="selectionChange"
      @pageSizeChange="pageSizeChange"
      @pageIndexChange="pageChange"
    >
      <!-- <template v-slot:caigouhetong>
       <el-table-column  align="left" label="采购合同" width="240" header-align="center">
          <template slot-scope="scope">
            <template v-if="scope.row.stocks && scope.row.stocks.length>0">
              <div v-for="item in scope.row.stocks">{{item.caigouhetong}}</div>
            </template>
          </template>
        </el-table-column>
     </template> -->
      <template v-slot:btns>
        <!-- <div></div> -->
        <el-table-column v-if="isPandian==='pandian' && (isCkName=='仓库管理员'||roleName=='系统管理员')" fixed="right" align="center" label="操作" width="120" header-align="center">
          <template slot-scope="scope">
            <Button type="primary" size="small" @click="editorIn(scope.row.id,'editor')">盘点</Button>
            <!-- <Poptip transfer confirm title="确认要删除吗？" @on-ok="deleteIn(scope.row)">
              <Button type="primary" style="margin-left: 10px;" size="small" ghost>删除</Button>
            </Poptip> -->
          </template>
        </el-table-column>
        <div v-else />
      </template>

    </xy-table>

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

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

  </div>
</template>

<script>
import {
  index,
  destroy
} from '@/api/inventory.js'
import {
  getInfo
} from '@/api/user.js'
import addInventorys from './components/addInventorys.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,
    addInventorys
  },
  data() {
    return {
      loading: false,
      userName: '',
      authName: '',
      roleName: '',
      isCkName: '',
      isPandian: '',
      select: {
        pageSize: 40,
        pageIndex: 1,
        keyword: '',
        wzbm: '',
        is_export: 0,
        min: '',
        max: '',
        rmin: '',
        rmax: ''
      },
      showcode: false,
      customForm: {
        customFormId: '',
        tableName: 'inventorys'
      },
      form: [],
      total: 0,
      list: [],
      spanArr: [], // 存储合并规则的数组
      position: 0, // 记录当前合并的起始位置
      table: [{
        type: 'selection',
        fixed: 'left'
      },
      {
        label: '基础信息',
        align: 'left',
        prop: 'wuzibianma_material_infos_wuzibianma_relation',
        multiHd: [{
          label: '物资编码',
          width: 120,
          prop: 'wuzibianma',
          align: 'center'
        },
        {
          label: '物资名称',
          prop: 'zichanmingcheng',
          align: 'center',
          width: 180,
          fixed: 'left'
        },
        {
          label: '物资类型',
          width: 120,
          prop: 'wuzileixing',
          align: 'center'
        },
        {
          label: '所属种类',
          width: 120,
          prop: 'wuzibianma_material_infos_wuzibianma_relation.fenlei_detail.value',
          align: 'center'
        },
        {
          label: '物资型号',
          prop: 'guigexinghao',
          align: 'center',
          width: 180
        },
        {
          label: '物资规格',
          prop: 'wuziguige',
          align: 'center',
          width: 180
        },
        {
          label: '单位',
          width: 120,
          prop: 'jiliangdanwei',
          align: 'center'
        }]
      },
      {
        label: '库存信息',
        prop: 'kucun',
        align: 'left',
        multiHd: [
          {
            label: '入库批次',
            width: 120,
            prop: 'rukupici'
          },
          {
            label: '在库数量',
            width: 120,
            prop: 'zaikushuliang'
          }
          // {
          //   label: "入库数量",
          //   width: 120,
          //   prop: 'rukushuliang'
          // },
        ]
      },
      {
        label: '物资明细',
        prop: 'stocks_items_info',
        align: 'left',
        multiHd: [
          {
            label: '物资状态',
            width: 120,
            prop: 'stocks_items_info.wuzizhuangtai_detail.value'
          },

          {
            label: '储备方式',
            width: 120,
            prop: 'stocks_items_info.chubeifangshi_detail.value'
          },
          {
            label: '储备年限',
            width: 120,
            prop: 'stocks_items_info.chubeinianxian'
          },
          {
            label: '生产日期',
            width: 120,
            prop: 'stocks_items_info.shengchanriqi'
          },
          {
            label: '入库日期',
            width: 120,
            prop: 'stocks_items_info.rukuriqi'
          },
          {
            label: '所在仓库',
            width: 120,
            prop: 'stocks_items_info.materialstorages.cangkumingcheng'
          },
          {
            label: '所在货架',
            width: 120,
            prop: 'stocks_items_info.shelfs.huojiamingcheng'
          },
          {
            label: '等级分类',
            width: 120,
            prop: 'stocks_items_info.dengjifenlei_detail.value'
          },
          {
            label: '产权信息',
            width: 120,
            prop: 'stocks_items_info.chanquanxinxi_detail.value'
          },
          {
            label: '存放要求',
            width: 120,
            prop: 'stocks_items_info.cunfangyaoqiu'
          },

          {
            label: '翻挆要求',
            width: 120,
            prop: 'stocks_items_info.fanduoyaoqiu'
          },
          {
            label: '试车要求',
            width: 120,
            prop: 'stocks_items_info.shicheyaoqiu'
          },
          {
            label: '保养频次',
            width: 120,
            prop: 'stocks_items_info.baoyangpinci'
          }

          // {
          //   label: '备注',
          //   prop:'stocks_beizhu',
          //   width: 180,
          // },
        ]
      }

      ],
      printObj: [],
      printArr: [],
      // 定义需要合并的列索引范围（从selection列开始计数）
      mergeColumnRange: {
        start: 1, // 基础信息分组的起始列索引
        end: 6 // 基础信息分组的结束列索引
      }
    }
  },
  mounted() {
    if (this.$route.path) {
      const path = this.$route.path.split('_')
      if (path[1]) {
        this.isPandian = 'pandian'
      }
    }
    this.getField()
    this.getindex()
    this.getUserName()
  },
  methods: {
    // filterSpans
    getSpanArr(data) {
      // 生成合并规则数组（保持不变）
      this.spanArr = []
      this.position = 0

      data.forEach((item, index) => {
        if (index === 0) {
          this.spanArr.push(1)
          this.position = 0
        } else {
          if (item.wuzibianma_material_infos_wuzibianma_relation.wuzibianma ===
                data[this.position].wuzibianma_material_infos_wuzibianma_relation.wuzibianma) {
            this.spanArr[this.position] += 1
            this.spanArr.push(0)
          } else {
            this.spanArr.push(1)
            this.position = index
          }
        }
      })
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // 通过列索引范围判断是否需要合并
      if (columnIndex >= this.mergeColumnRange.start && columnIndex <= this.mergeColumnRange.end) {
        const _row = this.spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      }
      // 其他列保持默认
      return {
        rowspan: 1,
        colspan: 1
      }
    },
    handleDataChange() {
      this.getSpanArr(this.list)
    },
    async getUserName() {
      getInfo().then(res => {
        console.log('res', res)
        this.userName = res.username
        this.authName = res.name
        for (var k of res.role) {
          if (k.name == '系统管理员') {
            this.roleName = k.name
          }
          if (k.name == '仓库管理员') {
            this.isCkName = '仓库管理员'
          }
        }
      }).catch(error => {})
    },
    selectionChange(e) {
      console.log(e)
      const _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) {
        const 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
    },
    search() {
      this.select.pageIndex = 1
      this.getindex()
    },
    async getindex() {
      this.loading = true
      const min = this.select.min ? this.select.min : 0
      const max = this.select.max ? this.select.max : 99999
      const rmin = this.select.rmin ? this.select.rmin : 0
      const rmax = this.select.rmax ? this.select.rmax : 99999
      const res = await index({
        page_size: this.select.pageSize,
        page: this.select.pageIndex,
        table_name: 'inventorys',
        sort_type: 'DESC',
        sort_name: 'wuzibianma',
        // is_export:this.select.is_export,
        filter: [{
          'key': 'wuzibianma',
          'op': 'like',
          'value': this.select.wzbm
        }, {
          'key': 'zichanmingcheng',
          'op': 'like',
          'value': this.select.keyword
        },
        {
          'key': 'rukushuliang',
          'op': 'range',
          'value': rmin + ',' + rmax
        },
        {
          'key': 'zaikushuliang',
          'op': 'range',
          'value': min + ',' + max
        }
        ]
      })
      // 筛选出 入库批次
      let stocks_items_arr = []
      res.list.data.map(item => {
        stocks_items_arr = item.stocks_items.filter(f => f.rukupici === item.rukupici)
        item.stocks_items_info = stocks_items_arr.length > 0 ? stocks_items_arr[0] : {}
      })
      this.list = res.list.data
      this.total = res.list.total
      this.loading = false
      this.handleDataChange()
    },
    pageSizeChange(e) {
      this.select.pageSize = e
      this.getindex()
    },
    pageChange(e) {
      this.select.pageIndex = e
      this.getindex()
    },
    editorIn(id, type) {
      this.$refs['addInventorys'].id = id
      this.$refs['addInventorys'].isShow = true
      this.$refs['addInventorys'].type = type
    },
    deleteIn(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) {
        const decode = decodeURIComponent(this.$route.meta.params?.custom_form)
        try {
          const 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
      this.form = res.data
        ?.filter((i) => i.list_show)
        .map((i) => {
          return i
        })
      console.log(this.form)
    }
  }

}
</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>
