<template>
  <template-page
    ref="pageRef"
    :getList="getList"
    :exportList="exportList"
    :operation="operation()"
    :optionsEvensGroup="optionsEvensGroup"
    :tableAttributes="tableAttributes"
    :tableEvents="tableEvents"
    :columnParsing="columnParsing"
  >
    <!-- 弹窗 -->
    <el-dialog
      title="仓库费规则配置"
      :visible.sync="showDialog"
      width="50%"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <el-form :model="dialogForm" label-width="100px" label-position="right">
        <el-form-item label="经销商编码" prop="customerNumber">
          <el-select
            v-model="dialogForm.customerNumber"
            placeholder="请选择活动区域"
            filterable
            class="inputStyle"
            v-el-select-loadmore="loadmore"
          >
            <!-- v-el-select-loadmore="loadMore" -->
            <el-option
              v-for="(item, index) in customerList"
              :key="index"
              :label="item.number"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="经销商名称" prop="customerName">
          <el-input v-model="dialogForm.customerName" class="inputStyle"></el-input>
        </el-form-item>
        <el-form-item label="仓库存放" class="sty" prop="freeDay">
          <el-input
            type="number"
            @mousewheel.native.prevent
            v-model="dialogForm.freeDay"
            class="inputStyle"
          />天内可免费受存储管理费用.
          <br />
          当超过
          <el-input
            type="number"
            @mousewheel.native.prevent
            v-model="dialogForm.freeDay"
            class="inputStyle"
          />天后,按每立方米
          <el-input v-model="dialogForm.toll" type="number" @mousewheel.native.prevent class="inputStyle" />
          元/天计算
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="hanleInfo(dialogForm)">确 定</el-button>
      </div>
    </el-dialog>
  </template-page>
</template>

<script>
import TemplatePage from '@/components/template/template-page-1.vue'
import import_mixin from '@/components/template/import_mixin.js'
import add_callback_mixin from '@/components/template/add_callback_mixin.js'
import Popu from '@/components/template/popu.vue'
import { downloadFiles, handleImport } from '@/utils/util'
import {
  addToll,
  deleteToll,
  getCustomerList,
  getListTollV2,
  updateToll,
  exportListTollV2,
  importStockV2
} from '@/api/basic_data/warehouse'

