<template>
  <div>
    <en-table-layout :tableData="tableData.data" :loading="loading" @selection-change="handleSelectionChange">
      <div slot="toolbar" class="inner-toolbar">
        <div class="toolbar-btns">
          <el-button size="mini" v-if="checkPermission(['channel:add'])" type="primary"
            @click="handleAddGoodsLend">新增</el-button>
          <el-button size="mini" v-if="checkPermission(['channel:delete'])" @click="handleDeleteGoodsLend()" type="danger"
            :disabled="multipleSelection.length === 0">删除</el-button>

        </div>
        <div class="toolbar-search">
          <en-table-search @search="searchEvent" @advancedSearch="advancedSearchEvent" placeholder="请输入" advanced
            advancedWidth="465">
           <!--  <template slot="advanced-content">
              <el-form ref="advancedForm" :model="advancedForm" label-width="90px">
                <el-form-item label="所属部门">
                  <el-cascader v-model="advancedForm.dept_id" :options="deptList" :props="{
                    label: 'name',
                    value: 'id',
                    emitPath: false,
                    checkStrictly: true
                  }" clearable></el-cascader>
                </el-form-item>
                <el-form-item label="状态">
                  <el-select v-model="advancedForm.status">
                    <el-option key="NEW" label="新创建" value="NEW" />
                    <el-option key="CONFIRMED" label="已确认" value="CONFIRMED" />
                    <el-option key="RETURNED" label="已归还" value="RETURNED" />
                  </el-select>
                </el-form-item>
                <el-form-item label="时间">
                  <el-date-picker v-model="advancedForm.goodsLend_time_range" type="daterange" align="center"
                    :editable="false" unlink-panels :clearable="true" :default-time="['00:00:00', '23:59:59']"
                    range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" value-format="timestamp"
                    :picker-options="{ disabledDate(time) { return time.getTime() - 1 >= new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()).getTime() + 86400000 - 1 }, shortcuts: MixinPickerShortcuts }">
                  </el-date-picker>
                </el-form-item>
              </el-form>
            </template> -->
          </en-table-search>
        </div>
      </div>

      <template slot="table-columns">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="渠道名称">
          <!-- <template slot-scope="scope">
            <router-link
              v-if="checkPermission(['goodsLend'])"
              style="color: #409eff;"
              :to="{ name: 'goodsLendDetail', params: { id: scope.row.id } }">
              {{ scope.row.sn }}
            </router-link>
            <span v-else>{{scope.row.sn}}</span>
          </template> -->
        </el-table-column>
        <el-table-column prop="intro" label="渠道说明">
          <!-- <template slot-scope="scope">{{ scope.row.lend_time | unixToDate }}</template> -->
        </el-table-column>
        <el-table-column prop="main_user" label="渠道负责人" />
        <el-table-column prop="bonus" label="渠道佣金比例" />
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button size="mini" v-if="checkPermission(['channel:update'])"
              @click="handleEditGoodsLend(scope.row)">编辑</el-button>
            <el-button type="success" size="mini"
              v-if="checkPermission(['channel:delete'])"
              @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="30%" center @close='addHandleCancle'>
        <el-form ref="addLendForm" :model="addLendForm" :rules="rules" label-width="120px">
          <el-form-item label="渠道名称:" prop="name">
            <el-input v-model="addLendForm.name" style="width: 200px;" placeholder="请输入渠道名称"></el-input>
          </el-form-item>
          <el-form-item label="渠道说明:" prop="intro">
            <el-input v-model="addLendForm.intro"  style="width: 200px;" placeholder="请输入渠道说明"></el-input>
          </el-form-item>
          <el-form-item label="渠道负责人:" prop="main_user">
            <el-input v-model="addLendForm.main_user"  style="width: 200px;" placeholder="请输入渠道负责人"></el-input>
          </el-form-item>
          <el-form-item label="渠道佣金比例:" prop="bonus">
            <el-input
             style="width: 200px;"
                placeholder="请输入佣金比例"
                v-model="addLendForm.bonus">
                <template slot="append">%</template>
              </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 {
      deptList: [],
      // 列表loading状态
      loading: false,
      // 列表参数
      params: {
        page_no: 1,
        page_size: 10
      },
      // 高级搜索数据
      advancedForm: {},
      // 列表数据
      tableData: '',
      dialogVisible: false,
      // 当前已选择的行
      multipleSelection: [],
      goodsLendForm: {},
      codeList:[],
      title:"",
      dialogVisibleForm:false,
      // 新增数据
      addLendForm:{
      },
      rules: {
        name: [
            { required: true, message: '请输入渠道名称', trigger: 'blur' },
          ],
          intro: [
            { required: true, message: '请输入渠道说明', trigger: 'blur' }
          ],
          main_user: [
            { required: true, message: '请输入渠道负责人', trigger: 'blur' }
          ],
          bonus: [
            {  required: true, message: '请输入渠道佣金比例', trigger: 'blur' },
            { pattern: /^(([1-9]?\d{0,1}(\.\d{1,2})?)|100|100\.(0){1,2})$/, message: '请输入0-100内的数字(最多2位小数)'  }
          ]
        },
      editId:"",
    }
  },
  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: {
    // 确认提交
    lendCommit(){
      this.$refs.addLendForm.validate((valid) => {
      if (valid) {
        if(this.title==='新增'){
           API_GoodsLend.addChannel(this.addLendForm).then(res=>{
            this.$message.success('添加成功!')
            this.dialogVisibleForm=false
            this.addLendForm={}
            this.GET_GoodsLendList()
           })
        }else if(this.title==='编辑'){
          API_GoodsLend.editChannel(this.editId,this.addLendForm).then(res=>{
            this.$message.success('修改成功!')
            this.dialogVisibleForm=false
            this.addLendForm={}
            this.editId=""
            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: 100,
                height: 100,
                render: 'table',
                colorDark: "#333333", //二维码颜色
                colorLight: "#ffffff", //二维码背景色
                correctLevel : QRCode.CorrectLevel.H
              })
          });
        },500)
    },
    handleEditGoodsLend(row) {
      this.title="编辑"
      this.addLendForm=row
      this.editId=row.id
      this.dialogVisibleForm=true
    },
    handleReturnGoodsLend(row) {
      this.$confirm('确定要删除吗？', '提示', { type: 'warning' }).then(() => {
        API_GoodsLend.deleteChannel(row.id).then(() => {
          this.$message.success('删除成功！')
          this.GET_GoodsLendList()
        })
      }).catch(() => { })
    },
    /** 状态 */
    statusFilter(val) {
      switch (val) {
        case 'NEW':
          return '新创建'
        case 'CONFIRMED':
          return '已确认'
        case 'RETURNED':
          return '已归还'
        default:
          return ''
      }
    },
    handleConfirmGoodsLend() {
      if (!this.multipleSelection || !this.multipleSelection.length) return this.$message.error('请先选择！')
        const ids = this.multipleSelection.map(item => item.id)
        this.codeList=ids
        this.dialogVisible = true
        this.creatQrCode()

    },
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getDeptList().then(response => {
        this.deptList = Foundation.buildTree(response, '0')
      })
    },
    /** 打印对账详情 */
    handlePrintGoodsLend() {
      Print({
        printable: 'deliverySheet',
        type: 'html',
        targetStyles: ['*'],
        ignoreElements: ['no-logs', 'goods-image', 'no-btn']
      })
    },
    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
    },
    /** 打印调整单 */
    handlePrintGoodsLendDialog(row) {
      // this.GET_GoodsLendDetail(row.id)
      this.dialogVisible = true
      this.codeList.push(row.id)
        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.channel(this.params).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;
    // text-align: left;
    //padding-left: 70px;
    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;
}
</style>
