<template>
  <div class="mod-config">
    <el-form :inline="true" label-position="top" :model="searchData">
      <el-form-item label="Buyer编码">
        <el-input v-model="searchData.buyerCode" clearable style="width: 160px" placeholder="请输入编码" />
      </el-form-item>
      <el-form-item label="Buyer名称">
        <el-input v-model="searchData.buyerName" clearable style="width: 220px" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="启用">
        <el-select v-model="searchData.active" clearable style="width: 120px">
          <el-option label="Y" value="Y" />
          <el-option label="N" value="N" />
        </el-select>
      </el-form-item>
      <el-form-item label=" ">
        <el-button type="primary" @click="getDataList()">查询</el-button>
        <el-button type="primary" @click="addModal()">新增</el-button>
        <el-button type="primary" @click="exportExcel()">导出</el-button>
      </el-form-item>
    </el-form>

    <el-table
      :height="height"
      :data="dataList"
      border
      v-loading="dataListLoading"
      style="width: 100%;">
      <el-table-column
        v-for="(item,index) in columnList"
        :key="index"
        :sortable="item.columnSortable"
        :prop="item.columnProp"
        :header-align="item.headerAlign"
        :show-overflow-tooltip="item.showOverflowTooltip"
        :align="item.align"
        :fixed="item.fixed === '' ? false : item.fixed"
        :min-width="item.columnWidth"
        :label="item.columnLabel" />
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="120"
        label="操作">
        <template slot-scope="scope">
          <el-link style="cursor: pointer" @click="updateModal(scope.row)">编辑 |</el-link>
          <el-link style="cursor: pointer" @click="deleteHandle(scope.row)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[20, 50, 100, 200, 500]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper" />

    <el-dialog title="Buyer维护" :close-on-click-modal="false" v-drag :visible.sync="modalFlag" width="580px">
      <el-form
        ref="modalForm"
        label-position="top"
        :model="modalData"
        :rules="rules"
        style="margin-left: 7px; margin-right: 7px;">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="编码" prop="buyerCode">
              <el-input v-model.trim="modalData.buyerCode" :disabled="modalDisableFlag" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用" prop="active">
              <el-select v-model="modalData.active" style="width: 100%">
                <el-option label="Y" value="Y" />
                <el-option label="N" value="N" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="名称" prop="buyerName">
              <el-input v-model.trim="modalData.buyerName" maxlength="300" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model.trim="modalData.remark" type="textarea" maxlength="255" show-word-limit :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-footer style="height:25px;margin-top: 60px;text-align:center">
        <el-button type="primary" @click="saveData()">保存</el-button>
        <el-button type="primary" @click="modalFlag = false">关闭</el-button>
      </el-footer>
    </el-dialog>
  </div>
</template>

<script>
import {
  searchPoBuyerPage,
  createPoBuyer,
  updatePoBuyer,
  deletePoBuyer
} from '@/api/order/poBuyer.js'
import excel from '@/utils/excel-util.js'

