<template>
  <div>
    <en-table-layout :tableData="tableData" :loading="loading" @selection-change="handleSelectionChange">
      <div slot="toolbar" class="inner-toolbar">
        <div class="toolbar-btns">
          <el-button size="mini" v-if="checkPermission(['goodsLend:add'])" type="primary"
            @click="handleAddGoodsLend">新增</el-button>
        </div>
        <div class="toolbar-search">
        </div>
      </div>

      <template slot="table-columns">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="名称">
        </el-table-column>
        <el-table-column prop="remark" label="备注">
          </el-table-column>
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button size="mini" v-if="checkPermission(['goodsLend:edit'])"
              @click="handleEditGoodsLend(scope.row)">编辑</el-button>
            <el-button type="success" size="mini"
              v-if="checkPermission(['goodsLend:del'])"
              @click="handleReturnGoodsLend(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </template>

      <!-- <el-pagination v-if="tableData" slot="pagination" @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange" :current-page="tableData.page_no" :page-sizes="[10, 20, 50, 100]"
        :page-size="tableData.page_size" layout="total, sizes, prev, pager, next, jumper" :total="tableData.data_total">
      </el-pagination> -->
    </en-table-layout>
    <el-dialog :title="title" :visible.sync="dialogVisibleForm"  width="940px" center @close='addHandleCancle'>
        <el-form ref="addLendForm" :model="addLendForm" :rules="rules" label-width="90px">
          <el-form-item label="编号" prop="code">
            <el-input
            placeholder="请输入编号"
                v-model="addLendForm.code">
              </el-input>
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input
            placeholder="请输入名称"
                v-model="addLendForm.name">
              </el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4}"
                placeholder="请输入内容"
                v-model="addLendForm.remark">
              </el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addHandleCancle ">取 消</el-button>
          <el-button type="primary" @click="lendCommit">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
