<template>
  <div class="mod-config">
    <!-- 查询条件 -->
    <el-form :inline="true" label-position="top" :model="searchData" @keyup.enter.native="getDataList()">
      <el-form-item :label="'物料编码'">
        <el-input v-model="searchData.partNo" clearable style="width: 120px"></el-input>
      </el-form-item>
      <el-form-item :label="'物料名称'">
        <el-input v-model="searchData.partDesc" clearable style="width: 120px"></el-input>
      </el-form-item>
      <el-form-item :label="' '">
        <el-button @click="getDataList()">查询</el-button>
        <el-button type="primary" @click="addModal()">新增</el-button>
        <el-button type="primary" @click="delModal()">删除</el-button>
        <download-excel
          :fields="fields()"
          :data="exportData"
          type="xls"
          :name="exportName"
          :header="exportHeader"
          :footer="exportFooter"
          :fetch="createExportData"
          :before-generate="startDownload"
          :before-finish="finishDownload"
          worksheet="导出信息"
          class="el-button el-button--primary el-button--medium">
          {{ "导出" }}
        </download-excel>
      </el-form-item>
    </el-form>

    <!-- 材料列表 -->
    <el-table
      :height="height"
      :data="dataList"
      border
      @selection-change="selectionBom"
      v-loading="dataListLoading"
      style="width: 100%;">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        :selectable="selectFlag"
        width="50">
      </el-table-column>
      <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">
        <template slot-scope="scope">
          <span v-if="!item.columnHidden">{{ scope.row[item.columnProp] }}</span>
          <span v-if="item.columnImage"><img :src="scope.row[item.columnProp]" style="width: 100px; height: 80px"/></span>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="100"
        label="操作">
        <template slot-scope="scope">
          <a type="text" size="small" @click="updateModal(scope.row)">编辑</a>
        </template>
      </el-table-column>
    </el-table>

    <!-- 复选统计 -->
    <selectDiv ref="selectDiv"></selectDiv>

    <!-- 分页插件 -->
    <el-pagination style="margin-top: 0px"
                   @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-pagination>

    <!-- bom新增/编辑模态框 -->
    <el-dialog :title="modalData.title" :close-on-click-modal="false" v-drag :visible.sync="modalFlag" width="495px">
      <el-form :inline="true" label-position="top" :model="modalData" :rules="rules" style="margin-left: 7px;margin-top: -5px;">
        <el-form-item prop="partNo" :rules="rules.partNo">
          <span slot="label" @click="getBaseList(116)"><a herf="#">物料编码</a></span>
          <el-input v-model="modalData.partNo" style="width: 221px"></el-input>
        </el-form-item>
        <el-form-item label="物料名称" prop="partDesc" :rules="rules.partDesc">
          <el-input v-model="modalData.partDesc" disabled style="width: 221px"></el-input>
        </el-form-item>
      </el-form>
      <el-footer style="height:30px;margin-top: 20px;text-align:center">
        <el-button type="primary" @click="saveData()">保存</el-button>
        <el-button type="primary" @click="modalFlag = false">关闭</el-button>
      </el-footer>
    </el-dialog>

    <!-- chooseList模态框 -->
    <ChooseList ref="baseList" @getBaseData="getBaseData"></ChooseList>
  </div>
</template>

<script>
import {
  bomManagementSearch, // bom列表查询
  bomManagementSave, // bom新增
  bomManagementEdit, // bom编辑
  bomManagementDelete, // bom删除
} from '@/api/part/bomManagement.js'
import ChooseList from '@/views/modules/common/Chooselist'