export default {
  components: { TemplatePage, Popu },
  mixins: [import_mixin, add_callback_mixin],
  data() {
    return {
      visible: false,
      // 事件组合
      // 事件组合
      optionsEvensGroup: [
        [
          [
            {
              name: '新增',
              click: this.addOn(() => {
                this.getCustomerList()
                this.showDialog = true
                this.type = 1
              }),
              isRole: this.$checkBtnRole('add', this.$route.meta.roles)
            }
          ]
        ],
        [
          [
            {
              name: '批量删除',
              click: async () => {
                if (this.recordSelected.length === 0) {
                  this.$message.error('请选择需要删除的数据')
                  return
                }
                let ids = this.recordSelected.map(v => {
                  return v.id
                })
                let params = { id: ids.join() }
                await deleteToll(params)
                this.$refs.pageRef.refreshList()
                this.$message.success('批量删除成功')
              },
              isRole: this.$checkBtnRole('del', this.$route.meta.roles)
            }
          ]
        ],
        [
          [
            {
              name: '导入',
              render: this.importButton(importStockV2)
            }
          ]
        ]
      ],
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: true
      }, // 关闭新增弹窗

      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      dialogForm: {
        id: null,
        customerName: '',
        customerNumber: '',
        freeDay: 0,
        toll: 0
      },
      sleectBox: {
        currentPage: 1, // 当前页码
        pageSize: 10, // 每页数量
        listTotal: 0 // 列表总数
      },
      baseURL: '',
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数
      importLoading: false, // 导入加载loading
      importFileList: [], // 导入列表

      customerList: [],
      showDialog: false,
      dataList: [],
      screenForm: {
        customerName: '',
        freeDay: '',
        toll: ''
      },
      type: null // 1 新增  2 修改  null 详情
    }
  },
  directives: {
    'el-select-loadmore': {
      bind(el, binding) {
        // 获取element-ui定义好的scroll盒⼦
        const SELECTWRAP_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
        SELECTWRAP_DOM.addEventListener('scroll', function () {
          /**
           * scrollHeight 获取元素内容⾼度(只读)
           * scrollTop 获取或者设置元素的偏移值,常⽤于, 计算滚动条的位置, 当⼀个元素的容器没有产⽣垂直⽅向的滚动条, 那它的scrollTop的值默认为0.
           * clientHeight 读取元素的可见⾼度(只读)
           * 如果元素滚动到底, 下⾯等式返回true, 没有则返回false:
           * ele.scrollHeight - ele.scrollTop === ele.clientHeight;
           */
          const condition = this.scrollHeight - this.scrollTop <= this.clientHeight
          if (condition) {
            binding.value()
          }
        })
      }
    }
  },
  methods: {
    // 列表请求函数
    getList(...p) {
      this.$refs.pageRef.showTable = false
      this.recordSelected = []
      return getListTollV2(...p)
    },
    // 列表导出函数
    exportList: exportListTollV2,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    operation() {
      return (h, { row, index, column }) => {
        return (
          <div class="operation-btns">
            {this.$checkBtnRole('edit', this.$route.meta.roles) ? (
              <el-button
                type="text"
                size="mini"
                class="textColor"
                onClick={() => {
                  this.getCustomerList()
                  this.editFn(row.id, row)
                }}
              >
                编辑
              </el-button>
            ) : null}
            {this.$checkBtnRole('del', this.$route.meta.roles) ? (
              <el-popconfirm
                confirm-button-text="好的"
                cancel-button-text="不用了"
                icon="el-icon-info"
                icon-color="red"
                title="内容确定删除吗？"
                onOnConfirm={() => this.hanleDelete(row.id)}
              >
                <el-button slot="reference" type="text"  size="mini" class="textColor el-popover-left">
                  删除
                </el-button>
              </el-popconfirm>
            ) : null}
          </div>
        )
      }
    },
    handleClose() {
      this.dialogForm = {
        customerName: '',
        customerNumber: '',
        freeDay: 0,
        toll: 0
      }
      this.addOff(() => {
        this.showDialog = false
      })()
    },
    editFn(id, row) {
      console.log(row)
      ;(this.dialogForm = {
        id: id,
        customerName: row.customerName,
        customerNumber: row.customerNumber,
        freeDay: row.freeDay,
        toll: row.toll
      }),
        (this.type = 2)
      this.showDialog = true
    },
    hanleInfo(dialogForm) {
      if (this.type === 1) {
        const params = {
          ...dialogForm
        }
        console.log(params, 78798)
        addToll(params).then(res => {
          this.$refs.pageRef.refreshList()
          this.$successMsg('保存成功')
          this.handleClose()
        })
      } else if (this.type === 2) {
        const paramss = {
          ...this.dialogForm
        }
        updateToll(paramss).then(res => {
          this.$successMsg('编辑成功')
          this.$refs.pageRef.refreshList()
          this.handleClose()
          this.diaLogForm.id = null
        })
      }
      this.showDialog = false
    },

    loadmore() {
      this.sleectBox.currentPage++
      this.getCustomerList()
    },
    getCustomerList() {
      let params = {
        pageNum: 1,
        pageSize: -1,
        keyword: ''
      }
      getCustomerList(params).then(res => {
        if (res.data.records.length) {
          this.customerList = [...this.customerList, ...res.data.records]
        }
        // this.listTotal = res.data.total;
      })
    },
    // hanleDetail(detail) {
    //   this.type = null;
    //   this.showDialog = true;
    //   this.diaLogForm = detail;
    // },

    handleExport() {
      let screenData = {
        customerName: this.screenForm.customerName,
        freeDay: this.screenForm.freeDay,
        toll: this.screenForm.toll
      }
      downloadFiles('stock/exportToll', screenData)
    },
    // 删除数据
    hanleDelete(id) {
      deleteToll({ id }).then(res => {
        this.$successMsg('删除成功')
        this.$refs.pageRef.refreshList()
      })
    },
    // 导入
    async handleImport(param) {
      this.importLoading = true
      const file = param.file
      console.log(file, 123)
      const formData = new FormData()
      formData.append('file', file)
      let result = await handleImport('stock/importToll', formData)
      this.importLoading = false
      this.importFileList = []
      if (result.code == 200) {
        this.$alert(result.message, '导入成功', {
          confirmButtonText: '确定'
        })
        this.$refs.pageRef.refreshList()
      } else {
        this.$alert(result.message, '导入失败', {
          confirmButtonText: '确定'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .sty {
  width: 85%;
  .el-form-item__content .el-input {
    width: 22%;
    margin: 0px 10px 16px 0;
  }
}
.zhu {
  padding-top: 18px;
}
.import-btn {
  display: inline-block;
  margin-right: 10px;
}
.set {
  margin-bottom: 30px;
}
.inputs {
  margin: 0 18px;
}
::v-deep .el-form {
  .inputStyle {
    width: 80%;
  }
}
::v-deep .dialog-footer {
  display: flex;
  justify-content: center;
}
::v-deep .el-dialog__header {
  background-color: #dddddd;
}
.inp {
  margin: 0 12px;
}

.right {
  margin-top: 12px;
  float: right;
}

.table {
  margin-top: 12px;
}
.search {
  display: flex;
  margin-top: 12px;
  ::v-deep .el-input {
    width: 50%;
    margin-right: 12px;
  }
}
.main {
  padding: 12px;
}
</style>