import * as API_GoodsLend from '@/api/goodsLend'
import Print from 'print-js'
import * as API_Setting from '@/api/setting'
import { Foundation } from '~/ui-utils'
import QRCode from 'qrcodejs2'
export default {
  name: 'goodsLend',
  data() {
    return {
      warehouseSn:"",
      warehouseList: [],
      // 列表loading状态
      loading: false,
      // 列表参数
      params: {
        page_no: 1,
        page_size: 10
      },
      // 高级搜索数据
      advancedForm: {},
      // 列表数据
      tableData: '',
      dialogVisible: false,
      // 当前已选择的行
      multipleSelection: [],
      goodsLendForm: {},
      codeList:[],
      title:"",
      dialogVisibleForm:false,
      // 新增数据
      addLendForm:{
        name:"",
        remark:""
      },
      rules: {
          name: [
            { required: true, message: '请选择输入名称', trigger: 'blur' }
          ],
          code:[
          { required: true, message: '请选择输入编号', trigger: 'blur' }
          ]
        },
        typeList:[],
        id:''
    }
  },
  mounted() {
    this.GET_GoodsLendList()
    this.GET_DeptList()
  },
  watch: {
    $route: {
      immediate: true,
      handler(newVal) {
        if (newVal.query.status) {
          this.params.status = newVal.query.status
          this.advancedForm.status = newVal.query.status
        }
        this.params.page_no = 1
        this.GET_GoodsLendList()
      }
    }
  },
  methods: {
    ceshi(){
      this.$router.push({name:"demo"})
    },
    gowareHouse(){
      this.dialogVisibleForm=false
      this.$router.push({ name: 'warehouseList'})
    },
    /* 选中仓库 */
    selWarehouse(val){
      const list=this.warehouseList.filter(el=>{
        return el.id===val
      })
      let obj = list[0]
      this.warehouseSn=obj.sn
    },
    // 确认提交
    lendCommit(){
      this.$refs.addLendForm.validate((valid) => {
      if (valid) {
        if(this.title==='新增'){
          this.addLendForm.code=this.warehouseSn+"-"+this.addLendForm.code
           API_GoodsLend.addCreateAreaType(this.addLendForm).then(res=>{
            this.$message.success('添加成功!')
            this.dialogVisibleForm=false
            this.warehouseSn=""
            this.addLendForm={}
            this.GET_GoodsLendList()
           })
        }else if(this.title==='编辑'){
          API_GoodsLend.editUpdateAreaType(this.id,this.addLendForm).then(res=>{
            this.$message.success('修改成功!')
            this.dialogVisibleForm=false
            this.id=''
            this.addLendForm={}
            this.GET_GoodsLendList()
           })
        }
      } else {
        this.$message.error('提交失败')
        return false;
      }
    })

    },
    addHandleCancle(){
      this.dialogVisibleForm=false
      this.addLendForm={}
    },
    handleCancle () {
      this.dialogVisible = false
      this.codeList=[]
    },
    // 二维码生成
    creatQrCode() {
      this.$nextTick(() => {
          this.codeList.forEach((item,index)=>{
            this.$refs.codeItem[index].innerHTML="";
              var qrcode = new QRCode(this.$refs.codeItem[index], {
                text: item, //二维码内容
                width: 600,
                height: 660,
                render: 'table',
                colorDark: "#333333", //二维码颜色
                colorLight: "#ffffff", //二维码背景色
                correctLevel : QRCode.CorrectLevel.H
              })
          });
        },500)
    },
    handleEditGoodsLend(row) {
      this.id=row.id
      this.title="编辑"
      this.addLendForm=row
      this.dialogVisibleForm=true
      // this.$router.push({ name: 'goodsLendEdit', params: { id: row.id }})
    },
    handleReturnGoodsLend(row) {
      this.$confirm('确定要删除吗？', '提示', { type: 'warning' }).then(() => {
        API_GoodsLend.removeAreaType(row.id).then(() => {
          this.$message.success('删除成功！')
          this.GET_GoodsLendList()
        })
      }).catch(() => { })
    },
    /** 状态 */
    statusFilter(val) {
      const obj=this.typeList.filter(el=>{
        return el.value===val
      })
      if(obj.length !== 0){
        return obj[0].label
      }else{
        return ""
      }

    },
    handleConfirmGoodsLend() {
      if (!this.multipleSelection || !this.multipleSelection.length) return this.$message.error('请先选择！')
        const ids = this.multipleSelection.map(item => item.code)
        this.codeList=ids
        this.dialogVisible = true
        this.creatQrCode()

    },
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getListAll().then(response => {
        this.warehouseList = response
        console.log(response);
      })
      API_Setting.getPage({dictType:"Warehouse_location_type",page_no: 1,page_size: 50}).then(res=>{
        this.typeList=res.data
      })
    },
    /** 打印对账详情 */
    handlePrintGoodsLend() {
      Print({
        printable: 'deliverySheet',
        type: 'html',
        targetStyles: ['*'],
        //style: 'body, html {font-size:300px !important;color:red;}', // 确保打印时应用这个样式
        ignoreElements: ['no-logs', 'goods-image', 'no-btn','elementToIgnore']
      })
    },
    handleDeleteGoodsLend() {
      if (!this.multipleSelection || !this.multipleSelection.length) return this.$message.error('请先选择！')
      this.$confirm('确定要删除这些借出单吗？', '提示', { type: 'warning' }).then(() => {
        const ids = this.multipleSelection.map(item => item.id)
        API_GoodsLend.deleteGoodsLend(ids).then(() => {
          this.$message.success('删除成功！')
          this.GET_GoodsLendList()
        })
      }).catch(() => { })
    },
    /** 多选改变 */
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size
      this.GET_GoodsLendList()
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page
      this.GET_GoodsLendList()
    },

    /** 添加调整单 */
    handleAddGoodsLend() {
      this.title="新增"
      this.dialogVisibleForm=true
      // this.$router.push({ name: 'goodsLendAdd'})
    },
    /** 打印调整单 */
    handlePrintGoodsLendDialog(row) {
      // this.GET_GoodsLendDetail(row.id)
      this.dialogVisible = true
      this.codeList.push(row.code)
        this.creatQrCode()
    },
    /** 获取调整单详情页面数据 */
    GET_GoodsLendDetail(id) {
      API_GoodsLend.getGoodsLendInfo(id).then(response => {
        this.goodsLendForm = response
        if (response.product_list && response.product_list.length) {
          var str = ''
          response.product_list.forEach(function(i) {
            str += i.product_name + '、'
          })
        }
        // 生成库位号二维码
        this.goodsLendForm.illustrate = str


      })
    },
    /** 搜索事件触发 */
    searchEvent(data) {
      this.params = {
        ...this.params,
        sn: data
      }
      Object.keys(this.advancedForm).forEach((key) => delete this.params[key])
      this.params.page_no = 1
      this.GET_GoodsLendList()
    },
    /** 高级搜索事件触发 */
    advancedSearchEvent() {
      this.params = {
        ...this.params,
        ...this.advancedForm
      }
      delete this.params.start_time
      delete this.params.end_time
      if (this.advancedForm.goodsLend_time_range) {
        this.params.start_time = parseInt(Number(this.advancedForm.goodsLend_time_range[0]) / 1000)
        this.params.end_time = parseInt(Number(this.advancedForm.goodsLend_time_range[1]) / 1000)
      }
      delete this.params.goodsLend_time_range
      this.params.page_no = 1
      this.GET_GoodsLendList()
    },
    /** 获取库存区域列表 */
    GET_GoodsLendList() {
      this.loading = true
      API_GoodsLend.getListAreaType().then(response => {
        this.loading = false
        this.tableData = response
      }).catch(() => { this.loading = false })
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
.print {
  margin-left: 790px;
}

.tips-t {
  display: flex;
  padding: 10px 0;

  div {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
  }
}

.tips-f {
  padding: 20px 0;
}

.face-image {
  display: block;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

/*  /deep/ .el-dialog__body {
  padding: 10px 20px;
}
/deep/.el-form{
    .el-form-item__content{
    display: flex;
  }
} */
/* @media print {
  html, body {
    font-size: 60pt !important;
    color: red;
  }
} */
</style>