export default {
  // 组件
  components: {
    ChooseList
  },
  // 监听
  watch: {
    searchData: {
      deep: true,
      handler: function (newV, oldV) {
        this.searchData.partNo = this.searchData.partNo.toUpperCase()
      }
    }
  },
  // 对象
  data () {
    return {
      // 导出
      exportData: [],
      exportName: 'bom物料列表' + this.dayjs().format('YYYYMMDDHHmmss'),
      exportHeader: ['bom物料列表'],
      exportFooter: [],
      resultList: [],
      // ======== 行高 ========
      height: 200,
      // ======== 分页 ========
      pageIndex: 1,
      pageSize: 50,
      totalPage: 0,
      selectedDataNum: 0,
      // 条件查询
      searchData: {
        site: this.$store.state.user.site,
        partNo: '',
        partDesc: '',
        page: 1,
        limit: 10
      },
      // 其它
      dataListLoading: false,
      // ======== 数据对象 ========
      modalData: {
        flag: '',
        title: '',
        site: this.$store.state.user.site,
        partNo: '',
        partDesc: '',
        createDate: '',
        createBy: '',
        updateDate: '',
        updateBy: ''
      },
      // ======== 数据列表 ========
      dataList: [],
      // ======== 列表表头 ========
      columnList: [
        {
          userId: this.$store.state.user.name,
          functionId: 104002,
          serialNumber: '104002Table1PartNo',
          tableId: '104002Table1',
          tableName: 'BOM信息表',
          columnProp: 'partNo',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '物料编码',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 120
        },
        {
          userId: this.$store.state.user.name,
          functionId: 104002,
          serialNumber: '104002Table1PartDesc',
          tableId: '104002Table1',
          tableName: 'BOM信息表',
          columnProp: 'partDesc',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '物料名称',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 120
        },

        {
          userId: this.$store.state.user.name,
          functionId: 104002,
          serialNumber: '104002Table1CreateDate',
          tableId: '104002Table1',
          tableName: 'BOM信息表',
          columnProp: 'createDate',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '创建时间',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 160
        },
        {
          userId: this.$store.state.user.name,
          functionId: 104002,
          serialNumber: '104002Table1CreateBy',
          tableId: '104002Table1',
          tableName: 'BOM信息表',
          columnProp: 'createBy',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '创建人',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 80
        },
        {
          userId: this.$store.state.user.name,
          functionId: 104002,
          serialNumber: '104002Table1UpdateDate',
          tableId: '104002Table1',
          tableName: 'BOM信息表',
          columnProp: 'updateDate',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '更新时间',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 160
        },
        {
          userId: this.$store.state.user.name,
          functionId: 104002,
          serialNumber: '104002Table1UpdateBy',
          tableId: '104002Table1',
          tableName: 'BOM信息表',
          columnProp: 'updateBy',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '更新人',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 80
        }
      ],
      // ======== 必填规则 ========
      rules: {
        partNo: [
          {
            required: true,
            message: ' ',
            trigger: 'change'
          }
        ],
        partDesc: [
          {
            required: true,
            message: ' ',
            trigger: 'change'
          }
        ]
      },
      // ======== 复选数据集 ========
      bomSelections: [],
      // ======== 模态框开关控制 ========
      modalFlag: false,
      modalDisableFlag: false,
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.height = window.innerHeight - 180
    })
  },
  created () {
    this.getDataList()
  },
  // js
  methods: {
    // ======== 分页相关方法 ========
    /**
     * 每页数
     * @param val
     */
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    /**
     * 当前页
     * @param val
     */
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getDataList()
    },

    // ======== 列表数据操作方法 ========
    /**
     * 未知
     * @returns {boolean}
     */
    selectFlag () {
      return true
    },
    /**
     * 获取数据列表
     */
    getDataList () {
      this.searchData.limit = this.pageSize
      this.searchData.page = this.pageIndex
      bomManagementSearch(this.searchData).then(({data}) => {
        if (data.code === 0) {
          this.dataList = data.page.list
          this.pageIndex = data.page.currPage
          this.pageSize = data.page.pageSize
          this.totalPage = data.page.totalCount
          this.$refs.selectDiv.setLengthAll( this.dataList.length)
        }
        this.dataListLoading = false
      })
    },
    /**
     * 复选列表信息
     * @param val
     */
    selectionBom (val) {
      this.bomSelections = val
      this.$refs.selectDiv.setLengthselected(this.bomSelections.length)
    },

    // ======== 新增/编辑模态框 ========
    /**
     * bom新增模态框
     */
    addModal () {
      this.modalData = {
        flag: '1',
        title: 'bom新增',
        site: this.$store.state.user.site,
        partNo: '',
        partDesc: '',
        createBy: this.$store.state.user.name
      }
      this.modalDisableFlag = false
      this.modalFlag = true
    },

    // ======== 新增/编辑/删除方法 ========
    /**
     * bom新增/编辑
     */
    saveData () {
      if (this.modalData.partNo === '' || this.modalData.partNo == null) {
        this.$message.warning('请选择物料编码！')
        return
      }
      if (this.modalData.partDesc === '' || this.modalData.partDesc == null) {
        this.$message.warning('请选择物料名称！')
        return
      }
      if (this.modalData.flag === '1') {
        bomManagementSave(this.modalData).then(({data}) => {
          if (data && data.code === 0) {
            this.getDataList()
            this.modalFlag = false
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {}
            })
          } else {
            this.$alert(data.msg, '错误', {
              confirmButtonText: '确定'
            })
          }
        })
      } else {
        bomManagementEdit(this.modalData).then(({data}) => {
          if (data && data.code === 0) {
            this.getDataList()
            this.modalFlag = false
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {}
            })
          } else {
            this.$alert(data.msg, '错误', {
              confirmButtonText: '确定'
            })
          }
        })
      }
    },
    /**
     * bom删除
     */
    delModal () {
      if(this.bomSelections.length === 0){
        this.$message.warning('请勾选要删除的BOM！')
        return
      }
      this.$confirm(`是否删除这 `+ this.bomSelections.length +` 条BOM?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let tempData = {
          informationList: this.bomSelections
        }
        bomManagementDelete(tempData).then(({data}) => {
          if (data && data.code === 0) {
            this.getDataList()
            this.bomSelections = []
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {}
            })
          } else {
            this.$alert(data.msg, '错误', {
              confirmButtonText: '确定'
            })
          }
        })
      }).catch(() => {
      })
    },

    // ======== chooseList相关方法 ========
    /**
     * 获取基础数据列表S
     * @param val
     * @param type
     */
    getBaseList (val, type) {
      this.tagNo = val
      this.$nextTick(() => {
        let strVal = ''
        if (val === 116) {
          strVal = this.modalData.partNo
        }
        this.$refs.baseList.init(val, strVal)
      })
    },
    /**
     * 列表方法的回调
     * @param val
     */
    getBaseData (val) {
      if (this.tagNo === 116) {
        this.modalData.partNo = val.part_no
        this.modalData.partDesc = val.part_desc
      }
    },

    // ======== 导出相关方法 ========
    /**
     * 导出excel
     */
    async createExportData () {
      this.searchData.limit = -1
      this.searchData.page = 1
      await bomManagementSearch(this.searchData).then(({data}) => {
        this.resultList = data.page.list
      })
      return this.resultList
    },
    startDownload () {
    },
    finishDownload () {
    },
    fields () {
      let json = '{'
      this.columnList.forEach((item, index) => {
        if (index == this.columnList.length - 1) {
          json += '"' + item.columnLabel + '"' + ':' + '"' + item.columnProp + '"'
        } else {
          json += '"' + item.columnLabel + '"' + ':' + '"' + item.columnProp + '"' + ','
        }
      })
      json += '}'
      let s = eval('(' + json + ')')
      return s
    }
  }
}
</script>