export default {
  name: 'poBuyer',
  data () {
    return {
      exportName: 'Buyer维护_' + this.dayjs().format('YYYYMMDDHHmmss'),
      height: 200,
      dataList: [],
      dataListLoading: false,
      pageIndex: 1,
      pageSize: 20,
      totalPage: 0,
      searchData: {
        site: this.$store.state.user.site,
        buyerCode: '',
        buyerName: '',
        active: '',
        page: 1,
        limit: 10
      },
      modalFlag: false,
      modalDisableFlag: false,
      modalData: {
        site: this.$store.state.user.site,
        buyerCode: '',
        buyerName: '',
        active: 'Y',
        remark: '',
        flag: '1'
      },
      columnList: [
        // {
        //   columnProp: 'site',
        //   headerAlign: 'center',
        //   align: 'center',
        //   columnLabel: 'Site',
        //   columnHidden: false,
        //   columnSortable: false,
        //   fixed: '',
        //   columnWidth: 100,
        //   showOverflowTooltip: true
        // },
        {
          columnProp: 'buyerCode',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '编码',
          columnHidden: false,
          columnSortable: false,
          fixed: '',
          columnWidth: 160,
          showOverflowTooltip: true
        },
        {
          columnProp: 'buyerName',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '名称',
          columnHidden: false,
          columnSortable: false,
          fixed: '',
          columnWidth: 260,
          showOverflowTooltip: true
        },
        {
          columnProp: 'active',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '启用',
          columnHidden: false,
          columnSortable: false,
          fixed: '',
          columnWidth: 90,
          showOverflowTooltip: true
        },
        {
          columnProp: 'remark',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '备注',
          columnHidden: false,
          columnSortable: false,
          fixed: '',
          columnWidth: 260,
          showOverflowTooltip: true
        }
      ],
      rules: {
        buyerCode: [
          { required: true, message: '请输入编码', trigger: 'blur' },
          { max: 50, message: '编码长度不能超过50', trigger: 'blur' }
        ],
        buyerName: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { max: 300, message: '名称长度不能超过300', trigger: 'blur' }
        ],
        active: [
          { required: true, message: '请选择启用状态', trigger: 'change' }
        ],
        remark: [
          { max: 255, message: '备注长度不能超过255', trigger: 'blur' }
        ]
      }
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.height = window.innerHeight - 180
    })
  },
  created () {
    this.getDataList()
  },
  methods: {
    getDataList () {
      this.dataListLoading = true
      const params = {
        ...this.searchData,
        site: this.$store.state.user.site,
        page: this.pageIndex,
        limit: this.pageSize
      }
      searchPoBuyerPage(params).then(({ data }) => {
        if (data && data.code === 0) {
          const pageData = data.page
          this.dataList = pageData && pageData.list ? pageData.list : []
          this.pageIndex = pageData && pageData.currPage ? pageData.currPage : 1
          this.pageSize = pageData && pageData.pageSize ? pageData.pageSize : this.pageSize
          this.totalPage = pageData && pageData.totalCount ? pageData.totalCount : 0
        } else {
          this.$message.error((data && data.msg) || '获取数据失败')
        }
      }).catch(err => {
        this.$message.error((err && err.message) || '获取数据失败')
      }).finally(() => {
        this.dataListLoading = false
      })
    },

    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },

    currentChangeHandle (val) {
      this.pageIndex = val
      this.getDataList()
    },

    addModal () {
      this.modalDisableFlag = false
      this.modalData = {
        site: this.$store.state.user.site,
        buyerCode: '',
        buyerName: '',
        active: 'Y',
        remark: '',
        flag: '1'
      }
      this.modalFlag = true
      this.$nextTick(() => {
        if (this.$refs.modalForm) {
          this.$refs.modalForm.clearValidate()
        }
      })
    },

    updateModal (row) {
      this.modalDisableFlag = true
      this.modalData = {
        site: row.site,
        buyerCode: row.buyerCode,
        buyerName: row.buyerName,
        active: row.active,
        remark: row.remark || '',
        flag: '2'
      }
      this.modalFlag = true
      this.$nextTick(() => {
        if (this.$refs.modalForm) {
          this.$refs.modalForm.clearValidate()
        }
      })
    },

    saveData () {
      this.$refs.modalForm.validate(valid => {
        if (!valid) return
        const payload = {
          ...this.modalData,
          site: this.$store.state.user.site
        }
        const api = payload.flag === '1' ? createPoBuyer : updatePoBuyer
        api(payload).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message.success('操作成功')
            this.modalFlag = false
            this.getDataList()
          } else {
            this.$message.error((data && data.msg) || '操作失败')
          }
        }).catch(err => {
          this.$message.error((err && err.message) || '操作失败')
        })
      })
    },

    deleteHandle (row) {
      this.$confirm(`确定删除Buyer【${row.buyerCode}】吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePoBuyer({
          site: row.site || this.$store.state.user.site,
          buyerCode: row.buyerCode
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message.success('删除成功')
            this.getDataList()
          } else {
            this.$message.error((data && data.msg) || '删除失败')
          }
        }).catch(err => {
          this.$message.error((err && err.message) || '删除失败')
        })
      }).catch(() => {})
    },

    exportExcel () {
      const params = {
        ...this.searchData,
        site: this.$store.state.user.site
      }
      excel.exportTable({
        url: '/poBuyer/list',
        columnMapping: this.columnList,
        mergeSetting: [],
        params,
        fileName: this.exportName + '.xlsx',
        rowFetcher: res => {
          if (res && res.data && res.data.code === 0) {
            return { rows: res.data.rows || [] }
          }
          return { rows: [] }
        },
        columnFormatter: [],
        dropColumns: []
      })
    }
  }
}
</script>

<style scoped>
.mod-config {
  padding: 0;
}

.el-table /deep/ .cell {
  height: auto;
  line-height: 1.5;
}
</style>
